		/**
		 * Name: radar.js
		 * Description: This javascript will place the translucent radar image over the corresponding geographic region using
		 * Google(c) map's API.
		 * 
		 *
		 * Note: some of this code, especially the rescaling method, is a derivative of Eric Meyer's excellent 
		 * HYDESim application(http://meyerweb.com/eric/tools/gmap/hydesim.html).
         *
         *
		 * @author Byron Wallace
		 * CASA (http://casa.umass.edu)
		 */

function showMap() {

		// -- Globals
		// Internet Explorer?
		var isIE = navigator.appName == 'Microsoft Internet Explorer' ? 1 : 0;

		// Width of map.
		var mapwidth = 600;

		// Radius in miles. (~25 km).
 		var radius = 15.5342798;
		// this variable holds a radius specified by the user via form input.
		var userRadius = 0;

		// The Google(c) map object.
		var map = new GMap(document.getElementById("map"));

		// Add controls.
		map.addControl(new GScaleControl());
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());

		// Radar coordinates.
		var centerOfRadar = new GPoint(-72.5172958, 42.3916550);

		// Center map over Amherst.
		map.centerAndZoom(centerOfRadar, 7);

		// Path to the radar image of the current velocity map. 
		// It is assumed (though not required) that this
		// image is being updated independently by some other script.
	    var currentVelocityImgURL = "http://gaia.cs.umass.edu/MA1/currentvel.png";
		// Path to the current radar image of the reflection map.
		var currentReflectionImgURL = "http://gaia.cs.umass.edu/MA1/currentreflect.png"
		// Path to 'base' image.
		var baseImgURL = "http://gaia.cs.umass.edu/MA1/base.png";
		// Path to footprint image.
		var footprint = "http://rerun.cs.umass.edu/CASA_RADAR/RadarFootprint.png";
		var refreshPeriod = 3000;
        // For parsing XML data
		var xmlDoc;
		
		// This is the image that is being displayed currently (reflection by default).
		var curImageURL = currentReflectionImgURL;

		// Map coordinate related globals. These are set in the scaleMap() routine.
		var center;
		var bounds;
		var width;
		var height;
		var longlen;
		var latlen;
		var widthmi;
		var heightmi;
		var mpp;
		
		// variables for the timer
		var secs;
		var timerID = null;
		var timerRunning = false;
		var delay = 1000;
		var refreshRate = 10;
		
		/**
		 * Here we add the Listener to the map object to catch all zoom events.
		 */
		GEvent.addListener(map, 'zoom', function() {
		  reload();
		});
				
		// Initial call.
		scaleMap();
		// Start timer.
