var tooltip;
var existingMarkers = [];
var fireMarkers=[];
var density=1;
var interval=0;
var radarInterval=0;
var progressObj;
var timeObj;
var iconObj;
var rall;
var mapZoom;
var precipOptions;
var weatherOptions;
var snotelValue=true;
var dataFilters;
var precipValue='P01I';
var divid=document.getElementById("map_canvas");

function updateMarkers(all){
	var stations=new Object;
	var formF1=document.getElementById("gustFilter");
	var formF2=document.getElementById("tempFilter");
	var formF3=document.getElementById("elevFilter");
	var formF4=document.getElementById("rhFilter");
	var densityForm=document.getElementById("densityForm")
	var xmlDiv=document.getElementById("xmlink");
	var kmlDiv=document.getElementById("kmlink");
	var permaDiv=document.getElementById("permalink");
	var bounds=map.getBounds();
	mapZoom=map.getZoom();
	var southWest=bounds.getSouthWest();
	var northEast=bounds.getNorthEast();
	var getVars = 'extents='+southWest.toUrlValue()+','+northEast.toUrlValue();
	request = GXmlHttp.create();
	//progressObj.src='/images/progress_bar.gif';
	map.addControl(loadingMessage,new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(312,246)));
	var label='';
	if (parseInt(formF1.gust.value)>0){label+='&mingust='+formF1.gust.value;}
	if (parseInt(formF2.temp.value)>0){label+='&mintemp='+formF2.temp.value;}
	if (parseInt(formF3.elev.value)>0){label+='&minelev='+formF3.elev.value;}
	if (parseInt(formF4.rh.value)>0){label+='&maxrh='+formF4.rh.value;}
	if (!snotelValue){label+='&snotel='+snotelValue;}
//find the density setting
	for (var i=0;i<densityForm.density.length;i++){
		if (densityForm.density[i].checked){
			break;
		}
	}
	density=densityForm.density[i].value;
	var url='/mesowest/GmwXJList.php?'+getVars+'&zoom='+mapZoom+'&mapsize='+divw+','+divh+'&density='+density+label;
	if (dataType=='precip'){
		url+='&precip=1'+'&value='+precipValue;
	}
	var xmlurl=url+'&format=xml';
	xmlDiv.innerHTML='<a href="'+xmlurl+'"><img style="border-style:none" src="/images/xml.gif" alt="download xml" title="download xml"\></a>';
	var kmlurl=url+'&format=kml';
	kmlDiv.innerHTML='<a href="'+kmlurl+'"><img style="border-style:none" src="/images/kml.gif" alt="download kml" title="download kml"\></a>';
	var permaurl='/mesowest/gmap.php?zoom='+mapZoom+'&'+getVars+'&density='+density;
	if (dataType=='precip'){
		permaurl+='&precip=1';
	}
	permaDiv.innerHTML='<a href="'+permaurl+'"><img style="border-style:none" src="/images/permalink.gif" alt="link to current view" title="link to current view"\></a>';
	rall=all;
	request.onreadystatechange=processRequest;
	request.open('GET',url,true);
	request.send(null);
	var densityForm=document.getElementById("densityForm")
	if (mapZoom>6){
		densityForm.density[3].disabled=false;
	}else{
		densityForm.density[3].disabled=true;
	}
}

