/*
**********************************************************
N.W. TREND ANALYSIS OF TEMPERATURE, PRECIP, & SWE

Google Maps Javascript

Josiah Mault
Office of the Washington State Climatologist
**********************************************************
*/

var centerLat = 46.17983;
var centerLong = -118.312012;
var startZoom = 6;
var startMapType = G_PHYSICAL_MAP; //G_HYBRID_MAP;

var tooltip;
var map;
var baseIcon;
var markers;
var xmlhttp;

function changeBodyClass(from, to) {
document.body.className = document.body.className.replace(from, to);
document.getElementById('loadingAlert').innerHTML = '<p><img src="../GMapfiles/loading.gif"><br><br><b>Loading...<b></p>';
return false;
}

function setAlertText(str) {
document.getElementById('loadingAlert').innerHTML = '<p>' + str + '</p>';
}

function init() {
  
  changeBodyClass('standby', 'loading');
  
  var d = document.getElementById('dataType');
  var sYR = document.getElementById('startYR');
  var eYR = document.getElementById('endYR');
  var p = document.getElementById('period');
  var dev = document.getElementById('stdDeviation').checked;
  var stavg = document.getElementById('stateAvg').checked;
  var trendLine = document.getElementById('trendLine').checked;
  var size = document.mapOptions.size[0].checked;
  
  var mapDataUrl = 'map_data.php?d=' + d.value + '&sYR=' + sYR.value + '&eYR=' + eYR.value + '&p=' + p.value + '&dev=' + dev + '&stavg=' + stavg + '&trend=' + trendLine + '&size=' + size;
  
  //Set the title for the map
  document.getElementById('mapTitle').innerHTML = mapTitle(sYR.value,eYR.value,d.value);
  
 xmlhttp = GXmlHttp.create();
    xmlhttp.open('GET', mapDataUrl, true);
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
            if (xmlhttp.status != 200) {
                setAlertText('Could not access map data.<br>Please contact <a mailto:climate@atmos.washington.edu>climate@atmos.washington.edu</a>');
            } else {
                var responseText = xmlhttp.responseText;
                markers = eval(responseText);
                if (!markers) {
                    setAlertText('Map data error.<br>Please contact <a mailto:climate@atmos.washington.edu>climate@atmos.washington.edu</a>');
                } else if (markers == ''){
                  setAlertText('No data available! Please select a different period. NOTE: SWE only available for Jan, Feb, Mar, Apr, & May.');
				} else {
                    initData();
                }
            }
        }
    }
    xmlhttp.send(null);
 }

