{% extends "layout_ol.html" %}

{% block url %}
    {% if url == None %}
        #
    {% else %}
        {{ url }}
    {% endif %}
{% endblock %}

{% block body %}

<script>
$(document).ready(function () {
	
	// set height of map div
    $("#map").height($(document).height()*0.5);
    $("#graph_body").height($("#ts").width()*0.22);
    $("#graph_anom_body").height($("#ts").width()*0.22);
    
    // set zoom step for map
    var e_lon = {{ ex1[0] }} - {{ ex2[0] }};
    var screen = $("#map").width();
    var zoom_v = 0;
    while (screen / 2 > e_lon) {
        zoom_v += 1
        screen = screen / 2
    }
    
    var n_lon = {{ex2[1]}} - {{ex1[1]}};
    var screen_h = $("#map").height();
    var zoom_h = 0;
    while (screen_h / 2 > n_lon) {
        zoom_h += 1
        screen_h = screen_h / 2
    }
    
    var zoom = zoom_h;
    
    if(zoom_v < zoom_h) {
    	zoom = zoom_v;
    }
    
    
    ts = new poetsViewer('', '{{host}}', {{port}}, '{{url}}');
    path = ts.trimSlash(window.location.pathname)
	
    var opacity = 0.75
	
    proj4326 = new OpenLayers.Projection("EPSG:4326");
		
    gphy = new OpenLayers.Layer.Google("Google Physical", {
		type: google.maps.MapTypeId.TERRAIN
    });
	osm = new OpenLayers.Layer.OSM("openstreetmap");
	map = new OpenLayers.Map("map");
	map.addControl(new OpenLayers.Control.LayerSwitcher());
	map.addLayers([osm, gphy]);
	map.setCenter(new OpenLayers.LonLat({{coord}}).transform(proj4326, map.getProjectionObject()), zoom);

	bounds = new OpenLayers.Bounds(); 				// bounding box for the overlay:
	bounds.extend(new OpenLayers.LonLat{{ex1}});
	bounds.extend(new OpenLayers.LonLat{{ex2}});
	bounds.transform(proj4326, map.getProjectionObject());
	
	image = new OpenLayers.Layer.Image('IMAGE', "_rimg/{{region}}&{{source}}&{{variable}}&{{max}}", bounds, new OpenLayers.Size(3400, 1600), { 
		'isBaseLayer': false,	// drawing overlay with the latest overlay image
		'alwaysInRange': true,
		'opacity' : opacity
	});
	map.addLayer(image);
	
	var mlayer = new OpenLayers.Layer()
	markers = new OpenLayers.Layer.Markers("Markers");
	map.addLayer(markers);
	
	map.events.register("click", map, function(e) {
		
		var lonlat = map.getLonLatFromViewPortPx(e.xy);
		var lonlat_o = map.getLonLatFromViewPortPx(e.xy);
		lonlat = lonlat.transform(map.getProjectionObject(), proj4326);
		
		markers.clearMarkers()
		var marker = new OpenLayers.Marker(lonlat_o);
        markers.addMarker(marker);
        
        $("#lon").val(lonlat.lon)
        $("#lat").val(lonlat.lat)
        
        ts.initDownLink();
        
        ts.expandDiv("ts");
    	ts.expandDiv("graph");
    	ts.foldDiv("graph_anom")
        ts.loadTS(lonlat.lon, lonlat.lat, {{sp_res}}, 
        		[{{range[0]}}, {{range[1]}}]);
	});
	
	ts.setVarSelect();
	ts.enableButtons({{max}}, {{max}});
	ts.initLegend();
	
	// LOAD IMAGE =============================================================
	function loadImg(date) {
		image.destroy();
        image = new OpenLayers.Layer.Image('IMAGE', '_rimg/{{region}}&{{source}}&{{variable}}&'+$('#slider').val(), bounds, new OpenLayers.Size(3400, 1600), {
            'isBaseLayer': false,
            'alwaysInRange': true,
            'opacity' : opacity
            });
        map.addLayer(image);
        markers.setZIndex(1001);
        image.setZIndex(1000);
        ts.initLegend();
	}
	
	// SLIDER =================================================================
	var values = [0, {{max}}];
	$("#slider").slider({
		formater: function(value) {
			$("#dateSelect").prop("selectedIndex", value);
			return $("#dateSelect option[value='"+$("#dateSelect").val()+"']").text();
		},
		min: values[0],
		max: values[1],
		value: values[1]
	}).on('slideStop',
		  function(ev){
		      val = $('#slider').val();
		      loadImg(val);
		      ts.enableButtons(val, {{max}});
		  }
	);
	
	// CONTROLLERS ============================================================
	$("#btn-prev").click(function(){
		val = parseInt($('#dateSelect').val())-1;
		$('#slider').val(val);
		$('#slider').slider({value:val});
		$("#dateSelect").prop("selectedIndex", val); 
		loadImg($('#slider').val());
		ts.enableButtons(val, {{max}});
        ts.sliderPos(val);
	});
	
	$("#btn-next").click(function(){
        val = parseInt($('#dateSelect').val())+1;
        $('#slider').val(val);
        $('#slider').slider({value:val});
        $("#dateSelect").prop("selectedIndex", val);
        loadImg($('#slider').val());
        ts.enableButtons(val, {{max}});
        ts.sliderPos(val);
    });
	
	$("#dateSelect").change(function() {
		val = $("#dateSelect").val();
		$('#slider').val(val);
        $('#slider').slider({value:val});
        loadImg($('#slider').val());
		ts.enableButtons(val, {{max}});
		ts.sliderPos(val);
	});
	
    $("#region").change(function() {
    	ts.setVarSelect();
        ts.initLink(path);
        ts.enableGo();
    });
    
    $("#dataset").change(function() {
        ts.initLink(path);
        ts.enableGo();
    });
    
    $("#anom").click(function() {
        ts.expandDiv('graph_anom');
        lon = $("#lon").val()
        lat = $("#lat").val()
        ts.loadTS(lon, lat, {{sp_res}}, {{ range }}, true);
        ts.initDownLink(true);
    });
	
});
</script>

