// 
// OpenLayers configuration parameters
//
OpenLayers.DOTS_PER_INCH              = 90.71428571428572;
OpenLayers.Util.onImageLoadErrorColor = 'transparent';
 
//
// Global variables
//
var selectCtrl;
var selectedFeature;
var selectedCut;                    // to store selected cut area (AMSR)
var n1features = new Array();			  // to store feature attributes
var cutfeatures = new Array();		  // to store cut attributes
var hash1 = new Array();						// to access feature.id via feature number
var hash2 = new Object();						// to access feature number via feature id
var lyrN1footprint;
var lyrCuts;
var aoi_layer;
var aoi_layer_style;
var temp_layer;
var map;
var maxResultCount = 200;           // this value has to be set in mapqueryresult1/2.php as well
var ctrlPanel;                      // custom OL control panel for displaying legend button
var popupLegend;                    // popup object for showing ice chart legend
var panelID=0;                      // stores ID of currently selected panel 

//
// start code here - everything inside the jQuery document.ready function
//
$(document).ready(function() {
	
	
	$('#tabs-map').tabs();                                 // initialize tabs (jQuery-UI)
	$('#tabs-links_AHR').tabs();                           // initialize tabs (jQuery-UI) - download links of AHR tab
  $('#tabs-links_SIC').tabs();                           // initialize tabs (jQuery-UI) - download links of SIC tab
  $('#tabs-links_ICH').tabs();                           // initialize tabs (jQuery-UI) - download links of ICH tab
  $('#tabs-links_NIC').tabs();                           // initialize tabs (jQuery-UI) - download links of NIC tab   
  $('#tabs-list').css('display', 'block');               // display content area  
  $('#seaiceconcentrationTab').css('display', 'block');  // display content area of tab: sea ice concentration
  $('#icechartTab').css('display', 'block');             // display content area of tab: ice chart   
  $('#icechartNICTab').css('display', 'block');          // display content area of tab: ice chart NIC 


  // ---------------------------------------------------------------------------
  // Initializing map object and adding all static layers
	// ---------------------------------------------------------------------------
	function init_map() {
		
		// Initialize map object		 
		var extent = new OpenLayers.Bounds(-5000000, -5000000, 5000000, 5000000);
    map = new OpenLayers.Map('mapdiv_AHR', 
     {projection: "EPSG:3031",
     	units: 'm',
//      displayProjection: new OpenLayers.Projection("EPSG:4326"),  
      minScale:      40000000,
      maxScale:      5000000,
      units:         "m", 
      scales:        [40000000, 20000000, 10000000, 5000000],
      numZoomLevels: 4,
      maxExtent: new OpenLayers.Bounds(-5000000, -5000000, 5000000, 5000000),
      restrictedExtent: extent, 
      controls: [
                  new OpenLayers.Control.PanZoom(),
                  new OpenLayers.Control.LayerSwitcher({'ascending':true}),
	                new OpenLayers.Control.Scale(),
	                new OpenLayers.Control.Navigation(),	                
	                new OpenLayers.Control.MousePosition({
	               	  prefix:"Long: ",
	               	  separator:", Lat: ",
	               	  displayProjection: new OpenLayers.Projection('EPSG:4326'), 
	               	  numDigits: 2	               	  
	               	})	                          
	              ]
	  });	  

    // Initialize layer: coastline - GeoServer direct
//    var lyrCstline = new OpenLayers.Layer.WMS(
//      "Antarctic Coastline",
//      "http://geos.polarview.aq/geoserver/wms",
//      {
//        layers:      'polarview:coastS10',        
//        transparent: true
//      } 
//    );
//    lyrCstline.isBaseLayer=true;       
//    lyrCstline.transitionEffect="resize";
//    lyrCstline.displayInLayerSwitcher=false;
    
    // Initialize layer: coastline  - GEOWEBCACHE
    var lyrCstline = new OpenLayers.Layer.WMS(
      "Antarctic Coastline",
      "http://geos.polarview.aq/geowebcache/service/wms",
      {
        layers:      'gwcPolarviewCoastS10',        
        format:      'image/png',
        transparent: true
      },
      {tileSize: new OpenLayers.Size(200,200)}
    ); 
    lyrCstline.isBaseLayer=true;       
    lyrCstline.transitionEffect="resize";
    lyrCstline.displayInLayerSwitcher=false;



    // Initialize layer: second coastline + graticule - GEOWEBCACHE
    var lyrCstlineGrid = new OpenLayers.Layer.WMS(
      "Coastline & Graticule",  
      "http://geos.polarview.aq/geowebcache/service/wms", 
      {
        layers:      'gwcPolarviewCoastS10Grat',       
        format:      'image/png',  
        transparent: true
      },
      {tileSize: new OpenLayers.Size(200,200)} 
    );
    lyrCstlineGrid.isBaseLayer=false;
    lyrCstlineGrid.setVisibility(true);  
    lyrCstlineGrid.displayInLayerSwitcher=false;
 
//    var lyrCstlineGrid = new OpenLayers.Layer.WMS(
//      "Coastline & Graticule",  
//      "http://geos.polarview.aq/geoserver/wms",
//      {
//        layers:      'PolarviewCoastS10Grat',       
//        format:      'image/png',  
//        transparent: true      }    
//    );
//    lyrCstlineGrid.isBaseLayer=false;
//    lyrCstlineGrid.setVisibility(true);  
//    lyrCstlineGrid.displayInLayerSwitcher=false; 


    
    // Initialize layer:  AMSR-E sea ice edge (15%)
    var lyrAMSREedge = new OpenLayers.Layer.WMS(
      "Sea ice edge (15%)",
      "http://geos.polarview.aq/geoserver/wms",
      {
        layers:      'polarview:iceedgeS15',                
        transparent: true        
      }
    );
    lyrAMSREedge.isBaseLayer=false;
    lyrAMSREedge.setVisibility(true);

    // Initialize layer: AMSR-E jpg image Bremen University
    var lyrAMSRE = new OpenLayers.Layer.Image(
      "AMSR-E Sea Ice Concentration",
      "http://www.polarview.aq/images/20_AMSRE/antarctic_AMSRE.3031.jpg",
     new OpenLayers.Bounds(-3958720, -3964989, 3964989, 4359921),
     new OpenLayers.Size(1264, 1328),
      {
        transparent: true
      }
    );
    lyrAMSRE.isBaseLayer=false;
    lyrAMSRE.setVisibility(false);

    // Initialize layer: DTU AMSR-E jpg image
    var lyrAMSR = new OpenLayers.Layer.Image(
      "AMSR Sea Ice Concentration (DTU)",
      "http://www.polarview.aq/images/30_DTU_AMSRE/latest/antarctic.WSM.jpg",
      new OpenLayers.Bounds(-3968146, -3986048, 3975853, 4368952),
      new OpenLayers.Size(2648, 2785),
      {
        transparent: true
      }
    );
    lyrAMSR.isBaseLayer=false;
    lyrAMSR.setVisibility(false);

    // Initialize layer: NASA Modis mosaic
    var lyrMODIS = new OpenLayers.Layer.Image(
      "MODIS Mosaic (yesterday)",
      "http://www.polarview.aq/images/21_MODIS/Antarctica.yesterday.terra.4km.jpg",
      new OpenLayers.Bounds(-3072125, -3071875, 3071875, 3072125),
      new OpenLayers.Size(1536, 1536),
      {
        transparent: true
      }
    );
    lyrMODIS.isBaseLayer=false;
    lyrMODIS.setVisibility(false);

    // Initialize layer: met.no sea ice chart as WMS
    var lyrIcechart = new OpenLayers.Layer.WMS(
      "Ice chart (met.no)",
      "http://geos.polarview.aq/geoserver/wms",
      {
        layers:      'iceChartWithLandMask',                
        transparent: true          
      }
    );
    lyrIcechart.isBaseLayer=false;
    lyrIcechart.setVisibility(false);

    // Initialize layer: NIC ice chart as WMS
    var lyrIcechartNIC = new OpenLayers.Layer.WMS(
      "Ice chart (NIC)",
      "http://geos.polarview.aq/geoserver/wms",
      {
        layers:      'polarview:antarctic_icechart_nic',                
        transparent: true          
      }
    );
    lyrIcechartNIC.isBaseLayer=false;
    lyrIcechartNIC.setVisibility(false);
      

    // Add layers to map
    map.addLayers([lyrAMSRE, lyrAMSR, lyrMODIS, lyrCstline,  lyrIcechart, lyrIcechartNIC, lyrAMSREedge, lyrCstlineGrid]);         
  }


  // ---------------------------------------------------------------------------
  // function displays popup triggered by custom OL control showing legend for icechart
	// ---------------------------------------------------------------------------
  function showLegend() {   	
  	if (popupLegend) {
  		//remove popup
  		map.removePopup(popupLegend); 
  		popupLegend = null;
    } else {  
    	// create popoup
    	if (panelID == 3) {  // ice chart NIC legend
    		popupLegend = new OpenLayers.Popup.AnchoredBubble( 
     	    "popupLegend", 
          map.getLonLatFromPixel(new OpenLayers.Pixel( 640, 2)),
          new OpenLayers.Size(200, 159),         
          "<img id='legend_icechartNIC' alt='Legend ice chart image' src='./images/resources/legend_icechartNIC.png'/>", 
          null,
          true
        );
      }
    	if (panelID == 2) {   // ice chart met.no legend
    	  popupLegend = new OpenLayers.Popup.AnchoredBubble( 
     	    "popupLegend", 
          map.getLonLatFromPixel(new OpenLayers.Pixel( 640, 2)),
          new OpenLayers.Size(200, 159),         
          "<img id='legend_icechart' alt='Legend ice chart image' src='./images/resources/legend_icechart.png'/>",
          null,
          true
        );   
      } 
      popupLegend.closeOnMove = true;
      popupLegend.setBackgroundColor("#222222");
      popupLegend.setOpacity(.8);
      popupLegend.setBorder("2px solid");   
      map.addPopup(popupLegend);
    }
  }


	// ---------------------------------------------------------------------------
	// Workaround for IE when resizing browser window
	// ---------------------------------------------------------------------------	
	function Reload() {	  
    if($.browser.msie) {
      window.location.href = window.location.href;     /* workaround for IE position:relative bug - reload page on windowresize*/			
    }
  }
  
  
	// ---------------------------------------------------------------------------
	// initialize all events for website
	// ---------------------------------------------------------------------------
  function init_events() {
    $('#ddarea_AHR').change(ddFilterChange);	
    $('#ddtime_AHR').change(ddFilterChange);	
    $('#scrollleft_AHR').click(changeSelectionL);
    $('#scrollright_AHR').click(changeSelectionR);
    $('#scrollleft_AHR').mouseenter(highlightPrevOn);
    $('#scrollleft_AHR').mouseleave(highlightOff);
    $('#scrollright_AHR').mouseenter(highlightNextOn);
    $('#scrollright_AHR').mouseleave(highlightOff);
    window.onresize=Reload;  
    
    // Init event for switching changing maps tab - change visibility accordingly
    $('#tabs-map').bind('tabsshow', function(event, ui) {
      // Objects available in the function context:
      ui.tab     // anchor element of the selected (clicked) tab
      ui.panel   // element, that contains the selected/clicked tab contents
      ui.index   // zero-based index of the selected (clicked) tab                 
      var panelid=ui.panel.id;      
      if ( (panelid=="asarhighresTab" )  || (panelid=="seaiceconcentrationTab") || (panelid=="icechartTab")  || (panelid=="icechartTab")  || (panelid=="icechartNICTab" ) ) { 
        switch(ui.index) {
          case 0:          	
          	loadLayerState (0);
      	    map.render("mapdiv_AHR");
      	    panelID=0;
            break;
          case 1:          	
          	loadLayerState (1);
      	    map.render("mapdiv_SIC");      	
      	    panelID=1;
      	    break;
          case 2:            
          	loadLayerState (2);
      	    map.render("mapdiv_ICH");      	
      	    panelID=2;
      	    break;
          case 3:            
          	loadLayerState (3); 
      	    map.render("mapdiv_NIC");
      	    panelID=3;
      	    break;      	    
      	}        
      }            
    });  
  }

	// ---------------------------------------------------------------------------
	// Function loads and sets the visibility state of the map's layers
	// ---------------------------------------------------------------------------	
	function loadLayerState(tab) {
		
//console.log("LOAD LAYER - tab: " + tab); 

    switch(tab) {
    	case 0:  
		    for (i=0; i<map.layers.length; i++) {		  
	        if(map.layers[i].name=="AMSR-E Sea Ice Concentration")    {map.layers[i].setVisibility(false);}
	        if(map.layers[i].name=="N1-Subsets")                      {map.layers[i].setVisibility(true);}
	        if(map.layers[i].name=="AMSR cuts")                       {map.layers[i].setVisibility(false);}
	        if(map.layers[i].name=="Sea ice edge (15%)")              {map.layers[i].setVisibility(true);}
	        if(map.layers[i].name=="Antarctic Coastline")             {map.layers[i].setVisibility(true);}
	        if(map.layers[i].name=="Coastline & Graticule")           {map.layers[i].setVisibility(true);}
	        if(map.layers[i].name=="AMSR Sea Ice Concentration (DTU)"){map.layers[i].setVisibility(false);}
	        if(map.layers[i].name=="Ice chart (met.no)")              {map.layers[i].setVisibility(false);}     
	        if(map.layers[i].name=="Ice chart (NIC)")                 {map.layers[i].setVisibility(false);}     
		    }
		    if (lyrN1footprint) {lyrN1footprint.displayInLayerSwitcher=true;}      // in this view, DO display layer in layer switcher
		    if (ctrlPanel) {map.removeControl(ctrlPanel)};                         // remove ice chart legend button if shown
		    if (popupLegend) {                                                     // remove legend popup if still visible
		    	map.removePopup(popupLegend);
		    	popupLegend = null;
		    }
		    break; 
    	case 1:  
		    for (i=0; i<map.layers.length; i++) {		  
	        if(map.layers[i].name=="AMSR-E Sea Ice Concentration")    {map.layers[i].setVisibility(true);}
	        if(map.layers[i].name=="N1-Subsets")                      {map.layers[i].setVisibility(false);}
	        if(map.layers[i].name=="AMSR cuts")                       {map.layers[i].setVisibility(true);}
	        if(map.layers[i].name=="Sea ice edge (15%)")              {map.layers[i].setVisibility(true);}
	        if(map.layers[i].name=="Antarctic Coastline")             {map.layers[i].setVisibility(true);}
	        if(map.layers[i].name=="Coastline & Graticule")           {map.layers[i].setVisibility(true);}
	        if(map.layers[i].name=="AMSR Sea Ice Concentration (DTU)"){map.layers[i].setVisibility(false);}
	        if(map.layers[i].name=="Ice chart (met.no)")              {map.layers[i].setVisibility(false);}
	        if(map.layers[i].name=="Ice chart (NIC)")                 {map.layers[i].setVisibility(false);}
		    }
		    lyrN1footprint.displayInLayerSwitcher=false;                           // in this view, do NOT display layer in layer switcher
		    if (ctrlPanel) {map.removeControl(ctrlPanel)};                         // remove ice chart legend button if shown
		    if (popupLegend) {                                                     // remove legend popup if still visible
		    	map.removePopup(popupLegend);
		    	popupLegend = null;
		    } 
		    break;
    	case 2:  
		    for (i=0; i<map.layers.length; i++) {
	        if(map.layers[i].name=="AMSR-E Sea Ice Concentration")    {map.layers[i].setVisibility(false);}
	        if(map.layers[i].name=="N1-Subsets")                      {map.layers[i].setVisibility(false);}
	        if(map.layers[i].name=="AMSR cuts")                       {map.layers[i].setVisibility(false);}
	        if(map.layers[i].name=="Sea ice edge (15%)")              {map.layers[i].setVisibility(false);}
	        if(map.layers[i].name=="Antarctic Coastline")             {map.layers[i].setVisibility(true);}
	        if(map.layers[i].name=="Coastline & Graticule")           {map.layers[i].setVisibility(true);} 
	        if(map.layers[i].name=="AMSR Sea Ice Concentration (DTU)"){map.layers[i].setVisibility(false);}
	        if(map.layers[i].name=="Ice chart (met.no)")              {map.layers[i].setVisibility(true);}
	        if(map.layers[i].name=="Ice chart (NIC)")                 {map.layers[i].setVisibility(false);}
		    }
		    lyrN1footprint.displayInLayerSwitcher=false;      // in this view, do NOT display layer in layer switcher
		    
		    // add custom control for displaying ice chart legend 
		    var ctrlLegendButton = new OpenLayers.Control.Button({
          displayClass: "customLegendButton",
          trigger:      showLegend,
          title:        "Show ice chart legend"
        });
        ctrlPanel = new OpenLayers.Control.Panel({
	        defaultControl: ctrlLegendButton
        }); 
        ctrlPanel.addControls([ctrlLegendButton]);
		    map.addControl(ctrlPanel);
		    
		    break;
    	case 3:  
		    for (i=0; i<map.layers.length; i++) {
	        if(map.layers[i].name=="AMSR-E Sea Ice Concentration")    {map.layers[i].setVisibility(false);}
	        if(map.layers[i].name=="N1-Subsets")                      {map.layers[i].setVisibility(false);}
	        if(map.layers[i].name=="AMSR cuts")                       {map.layers[i].setVisibility(true);} 
	        if(map.layers[i].name=="Sea ice edge (15%)")              {map.layers[i].setVisibility(false);}
	        if(map.layers[i].name=="Antarctic Coastline")             {map.layers[i].setVisibility(true);}
	        if(map.layers[i].name=="Coastline & Graticule")           {map.layers[i].setVisibility(true);} 
	        if(map.layers[i].name=="AMSR Sea Ice Concentration (DTU)"){map.layers[i].setVisibility(false);}
	        if(map.layers[i].name=="Ice chart (met.no)")              {map.layers[i].setVisibility(false);}
	        if(map.layers[i].name=="Ice chart (NIC)")                 {map.layers[i].setVisibility(true);}
		    }
		    lyrN1footprint.displayInLayerSwitcher=false;      // in this view, do NOT display layer in layer switcher
		    
		    // add custom control for displaying ice chart legend 
		    var ctrlLegendButton = new OpenLayers.Control.Button({
          displayClass: "customLegendButton",
          trigger:      showLegend,
          title:        "Show ice chart legend"
        });
        ctrlPanel = new OpenLayers.Control.Panel({
	        defaultControl: ctrlLegendButton
        }); 
        ctrlPanel.addControls([ctrlLegendButton]);
		    map.addControl(ctrlPanel);
		    
		    break;
		}
	}	
	
	function highlightOn (dir) {
		if (selectedFeature != undefined) {
      var currentId = hash2[selectedFeature.id];
      var newId = currentId + dir;
      if ((newId < 0) || (newId >= hash1.length)) {
        // not possible! out of bounds
      } else {
        //check if next feature is visible in current ViewPort
        //get bounds of viewport first
        var ul = map.getLonLatFromPixel(new OpenLayers.Pixel(0, 0));
        var lr = map.getLonLatFromPixel(new OpenLayers.Pixel(map.getSize().w, map.getSize().h ));

        //now convert bounds to polygon 
        wktString = "POLYGON((" + ul.lon + " " + ul.lat + ", " + ul.lon + " " + lr.lat + ", " + lr.lon + " " + lr.lat + ", " + lr.lon + " " + ul.lat + ", " + ul.lon + " " + ul.lat + "))";
        var viewportFeature = new OpenLayers.Format.WKT().read(wktString);       

        //intersect with upcoming feature
        var endOfArray = false;
        var intersect = viewportFeature.geometry.intersects(lyrN1footprint.features[newId].geometry);
        while ( !endOfArray && !intersect ) {
          newId += dir;
          if ((newId < 0) || (newId >= lyrN1footprint.features.length)) {
          	endOfArray = true;
          } else {
          	intersect = viewportFeature.geometry.intersects(lyrN1footprint.features[newId].geometry);
          }
        }

        // only highlight next footprint if inside viewport
        if (!endOfArray) {
          var geomClone = new OpenLayers.Geometry();
          geomClone = lyrN1footprint.features[newId].geometry.clone()
          var newFeature = new OpenLayers.Feature.Vector(geomClone);    
          var tempLayerStyle = new OpenLayers.StyleMap({
            "default": new OpenLayers.Style({
              fillOpacity: 0.2,
              fillColor: "#999900",
              strokeColor: "#FFFF00",
              strokeWidth: 2
              })          
          });   
          temp_layer = new OpenLayers.Layer.Vector("temp", {styleMap: tempLayerStyle}); 
          temp_layer.addFeatures(newFeature);
          map.addLayer(temp_layer);        
        }
      }
	  }
  }	
	
  function highlightPrevOn () {
    highlightOn(-1);
  }
  
  function highlightNextOn () {
    highlightOn(1);
  }

  function highlightOff () {
    //alert("out");
    if (temp_layer != undefined) {
      temp_layer.destroyFeatures();      
      if (map.getLayersByName("temp").length > 0) {      	
        map.removeLayer(temp_layer);	
      }     	    
    }
  }

  function changeSelection(dir) {		
  	if (selectedFeature != undefined) {
      var currentId = hash2[selectedFeature.id];
      var newId = currentId + dir;
      if ((newId < 0) || (newId >= hash1.length)) {
        // not possible! out of bounds
      } else {
        //check if next feature is visible in current ViewPort
        //get bounds of viewport first
        var ul = map.getLonLatFromPixel(new OpenLayers.Pixel(0, 0));
        var lr = map.getLonLatFromPixel(new OpenLayers.Pixel(map.getSize().w, map.getSize().h ));

        //now convert bounds to polygon 
        wktString = "POLYGON((" + ul.lon + " " + ul.lat + ", " + ul.lon + " " + lr.lat + ", " + lr.lon + " " + lr.lat + ", " + lr.lon + " " + ul.lat + ", " + ul.lon + " " + ul.lat + "))";
        var viewportFeature = new OpenLayers.Format.WKT().read(wktString);       

        //intersect with upcoming feature
        var endOfArray = false;
// console.log("newId: "+newId);      
// console.log(lyrN1footprint.features.length);
// console.log(lyrN1footprint.features[0].id);


        var intersect = viewportFeature.geometry.intersects(lyrN1footprint.features[newId].geometry);
        while ( !endOfArray && !intersect ) {
          newId += dir;
          if ((newId < 0) || (newId >= lyrN1footprint.features.length)) {
          	endOfArray = true;
          } else {
          	intersect = viewportFeature.geometry.intersects(lyrN1footprint.features[newId].geometry);
          }
        }
        // only select new footprint if inside viewport
        if (!endOfArray) {
          selectCtrl.unselectAll();
          selectCtrl.select(lyrN1footprint.features[newId]);
        }
      }
    }
	}
	
	function changeSelectionL() {
	  changeSelection(-1);
	  highlightOff();
	  highlightOn(-1);
  }
	
	
	function changeSelectionR() {
	  changeSelection(1);
	  highlightOff();
	  highlightOn(1);
  }
	
		
  function zoomToAOI(filterArea) {
    // load AOI via AJAX 
 
    var request = OpenLayers.Request.GET({
      url: "http://www.polarview.aq/beta/mapqueryAOI.php?area="+filterArea,
      async: false
    });
//alert("AOI: " + request.responseText);
    var type = "wkt";
    var features = new OpenLayers.Format.WKT({
      'internalProjection': map.baseLayer.projection,
      'externalProjection': new OpenLayers.Projection("EPSG:3031")
    }).read(request.responseText);  
// console.log(request.responseText);      
    var bounds;
    if(features) {
      if(features.constructor != Array) {
        features = [features];
      }
      for(var i=0; i<features.length; ++i) {    	
        if (!bounds) {
          bounds = features[i].geometry.getBounds();
        } else {
          bounds.extend(features[i].geometry.getBounds());
        }
      }
      // check if aoi_layer exists already
      if (aoi_layer != undefined) {
      	aoi_layer.destroyFeatures();      	
      } else {      	
      	// set style for vector features      
        var aoiLayerStyle = new OpenLayers.StyleMap({
          "default": new OpenLayers.Style({
            fillOpacity: 0.08,
            fillColor: "#88AAEE",            // alternative: #88AAEE
            strokeColor: "#88AAEE",          // alternative: #88AAEE 
            strokeWidth: 0.5
          })          
        });   
        aoi_layer = new OpenLayers.Layer.Vector("AOIs", {styleMap: aoiLayerStyle});        
      }
      // add layer, if not existing already      
      if (map.getLayersByName("AOIs").length == 0) {      	 
      	map.addLayer(aoi_layer);
      }
      aoi_layer.addFeatures(features);   
//      map.zoomToExtent(bounds);
    } else {
    	// no aoi filter - zoom out completely and hide AOI layer
    	if (aoi_layer != undefined) {
      	aoi_layer.destroyFeatures();      
        if (map.getLayersByName("AOIs").length > 0) {      	 
        	map.removeLayer(aoi_layer);	
        }
      }
      // set zoom level to 0 (=1:40000000) and center map
      map.setCenter(new OpenLayers.LonLat(0, 0), 0); 
    }
  }

	        
  function onFeatureSelect(feature) {
    selectedFeature = feature;            
    var ssfilename = n1features[hash2[feature.id]].ssname;
    var ssacqtime = n1features[hash2[feature.id]].acqtime;
    var fs1 = n1features[hash2[feature.id]].fs1;
    var fs2 = n1features[hash2[feature.id]].fs2;
    var fs3 = n1features[hash2[feature.id]].fs3;
            
    //alert(ssacqtime);
    //$('#acqtime').html=ssacqtime;   // why not working?
            
    // change download links
    document.getElementById('acqtime').innerHTML=ssacqtime;
    document.getElementById('linkJPGlow').href='./images/92_jpgsmall/'+ssfilename+'.jpg';
    document.getElementById('linkJPGhigh').href='./images/91_jpgfull/'+ssfilename+'.final.jpg';
    document.getElementById('linkJPG2000').href='http://ias.polarview.aq:8080/viewer/webstart.jsp?file='+ssfilename+'.utm.jp2';
    document.getElementById('linkGeoTIFF').href='./images/89_geotiff/'+ssfilename+'.tar.gz';
            
    // change file sizes
    document.getElementById('fs1').innerHTML=fs1;
    document.getElementById('fs2').innerHTML=fs2;
    document.getElementById('fs3').innerHTML=fs3;
            
    //change preview image with transition effect and some time to preload it
    newimg = new Image();
    newimg.src = './images/93_pngthumbnaillarge/'+ssfilename+'.tn_large.png';    
    $('#previewimage_AHR').fadeOut(300, function () {
      $('#previewimage_AHR').attr('src', newimg.src);
      $('#previewimage_AHR').fadeIn(300);
    });
  }
  
  
  function onFeatureUnselect(feature) {
  }    

  // Event handler OnSelect of cut-area - layer AMSR
  function onCutSelect(feature) {
  
    //this case if sea ice concentration tab is active
    if (panelID == 1) {
      selectedCut = feature;
      //alert(ssacqtime);
      //$('#acqtime').html=ssacqtime;   // why not working?

      // change download links
      document.getElementById('sicdata').innerHTML=cutfeatures[selectedCut.attributes.id].amsredate;
      // document.getElementById('linkGIFselected').href='./images/30_DTU_AMSRE/latest/'+cutfeatures[selectedCut.attributes.id].shortname+'.gif';
      // document.getElementById('linkTIFselected').href='./images/30_DTU_AMSRE/latest/'+cutfeatures[selectedCut.attributes.id].shortname+'.tar.gz';
      // document.getElementById('linkGIFcontinent').href='./images/30_DTU_AMSRE/latest/antarctic.gif';
      // document.getElementById('linkTIFcontinent').href='./images/30_DTU_AMSRE/latest/antarctic.tar.gz';
      document.getElementById('linkGIFselected').href='./images/20_AMSRE/latest/'+cutfeatures[selectedCut.attributes.id].shortname+'.gif';
      document.getElementById('linkTIFselected').href='./images/20_AMSRE/latest/'+cutfeatures[selectedCut.attributes.id].shortname+'.tar.gz';
      document.getElementById('linkGIFcontinent').href='./images/20_AMSRE/latest/antarctic.gif';
      document.getElementById('linkTIFcontinent').href='./images/20_AMSRE/latest/antarctic.tar.gz';

      // change file sizes
      document.getElementById('fs1cut').innerHTML=cutfeatures[selectedCut.attributes.id].fs1;
      document.getElementById('fs2cut').innerHTML=cutfeatures[selectedCut.attributes.id].fs2;
      document.getElementById('fs3cut').innerHTML=cutfeatures[selectedCut.attributes.id].fs3;
      document.getElementById('fs4cut').innerHTML=cutfeatures[selectedCut.attributes.id].fs4;

      //change preview image with transition effect and some time to preload it
      newimg = new Image();
      // newimg.src = './images/30_DTU_AMSRE/latest/'+cutfeatures[selectedCut.attributes.id].shortname+'.jpg';
      newimg.src = './images/20_AMSRE/latest/'+cutfeatures[selectedCut.attributes.id].shortname+'.jpg';
      $('#previewimage_SIC').fadeOut(300, function () {
        $('#previewimage_SIC').attr('src', newimg.src);
        $('#previewimage_SIC').fadeIn(300);
      });
    }

    //this case if sea ice chart NIC tab is active
    if (panelID == 3) {
      selectedCut = feature;

      // change download links
      document.getElementById('linkNICJPG').href='./images/24_NICcharts/antarctic/current/'+cutfeatures[selectedCut.attributes.id].shortname+'.jpg';
      document.getElementById('linkNICTIF').href='./images/24_NICcharts/antarctic/current/'+cutfeatures[selectedCut.attributes.id].shortname+'.tif.tar.gz'; 

      // change file sizes
      document.getElementById('fsicechartNICJPG').innerHTML=cutfeatures[selectedCut.attributes.id].fsNIC1;
      document.getElementById('fsicechartNICTIF').innerHTML=cutfeatures[selectedCut.attributes.id].fsNIC2;  
      
      //change preview image with transition effect and some time to preload it
      newimg = new Image();
      newimg.src = './images/24_NICcharts/antarctic/current/'+cutfeatures[selectedCut.attributes.id].shortname+'.tn_large.jpg';
      $('#previewimage_NIC').fadeOut(300, function () {
        $('#previewimage_NIC').attr('src', newimg.src);
        $('#previewimage_NIC').fadeIn(300);
      });
    }   
  }
  
  
  function onCutUnselect(feature) {
  }    

  function handleResponseAOIFilter1() {	
    if(request1.readyState == 4){
      if(request1.status == 200) {
 //alert(request1.responseText);	      

        // generate JSON object out of http response 
        var func = new Function("return "+request1.responseText);      
        var objt = func();      
//alert("response1: " + request1.responseText);           
        document.getElementById('debug').innerHTML="Ob:"+objt.length;
        // destroy pre-existing vector elements or generate lyrN1footprint
        if (lyrN1footprint!=undefined) {        		
          lyrN1footprint.destroyFeatures();
        } else {          
          // set style for vector features      
          var vectorLayerStyle = new OpenLayers.StyleMap({
            "default": new OpenLayers.Style({
              fillOpacity: 0.2,
              fillColor: "#990000",            // alternative: #88AAEE
              strokeColor: "#990000",          // alternative: #88AAEE 
              strokeWidth: 1
            }),
            "temporary": new OpenLayers.Style({
              fillOpacity: 0.2,
              fillColor: "#999900",
              strokeColor: "#FFFF00",
              strokeWidth: 2
            }),
            "select": new OpenLayers.Style({
              fillOpacity: 0.4,
              fillColor: "#999900",
              strokeColor: "#FFFF00",
              strokeWidth: 3
            })
          });     
      
          lyrN1footprint = new OpenLayers.Layer.Vector("N1-Subsets", {styleMap: vectorLayerStyle});          
          map.addLayer(lyrN1footprint); 
          
          // make vector features selectable
          var highlightCtrl = new OpenLayers.Control.SelectFeature(lyrN1footprint, {
            hover: true,
            highlightOnly: true,
            renderIntent: "temporary",
            eventListeners: {}
          });

          selectCtrl = new OpenLayers.Control.SelectFeature(lyrN1footprint,
            {clickout: true, onSelect: onFeatureSelect, onUnselect: onFeatureUnselect}
          );

          map.addControl(highlightCtrl);
          map.addControl(selectCtrl);
          highlightCtrl.activate();
          selectCtrl.activate();               
        }
      
        var geojson_format = new OpenLayers.Format.GeoJSON();
        
        //empty hash            
        //while(hash1.length>0){hash1.pop();}
        hash1 = []
        hash2 = []
      
        // populate feature collection       
        //alert("Number of features in GeoJSON query: " + objt.length);
        if (objt.length > 0) {
          for (var inti=0; inti<objt.length; inti++) {     
          	if (inti < maxResultCount) {
              lyrN1footprint.addFeatures(geojson_format.read(objt[inti]));   
              hash1.push(lyrN1footprint.features[lyrN1footprint.features.length-1].id);
              hash2[lyrN1footprint.features[lyrN1footprint.features.length-1].id] = lyrN1footprint.features.length-1
            } else {            	
            	$("#errormsg").css('display', 'inline').fadeTo(3000, .99).fadeOut(1500);            	
            }
          }
        }       
		  }      	
 	  }
  }    
	
	
  function handleResponseAOIFilter2() {	
    if(request2.readyState == 4){
  	  if(request2.status == 200) {  	  
        // generate JSON object out of http response 
        var func2 = new Function("return "+request2.responseText);
        var objt2 = func2(); 
        document.getElementById('debug').innerHTML="Ob:"+objt2.length;
          
        //empty array
        n1features = [];        

        //fill array
        if (objt2.length > 0) {
          for (var inti2=0; inti2<objt2.length; inti2++) {
          	if (inti2 < maxResultCount) {
              n1features.push(objt2[inti2]);
            }
          }
        }
//        console.log("n1features: " + n1features.length);
      }      	
    }
  }    


  // 
  // onChange event handler for dd-lists "area" and "time"
  //
  function ddFilterChange() {
    //get filter values

    //var filterArea = document.getElementById("ddarea");
    //var filterTime = document.getElementById("ddtime");
    var filterArea;
    var filterTime;
    var o;
    var h;
    $('.areaoption').each(function(){
	    o=$(this).attr("selected");
	    h=$(this).html();
      //console.log(o + " / " + h);	
	  if (o) {filterArea=h;}
    });
    $('.timeoption').each(function(){
	    o=$(this).attr("selected");
	    h=$(this).html();
      //console.log(o + " / " + h);	
	    if (o) {filterTime=h;}
    });

    //zoom to AOI
    zoomToAOI(filterArea);

    // cast http request
    var _url1="http://www.polarview.aq/beta/mapqueryresult1.php?area=" + filterArea.replace(/ /g, "+") + "&time=" + filterTime.replace(/ /g, "+");
    httpRequest1("GET", _url1, true, handleResponseAOIFilter1);
  
    // cast http request for feature information
    var _url2="http://www.polarview.aq/beta/mapqueryresult2.php?area=" + filterArea.replace(/ /g, "+") + "&time=" + filterTime.replace(/ /g, "+");
    httpRequest2("GET", _url2, true, handleResponseAOIFilter2);
  }



  // Handle function for AJAX requesting AMSR cuts
  // Displays cut outlines as layer
  function handleResponseCuts1() {	
    if(request3.readyState == 4){
      if(request3.status == 200) {
        // generate JSON object out of http response 
        var func3 = new Function("return "+request3.responseText);            
        var objt3 = func3();      
        // destroy pre-existing vector elements or generate lyrN1footprint

        if (lyrCuts!=undefined) {        		        		
          lyrCuts.destroyFeatures();
        } else { 
          // set style for vector features      
          var vectorLayerStyleCuts = new OpenLayers.StyleMap({
            "default": new OpenLayers.Style({
              fillOpacity: 0.2,
              fillColor: "#5577DD",            // alternative: #88AAEE
              strokeColor: "#5577DD",          // alternative: #88AAEE 
              strokeWidth: 1
            }),
            "temporary": new OpenLayers.Style({
              fillOpacity: 0.2,
              fillColor: "#88AAEE",
              strokeColor: "#88AAEE",
              strokeWidth: 2
            }),
            "select": new OpenLayers.Style({
              fillOpacity: 0.4,
              fillColor: "#88AAEE",
              strokeColor: "#88AAEE",
              strokeWidth: 3
            })
          });           
          lyrCuts = new OpenLayers.Layer.Vector("AMSR cuts", {styleMap: vectorLayerStyleCuts});       
          map.addLayer(lyrCuts); 
          lyrCuts.setVisibility(false);
          lyrCuts.displayInLayerSwitcher=false; 

          // make vector features selectable
          var highlightCtrlCuts = new OpenLayers.Control.SelectFeature(lyrCuts, {
            hover: true,
            highlightOnly: true,
            renderIntent: "temporary",
            eventListeners: {}
          });

          selectCtrlCuts = new OpenLayers.Control.SelectFeature(lyrCuts,
            {clickout: true, onSelect: onCutSelect, onUnselect: onCutUnselect}
          );

          map.addControl(highlightCtrlCuts);
          map.addControl(selectCtrlCuts);
          highlightCtrlCuts.activate();
          selectCtrlCuts.activate();               
        }
      
        var geojson_format_cuts = new OpenLayers.Format.GeoJSON();
        
        // populate feature collection       
        if (objt3.length > 0) {
          for (var inti=0; inti<objt3.length; inti++) {     
          	if (inti < maxResultCount) {
          		a = geojson_format_cuts.read(objt3[inti]);
              a[0].attributes.id=inti;
              lyrCuts.addFeatures(a);                 
            } else {            	
            	$("#errormsg").css('display', 'inline').fadeTo(3000, .99).fadeOut(1500);            	
            }
          }
        }       
		  }      	
 	  }
  }    

  // Handle function for AJAX requesting AMSR cuts
  // Get attributes
  function handleResponseCuts2() {	
    if(request4.readyState == 4){
  	  if(request4.status == 200) {  	  
        // generate JSON object out of http response 
        var func4 = new Function("return "+request4.responseText);
        var objt4 = func4(); 
          
        //empty array
        cutfeatures = [];        

        //fill array
        if (objt4.length > 0) {
          for (var inti4=0; inti4<objt4.length; inti4++) {
          	if (inti4 < maxResultCount) {          		
              cutfeatures.push(objt4[inti4]);
            }
          }
        }
      }      	
    }  	
  }

  // Function initiates loading of AMSR-Cuts via AJAX  
  function loadAMSRCuts() {
    // cast http request - get geometry
    var url3="http://www.polarview.aq/beta/mapqueryCuts1.php";
    httpRequest3("GET", url3, true, handleResponseCuts1);
    // cast http request - get attributes
    var url4="http://www.polarview.aq/beta/mapqueryCuts2.php";
    httpRequest4("GET", url4, true, handleResponseCuts2);
  }
    
    
  function init_GE() {
    google.earth.createInstance("map3d", initCallback_GE, failureCallback_GE);  
  }
 
  function initCallback_GE(object) {
    ge = object;
    ge.getWindow().setVisibility(true);

    // set options
    var options = ge.getOptions();  
    options.setStatusBarVisibility(true);
    options.setScaleLegendVisibility(true);
    options.setAtmosphereVisibility(true);
    options.setMouseNavigationEnabled(true);  
    ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
  
    // set camera to Antarctica  
    var camera = ge.createLookAt('');
    camera.set(-70, 0,
      10000000, // altitude
      ge.ALTITUDE_RELATIVE_TO_GROUND,
      0, // heading
      -85, // straight-down tilt
      5000 // range (inverse of zoom)
    );
    ge.getView().setAbstractView(camera);
    
    // if the page loaded with checkboxes checked, load the appropriate KML files
    if (document.getElementById('n1fileslast1day').checked) loadKml('n1fileslast1day');
    if (document.getElementById('n1fileslast3days').checked) loadKml('n1fileslast3days');
    if (document.getElementById('seaiceedge15s').checked) loadKml('seaiceedge15s');
    if (document.getElementById('seaicecon').checked) loadKml('seaiceconcentration');
    if (document.getElementById('icechart').checked) loadKml('icechart');
    
    // the following lines account for Andrew's special KML layers not visible to the public
    if (document.getElementById('sst')) {
      if (document.getElementById('sst').checked) loadKml('sst');
    }
    if (document.getElementById('chla')) {
      if (document.getElementById('chla').checked) loadKml('chla');
    }
  }
 
  function failureCallback_GE(object) {
  }

  
  // 
  // Now start the scripts, depending which page is loaded
  //
  var filename = document.location.href;
  if (filename.indexOf('mapview.php') != -1) {    
	  init_events();	
	  init_map();	
	  ddFilterChange();
	  loadAMSRCuts(); 	  
	  loadLayerState(0);          // load default state of Layers in map tab 0 (=ASAR High-Res)
	}

  if (filename.indexOf('data_googleearth.php') != -1) {        
    init_GE();
	}
	
  if (filename.indexOf('data_googleearth_plus.php') != -1) {        
    init_GE();
	}

});

