var googleMap			= null;
var geocoder			= null;
var geomarker			= null;
var currTimestamp		= null;
var currDtg				= null;
var radarUpdater		= null;
var radarSpeed			= 1;
var radarObsIndex		= 0;
var radarTransparency	= 40;
var radarSpeed			= 0.500;
var radar				= null;
var doLoop 				= false;
var inLoop 				= false;
var oldTimestamp		= null;
var zoomendListener     = null;

function initMCRadar() {
	$(document).ready(function(){
		if (GBrowserIsCompatible()) {
			googleMap = new GMap2($('#myGoogleMap')[0]);
			
			//control for map/satellite/terrain
			googleMap.addMapType(G_PHYSICAL_MAP);
			var mapControl = new GHierarchicalMapTypeControl();
			mapControl.clearRelationships();
			mapControl.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, "Labels", false);
			
			// Add controls after you've specified the relationships
			googleMap.addControl(mapControl);
			googleMap.addControl(new GScaleControl());
			
			
			// Restrict zooming
			var mt = googleMap.getMapTypes();
			for (var i = 0; i < mt.length; i++) {
				var minRes = mt[i].getMinimumResolution();
				var maxRes = mt[i].getMaximumResolution();
				
				if (minZoom > minRes) 
					mt[i].getMinimumResolution = function(){
						return minZoom;
					}
				if (maxZoom < maxRes) 
					mt[i].getMaximumResolution = function(){
						return maxZoom;
					}
			}
			
			// Control
			googleMap.addControl(new GLargeMapControl());
			googleMap.addControl(new GMapTypeControl());
			
			// Settings
			//googleMap.enableDoubleClickZoom();
			googleMap.enableScrollWheelZoom();
			//googleMap.disableDoubleClickZoom();
			//googleMap.disableScrollWheelZoom();
			googleMap.disableDragging();
			
			// Add components					
			// set map type
			googleMap.setMapType(G_PHYSICAL_MAP);
			
			// Set initial map position
			positionMap();
			
			// Set geocoder
			geocoder = new GClientGeocoder();
			
			// Restrict panning
			if (mapBounds != null) {
				GEvent.addListener(googleMap, "move", function(){
					var C = googleMap.getCenter();
					if (mapBounds.contains(C)) {
						return;
					}
					
					var X = C.lng();
					var Y = C.lat();
					
					var AmaxX = mapBounds.getNorthEast().lng();
					var AmaxY = mapBounds.getNorthEast().lat();
					var AminX = mapBounds.getSouthWest().lng();
					var AminY = mapBounds.getSouthWest().lat();
					
					if (X < AminX) {
						X = AminX;
					}
					if (X > AmaxX) {
						X = AmaxX;
					}
					if (Y < AminY) {
						Y = AminY;
					}
					if (Y > AmaxY) {
						Y = AmaxY;
					}
					
					googleMap.setCenter(new GLatLng(Y, X));
				});
			} //mapBounds not null	
			
			// Create Radar
			radar = new MCRadar(35, mapBounds);
			
			// Load latest timestamp
			loadTimestamp();
			
			googleMap.addOverlay(radar);
			
			/* Free memory */
			X = null;
			Y = null;
			C = null;
			mt = null;
		}
	});
}

function positionMap() {
	// determine startup view box from custom cornerpoints
	if (swPoint != null && nePoint != null) {
		var bounds	= new GLatLngBounds(swPoint, nePoint);
		var initialZoom = (initZoom==null) ? googleMap.getBoundsZoomLevel(bounds) : initZoom;
		googleMap.setCenter(bounds.getCenter(), initialZoom);
	}
	else {
		// from mapbounds
		if (mapBounds!=null) {
			var initialCenter = (initLatLng==null) ? mapBounds.getCenter() : initLatLng ;
			var initialZoom = (initZoom==null) ? googleMap.getBoundsZoomLevel(mapBounds) : initZoom;
		 	googleMap.setCenter(initialCenter, initialZoom);			
		}
		// from radarbounds
		else if ( (radar!=null) && (radar.getRadarBounds()!=null) ) {
			var initialCenter = (initLatLng==null) ? radar.getRadarBounds().getCenter() : initLatLng ;
			var initialZoom = (initZoom==null) ? googleMap.getBoundsZoomLevel(radar.getRadarBounds()) : initZoom;
			googleMap.setCenter(initialCenter, initialZoom);
		}
	}
	/* Free memory */
	initialZoom = null;
	initialCenter = null;
}

/** loads a timestamp to check whether the dataset must be updated*/
function loadTimestamp() {
	xmlhttpGet("/timestamp?nc=" + (new Date()).getTime(),processTimestamp);
}

/** 
 * Is called while loading the XML, after ready, it will get the timestamp.
 * If the timestamp changes, the dtgs are reloaded.
 * */
function processTimestamp(xmlHttpReq) {
	var timestamp		= xmlHttpReq.responseText;
	if (timestamp != currTimestamp) {
		currTimestamp	= timestamp;
		if (radar == undefined || radar == null) {
			return false;
		}
		else {
			radar.setTimestamp(currTimestamp);
			loadDtgs();
		}
	}
	radarUpdater = setTimeout(loadTimestamp, 120*1000);
	/* Free memory */
	timestamp = null;
}

/** load the DTG's and Radar images */
function loadDtgs() { 
	xmlhttpGet("/dtgs?nc=" + (new Date()).getTime(),processDtg);
}