<input type="hidden" id="variable" value="{{variable}}" />
<div class="row">
	<div class="panel panel-default">
	  <div class="panel-heading">
	    <form class="form-inline" role="form">
	        <div class="form-group">
	            <label class="sr-only" for="region">Regions</label>
	            <select class="form-control" id="region">
	                <option value=''>REGION</option>
                        {% for reg in regions %}
                            {% set checked = '' %}
                            {% if reg['code'] == region %}
                                {% set checked = 'selected="selected"' %}
                            {% endif %}
                            <option value="{{ reg['code'] }}" {{ checked }}>{{ reg['name'] }}</option>
	                    {% endfor %}
	            </select>
	        </div>
	        <div class="form-group">
	            <label class="sr-only" for="dataset">Datasets</label>
	            <select class="form-control" id="dataset">
	                <option value=''>DATASET</option>
	            </select>
	        </div>
	        <a href='' class='btn btn-primary' id="go">
	           <span class="glyphicon glyphicon-chevron-right"></span> GO
	        </a>
	        <input id="source" type="hidden" value="{{ source }}" />
	        <input id="lon" type="hidden" />
	        <input id="lat" type="hidden" />
	    </form>
	  </div>
	  
	  <div class="panel-body" style="position:relative; padding:0px;">
	    <div id='map' style="height:z-index:0;"></div>
	    <div style="position: absolute; bottom: 17px; left:0px; right:0px; z-index:9999;">
            <img id='legend' src='' style="width: 100%; max-width: 400px; height: auto;"/>
        </div>
	  </div>
	  
		<div class="panel-footer" align="center">
			<div class="hidden-xs">
			 	<input type="text" style="width:100%;" id="slider">
			 </div>
			 <div class="row">
			    <form class="form-inline" style="margin-top:8px;">
			    	<div class="col-xs-4 col-md-5" style="padding:0px" align='right'>
				    	<button type="button" class="btn btn-default" id="btn-prev">
				           <span class="glyphicon glyphicon-chevron-left"></span>
				        </button>
				    </div>
				    <div class="col-xs-4 col-md-2" style="padding:0px 5px">
				        <select id="dateSelect" class="form-control">
				            {% for dat in dates %}
				                <option value="{{ dat['id'] }}">{{ dat['date'] }}</option>
				            {% endfor %}
				        </select>
				    </div>
				    <div class="col-xs-4 col-md-5" style="padding:0px" align='left'>
				        <button type="button" class="btn btn-default" id="btn-next">
			          		<span class="glyphicon glyphicon-chevron-right"></span>
			         	</button>
			        </div>
			    </form>
			 </div>
		</div>
	</div>
</div>

<div class="row" id="ts" style="visibility:hidden; height:0px; overflow: hidden;">
	<div class="panel panel-default" id="graph" style="visibility:hidden; height:0px;">
		<div class="panel-body">
			<div id="graph_body" style="height:250px; max-height:250px; min-height:100px;"></div>
		</div>
		<div class="panel-footer">
		   <div class="row">
		       <div class="col-md-6" id="graph_footer"></div>
		       <div class="col-md-6" align="right">
		           <button class='btn btn-default' id="anom">calc anomalies</button>
		           <a href='' class='btn btn-default' id="download">
		               <span class="glyphicon glyphicon-download-alt"></span> download
		           </a>
		       </div>
		   </div>
		</div>
	</div>
	
	<div class="panel panel-default" id="graph_anom" style="visibility:hidden; height:0px;">
	    <div class="panel-body">
	        <div id="graph_anom_body" style="height:250px; max-height:250px; min-height:100px;"></div>
	    </div>
	    <div class="panel-footer">
	       <div class="row">
	           <div class="col-md-6" id="graph_anom_footer"></div>
	           <div class="col-md-6" align="right">
	               <a href='' class='btn btn-default' id="download_anom">
	                   <span class="glyphicon glyphicon-download-alt"></span> download
	               </a>
	           </div>
	       </div>
	    </div>
	</div>
</div>

{% endblock %}