function initData(){
	if (GBrowserIsCompatible()) {
	  	map = new GMap2(document.getElementById("map"));
		map.addControl(new GLargeMapControl(),new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 90)));
		map.addMapType(G_PHYSICAL_MAP);
		map.addControl(new GMapTypeControl());
		map.addControl(new GScaleControl());
		map.addControl(new GOverviewMapControl(new GSize(150,150)));
		map.setCenter(new GLatLng(centerLat,centerLong), startZoom, startMapType);
		
		//add custom controls to map
		map.addControl(new CustomControl(),new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(27, 14)));
		
		//tooltip
		tooltip = document.createElement("div");
		map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
		tooltip.style.visibility="hidden";
		
		// Create a base icon for all of our markers that specifies the
		// shadow, icon dimensions, etc.
		baseIcon = new GIcon();
		baseIcon.iconSize = new GSize(35, 35);
		baseIcon.iconAnchor = new GPoint(17.5, 17.5);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);

		for(id in markers){
		createMarker(markers[id].latitude, markers[id].longitude, markers[id].IconImage, markers[id].url, markers[id].name);
}
		  
		  //Click event handler (on map object) for zoom box
      GEvent.addListener(map, 'click', function(zoomboxOverlay, boxpoint){
        if (!isClickZoom) return;
        if (zoomboxOverlay) return; //zoomboxOverlay was clicked, do nothing user must click once more time
            
        //click event has been raised for box operation
        //Check if it is 1st or 2nd click (begin or end of box zoom operation)
          
        if (!drawSatus){
          //It's 1st click
          //store mousedown point coordinates into iniPoint
          iniPoint = boxpoint;
          
          //Set drawstatus to true
          drawSatus = true;
        }
        else{
          //It's 2nd click
          //Don't set isClickZoom to false into this event, because it occurs 
              //before selectrect click event, do it into this one
          drawSatus = false;
            
          //Get correct SW and NE points coordinates
          if (iniPoint.lat()>boxpoint.lat()){
            if (iniPoint.lng()<boxpoint.lng()){
              var geoSW = new GLatLng(boxpoint.lat(),iniPoint.lng(),false);
              var geoNE = new GLatLng(iniPoint.lat(),boxpoint.lng(),false);
            }
            else{
              var geoSW = new GLatLng(boxpoint.lat(),boxpoint.lng(),false);
              var geoNE = new GLatLng(iniPoint.lat(),iniPoint.lng(),false);
            }   
          }
          else{
            if (iniPoint.lng()<boxpoint.lng()){
              var geoSW = new GLatLng(iniPoint.lat(),iniPoint.lng(),false);
              var geoNE = new GLatLng(boxpoint.lat(),boxpoint.lng(),false);
            }
            else{
              var geoSW = new GLatLng(iniPoint.lat(),boxpoint.lng(),false);
              var geoNE = new GLatLng(boxpoint.lat(),iniPoint.lng(),false);
            }    
          }
    
          //define LatLngBound             
          var geoRectBounds = new GLatLngBounds(geoSW,geoNE);
            
          //Define new center
          var newCenter = new GLatLng(((geoRectBounds.getSouthWest()).lat()+(geoRectBounds.getNorthEast()).lat())/2,
                ((geoRectBounds.getSouthWest()).lng()+(geoRectBounds.getNorthEast()).lng())/2 ,false );
            
          //zoom map
          var newZoom = map.getBoundsZoomLevel(geoRectBounds);
          map.setCenter(newCenter,newZoom);
        }
    	});
    	
    	changeBodyClass('loading', 'standby');

}

// display a warning if the browser was not compatible
    else {
      document.getElementById('loadingAlert').innerHTML = '<p>Sorry, Google Maps is not compatible with your current browser settings. <a href="http://local.google.com/support/bin/answer.py?answer=16532&topic=1499">More information.</a></p>';
	  //alert("Sorry, Google Maps is not compatible with your current browser settings, javascript must be enabled!");
    }
}

//function containing custom controls/buttons
function CustomControl() {
}
CustomControl.prototype = new GControl();

// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.
CustomControl.prototype.initialize = function(map) {
  var container = document.createElement("div");
  
  //Add Reference Point Control/button
  var refptDiv = document.createElement("div");
  var refptDivBtn = document.createElement("img");
  container.appendChild(refptDiv);
  container.appendChild(refptDivBtn);
  refptDivBtn.setAttribute("title","Plot Reference Point");
  refptDivBtn.style.cursor="pointer";
  refptDivBtn.style.marginBottom="3px";
  refptDivBtn.src = "../GMapfiles/pin.png";
  GEvent.addDomListener(refptDivBtn, "click", function() {
    var theHandle = document.getElementById("handleRefPt"); //this & next 3 lines for movable Search div
	var theRoot   = document.getElementById("rootRefPt"); //called from dom-drag.js
	Drag.init(theHandle, theRoot);
    toggleLayer('rootRefPt');
  });
  
  map.getContainer().appendChild(container);

  //Legend Control/button
  var legendDiv = document.createElement("div");
  var legendDivBtn = document.createElement("img");
  container.appendChild(legendDiv);
  container.appendChild(legendDivBtn);
  legendDivBtn.setAttribute("title","Legend");
  legendDivBtn.style.cursor="pointer";
  legendDivBtn.style.marginBottom="3px";
  legendDivBtn.src = "../GMapfiles/legend.png";
  GEvent.addDomListener(legendDivBtn, "click", function() {
    var theHandle = document.getElementById("handleLegend"); //this & next 3 lines for movable Legend div
	var theRoot   = document.getElementById("rootLegend"); //called from dom-drag.js
	Drag.init(theHandle, theRoot);
    toggleLayer('rootLegend');
  });
  
  map.getContainer().appendChild(container);
  
  //Box Zoom Control/Button
      var boxzoomDiv = document.createElement("div");
      var boxzoomBtn = document.createElement("img");
      container.appendChild(boxzoomDiv);
      container.appendChild(boxzoomBtn);
      boxzoomBtn.setAttribute("title","Box Zoom");
      boxzoomBtn.style.cursor="pointer";
      boxzoomBtn.style.marginBottom="3px";
      boxzoomBtn.src = "../GMapfiles/zoombox.png";
      //When clicking the button, it will activate Box Zoom function
      GEvent.addDomListener(boxzoomBtn, "click", function(){
        boxzoomHandler(map);
      });

  map.getContainer().appendChild(container);
  return container;
}
//************ END CONTROL CODE ***********