// -tt		initTimer();

		/**
          * Called when the user resets the settings via the 'set' button.
 	      */
		function setParams(form){
		  addNewRadius(form);
		  // 0 corresponds to the reflection image.
          if (form.image.value == 0){
                curImageURL = currentReflectionImgURL;
		  } else {
                curImageURL = currentVelocityImgURL;
		  }
          setRefreshRate(form);
		}
		
		/**
		 * Reads the timestamp image from the local xml file ("timestamp.txt")
		 * and places on to the page.
         */
		function displayImageTimestamp(){
		  var url = "http://gaia.cs.umass.edu/MA1/timestamp.xml";
		  // branch for native XMLHttpRequest object
    	  if (window.XMLHttpRequest) {
            xmlDoc = new XMLHttpRequest();
            xmlDoc.onreadystatechange = processReqChange;
            xmlDoc.open("GET", url, true);
            xmlDoc.send(null);
    	  // branch for IE/Windows ActiveX version
    	  }	else if (window.ActiveXObject) {
        	xmlDoc = new ActiveXObject("Microsoft.XMLHTTP");
        	if (xmlDoc) {
              xmlDoc.onreadystatechange = processReqChange;
              xmlDoc.open("GET", url, true);
              xmlDoc.send(null);
          	}
     	  }
		}

		function processReqChange() {
			// only if req shows "complete"
			if (xmlDoc.readyState == 4) {
				// only if "OK"
				if (xmlDoc.status == 200) {
					// ...processing statements go here...
					response  = xmlDoc.responseXML.documentElement;
					method = "<font face='Arial' size='2'> Radar image last updated at: " + response.getElementsByTagName('time')[0].firstChild.data + "</font>";
					window.document.getElementById('date').innerHTML = method;
					//date.innerHTML = method;
				} else {
					alert("There was a problem retrieving the XML data:\n" + req.statusText);
				}
			}
		}

        /** 
         * Sets the refresh rate based on the input contained in the form param.
		 */
		function setRefreshRate(form){
              var refRate = form.inputbox.value;
              if (!(refRate == "")){
                refreshRate = refRate;
          	    secs = 0;
		        startTheTimer();
	        } else{
                alert("Please enter a valid refresh rate.");
		    }
		}
		
		/**
		 * Modifies the userRadius variable.
		 */
	    function addNewRadius(form){
		  var test = form.rinputbox.value;
		  if (test == ""){
		    // If it's empty don't do anything.
		  }else if(test < 0){
		    alert("Not a valid radius!");  
		  }else{
		    userRadius = test;
		  }
		}

		/**
		 * This method initializes the google map and centers it the radar tower (in Amherst).
		 */
		function scaleMap(){ 
		  center = map.getCenterLatLng();
		  bounds = map.getBoundsLatLng();
		  width = bounds.maxX - bounds.minX;
		  height = bounds.maxY - bounds.minY;
		  longlen = lonscale(center.y);
		  latlen = latscale(center.y);
		  widthmi = longlen * width;
		  heightmi = latlen * height;
		  mpp = widthmi/mapwidth;
		  
		  var base = new GIcon();
		  //base.image = currentReflectionImgURL;
		  base.image = curImageURL;
		  base.shadow = "http://gaia.cs.umass.edu/MA1/base.png";
		  base.shadowSize = new GSize(1, 1);
		  
		  var icon = new GIcon(base);
		  icon.iconSize = new GSize(radius*2/mpp, radius*2/mpp);
		  icon.iconAnchor = new GPoint(radius/mpp, radius/mpp);

		  var marker = new GMarker(centerOfRadar, icon);
		  map.addOverlay(marker);
	
		  var footprintBase = new GIcon();
		  footprintBase.image = footprint;
		  footprintBase.shadow = "http://gaia.cs.umass.edu/MA1/base.png";
		  footprintBase.shadowSize = new GSize(1,1);
		  
		  var footprintIcon = new GIcon(footprintBase);
		  footprintIcon.iconSize = new GSize(radius*2/mpp, radius*2/mpp);
		  footprintIcon.iconAnchor = new GPoint(radius/mpp, radius/mpp);
		  
		  var footprintMarker = new GMarker(centerOfRadar, footprintIcon);
		  map.addOverlay(footprintMarker);
             
		  if (userRadius!=0){
		    // if it doesn't equal 0 then the user has specified a new radius to draw
			var userFootprint = new GIcon();
			userFootprint.image = footprint;
			userFootprint.shadow = "http://gaia.cs.umass.edu/MA1/base.png";
		    userFootprint.shadowSize = new GSize(1,1);
			
			var userFootprintIcon = new GIcon(userFootprint);
			userFootprintIcon.iconSize = new GSize(userRadius*2/mpp, userRadius*2/mpp);
			userFootprintIcon.iconAnchor = new GPoint(userRadius/mpp, userRadius/mpp);
			
			var userFootprintMarker = new GMarker(centerOfRadar, userFootprintIcon);
			map.addOverlay(userFootprintMarker);
		  }
		  // Resolves PNG transparency issues in IE
		  ieFix();
		  // get the timestamp for the image we just pulled in
// -tt		  displayImageTimestamp();
		}

		/**
		 * Clears overlays and reinitializes map via the scaleMap() method.
		 */
		function reload(){
		  map.clearOverlays();  
		  scaleMap();
		}

		/**
		 * Starts the timer.
		 */
		 function initTimer(){
		   // Set the length of the timer, in seconds
		   secs = 10;
		   stopTheClock();
		   startTheTimer();
		}
		
		/**
		 * Stops the timer.
		 */
		function stopTheClock(){
		  if(timerRunning){
		    clearTimeout(timerID);
		  }
              timerRunning = false;
		}

		/**
		 * Starts timer.
		 */
		function startTheTimer(){
		  if (secs==0){
		    stopTheClock();
 		    // Time has elapsed; force a reload
		    //document.write("Updating radar image...");
 		    reload();
		    //document.write("Complete.");
		    // Restart the timer.
		    secs = refreshRate;
                startTheTimer();
              } else{
                self.status = secs;
                secs = secs - 1;
                timerRunning = true;
                timerID = self.setTimeout("startTheTimer()", delay);
		  }
		}
		 

	    /**
		 * Scales the latitude.
		 */
		function latscale(latitude) {
			var m1 = 111132.92;
			var m2 = -559.82;
			var m3 = 1.175;
			var m4 = -0.0023;
			var lat = latitude * ((2.0 * Math.PI)/360.0);
			var latlen = m1 + (m2 * Math.cos(2 * lat)) + (m3 * Math.cos(4 * lat)) + (m4 * Math.cos(6 * lat));
			return (latlen / 12 * 39.370079) / 5280;
		}


	    /**
		 * Scales the longitude.
		 */
		function lonscale(latitude) {
			var p1 = 111412.84;
			var p2 = -93.5;
			var p3 = 0.118;
			var lat = latitude * ((2.0 * Math.PI)/360.0);
			var longlen = (p1 * Math.cos(lat)) + (p2 * Math.cos(3 * lat)) + (p3 * Math.cos(5 * lat));
			return (longlen / 12 * 39.370079) / 5280;
		}
		

		/**
		 * Routine from Mathew Williams.
		 * Cycles through all images and loads them in via Microsoft's "AlphaImageLoader" because native transparent           
             * PNG support is apparently an idea Microsoft doesn't like.
		 */
		function ieFix () { 
			if (isIE) { 
				for (var i = 0; i < map.overlays.length; i++) { 
					map.overlays[i].iconImage.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + map.overlays[i].icon.image + "', sizingMethod='scale');" 
					if (i == 1000) alert('runaway script!'); 
				} 
			}
		}
}