function processRequest(evt){
	if (request.readyState==4){
		var balloon;
		var point;
		var jscript = request.responseText;
		eval(jscript);
		timeObj.innerHTML='Display Updated: '+Date();
		if (dataType=='weather'){
			//iconObj.innerHTML=count;
		}
		if (rall){

			for (var k in existingMarkers){
				map.removeOverlay(existingMarkers[k]);
				delete existingMarkers[k];
			}
			var holdar=[];
			for (k in existingMarkers){
				holdar[k]=existingMarkers[k];
			}
			existingMarkers=[];
			for (k in holdar){
				existingMarkers[k]=holdar[k];
			}
			delete holdar;
			//holdar=[];
		}else{
			for (var k in existingMarkers){
				if (!stations[k]){
					map.removeOverlay(existingMarkers[k]);
					delete existingMarkers[k];
				}
			}
			var holdar=[];
			for (k in existingMarkers){
				holdar[k]=existingMarkers[k];
			}
			existingMarkers=[];
			for (k in holdar){
				existingMarkers[k]=holdar[k];
			}
			delete holdar;
			//holdar=[];
		}
		var formOb=document.getElementById("dataDisplayForm");
		for (var k in stations){
			if (!existingMarkers[k]){
				if (stations[k].id){
					point=new GLatLng(stations[k].latitude,stations[k].longitude);
					balloon=stations[k].name+'<br>'+stations[k].id;
					label='';
					if (dataType=='precip'){
						if (precipValue=='P01I'){
							if (parseFloat(stations[k].hr1Precip)>0){
								label='precip='+stations[k].hr1Precip;
							}
						}else if (precipValue=='P03I'){
							label='precip='+stations[k].hr3Precip;
						}else if (precipValue=='P06I'){
							label='precip='+stations[k].hr6Precip;
						}else if (precipValue=='P12I'){
							label='precip='+stations[k].hr12Precip;
						}else if (precipValue=='P24I'){
							label='precip='+stations[k].hr24Precip;
						}else if (precipValue=='P00A'){
							label='precip='+stations[k].PrecipMidnight;
						}else if (precipValue=='P13A'){
							label='precip='+stations[k].Precip1300;
						}
					}else{
						if (formOb.dataDisplay[0].checked){
							label='temp='+stations[k].Temp;
						}
						if (formOb.dataDisplay[1].checked){
							label+='&winds='+stations[k].Winds;
							label+='&windd='+stations[k].Windd;
						}
						if (formOb.dataDisplay[2].checked){
							label+='&gust='+stations[k].Gust;
						}
						if (formOb.dataDisplay[3].checked){
							label+='&rh='+stations[k].Relh;
						}
						if (formOb.dataDisplay[4].checked){
						label+='&dew='+stations[k].Dewp;
						}
						if (formOb.dataDisplay[5].checked){
							label+='&slp='+stations[k].SLP;
						}
					}
					if (label.length>0){
						existingMarkers[k] = createMarker(point,stations[k],label);
						map.addOverlay(existingMarkers[k]);
					}
				}//if stations[i].id
			}//if existingMarkers
		//progressObj.src='/images/clear.gif';
		}//for k in stations
		index=0;
		for (k in existingMarkers){
			index++;
		}
		iconObj.innerHTML='Stations Displayed: '+index;
		delete stations;
		map.removeControl(loadingMessage);
	}//if readstate==4
}//function();

function createMarker(point,stationData,label){
//create an icon using the png files in roadWx/images.
	var icon = new GIcon();
	
	if (dataType=='weather'){
		icon.image = "/images/mwIcon3.php?"+label;
		icon.iconSize = new GSize(45 ,40);
		icon.iconAnchor = new GPoint(25, 30);
		icon.infoWindowAnchor = new GPoint(0, 0);
	}else{
		icon.image = "/images/precipIcon.php?"+label;
		icon.iconSize = new GSize(32 ,32);
		icon.iconAnchor = new GPoint(25, 30);
		icon.infoWindowAnchor = new GPoint(0, 0);
	}

	var marker=new GMarker(point,icon);
	var inner=createPopup(stationData);
	marker.tooltip='<div style="width:200;font-size:11;font-family:\'Arial\';color:black;background:#e6e6fa;border:1px solid blue;margin:7px;padding:4px;z-index:300;position:relative;"><img src='+icon.image+'>'+inner+'</div>';
	GEvent.addListener(marker,"click",function(){
		if (interval){
			clearInterval(interval);
		}
		getTimeSeries(stationData.id);
		interval=setInterval('getTimeSeries(\''+stationData.id+'\')',900000);
	});
	GEvent.addListener(marker,"mouseover", function() {
		showTooltip(marker);
        });        
        GEvent.addListener(marker,"mouseout", function() {
		tooltip.style.visibility="hidden"
        });
	delete icon;
	delete marker;
	return marker;
}

function getTimeSeries(id){
	//progressObj.src='/images/progress_bar.gif';
//loadingMessage=new HtmlControl('<div class="progress" align="center">Time Series Loading Below Map!</div>');
map.addControl(loadingMessage,new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(312,246)));
	var timediv=document.getElementById("time_series");
	//progressObj.src='/images/progress_bar.gif';
	var url='/mesowest/getobext.php?sid='+id+'&banner=gmap&raw=0';
	var request = GXmlHttp.create();
	request.open('GET',url,true);
	request.onreadystatechange=function(){
		if (request.readyState==4){
			var jscript = request.responseText;
			var timediv=document.getElementById("time_series");
			timediv.innerHTML=jscript;
		//	progressObj.src='/images/clear.gif';
			map.removeControl(loadingMessage);
		}
	}
	request.send(null);
}

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 height=0;
var x = offset.x - point.x - anchor.x + width; var y = offset.y - point.y -anchor.y -height; var center = map.getCenter(); // lat,lng 
var centerPoint = map.getCurrentMapType().getProjection().fromLatLngToPixel( center,map.getZoom());

	divw=divid.style.width;
	divh=divid.style.height;
	var mapWidth=parseInt(divw.slice(0,-2));
	var mapHeight=parseInt(divh.slice(0,-2));
	var tooltipWidth=250; // for some reason need this with Firefox // can't use tooltip.clientWidth;

	if (offset.y - height - anchor.y < centerPoint.y - mapHeight/2 ) y = y + height + anchor.y; 
	if (offset.x + tooltipWidth - anchor.x + width > centerPoint.x + mapWidth/2) x = x - tooltipWidth - width;

	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y)); 
	pos.apply(tooltip); 
	tooltip.style.visibility="visible";
	delete pos;
}