// *********** START of function which displays the tooltip ************
function showTooltip(marker) {		
      	tooltip.innerHTML = marker.tooltip;
	var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
	var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
	var anchor=marker.getIcon().iconAnchor;
	var width=marker.getIcon().iconSize.width;
	var height=tooltip.clientHeight;
	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y -height)); 
	pos.apply(tooltip);
	tooltip.style.visibility="visible";
	// Code From PdMarkers www.pixeldevelopment.com/pdmarker.asp
	// for tooltip opacity
    var b = 90;
	var c = b / 100;
	if (tooltip)
	{
		if(typeof(tooltip.style.filter)=='string'){tooltip.style.filter='alpha(opacity:'+b+')';}
		if(typeof(tooltip.style.KHTMLOpacity)=='string'){tooltip.style.KHTMLOpacity=c;}
		if(typeof(tooltip.style.MozOpacity)=='string'){tooltip.style.MozOpacity=c;}
		if(typeof(tooltip.style.opacity)=='string'){tooltip.style.opacity=c;}
	}
	// end of PdMarkers code 
      }

//********** END OF TOOLTIP FUNTION CODE ***********

// info window content
// A function to create a marker";
function createMarker(latitude, longitude, IconImage, url, name) {
    var point = new GLatLng(latitude,longitude);
	var icon = new GIcon(baseIcon, IconImage);
	var marker = new GMarker(point, icon);
// store the name so that the tooltip function can use it
        marker.tooltip = '<div class="tooltip">'+name+'</div>';
		GEvent.addListener(marker, "click", function() {
		window.open(url,'graph','width=650,height=465,scrollbars=no,location=no,resizable=yes');
		}); 
		map.addOverlay(marker);

// Marker "mouseover" and "mouseout" listeners for tooltip
        GEvent.addListener(marker,"mouseover", function() {
          showTooltip(marker);
        });        
        GEvent.addListener(marker,"mouseout", function() {
		tooltip.style.visibility="hidden"
        });        
return marker;
}

//the following is for the title based on map parameters
function mapTitle(sYR,eYR,datatype) {
  var datatypetitle;

	if (datatype == 'USHCN_UmeanT') {
  		datatypetitle = 'Mean Temperature';
	} else if (datatype == 'USHCN_UmaxT') {
		datatypetitle = 'Max. Temperature';
	} else if (datatype == 'USHCN_UminT') {
  		datatypetitle = 'Min. Temperature';
	} else if (datatype == 'USHCN_precip') {
  		datatypetitle = 'Precipitation';
	} else if (datatype == 'USHCN_swe') {
  		datatypetitle = 'Snow Water Equivalent (SWE)';}
return datatypetitle + ' Trend Analysis ' + sYR + '-' + eYR;
}

window.onload = init;
window.onunload = GUnload;