/*
**********************************************************
N.W. TREND ANALYSIS OF TEMPERATURE, PRECIP, & SWE

Google Maps Javascript

Josiah Mault
Office of the Washington State Climatologist
**********************************************************
*/

var centerLat = 46.792538;
var centerLong = -123.030396;
var startZoom = 8;
var startMapType = G_PHYSICAL_MAP;

var tooltip;
var map;
var baseIcon;
var markers;
var xmlhttp;
var newCenter = null;

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('day');

  var mapDataUrl = 'map_data.php?d=' + d.value;
  
  //Set the title for the map
  
document.getElementById('mapTitle').innerHTML = mapTitle(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 GHierarchicalMapTypeControl());
		map.addControl(new GScaleControl());
		map.addControl(new GOverviewMapControl(new GSize(100,100)));
		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)));
		
		/* first set of options is for the visual overlay.*/
        var boxStyleOpts = {
          opacity: .2,
          border: "1px dashed red"
        }

        /* second set of options is for everything else */
        var otherOpts = {
          buttonHTML: "<img src='../../GMapfiles/zoombox.png' alt='Drag Zoom'/>",
          buttonZoomingHTML: "<img src='../../GMapfiles/zoombox-activated.png' />",
          overlayRemoveTime: 1000,
          buttonStartingStyle: {width: '18px', height: '18px'}
		};
  
        map.addControl(new DragZoomControl(boxStyleOpts, otherOpts),new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(27,33)));

		//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(65, 15);
		baseIcon.iconAnchor = new GPoint(32.5, 7.5);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);


		for(id in markers){
		createMarker(markers[id].latitude, markers[id].longitude, markers[id].IconImage, markers[id].name);
	}
    	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 refreshMap() {
  changeBodyClass('standby', 'loading');
  
  var center = map.getCenter();
  centerLat = center.lat();
  centerLong = center.lng();
  startZoom = map.getZoom();
  startMapType = map.getCurrentMapType();

  init();
}
//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, 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(day) {
  var datatypetitle;

	if (day == 1) {
  		datatypetitle = 'Precipitation Totals for December 1, 2007';
	} else if (day == 2) {
		datatypetitle = 'Precipitation Totals for December 2, 2007';
	} else if (day == 3) {
		datatypetitle = 'Precipitation Totals for December 3, 2007';
	} else if (day == 4) {
		datatypetitle = 'Precipitation Totals for December 4, 2007';
	} else if (day == 'total') {
		datatypetitle = 'Precipitation Totals for December 1-4, 2007';
	}
return datatypetitle;
}

window.onload = init;
window.onunload = GUnload;