/** Is called while loading the XML, after ready, it will locate the GMS stations */
function processDtg(xmlHttpReq) {
	var mySelect = document.getElementById('dtg');
	if (mySelect == undefined || mySelect == null) {
		//alert("Sorry but your browser has not loaded the Rain Today page correctly and therefore the site may not load correctly for you. Please try clearing your cache and/or CTRL-F5 to try again.");
		return false;
	}
    mySelect.options.length = 0; 
	
	response = xmlHttpReq.responseXML.documentElement;
	if (response == undefined || response == null) {
		response = xmlHttpReq.responseXML.documentElement;
		if (response == undefined || response == null) {
			//alert("Sorry but your browser is not reading the radar information and therefore the site may not load correctly for you. Try clearing your browser cache and re-trying.");
			return false;
		}
	}
	var idx	= 0;
	var setSelected = false;
	var dtgs		= response.getElementsByTagName('dtg');
	for (var i = 0; i < dtgs.length; i++) {
		var dtg = dtgs[i];
		var name	= dtg.getAttribute("name");
 		var value	= dtg.getAttribute("value");
		var fcst	= dtg.getAttribute("fcst");
		if (fcst == "true") {
			name += " *";
		}
 		if (idx == 0) {
 			idx				= i;
 			radarObsIndex	= i;
 		}
		mySelect.options[i] = new Option (name,value);
		if (fcst == "true") {
			mySelect.options[i].style.color = 'red';
		}
		else {
			if (setSelected == false) {
				mySelect.options[i].selected = true;
				setSelected = true;
			}
		}
		/* Free memory */
		name = null;
		value = null;
		radarObsIndex = null;
 	}

 	if ($('#dtg').length > 0) {
		$('#dtg').selectedIndex	= idx;
		if (typeof(mapType) == "undefined") {
			if (document.getElementById('dtg').options[$('#dtg')[0].selectedIndex].style.color == "red") {
				setCurrDtg(document.getElementById('dtg').options[$('#dtg')[0].selectedIndex].value, 'fcst');
			}
			else {
				setCurrDtg(document.getElementById('dtg').options[$('#dtg')[0].selectedIndex].value, 'obs');
			}
		}
		else {
			setCurrDtg(document.getElementById('dtg').options[$('#dtg')[0].selectedIndex].value, mapType);
		}
 	}
	/* Free memory */
	dtg = null;
	name = null;
	value = null;
	mySelect = null;
}

/** Sets the DTG. If the dtg changes the data will be refreshed */
function setCurrDtg(dtg,type) {
	if (dtg != currDtg) {
		currDtg	= dtg;
		if (typeof(type) == "undefined" || type == null) {
			if (document.getElementById('dtg').options[$('#dtg')[0].selectedIndex].style.color == "red") {
				radar.setDtg(document.getElementById('dtg').options[$('#dtg')[0].selectedIndex].value, 'fcst');
			}
			else {
				radar.setDtg(document.getElementById('dtg').options[$('#dtg')[0].selectedIndex].value, 'obs');
			}
		}
		else {
			radar.setDtg(dtg,type);
		}
	}
        var dtgcopy = $("#dtg_copy");
        if ( dtgcopy ) {
			$('#dtg_copy').html('Current date/time selected: ' + $('#dtg :selected').text());
        }
		var dtgcopy2 = $("#dtg_label");
		if (dtgcopy2) {
			$("div#dtg_label").html($('#dtg :selected').text() + "<p><br /><a href='#' onclick='$(\"div#dtg_label\").hide();'>Hide</a></p>");
		}
}

function changeRadarBounds(xmlHttpReq) {
    var boundaryResponse = xmlHttpReq.responseXML.documentElement;
	var boundaries = boundaryResponse.getElementsByTagName('boundary');
	if (boundaries.length>0) {
		var boundary=boundaries[0];
		var latLonMin = new GLatLng(getAttribute('lat_min'),boundary.getAttribute('lon_min') );
		var latLonMax = new GLatLng(boundary.getAttribute('lat_max'),boundary.getAttribute('lon_max') );
		var radarBounds	= new GLatLngBounds(latLonMin,latLonMax);
		radar.setRadarBounds(radarBounds);
		
		//go to new radar center
		if (! (googleMap.getBounds().intersects(radarBounds)) ) {
			var radarCenter = radarBounds.getCenter();
			googleMap.setCenter(radarCenter);
			radarCenter = null;
		} //if no intersect
		/* Free memory */
		boundary = null;
		latLonMin = null;
		latLonMax = null;
		radarBounds = null;
	} //if boundary found
}

/** moves the frame 1 upwards or downwards */
function setSwitchFrame(plusmin){
	var select	= $('#dtg')[0];
 	var idx = select.selectedIndex - plusmin;
	idx	= idx % select.length;
	if (idx<0) idx=select.length-1;
	select.selectedIndex=idx;
	setCurrDtg(select.value);
	/* Free memory */
	select = null;
}

function setFrame(idx){
	$('#dtg')[0].selectedIndex=idx;
}

/** set doLoop variable and pics */
function setLooping(newValue){
	doLoop=newValue;
	if (newValue==true) {
		$('#radar_start').attr('src','/images/player/btn_play_disabled.png');
		$('#radar_stop').attr('src','/images/player/btn_stop_enabled.png');
	 	if (!inLoop) {
			loopRadar(); //switch the loop on
		}
	}
	else {
		$('#radar_start').attr('src','/images/player/btn_play_enabled.png');
		$('#radar_stop').attr('src','/images/player/btn_stop_disabled.png');
	}
}

/** do the loop */
function loopRadar() {
	if (!doLoop) {
		inLoop = false;
		return;
	}
	inLoop=true;
	setSwitchFrame(1);		
	delay = radarSpeed * 1000;
	
	if ($('#dtg')[0].selectedIndex == 0) {
		delay *= 5;		
	}
	setTimeout("loopRadar()", delay);
	delay = null;
}