function createPopup(stationData){
	var html;
	html='<div style="width:200;font-size:12;font-family:\'Arial\';color:white;background:blue">'+stationData.id+'</div>';
	html=html+'Name:'+stationData.name+'<br>';
	html=html+'Location:'+stationData.latitude+'/'+stationData.longitude+' @ '+stationData.elev+' ft.<br>';
	html=html+'Mesonet:'+stationData.provider+'<br>';
	if (stationData.Temp){
		html=html+'Update: '+stationData.Date+'<br>';
	}
	if (stationData.Temp){
		html=html+'Temp: '+stationData.Temp+'<br>';
	}
	if (stationData.Relh){
		html=html+' Relh: '+stationData.Relh+'<br>';
	}
	if (stationData.Relh){
		html=html+' Dew Point: '+stationData.Dewp+'<br>';
	}
	if (stationData.Wind){
		html=html+' Wind: '+stationData.Wind+'<br>';
	}
	if (stationData.Gust){
		html=html+' Gust: '+stationData.Gust+'<br>';
	}
	if (stationData.Altimeter){
		html=html+' Altimeter: '+stationData.Altimeter+'<br>';
	}
	if (stationData.SLP){
		html=html+' SLP: '+stationData.SLP+'<br>';
	}
	if (stationData.Weather){
		html=html+' Weather: '+stationData.Weather+'<br>';
	}
	if (stationData.Visibility){
		html=html+'Visibility: '+stationData.Visibility+'<br>';
	}
	if (stationData.Clouds){
		html=html+'Clouds: '+stationData.Clouds+'<br>';
	}
	if (stationData.hr1Precip){
		html=html+'1 Hour Precip: '+stationData.hr1Precip+'<br>';
	}
	if (stationData.hr3Precip){
		html=html+'3 Hour Precip: '+stationData.hr3Precip+'<br>';
	}
	if (stationData.hr6Precip){
		html=html+'6 Hour Precip: '+stationData.hr6Precip+'<br>';
	}
	if (stationData.hr12Precip){
		html=html+'12 Hour Precip: '+stationData.hr12Precip+'<br>';
	}
	if (stationData.hr24Precip){
		html=html+'24 Hour Precip: '+stationData.hr24Precip+'<br>';
	}
	if (stationData.PrecipMidnight){
		html=html+'Precip Since Mid.: '+stationData.PrecipMidnight+'<br>';
	}
	if (stationData.hr24Precip){
		html=html+'Precip Since 13:00: '+stationData.Precip1300+'<br>';
	}
	if (stationData.a1hrPrecip){
		html=html+'1hr Precip: '+stationData.a1hrPrecip+'<br>';
	}
	if (stationData.a3hrPrecip){
		html=html+'3hr Precip: '+stationData.a3hrPrecip+'<br>';
	}
	if (stationData.a6hrPrecip){
		html=html+'6hr Precip: '+stationData.a6hrPrecip+'<br>';
	}
	if (stationData.a24hrPrecip){
		html=html+'24hr Precip: '+stationData.a24hrPrecip+'<br>';
	}
	if (stationData.a5minrecip){
		html=html+'5 min Precip: '+stationData.a5minPrecip+'<br>';
	}
	if (stationData.a10minrecip){
		html=html+'10 min Precip: '+stationData.a10minPrecip+'<br>';
	}
	if (stationData.a15minrecip){
		html=html+'15 min Precip: '+stationData.a15minPrecip+'<br>';
	}
	if (stationData.a30minrecip){
		html=html+'30 min Precip: '+stationData.a30minPrecip+'<br>';
	}
	if (stationData.SnowTotal){
		html=html+'Snow Total: '+stationData.SnowTotal+'<br>';
	}
	if (stationData.SnowInterval){
		html=html+'Snow Interval: '+stationData.SnowInterval+'<br>';
	}
	return html;
}

function createZoomAreas(){
	var zoomForm=document.getElementById("zoomDiv");
	var newForm=document.createElement('FORM');
	newForm.id='zoomForm';
	var dropDown=document.createElement('SELECT');
	dropDown.setAttribute('Name','zoomDrop');
	dropDown.id='zoomDrop';
	dropDown.onchange=zoomToRegion;
	var option;
	for (zoom in zoomAreas){
//GLog.writeUrl(zoom);
		option=document.createElement('option');
		option.value='------'+zoom+'------';
		option.appendChild(document.createTextNode('----------'+zoom+'----------'));
		dropDown.appendChild(option);
		for (j in zoomAreas[zoom]){
			option=document.createElement('option');
			option.value=j;
			option.appendChild(document.createTextNode(j));
			dropDown.appendChild(option);
		}
	}
	newForm.appendChild(dropDown);
	zoomForm.appendChild(newForm);
}

function zoomToRegion() {
	formName=document.getElementById('zoomForm');
	z=formName.zoomDrop.options[formName.zoomDrop.options.selectedIndex].value;
	for (zoom in zoomAreas){
		for (j in zoomAreas[zoom]){
			if (z==j){
				templat=zoomAreas[zoom][j].zoomLat;
				templon=zoomAreas[zoom][j].zoomLon;
				tempzoom=zoomAreas[zoom][j].zoomLevel;
				map.setCenter(new GLatLng(templat, templon), tempzoom);
			}
		}
	}
}

function setDensity(){
	var densityForm=document.getElementById("densityForm")
	for (var i=0;i<densityForm.density.length;i++){
		if (densityForm.density[i].checked){
			break;
		}
	}
	density=densityForm.density[i].value;
	updateMarkers(0);
}

function expand(){
	var disclaimDiv=document.getElementById("disclaimer");
	if (disclaimDiv.style.display=="none"){
		disclaimDiv.style.height="200px";
		disclaimDiv.style.display="inline";
	}else{
		disclaimDiv.style.display="none";
		disclaimDiv.style.height="0px";
	}
}
function checkPolygons(){
	map.addControl(loadingMessage,new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(312,246)));
	var formOb=document.getElementById("overlayForm");
	for (i=0;i<formOb.overlay.length;i++){
		if (formOb.overlay[i].checked && shapes[i].length==0){
			loadPolygons(formOb.overlay[i].value,shapes[i],color[i]);
		}else if (!formOb.overlay[i].checked){
			clearPolygons(shapes[i]);
			shapes[i]=new Array();
		}
	}
	//progressObj.src='/images/clear.gif';
	map.removeControl(loadingMessage);
}
	

function loadPolygons(layer,shapes,color){
	var success;
	var lay;
		if (layer=='fwxzone'){lay='zone';}
		else {lay=layer;}
	for (i=0;i<overlays[layer].length;i++){
		group=overlays[layer][i];
		success = polyLoader.loadStyledPolygon(
		'nws.'+lay+'.'+group, 
		function(theLoadedPolygon){ 
			map.addOverlay(theLoadedPolygon);
			shapes.push(theLoadedPolygon);
		},
		{ // the stroke settings
			color: color,
			opacity: 1.0,
			weight: 1
		},
		{ // the fill settings
			fill: false,
			color: color,
			opacity: 0.4,
			outline: true
		}
	);
	if(!success)
		GLog.writeUrl('ERROR: Invalid polygon ID. No loader was found to load this ID. Try another ID. - '+layer+'.'+group);
	}
}

function clearPolygons(shapes){
	for(var i = 0; i < shapes.length; i++){
		map.removeOverlay(shapes[i]);
	}
}
function setdataType(){
	var dataTypeForm=document.getElementById("dataType")
	for (var i=0;i<dataTypeForm.dataType.length;i++){
		if (dataTypeForm.dataType[i].checked){
			break;
		}
	}
	dataType=dataTypeForm.dataType[i].value;
	if (dataType=='precip'){
		weatherOptions.style.display="none";
		precipOptions.style.display="inline";
		dataFilters.style.visibility="hidden";
	}else{
		weatherOptions.style.display="inline";
		precipOptions.style.display="none";
		dataFilters.style.visibility="visible";
	}
	updateMarkers(1);
}
function setPrecip(){
	var precipForm=document.getElementById("precipDisplayForm")
	for (var i=0;i<precipForm.precipDisplay.length;i++){
		if (precipForm.precipDisplay[i].checked){
			break;
		}
	}
	precipValue=precipForm.precipDisplay[i].value;
	updateMarkers(1);
}
function setSnotel(){
	var snotelBox=document.getElementById("snotelBox")
	snotelValue=snotelBox.checked;
	updateMarkers(1);
}
