/* Copyright (c) 2007 Western Transportation Ins. of Montana State University
*
*     http://www.montana.edu/wti
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* Author: Mehmet Alkanlar, Shaowei Wang, others
*/
//var isInfoWindowOpened = false; //check wheather infowindow is opened or not.
var county="";  
var theDataDoc;
var stationSummary = new Object();
stationSummary.CALTRANS= new Array();
stationSummary.MADIS= new Array();
stationSummary.Mesowest= new Array();
var wxmap = new Object(); //define a wxmap object which has many properties like mapTime, mapType,mapTile, etc.
wxmap.mapTime=null;   //the time shown above the map
wxmap.mapFromTime=null;
wxmap.ahpsTime=null;
wxmap.nwsTime=null;
wxmap.mapType='temp';   //map type like temp,wspd,wx,pop12 etc. start with temperature, overlays name temp-****.png 
wxmap.mapTitle =null;  //map title name
wxmap.currentTime='';
wxmap.weburl="";
wxmap.tabName= "Recent Conditions";
wxmap.tabSelected="Current";  //by default, show current tab

wxmap.CurrentSelected=0; 
wxmap.ForecastSelected=0;
wxmap.ForecastTimeSelected=0;
wxmap.StationsSelected=0;

wxmap.lat=null; //center latitude
wxmap.lng=null; //center longitude
wxmap.z=null; //zoom level
wxmap.savedlink=false;  //page loaded from saved link 
wxmap.savedclick;  //save the clicked marker object for retrigger
wxmap.zoomtoselected=null;
wxmap.clientWidth = 0;
wxmap.clientHeight = 0;
var markerbatch = [];
var openMarker=null;
var startlat;
var startlon;
var waitingPopup=null;
var autorefreshed=true; //true value if auto refreshed the viewport	
var forecastTimes = new Array();
var forecastTime = null; //this just for creating forecast map png file name
var forecastTimesGMT = new Array();
var CurrentList=new Array("temp","wspd","p01","p24","humidity","AHPS24");
var ForecastList=new Array("temp","wspd","wgust","rhm","sky","pop12","qpf","snow", "wx");
var StationsList=new Array("all","rwis","meso","mad");
var Tabbuttons = new Array();
Tabbuttons["Current"] = false;
Tabbuttons["Forecast"] = false;
Tabbuttons["Stations"] = false;
Tabbuttons["Alerts"] = false;

var disp_name = new Array();
disp_name["Current"] = 'Recent Conditions';
disp_name["Forecast"]= 'Forecast';
disp_name["Stations"]= 'Stations';
disp_name["Alerts"]= 'Alerts';

var wxdisp_name= new Array();
wxdisp_name["temp"]= '- Air Temperature - ';
wxdisp_name["wspd"]= '- Wind Speed - ';
wxdisp_name["wgust"]= '- Wind Gust Speed - ';
wxdisp_name["rhm"]= '- Relative Humidity - ';
wxdisp_name["humidity"] = '- Relative Humidity -';
wxdisp_name["pop12"]= '- 12-hour Probability of Precipitation -';
wxdisp_name["p01"]= '- Hourly Precipitation -';
wxdisp_name["p24"]= '- 24-hour Precipitation -';
wxdisp_name["wx"]= '- Weather -';
wxdisp_name["fog"]= ' - Fog - ';
wxdisp_name["snow"]= '- Snow -';
wxdisp_name["sky"]= '- Sky Cover -';
wxdisp_name["qpf"]= '- 6-hour Amount of Precipitation - ';
wxdisp_name["all"]= '- All Stations Status - ';
wxdisp_name["meso"]= '- Mesowest Station Status - ';
wxdisp_name["mad"]= '- Madis Station Status - ';
wxdisp_name["rwis"]= '- Caltrans RWIS Status - ';
wxdisp_name["AHPS24"]= '- NWS Observed 24 hour Precipitation - ';

var triggeredAlerts=new Array();
var alertType=null;
var alertID=null;
var alertHTML='';
var alertInfos='';
var numAlerts=0;
var alertStations=0;
var zoomtopanelHTML=null;
var mgr = null;  //marker manager object
var timerID = null;
var playtimer = null;
var period = 300000; // cycle time for auto reload of data
var NElat0, NElng0,SWlat0,SWlng0;  //the initial viewport lat,long
// Overlays need updating so they read from 
// http://153.90.200.78/NDFD/plot/png/
var map; 
var moveendListener;
var StationOverlay;
var AHPS24Overlay;
var warningInURL=false;
var selectWind = new Array(3);

function onLoad() {
	var index;
	//get all the url variables(for e.g this=that&multiple=variables
	var $_GET = new Array();
	changeresolution();
	if(window.location.search) {
		var query = window.location.search.substr(1);
		var pairs = query.split(/&|;/);
		for(var i = 0; i < pairs.length; i++) {
			var pair = pairs[i].split("=");
			$_GET[unescape(pair[0])] = unescape(pair[1]);
		}
	}
	map = new GMap2(document.getElementById("map"));
	TypeString = new String("CurrentForecastStationsAlerts");
	
	selectWind[0]=0;
	selectWind[1]=0;
	selectWind[2]=0;
	
	if (typeof($_GET['lat'])=="undefined"|| typeof($_GET['lng'])=="undefined"|| typeof($_GET['z'])=="undefined"|| typeof($_GET['i'])=="undefined"|| typeof($_GET['tb'])=="undefined"||TypeString.search($_GET['tb'])==-1)
	{
		map.setCenter(new GLatLng(37.0000, -120.100), 6); //default show whole california
	}
	else
	{
                if (typeof($_GET['adv'])=="undefined"||typeof($_GET['watch'])=="undefined"||typeof($_GET['warning'])=="undefined")
		{
                selectWind[0]=0;
                selectWind[1]=0;
                selectWind[2]=0;

		}
		else
		{
                selectWind[0]=$_GET['adv'];
                selectWind[1]=$_GET['watch'];
                selectWind[2]=$_GET['warning'];
		warningInURL=true;
		} 
		wxmap.lat=parseFloat($_GET['lat']);
		wxmap.lng=parseFloat($_GET['lng']);
		wxmap.z=parseFloat($_GET['z']);
		index=$_GET['i'];
		wxmap.tabSelected=$_GET['tb'];

		if (wxmap.tabSelected=="Current")
		{
		wxmap.CurrentSelected=index;
		wxmap.mapType=CurrentList[index];
		} 
		else if (wxmap.tabSelected=="Forecast")
		{
		wxmap.ForecastSelected=index;
		wxmap.mapType=ForecastList[index];
		}
		else if (wxmap.tabSelected=="Stations")
		{
		wxmap.StationsSelected=index;
		wxmap.mapType=StationsList[index];
		}
		
		map.setCenter(new GLatLng(wxmap.lat, wxmap.lng), wxmap.z);		
		wxmap.savedlink=true;	
	}

	if (typeof($_GET['popup'])!= "undefined")
	{
		waitingPopup = $_GET['popup'];
	}
	
	if (typeof($_GET['alertType'])!="undefined")
	{
		alertType=$_GET['alertType'];
	}
	
	if (typeof($_GET['alertID'])!="undefined")
	{
		alertID=$_GET['alertID'];
	}

	//alert("Vars at onLoad(): " + selectWind[0] + ", " + selectWind[1] + ", " + selectWind[2]);

	if(wxmap.savedlink==true && wxmap.tabSelected=="Alerts" && alertType=="Current" && alertID==2)
	{
		//alert("Saved Link, checking params.");
		checkWind(parseInt($_GET['adv']), parseInt($_GET['watch']), parseInt($_GET['warning']));
	}

	map.enableContinuousZoom();
	map.enableDoubleClickZoom();
	map.addMapType(G_PHYSICAL_MAP);
	var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(100,5));
	map.addControl(new GScaleControl(), pos);
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	overviewControl=new GOverviewMapControl();
	map.addControl(overviewControl);
	//overviewControl.hide(true);  //hide the Overview control first time load
	//map.enableGoogleBar();  google search bar in map
	mgr = new MarkerManager(map);
	moveendListener=GEvent.addListener(map, "moveend", viewport_stations);

	GEvent.addListener(map,"infowindowclose",function()
		{
		openMarker = null;
		if(document.getElementById('calBorder'))
		{
			//alert("calBorder is not null");
			closewin();
		}

		if(Math.abs(startlat-map.getBounds().getNorthEast().lat()) > 0.1 || Math.abs(startlon-map.getBounds().getNorthEast().lng()) > 0.1)
			viewport_stations();
		});


	/*get initial lat long frame*/
	NElat0 = roundNumber(map.getBounds().getNorthEast().lat(),3);
	NElng0 = roundNumber(map.getBounds().getNorthEast().lng(),3);
	SWlat0 = roundNumber(map.getBounds().getSouthWest().lat(),3);
	SWlng0 = roundNumber(map.getBounds().getSouthWest().lng(),3);

	var mapdiv = document.getElementById("map");
	var menubackground = document.createElement("div");
	var menucontrol = document.getElementById("zoomControlPanes");
	menucontrol.style.display="none";
	menubackground.className = "background";
	menubackground.id = "zoomControlPanesBackground";


	menubackground.appendChild(menucontrol.cloneNode(true));
	menucontrol.parentNode.removeChild(menucontrol);
	
	var tabbuttons = document.createElement("div");
	tabbuttons.style.position = "absolute";
	tabbuttons.style.left = "100px";
	tabbuttons.style.zIndex = 202;
	
	tabbuttons.innerHTML += '<div id="CurrentTab" class="tabbutton" style="left: 0px; width: 110px;" title="Click to show/hide menu"><a onclick="changePane(\'Current\');"><div class="tabbuttoninnerselected">Recent Conditions</a></div></div>';
	tabbuttons.innerHTML += '<div id="ForecastTab" class="tabbutton" style="left: 111px; width: 60px;" title="Click to show/hide menu"><a onclick="changePane(\'Forecast\');"><div class="tabbuttoninner">Forecast</a></div></div>';
	tabbuttons.innerHTML += '<div id="StationsTab" class="tabbutton" style="left: 172px; width: 55px;" title="Click to show/hide menu"><a onclick="changePane(\'Stations\');"><div class="tabbuttoninner">Stations</a></div></div>'
	tabbuttons.innerHTML += '<div id="AlertsTab" class="tabbutton" style="left: 228px; width: 40px;" title="Click to show/hide menu"><a onclick="changePane(\'Alerts\');"><div class="tabbuttoninner">Alerts</a></div></div>';
	mapdiv.appendChild(menubackground);
	mapdiv.appendChild(tabbuttons);

    	Tabbuttons["Current"] = true;    
	
	
	if (!wxmap.savedlink)
	{
		initializeCurrent(wxmap.CurrentSelected);   
		TabPane();
	}
	else
	{
		TabPane();
		changePane(wxmap.tabSelected);		
		wxmap.savedlink=false;
		if($_GET['stid'])
			markerPopup($_GET['stid']);
	}


	/*the following codes are for Chris to see county boundary  added 2/8/2008 by sw
	var countyOverlay = new GGroundOverlay ("http://153.90.200.46/GM/county.png",
	new GLatLngBounds(new GLatLng(32, -125),
	new GLatLng(42.5, -113.75)));
	map.addOverlay(countyOverlay); 

	*/
    rightMenu= new ContextMenu(map);
	map.addControl(new GZoomControl({sColor:'#000',nOpacity:.3,sBorder:'1px solid yellow'}), new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(4,280)));
	setInterval("callviewport_stations()",period);
	setInterval(testAlert, period);
	

	

	//to get x,y of boundary/
	/** CA
	lat1 = 42.5; 
	lat2 = 32;
	lon1 = -113.75; 
	lon2 = -125;
	// OREGON
	lat1 = 41.85;
	lat2 = 46.5;
	lon1 = -124.76;
	lon2 = -116.2;
	

	var projection = new GMercatorProjection(15);
	testpoint1= projection.fromLatLngToPixel(new GLatLng(lat1, lon1), 9);
	testpoint2= projection.fromLatLngToPixel(new GLatLng(lat2, lon2), 9);
	alert(testpoint1.x-testpoint2.x);
	alert(testpoint1.y-testpoint2.y);
	*/
}

function checkWind(adv, watch, warning)
{
	var reg = /[\D]/g;

	if(isInt(adv) && isInt(watch) && isInt(warning) && adv > 0 && watch > 0 && warning > 0 && adv < watch && watch < warning)
	{
		//alert("Acceptable URL params");
		selectWind[0] = adv;
		selectWind[1] = watch;
		selectWind[2] = warning;

		//alert("checkWind(): Valid URL params, setting cookie => " + adv + ", " + watch + ", " + warning);
		setCookie(adv,watch,warning);
	}
	else
	{
		//alert("Incorrect URL params, zeroing.");
		selectWind[0] = 0;
		selectWind[1] = 0;
		selectWind[2] = 0;
		setCookie(0,0,0);
	}
}
function isInt(x)
{
	var y=parseInt(x);
	if(isNaN(y)) return false;
	return x==y && x.toString()==y.toString();
}
function alertSize() {
  
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    wxmap.clientWidth = window.innerWidth;
    wxmap.clientHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    wxmap.clientWidth = document.documentElement.clientWidth;
    wxmap.clientHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    wxmap.clientWidth = document.body.clientWidth;
    wxmap.clientHeight = document.body.clientHeight;
  }
}


//changing size of map according to the different screen resolution, 1024*768, 1280x1024 or any other
function changeresolution()
{
	alertSize();
	screenW=wxmap.clientWidth;
	screenH=wxmap.clientHeight;
	var mapdiv = document.getElementById("map");
	if (screenH>=150)
	{
	mapdiv.style.height=screenH-150+"px";
	}
	//alert(mapdiv.style.height);
}
/*
To display forcast air temp, wind speed/direction, wx info on top of forecast overlay
as well as the current conditions -m 
*/

function callviewport_stations() {
	autorefreshed=true;
	viewport_stations();
	autorefreshed=false; 
}
function viewport_stations(datetime){
	var docname=null;

	if (!map.getInfoWindow().isHidden())  return;  //do nothing if infowindow is opened.
        
	var requestType = wxmap.mapType;
	var zoom = map.getZoom();
	var NElat = roundNumber(map.getBounds().getNorthEast().lat(),3);
	var NElng = roundNumber(map.getBounds().getNorthEast().lng(),3);
	var SWlat = roundNumber(map.getBounds().getSouthWest().lat(),3);
	var SWlng = roundNumber(map.getBounds().getSouthWest().lng(),3);
	//if reset to full overview, then reset zoom menu
	if( NElat==NElat0 && NElng==NElng0 &&SWlat==SWlat0 && SWlng==SWlng0)
	{
		resetDistrictZoom();
		resetCountyZoom();
		resetCountyRoadZoom();
		resetDistrictRoadZoom();
		resetCityZoom();
	}

	//mgr.clearMarkers(); //fixed a bug when switch from airtemp to wind icon exist
	if (zoom >= 6)
	{
		//here we only reload NWS red flag alert,etc by auto refresh
		if (!autorefreshed) 
		{
			if (alertType=="Forecast" &&alertID!=3 && alertID!=4) //reload if alert type is current or crosswind alert
			{
				autorefreshed=false;	
			}
			else 
			{
				autorefreshed=true;	
			}
		}
		
		
		if (Tabbuttons["Forecast"])
		{    	
			wxmap.nwsTime=null;//enable reload of NWSalert
		    Popup();
			docname = "hwgen.php?t="+wxmap.mapType+"&NElat="+NElat+"&NElng="+NElng+"&SWlat=" +SWlat + "&SWlng="+SWlng+"&start='"+ newTime + "'" + "&ml=" + zoom;
			if (wxmap.mapType=="wspd" ||wxmap.mapType=="wgust")
				GDownloadUrl(docname, function(doc)
                                    {
                                        if(wxmap.mapType == requestType) constructHwWindMarkers(doc);
                                    });
			else
				GDownloadUrl(docname, function(doc)
                                    {
                                        if(wxmap.mapType == requestType) constructHwMarkers(doc);
                                    });			
		} // if tabbuttons[forecast]
		else if (Tabbuttons["Current"])
		{ 
		wxmap.nwsTime=null;//enable reload of NWSalert
		    Popup();
			if(wxmap.mapType=="AHPS24")  //add for AHPS 24 hour precip raster graph overlay
			{
				updateAHPS24Overlay();
				docname = "hwPrecipgen.php?t="+wxmap.mapType+"&NElat="+NElat+"&NElng="+NElng+"&SWlat=" +SWlat + "&SWlng="+SWlng+"&ml=" + zoom;
				GDownloadUrl(docname, function(doc)
                                    {
                                        if(wxmap.mapType == requestType) consHwPrecipMarkers(doc);
                                    });
			}
			else
			{
				docname = "currentgen.php?t="+wxmap.mapType+"&NElat="+NElat+"&NElng="+NElng+"&SWlat=" +SWlat + "&SWlng="+SWlng+ "&ml=" + zoom;
				if (datetime!=null) docname +="&datetime="+datetime;
				GDownloadUrl(docname, function(doc)
                                    {
                                        if(wxmap.mapType == requestType) constructMarkers(doc);
                                    });
			}
		}
		else if (Tabbuttons["Stations"])
		{
			wxmap.nwsTime=null;//enable reload of NWSalert
		    Popup();
			if (zoom >= 8) {
			docname ="stations.php?t="+wxmap.mapType+"&NElat="+NElat+"&NElng="+NElng+"&SWlat=" +SWlat + "&SWlng="+SWlng+ "&ml=" + zoom;
			if(StationOverlay!=null) map.removeOverlay(StationOverlay);
			GDownloadUrl(docname, function(doc)
                            {
                                if(wxmap.mapType == requestType) constructMarkers(doc);
                            });
			} 
			else
			{
			    StationsOverlay(wxmap.mapType);
			}
		}
		else if (Tabbuttons["Alerts"] &&autorefreshed)
		{
            wxmap.nwsTime=null;//enable reload of NWSalert

		    Popup();
			if (alertType=="Current" && alertID!=null && alertID!=2 && (viewport_stations.caller == null || viewport_stations.caller.name != ""))
			{
				docname = "alertgen.php?&NElat="+NElat0+"&NElng="+NElng0+
					"&SWlat=" +SWlat0 + "&SWlng="+SWlng0;
				docname+="&alertType=Current&alertID="+alertID;
				GDownloadUrl(docname, function(doc)
					{
						if(wxmap.mapType == requestType) constructMarkers(doc);
					});
			}
			else if(alertType=="Current" && alertID==2 && selectWind[0]!=0 && selectWind[0]!="undefined"  && selectWind[1]!=0 && selectWind[1]!="undefined" && selectWind[2]!=0 && selectWind[2]!="undefined")
			{
				if(selectWind[0] < selectWind[1] && selectWind[1] < selectWind[2])
				{
					docname = "adjustWind.php?&NElat=" + NElat + "&NElng=" + NElng + "&SWlat=" + SWlat + "&SWlng=" + SWlng;
					docname += "&val1=" + selectWind[0] + "&val2=" + selectWind[1] + "&val3=" + selectWind[2];
					
					GDownloadUrl(docname, function(doc)
						{  
							constructAdjustableWindMarkers(doc);
						});
				}
				else
				{
					alert("Incorrect parameters selected. Advisory value must be less than Watch value; and Warning value must be greater than both.  All 3 parameters must be selected.");	
					
					if(document.getElementById("dwindow").style.display != "none")
						closePopup();
				}
			}
			else if (alertType=="Forecast" && alertID!=null )
			{
				if(alertID==3)
				{
					wxmap.nwsTime=null;//enable reload of NWSalert
					docname = "alertgen.php?&NElat="+NElat+"&NElng="+NElng+"&SWlat=" + SWlat + "&SWlng="+SWlng+"&start='";
					docname += forecastTimesGMT[document.getElementById("selectTime").selectedIndex] + "'&ml=" + zoom;
					docname+="&alertType=Forecast&alertID="+alertID;
					GDownloadUrl(docname, function(doc)
						{
							if(wxmap.mapType == requestType) constructHwWindMarkers(doc);
						});
				}
				else if(alertID==4)
				{
					wxmap.nwsTime=null;
					
					forecastTime = parseForecastTime(forecastTimesGMT[document.getElementById("selectTime").selectedIndex]);
					var overlayName = wxmap.weburl+"/NDFD/plot/png/fog-" + forecastTime + ".png";
					map.clearOverlays();
					var newOverlay = new GGroundOverlay(overlayName, new GLatLngBounds(new GLatLng(32,-125), new GLatLng(42.5,-113.75)));
					map.addOverlay(newOverlay);

					docname = "alertgen.php?&NElat="+NElat+"&NElng="+NElng+"&SWlat="+SWlat+"&SWlng="+SWlng+"&start='";
					docname += forecastTimesGMT[document.getElementById("selectTime").selectedIndex] + "'&ml=" + zoom;
					docname += "&alertType=Forecast&alertID="+alertID;


					GDownloadUrl(docname, function(doc)
					{
						if(wxmap.mapType == requestType) constructHwMarkers(doc);
					});
				}
				else if(alertID==5)
				{
					getNDFDAlert(alertID);
				}
				else if(alertID==6)
				{
					wxmap.nwsTime=null;//enable reload of NWSalert
					forecastTime = parseForecastTime(forecastTimesGMT[document.getElementById("selectTime").selectedIndex]);
					var overlayName = wxmap.weburl+"/NDFD/plot/png/rfpi-" + forecastTime + ".png";
					map.clearOverlays();
					var  newOverlay =  new GGroundOverlay (
							overlayName,  new GLatLngBounds(new GLatLng(32, -125),
							new GLatLng(42.5, -113.75)));

					map.addOverlay(newOverlay);
					closePopup();
				}
				else if (zoom >=12)
				{
					docname = "alertgen.php?&NElat="+NElat+"&NElng="+NElng+"&SWlat=" +
						SWlat + "&SWlng="+SWlng+"&start='"+ forecastTimesGMT[0] + "'" +
						"&ml=" + zoom;
					docname+="&alertType=Forecast&alertID="+alertID;
					GDownloadUrl(docname, function(doc)
						{
							if(wxmap.mapType == requestType) constructHwMarkers(doc);
						});
				}
				else
				{
					mgr.clearMarkers();
					closePopup();
				}
			}
                        else if(alertID==1 && alertType=="Current")
                        {
                        closePopup();
                        }
			else
			{
				mgr.clearMarkers();//shaowei added 9/8/09 to fix bug: Stations->Drag zoom -> Alerts- > return to last result
				closePopup();
			}
		}
//	closePopup();
	}// if zoom>=6
	else 
	{
		mgr.clearMarkers();
	}
	
}

//Method to build icons that lay on top of Forecast overlays
function constructHwMarkers (doc)
{
	var xmlDoc = GXml.parse(doc);
	var markers = xmlDoc.documentElement.getElementsByTagName("marker");
	var iconSize;
	mgr.clearMarkers();
	deleteMarkers();
	var desc,lat, lng, dt,data,mp,point,iconstr,county,over;

	//Popup();

	if(wxmap.mapType=="alert"&& (alertType=="Current" || alertID == 3 || alertID == 4))
	{
		alertStations=markers.length;
		document.getElementById("alertsTriggered").innerHTML=alertStations + " triggered."
                document.getElementById("AlertsTab").style.background="#FFFFFF";
	}
	else if (wxmap.mapType=="alert")
	{
		document.getElementById("alertsTriggered").innerHTML="";
	}

	for (var i = 0; i < markers.length; i++){
		desc = markers[i].getAttribute("desc");
		lat = parseFloat(markers[i].getAttribute("lat"));
		lng = parseFloat(markers[i].getAttribute("lng"));
		county = markers[i].getAttribute("c");
		dt = markers[i].getAttribute("dt");
		data = markers[i].getAttribute("data");
		mp = markers[i].getAttribute("mp");
		point = new GLatLng(lat, lng);
		iconstr = "DOTS/";
		//fix bug of value 9999 missing data
		if (data=="9999") continue;
		
		if (wxmap.mapType=="alert")
		{
			iconSize = 16;
			tempdata=data.split(",")
			data = rtrim(tempdata[0]);

			switch (data)
			{
			case "Blowing":
			  break;
			case "Smoke":
			  break;
			case "Mix":
			  break;
			case "Fog":
				iconstr += "WxIcons/" + data + ".png";
				break;
			case "Rain":
				iconstr += "WxIcons/" + data + ".png";
			  	break;
			case "None":
				iconstr += "WxIcons/" + data + ".png";
			  	break;
			case "Snow":
				iconstr += "WxIcons/" + data + ".png";
				break;
			case "Haze":
				iconSize = 27;
				iconstr += "WxIcons/" + data + ".png";	
				break;
			case "CrossWindHW":
				var spd=20;
				var Length = 10+spd;
				// Sets arrow width
				var Width = Math.ceil(Length / 6)+1;
				//var Width = Length / 6+1;
				var arrowLength = Width;
				iconSize = Length + arrowLength + 6;
				var sdir=rtrim(tempdata[1]);
				var pointid=rtrim(tempdata[2]);
				if (sdir=="") {
					iconSize=20;
					iconstr = "DOTS/Wind/nobearing.png";
				}
				else {
			    iconstr = "DOTS/Wind/" + "20" + "_" + sdir + ".png";
				}
				break;
		    default:
			    continue;
			}
		}		
		else if (wxmap.mapType == "wx"/* ||wxmap.mapType=="alert"*/)
		{
			iconSize = 16;
			tempdata=data.split(",")
			data = rtrim(tempdata[0]);

			switch (data)
			{
			case "Blowing":
			case "Fog":
			case "Smoke":
				iconstr += "WxIcons/" + data + ".png";
				break;
			case "Mix":
			case "Rain":
			case "None":
			case "Snow":
				iconstr += "WxIcons/" + data + ".png";
				break;
			case "Haze":
				iconSize = 27;
				iconstr += "WxIcons/" + data + ".png";	
				break;
		    default:
			    continue;
			}		
		}	
		else if(wxmap.mapType == "fog")
		{
			iconSize = 16;
			tempdata=data.split(",");
			data = rtrim(tempdata[0]);
			
			switch(data)
			{
			  case "Blowing":
			  	break;
			  case "Smoke":
			  	break;
			  case "Fog":
			  	iconstr += "WxIcons/Fog.png";
				break;
			  case "Mix":
			  	break;
			  case "Rain":
			  	break;
			  case "None":
			  	iconstr += "WxIcons/None.png";
				break;
			  case "Snow":
				break;
			  default:
			  	continue;
			}
		}
		else if(wxmap.mapType=="qpf")
		{
			iconSize = 20;
			iconSize = (data < "0.01")? (16):(26);
			if(data != "0")
			{
				iconSize = 26;
			}
			iconstr += wxmap.mapType + "/" + data + ".png";
		}
		else
		{
			var type;
			switch (wxmap.mapType)
			{
			case "temp": type = "Temperature";
				break;
			case "sky":  type = "Skycover";
				break;
			case "rhm":  type = "Humidity";
				break;
			case "pop12": type = "pop12";
				break;
			case "snow":  type  ="snow";
				break;
			}

			if (type=="snow")
			{
				if (data < 0.1)
				{ 
					iconSize = 16;
				}
				else
				{
					iconSize = 26;
				}
				if (parseFloat(data) >6) {
					iconstr += type + "/6.png";
				}
				else {
					iconstr += type + "/" + roundNumber(data,1) + ".png";
				}
			}
			else
			{
			iconSize = 20;
			iconstr += type + "/" + Math.round(data) + ".png";
			}
		}
		var htmlTag = "<font size=\"2\" face=\"calibri\"><b>Highway: " + desc + " County: "+county+" Milepost:" + mp + "</b><br>Latitude: " + lat + " Longitude: " + lng + "<br>Forecast for " + dt +":</font><br><br><font size =\"4\">";

		//Formatting block
		if(wxmap.mapType=="temp")
		{
			htmlTag += " " + Math.round(data) + "°F";
		}
		else if(wxmap.mapType=="qpf")
		{
			htmlTag += " " + data + "\"";
		}
		else if(wxmap.mapType=="pop12" || wxmap.mapType=="sky" ||wxmap.mapType=="rhm" )
		{
			htmlTag += " " + Math.round(data) + "%";
		}
		else if(wxmap.mapType=="wx" && data=="None")
		{
			htmlTag += " Sunny";
		}
		else if(wxmap.mapType=="fog")
		{
			htmlTag += " " + tempdata[1];
		}
		else
		{
			if(wxmap.mapType=="wx")
			{
				htmlTag += " " + tempdata[1];
			}
			else if (wxmap.mapType != "alert") {
				htmlTag += " " + data+ " in.";
			}
			 else {
				htmlTag += " " + data;
			 }
		}

		over = "Highway: " + desc + " County: "+county+" Milepost: " + mp + " Forecast for " + dt+" Station ID:"+desc+county+mp;
		var icon = new GIcon();
		icon.iconSize = new GSize(iconSize, iconSize);
		icon.iconAnchor = new GPoint(iconSize / 2, iconSize / 2);
		icon.infoWindowAnchor = new GPoint(iconSize / 4, iconSize / 4);
		icon.image = iconstr;

		if (wxmap.mapType=="alert" &&data=="CrossWindHW") 
		{
			var marker =createMarkerBearingChange(point,pointid, icon, sdir,over,desc,mp);
		}
		else 
		{
			var marker = createMarker(point, htmlTag, icon, over);
		}
		markerbatch.push(marker);		
	}

	mgr.addMarkers(markerbatch, 6);
	mgr.refresh();

	closePopup();
}

//Dynamic create wind speed/direction icons on top of forecast wind speed layer
function constructHwWindMarkers(doc){
	var xmlDoc = GXml.parse(doc);
	var markers = xmlDoc.documentElement.getElementsByTagName("marker");
	
	if(wxmap.mapType=="alert"&& alertID == 3)
	{
            alertStations=markers.length;
            document.getElementById("alertsTriggered").innerHTML=alertStations + " triggered."
            document.getElementById("AlertsTab").style.background="#FFFFFF";
	}
        var iconSize = 24; //change from 18 to 24
	mgr.clearMarkers();
	deleteMarkers();
	var desc;
	var lat;
	var lng;
	var dt;
	var data;
	var spd;
	var dir;
	var mp;
	var point;
	var intdir;
	var county;
	for (var i = 0; i < markers.length; i++){

		desc = markers[i].getAttribute("desc");
		county = markers[i].getAttribute("c");
		lat = parseFloat(markers[i].getAttribute("lat"));
		lng = parseFloat(markers[i].getAttribute("lng"));
		dt = markers[i].getAttribute("dt");
		data = markers[i].getAttribute("data");
		spd = parseInt(data.split(",")[0]);
		dir = data.split(",")[1];
		mp = markers[i].getAttribute("mp");
		point = new GLatLng(lat, lng);
		intdir = parseInt(dir);
		intdir = parseInt((intdir + 5) / 10) * 10;
		sdir = intdir + '';
		if (data=="9999") continue; //fix 9999 data missing bug
		if (spd < 1){
			var iconstr = "DOTS/WindIcons/0.png";
		}
		else if (spd < 50){
			var iconstr = "DOTS/WindIcons/" + spd + "_" + sdir + ".png";
		}
		else{
			var iconstr = "DOTS/WindIcons/" + "50" + "_" + sdir + ".png";
		}

		if (spd<1)
		{
			iconSize=9;
		}
		else if (spd >= 1 && spd <=50)
		{
			Length = 10+spd;//5+Math.round(Math.LOG2E * Math.log(spd)*5);
			// Sets arrow width
			var Width = Math.ceil(Length / 6)+1;
			//var Width = Length / 6+1;
			var arrowLength = Width;
			iconSize = Length + arrowLength + 6;

		}
		else if (spd > 50)
		{
			Length = 80;//5+Math.round(Math.LOG2E * Math.log(70)*5);
			// Sets arrow width
			var Width = Math.ceil(Length / 6)+1;
			//var Width = Length / 6+1;
			var arrowLength = Width;
			iconSize = Length + arrowLength + 6;
		} 
                if(wxmap.mapType == "alert" && parseInt(alertID) == 3)
                {
                    Length = 40;
                    Width = Math.ceil(Length/6)+1;
                    var arrowLength = Width;
                    iconSize = Length + arrowLength + 6;
                }
		var htmlTag = "<font size=\"2\" face=\"calibri\"><b> Highway: " + desc + " County: "+county+" Milepost: " + mp + "</b><br>Latitude: " + lat + " Longitude: " + lng + "<br>Forecast for " + dt +":</font><br><br><font size =\"4\">"+spd+" mph from "+ dir+" degrees";
		var over = "Highway: " + desc +  " County: "+county+" Milepost: " + mp + " Wind speed: " + spd + " mph from " + dir + " degrees Updated at " + dt+" Station ID:"+desc+county+mp;
		var icon = new GIcon();
		icon.iconSize = new GSize(iconSize, iconSize);
		icon.iconAnchor = new GPoint(iconSize / 2, iconSize / 2);
		icon.infoWindowAnchor = new GPoint(iconSize / 2, iconSize / 2);
		icon.image = iconstr;
		var marker = createMarker(point, htmlTag, icon, over);
		markerbatch.push(marker);
	}
	mgr.addMarkers(markerbatch, 6);
	mgr.refresh();
	closePopup();
}


function update_legend()
{
	if (wxmap.tabName== "Recent Conditions" && wxmap.mapType=="wspd")
	{
		document['legend'].src=wxmap.weburl+"/NDFD/plot/png/wspdlegend.png";
	}
	else if (wxmap.tabName == "Recent Conditions" && (wxmap.mapType == "p01" || wxmap.mapType == "p24"))
	{
		document['legend'].src = wxmap.weburl+"/NDFD/plot/png/p01legend.png";
	}
	else if (wxmap.mapType=="wx")
	{
		document['legend'].src=wxmap.weburl+"/NDFD/plot/png/"+wxmap.mapType+"legend-"+forecastTime+".png";
	}	  
	else if(wxmap.mapType=="alert")
	{	
		if( alertID==1)
		{
			document['legend'].src=wxmap.weburl+"/NDFD/plot/png/ICYlegend.png";
		}
		else if(alertID==2)
		{
			document['legend'].src=wxmap.weburl+"/NDFD/plot/png/windAdjLegend.png";
		}
		else if(alertID==3)
		{
			document['legend'].src=wxmap.weburl+"/NDFD/plot/png/crosswindLegend.png";
		}
		else if(alertID==5)
		{
			document['legend'].src=wxmap.weburl+"/NDFD/plot/png/NWSLegend.png";
		}
                else if(alertID==6)
                {
                        document['legend'].src=wxmap.weburl+"/NDFD/plot/png/rfpilegend.png";
                }
		else if(alertID==7)
		{
			document['legend'].src=wxmap.weburl+"/NDFD/plot/png/wspdlegend.png";
		}
		else
		{
			document['legend'].src=wxmap.weburl+"/NDFD/plot/png/null.png";
		}
		
	}
    else
	{
		document['legend'].src=wxmap.weburl+"/NDFD/plot/png/"+wxmap.mapType+"legend.png";
	}	  
}

function update_maptitle()
{
	if(Tabbuttons["Forecast"] && (wxmap.mapType == "pop12" || wxmap.mapType == "qpf" ||wxmap.mapType == "snow"))
		document.getElementById("mapName").innerHTML=wxmap.mapTitle+" "+wxmap.mapFromTime+" to "+wxmap.mapTime;
	else if(wxmap.mapType!="AHPS24" || wxmap.ahpsTime == null)
		document.getElementById("mapName").innerHTML=wxmap.mapTitle+" "+wxmap.mapTime;
	else
		document.getElementById("mapName").innerHTML=wxmap.mapTitle+" Ending "+wxmap.ahpsTime;
	update_legend();
}

function resetMap()

{
	map.setCenter(new GLatLng(37.0000, -120.100), 6);
}

function roundNumber(float,dec)
{
	return Math.round(float*Math.pow(10,dec))/Math.pow(10,dec);
}

function resetDistrictZoom()
{
	if(document.getElementById)
	{
		document.getElementById("selectDistrict").selectedIndex=0;
	}
}

function resetCityZoom()
{
	if (document.getElementById){
		document.getElementById("selectCity").selectedIndex=0;
	}
}
function resetCountyZoom()
{
	if (document.getElementById){
		document.getElementById("selectCounty").selectedIndex=0;
	}
}
function resetCountyRoadZoom()
{
	if (document.getElementById){
		document.getElementById("selectRoad").selectedIndex=0;
	}
}
function resetDistrictRoadZoom()
{
	if (document.getElementById){
		document.getElementById("selectRoad2").selectedIndex=0;
	}
}


// change the time of the desired forecast layer
// then get new overlay - only if the flag is set -m
function changeTime(index,refresh_overlay)
{	
	newTime = forecastTimesGMT[index];
	wxmap.mapTime=forecastTimes[index];
	forecastTime = parseForecastTime(newTime);
    	wxmap.ForecastTimeSelected=index;

	
	switch(wxmap.mapType)
	{
	case "pop12":
		if(index < 4) //previous time on a 12 hour scale
			wxmap.mapFromTime = forecastTimes[parseInt(index) + 4].split(" ")[0];
		else
			wxmap.mapFromTime = forecastTimes[parseInt(index) - 4].split(" ")[0];
		break;
	case "qpf":
	case "snow":
		if(index < 2) //previous time on a 6 hour scale
			wxmap.mapFromTime = forecastTimes[parseInt(index) + 6].split(" ")[0];
		else
			wxmap.mapFromTime = forecastTimes[parseInt(index) - 2].split(" ")[0];
		break;
	default:
		if(index == 0) //previous time on a 3 hour scale
			wxmap.mapFromTime = forecastTimes[parseInt(index) + 7].split(" ")[0];
		else
			wxmap.mapFromTime = forecastTimes[parseInt(index) - 1].split(" ")[0];
		break;
	}//end switch
	
        //disable forecast navigation button 
        var obj=document.getElementById("selectTime");
        //obj.selectedIndex = index;
        var PrevButton=document.getElementById("PrevTimeButton");
        var NextButton=document.getElementById("NextTimeButton");
        var total = obj.length - 1;
        var sel = obj.selectedIndex;
        if (sel==0 )
        {
                PrevButton.className="buttondisabled";
                PrevButton.onclick = null;
        }
        else
        {
                PrevButton.className="button";
                PrevButton.onclick=function(){FCNextTime(-1);};
        }
        if (sel==total )
        {
                NextButton.className="buttondisabled";
                NextButton.onclick = null;
        }
        else
        {
                NextButton.className="button";
                NextButton.onclick = function(){FCNextTime(1);};
        }	
	

	if (refresh_overlay)
	{	
		updateForecastOverlay();
		viewport_stations();
	}
	
        update_maptitle();
}

//change the type of hte desired forecast layer
// then get new overlay
function FCchangeType(index)
{
	wxmap.mapType = ForecastList[index];
	wxmap.ForecastSelected=index;
	wxmap.mapTitle=wxmap.tabName+"  "+ wxdisp_name[wxmap.mapType];
	updateTimeDropDownMenu();
        updateForecastOverlay();   
	viewport_stations();
	update_maptitle();
}

function CCchangeType(index)  //select current layer
{
	if (wxmap.tabSelected=="Current")
	{
	wxmap.CurrentSelected=index;
	wxmap.mapType = CurrentList[index];	
	}
	else if (wxmap.tabSelected=="Stations")
	{
	wxmap.StationsSelected=index;
	wxmap.mapType = StationsList[index];
	}
	map.clearOverlays();
	viewport_stations();   
	wxmap.mapTitle=wxmap.tabName+"  "+ wxdisp_name[wxmap.mapType];
	wxmap.mapTime=wxmap.currentTime;
	
	update_maptitle();
}

function updateForecastOverlay()
{
        if(wxmap.mapType == "alert" && alertID == 6)
            var overlayName = wxmap.weburl+"/NDFD/plot/png/rfpi-" + forecastTime + ".png";
        else
            var overlayName = wxmap.weburl+"/NDFD/plot/png/" + wxmap.mapType + "-" + forecastTime + ".png";
	
	//alert(wxmap.mapType);
	var  newOverlay =  new GGroundOverlay (

		overlayName,  new GLatLngBounds(new GLatLng(32, -125),
		new GLatLng(42.5, -113.75)));

	map.clearOverlays();
	map.addOverlay(newOverlay);
}

function updateAHPS24Overlay()
{
	var overlayName = wxmap.weburl+"/NDFD/plot/png/" + wxmap.mapType + "precip.png";
	if (AHPS24Overlay!=null) map.removeOverlay(AHPS24Overlay);
	AHPS24Overlay =  new GGroundOverlay (

		overlayName,  new GLatLngBounds(new GLatLng(32, -125),
		new GLatLng(42.5, -113.75)));
	map.addOverlay(AHPS24Overlay);

}

function updateCountyOverlay(county)
{
	var overlayName = wxmap.weburl+"/NDFD/plot/png/county_overlay/" + trimString(county) + "_overlay.png";

	var newOverlay =  new GGroundOverlay (

		overlayName,  new GLatLngBounds(new GLatLng(32, -125),
		new GLatLng(42.5, -113.75)));

	map.clearOverlays();
	map.addOverlay(newOverlay);
	viewport_stations();
}

function trimString(a_string)
{
	var tmp, tmp_;
	tmp = a_string.replace(/ /g, "");
	tmp_ = tmp.toLowerCase();

	return tmp_;
}


// xml file has GMT time in form 2007-07-25 21:00:00
// pngs named temp-dh00.png
function parseForecastTime(newTime)
{

	day = newTime.substring(8,10);
	hour = newTime.substring(11,13);

	if (hour.length == 1)
		hour = "0" + hour;

	result = day + hour + "00";	
	//why do we need the following codes?  1/24/2008
	//forecastTimes[i-1]=theDataDoc.getElementsByTagName("datetime")[i].firstChild.nodeValue;
	return result;
}




function TabPane()
{	
	//get the height of the layer we're embedded in
	var height = document.getElementById("zoomControlPanes").style.height;

	//take off the "px" part of the string
	height = height.substr(0,height.indexOf("px"));
		//add control panel table
	var	inner_html_string = "<table><tbody><tr><td><div id='control_panel'> <table border='0' align='left' cellpadding='0' cellspacing='0'><tbody><tr><td height='36'><div align='left'><strong>Layer:</strong></div></td></tr>";
	inner_html_string = inner_html_string + "<tr><td><div align='left'><form> <select id='current_menu' onchange='CCchangeType(this.form.selectLayer.selectedIndex)' name='selectLayer'><option value='temp' selected='selected'>Air Temperature</option><option value='wspd'>Wind Speed</option><option value='p01' >Precipitation Within Last Hour</option><option value='p24' >Precipitation Within Last 24 Hours</option><option value='humidity' >Humidity</option><option value='AHPS24' >NWS Observed 24 hour Precip.</option></select></form></div></td></tr></tbody></table></div></td></tr><tr><td>";

	document.getElementById("zoomControlPanes").innerHTML = inner_html_string + document.getElementById("zoomControlPanes").innerHTML + "</td></tr></tbody></table>";

}

function SavezoomPanel()
{
	zoomtopanelHTML=document.getElementById("zoom_panel").innerHTML;
}

function restorezoomPanel()
{
	if (zoomtopanelHTML!=null)
	{
		document.getElementById("zoom_panel").innerHTML = zoomtopanelHTML;
	}
}

function changePane(selected) 
{
	// IF same button has been selected and no pasted URL
	if(Tabbuttons[selected]&&!wxmap.savedlink)
	{
		if(selectWind[0] >= 0 && selectWind[1] >= 0 && selectWind[2] >= 0)
			toggleControlView(1);
		else
			toggleControlView(0);
		
		return;
	}
	else if(wxmap.savedlink && wxmap.tabSelected=="Alerts" && alertID==2)
	{
		toggleControlView(1);
	}
	// ELSE IF tab is collapsed
	else if(collapsed)
	{	
		// IF the tab we are coming FROM was Adjustable Wind
		if(wxmap.tabSelected=="Alerts" && alertID==2)
			toggleControlView(0);
	}

	// ELSE IF tab is open and a different tab was selected
	else if(!collapsed && !Tabbuttons[selected])
	{
		// IF they are coming FROM the alerts tab and going to a different tab (simple resize)
		if(wxmap.tabSelected=="Alerts" && alertID==2)
			document.getElementById("zoomControlPanesBackground").style.height = "150px";
	}
	
	// change current selection to the tab we are now looking at
	for(key in Tabbuttons)
	{
		if(selected == key)
		{
			Tabbuttons[key] = true;
			wxmap.tabSelected=key;
			document.getElementById(key + "Tab").lastChild.setAttribute("className", "tabbuttoninnerselected");
			document.getElementById(key + "Tab").lastChild.setAttribute("class", "tabbuttoninnerselected");
		}//end if
		else
		{
			Tabbuttons[key] = false;
			document.getElementById(key + "Tab").lastChild.setAttribute("className", "tabbuttoninner");
			document.getElementById(key + "Tab").lastChild.setAttribute("class", "tabbuttoninner");
		}//end else
	
	}//for key	
	

	// IF tab is collapsed
	if(collapsed)
	{
		// current tab we are looking at is adjust wind, make room for controls	
		if(wxmap.tabSelected=="Alerts" && alertID==2)
			toggleControlView(1);
		else
			toggleControlView(0);
	}
	

	if(Tabbuttons["Forecast"])
	{			
		forecast_timestamp(); // get the forecast timestamp to see if it's avaiable
		if(!ForecastAvailable()) 
		{
			alert('Forecast is not available. Please try again later');
			return;
		}
		wxmap.tabName="National Digital Forecast";
		restorezoomPanel();
		initializeForecast(wxmap.ForecastSelected);
		// set the menu item
		document.getElementById("forecast_menu").selectedIndex = wxmap.ForecastSelected;
		document.getElementById("zoom_panel").style.visibility = "visible";

	}
	else if(Tabbuttons["Current"])
	{
		Popup();  //call to show pop up windows
		inner_html_string = "<table border='0' align='left' cellpadding='0' cellspacing='0'><tr><td height='36'><div align='left'><strong>Layer:</strong></div></td></tr>";
		inner_html_string = inner_html_string + "<tr><td><div align='left'> <form><select  id='current_menu' onchange='CCchangeType(this.form.selectLayer.selectedIndex)' name='selectLayer'>";
		inner_html_string = inner_html_string +"<option value='temp' selected='selected'>Air Temperature</option><option value='wspd'>Wind Speed</option><option value='p01' >Precipitation Within Last Hour</option><option value='p24' >Precipitation Within Last 24 Hours</option><option value='humidity'>Humidity</option><option value='AHPS24' >NWS Observed 24 hour Precip.</option></select></form></div></td></tr></table>";
		document.getElementById("control_panel").innerHTML = inner_html_string;
		wxmap.tabName="Recent Conditions";
		restorezoomPanel();
		initializeCurrent(wxmap.CurrentSelected);
		// set the menu item
		document.getElementById("current_menu").selectedIndex = wxmap.CurrentSelected;
		document.getElementById("zoom_panel").style.visibility = "visible";
	}

	//added 2/8/2008 shaowei for RWIS tab display
	else if(Tabbuttons["Stations"])
	{
		//Popup();  //call to show pop up windows
		inner_html_string = "<table border='0' align='left' cellpadding='0' cellspacing='0'><tr><td height='30px'><div align='left'><strong>Stations:</strong></div></td></tr>";
		inner_html_string += "<tr><td><div align='left'><form><select  id='current_menu' onchange='CCchangeType(this.form.selectStations.selectedIndex)' name='selectStations'>";
		inner_html_string += "<option value='all' selected='selected'>All</option><option value='rwis'>RWIS</option><option value='meso'>MESOWEST</option><option value='mad'>MADIS</option></select></form></div></td></tr>";
		//inner_html_string +="<tr class='scrollTable' height='36'><td><div  id='stationsummary'></div></td></tr><tr><td >";
		inner_html_string +="<tr><td><div style='margin-top:5px;margin-left:5px' id='stationsummary'></div></td></tr>";
		/*inner_html_string +="<TABLE cellspacing=0 cellpadding=2 id=header> <COL WIDTH=10><COL WIDTH=210>";
		inner_html_string +="<tr><th width=10px >ID</th><th width=210px align='center' >Name</th></tr></TABLE>";
		inner_html_string +="<div id='countlabel' STYLE='overflow: auto; width: 260px; height: 280px; border-left: 0px gray solid; border-bottom: 0px gray solid; padding:0px; margin: 0px'></div></td></tr></table>";
		*/
		document.getElementById("control_panel").innerHTML = inner_html_string;
		wxmap.tabName="Stations";
		restorezoomPanel();
		initializeCurrent(wxmap.StationsSelected);
		document.getElementById("current_menu").selectedIndex = wxmap.StationsSelected;
		document.getElementById("zoom_panel").style.visibility = "visible";
		station_summary();
	}
	//added 6/16/2008 shaowei for Alert tab display
	else if(Tabbuttons["Alerts"])  
	{
		forecast_timestamp(); //read time list for alert display. 
		wxmap.tabName="Alerts";
		wxmap.mapType="alert";
		inner_html_string='          <div style="font-size:15px; margin-left:10px;"><strong>Time&nbsp;Frame: </strong></div>';
		inner_html_string+=		  '<div style="margin-left:30px; margin-top:10px; margin-bottom:10px;">';
		inner_html_string+='          <select  onchange="parent.getSensorList(this)" id="selectAlertType" name="selectAlertType" style="width:180px;">';
		inner_html_string+='            <option value="" selected="selected">(Select)</option>';
		inner_html_string+='            <option value="Current" >Recent Conditions</option>';
		inner_html_string+='            <option value="Forecast">Forecast</option>';
		inner_html_string+='          </select>';
		inner_html_string+='        </div>';
		
		inner_html_string+='			<div style="font-size:15px; margin-left:10px"><strong>Alert&nbsp;Criteria:&nbsp;&nbsp;</strong>';
                inner_html_string+='<span id="alertsTriggered" style="margin-bottom: 0px;">' + alertStations + ' triggered.</span></div>';
		inner_html_string+='			<div id="selectAlertCriteria" style="margin-left:30px; margin-top:10px; margin-bottom:10px;">';
		inner_html_string+='			  <select style="width:180px;">';
		inner_html_string+='				<option value="" selected="selected">select a time frame</option>';
		inner_html_string+='			  </select>';
		inner_html_string+='			</div>';
		

	        document.getElementById("AlertsTab").style.background = "#FFFFFF";	
		document.getElementById("control_panel").innerHTML = inner_html_string;
	
                if(alertType=="Current" && parseInt(alertID) <= 2)
		{
			document.getElementById("selectAlertType").options[1].selected=true;
			getSensorList(document.getElementById("selectAlertType"));				
		}
		else if(alertType=="Forecast" && parseInt(alertID) > 2)
		{
			document.getElementById("selectAlertType").options[2].selected=true;
			getSensorList(document.getElementById("selectAlertType"));
		}
		restorezoomPanel();
		initializealert();	
	}
}

function initializealert()
{
	map.clearOverlays();
	//viewport_stations();   
	wxmap.mapTitle=wxmap.tabName+"  ";
	wxmap.mapTime=wxmap.currentTime;
	
	update_maptitle();
}


function ForecastAvailable()
{
	if (forecastTimes.length > 1) return true;
	else return false;
}

// This function properly updates the time dropdown menu in forecast display - mehmet
function updateTimeDropDownMenu()
{
	var time_menu = document.getElementById("selectTime");
	if(!time_menu) return;

        var currtime = (time_menu.selectedIndex > 0) ? time_menu.options[time_menu.selectedIndex].text : "";
        var index = -1;
        // clear the dropdown

	for(i=time_menu.options.length-1;i>=0;i--)
	{
		time_menu.remove(i);
	}
	var base;
	switch (wxmap.mapType)
	{
	case "pop12":
                base = 12;
		break;
	case "qpf":
	case "snow":
		base = 6;
		break;
	default:
		base = 1; // everything will be equal to 0 in base 1	
	}
	var first = true;
	var optn;
        
        var j = -1;
	for (i=0;i<8;i++)
	{    

		if((parseInt(forecastTimesGMT[i].substring(11,13),10)%base)== 0) 
		{

                        j++;
			optn = document.createElement("OPTION");
			optn.text = forecastTimes[i];
			optn.value = i;
			time_menu.options.add(optn);
                        if(currtime == forecastTimes[i])
                            index = j;
		}
	}
        if(index < 0)
        {
            time_menu.selectedIndex = 0;
            changeTime(time_menu.options[0].value, true);
        }
        else
        {
            time_menu.selectedIndex = index;
            changeTime(time_menu.options[index].value, true);
        }
}

function initializeForecast(index){
	window.clearInterval(timerID);
	mgr.clearMarkers();
        var html_string="<form><table border='0' align='left' cellpadding='0' cellspacing='0'><tr><td  height='34'><div  align='left'><strong>Time:</strong></div></td></tr>";
        html_string+="<tr><td align='left' width='160'>";
        html_string+="<select id='selectTime' onchange='changeTime(this.form.selectTime.options[this.form.selectTime.selectedIndex].value,true)' name='selectTime'>";
        html_string+="</select></td>";
        html_string+="<td align='center' width='25'><div id='PrevTimeButton' class='button' onclick='FCNextTime(-1)'><</div></td>";
        html_string+="<td align='left' width='65'><div id='NextTimeButton' class='button' onclick='FCNextTime(1)'>></div></td>";
        //html_string+="<td align='right'><div id='PlayButton' class='button' onclick='cycleTime()'>Play</div></td>";
        html_string+="</tr>";
        html_string+="<tr><td height='36'><div align='left'><strong>Layer:</strong></div></td></tr>";
        html_string+="<tr><td colspan=3><div align=\"left\"><select  id='forecast_menu' onchange=\"FCchangeType(this.form.selectLayer.selectedIndex)\" name=\"selectLayer\">";

        var longnamelist=new Array("Air Temperature", "Wind Speed", "Wind Gust Speed", "Humidity", "Sky Cover", "12-hour Probability of Precipitation", "6-hour Amount of Precipitation", "Snow", "Weather");
        for(var i = 0; i < ForecastList.length; i++)
        {
            html_string += "<option value=\"" + ForecastList[i] + "\"";
            if(wxmap.mapType==ForecastList[i])
                html_string += "selected=\"selected\" ";
            html_string += ">" + longnamelist[i] + "</option>";
        }
        html_string+="</select></div></td></tr></table></form>";
	document.getElementById("control_panel").innerHTML = html_string;
	newTime = forecastTimesGMT[0];
	forecastTime = parseForecastTime(newTime);
	wxmap.mapTime=forecastTimes[0];
	FCchangeType(index);
	forecast_timestamp();
}	
function initializeCurrent(index){

	window.clearInterval(timerID); // seems unnecessary
	CCchangeType(index);
	closePopup();
	current_timestamp(); //read current timestamp, iterate as long as current display is active
}

function createMarker(point, html,inputIcon,name) {
	var marker = new GMarker(point, {icon:inputIcon, title:name});    
	marker.clickhandle = GEvent.addListener(marker, "click", function()
	{   
		openMarker = marker;
		startlat = map.getBounds().getNorthEast().lat();
		startlon = map.getBounds().getNorthEast().lng();
		marker.openInfoWindowHtml(html);
	});

	return marker;
}

function createTabMarker(point,inputIcon,name,stationID,type,dt,pave) {
	var marker = new GMarker(point, {icon:inputIcon, title:name});    
	marker.clickhandle = GEvent.addListener(marker, "click", function()
	{				
		openMarker = marker;
		startlat = map.getBounds().getNorthEast().lat();
		startlon = map.getBounds().getNorthEast().lng();
		GDownloadUrl( 'popup.php?id='+ stationID + '&type=' + type + '&dt='+dt+'&pave='+pave, function(doc)
		{
			if (pave == 0)
				{				
					marker.openInfoWindow(doc);					
				}
			else 
			{
				var temp = new Array();
				temp = doc.split('TABSEPARATOR');
				marker.openInfoWindowTabsHtml([new GInfoWindowTab('General',temp[0]), new GInfoWindowTab('Pavement',temp[1])]);
			}
		}
		);
	}
	); // listener 
	
	return marker;
}

var histTabContents = null;
var paveHistTabContents = null;
function getHistorical(stationID,st, pave, first)
{
	if(pave == 1)
	{
		var sensor = document.getElementById("pavesensor");
		var type=document.getElementById("pave_historical_sensor").value;
		if(first)
			paveHistTabContents = sensor.innerHTML.substring(0,sensor.innerHTML.length);
	}
	else
	{
		var sensor = document.getElementById("sensor");
		var type=document.getElementById("historical_sensor").value;
		if (first)
			histTabContents = sensor.innerHTML.substring(0,sensor.innerHTML.length);
	}
	var dt1 = document.getElementById("date1").value;	
	var dt2 = document.getElementById("date2").value;
	
		
	GDownloadUrl( 'historical.php?id='+ stationID + '&type=' + type+'&d1='+dt1+'&d2='+dt2+'&start='+st+'&pave='+pave, 
	function(doc)
		{			
			sensor.innerHTML =doc;	
			//refresh
			map.updateInfoWindow(map.getInfoWindow().getTabs());
		}
		);	
}
var divContents =null;
var paveDivContents = null;
function historicalView(stationID,dt, pave)
{	
	if(pave == 1)
	{
		var sensor = document.getElementById("pavesensor");
		paveDivContents = sensor.innerHTML.substring(0,sensor.innerHTML.length);
	}
	else
	{
		var sensor = document.getElementById("sensor");
		divContents = sensor.innerHTML.substring(0,sensor.innerHTML.length);
	}
		GDownloadUrl( 'historical.php?id='+stationID+'&type='+wxmap.mapType+'&dt='+dt+'&pave='+pave, 
	function(doc)
		{
			sensor.innerHTML =doc;	
			map.updateInfoWindow(map.getInfoWindow().getTabs());
		}
		);			
}
function histBack(step, pave)
{
	if(pave ==1)
	{
		var sensor = document.getElementById("pavesensor");
		sensor.innerHTML = (step==1)? paveDivContents: paveHistTabContents;
	}
	else
	{
		var sensor = document.getElementById("sensor");
		sensor.innerHTML = (step==1)? divContents: histTabContents;
	}
	map.updateInfoWindow(map.getInfoWindow().getTabs());
}
function moveGen(code, pave)
{
	var start =	document.getElementById("start");
	var per_page = document.getElementById("per_page");
	var count =	document.getElementById("row_count");
	
	switch(code)
	{
		case 1:
		start.value=0;
		break;
		case 2:
		start.value= Math.max(0,parseInt(start.value) - parseInt(per_page.value));
		break;
		case 3:
		var next = parseInt(start.value) + parseInt(per_page.value);
		start.value= ( next >= count.value)? start.value : next ;
		break;
		case 4:		
		var res = parseInt(count.value)%parseInt(per_page.value);
		res = (res == 0) ? parseInt(per_page.value) : res;
		start.value = parseInt(count.value) - res;
	
		if(start.value < 0)
			start.value=0;
	
		//alert("res: " + res + ", start.value: " + start.value);
		break;
	}	
	stationID = document.getElementById("sta_id").value;
	getHistorical(stationID,start.value, pave);
}
function constructMarkers(doc){
	var iconSize=20;
	var marker=null;
	var xmlDoc = GXml.parse(doc);	
	var markers = xmlDoc.documentElement.getElementsByTagName("marker");
	mgr.clearMarkers();
	deleteMarkers();

	var id;
	var desc;
	var dataInfo;
	var lat;
	var lng;
	var data;
	var dt;
	var point;
	var iconstr;
	var dir;	
	var over;
	var pave;
	var active_counter = 0;
        var failed;
	if(wxmap.mapType=="alert")
	{
		alertStations=markers.length;
		document.getElementById("alertsTriggered").innerHTML=alertStations + " triggered.";
                if(alertStations == 0)
                    document.getElementById("AlertsTab").style.background="#FFFFFF";
	}
	for (var i =0 ; i < markers.length; i++) {
		// obtain the attribues of each marker
		id = markers[i].getAttribute("id");
		desc = markers[i].getAttribute("desc");
		lat = parseFloat(markers[i].getAttribute("lat"));
		lng = parseFloat(markers[i].getAttribute("lng"));
		data = markers[i].getAttribute("data");
		dt = markers[i].getAttribute("dt");
		ds = markers[i].getAttribute("ds");
		pave = markers[i].getAttribute("r");
		active = markers[i].getAttribute("a");		
                failed = markers[i].getAttribute("f");
		if ( i==0) 	TotalStations = markers[0].getAttribute("total");	
		point = new GLatLng(lat,lng);
		iconstr = "DOTS/";        

		switch (wxmap.mapType)
		{
		case "alert":
			iconSize = 24;
			switch(alertID)
			{
				case "1":			
					dataInfo = " Ice Warning";
					iconstr = iconstr + "Alert/ICY.png";
					break;
				case "2":
					iconSize = 30;
                                        switch(data)
                                        {
                                            case "3":
                                                dataInfo = " High Wind Warning";
                                                iconstr = iconstr + "Alert/HIGHWIND.png";
                                                break;
                                            case "2":
                                                dataInfo = " Wind Warning";
                                                iconstr = iconstr + "Alert/WINDWARN.png";
                                                break;
                                            case "1":
                                                dataInfo = " Wind Advisory";
                                                iconstr = iconstr + "Alert/WINDADV.png";
                                                break;
                                        }
					break;
				default:
			}
			break;
		case "temp":
			dataInfo = "Temperature: " + data  + " Fahrenheit";
			iconstr = iconstr + "Temperature/" + data + ".png";
			break;
		case "humidity":
			dataInfo = "Humidity: " + data + " %";
			iconstr = iconstr + "Humidity/" + Math.round(data) + ".png";
			break;
		case "p24":
		case "p01":
			dataInfo = (wxmap.mapType == "p01")? "1h Precipitation: " : "24h Precipitation: ";
			dataInfo += data + " in.";				
			if(data == 0)
			{
				iconstr += "Precip/0.png";
				iconSize = 16;
			}
			else if((data < 0.01) && (data > 0) )
			{
				iconstr += "Precip/0.001.png";
				iconSize = 16;
			}
			else if((data < 1.0) && (data >= 0.01) ) 
			{
				iconSize = 26;
				iconstr += "Precip/" + data + ".png";
			}
			//modified so that icons display exact value but all icons >3 have same color
			else if((data >= 1.0) && (data < 10.0))
			{		
				iconSize = 26;
				iconstr += "Precip/" + data + ".png";
			}
			// corner case
			else
			{
				iconSize = 26;
				iconstr += "Precip/10.0.png";
			}

			break;
		case "wspd":
                        
			dir = markers[i].getAttribute("dir");
			if (data =="" || dir =="")
			{
				break;  //fixed the dash icon bug 5/23/2008 no wind speed data
			}
			data = parseInt(data);
			var intdir = parseInt(dir);
			intdir = parseInt((intdir+5) / 10) * 10;
			sdir = intdir + '';
			point = new GLatLng(lat,lng);
			if (data < 1)
			{
				iconstr = "DOTS/WindIcons/0.png";
			}
			else if (data <50)
			{
				iconstr = "DOTS/WindIcons/" + data + "_" + sdir + ".png";
			}
			else
			{
				iconstr = "DOTS/WindIcons/" + "50" + "_" + sdir + ".png";  
			}               

			if (data<1)
			{
				iconSize = 9;
			}
			else if (data >= 1 && data <=50)
			{
				Length = 10+data;//5+Math.round(Math.LOG2E * Math.log(spd)*5);
				// Sets arrow width
				var Width = Math.ceil(Length / 6)+1;
				iconSize = Length + Width + 6;
			}
			else if (data > 50)
			{
				Length = 80;//5+Math.round(Math.LOG2E * Math.log(70)*5);
				// Sets arrow width
				var Width = Math.ceil(Length / 6)+1;
				//var Width = Length / 6+1;
				var arrowLength = Width;
				iconSize = Length + arrowLength + 6;
			}
			dataInfo =  data + " mph from " + dir + " degrees";	
			break; // case wspd
		case "all":
		case "rwis":
		case "meso":
		case "mad":
		   dataInfo ="";
			iconSize = 12;
			if (active==1)
			{
                                data = (failed == 0) ? "green" : "red";
				active_counter++;
			}
			else 
				data = "grey";
			iconstr +="Stations/"+ds+"_"+ data + ".png";	
			break;
		}
		over =  desc + " " + dataInfo + " Station ID:"+id;         

		var icon = new GIcon();
		icon.iconSize = new GSize(iconSize, iconSize);

		icon.iconAnchor = new GPoint(iconSize/2, iconSize/2);
		icon.infoWindowAnchor = new GPoint(iconSize/2, iconSize/2);
		icon.image = iconstr;
		// finally create the marker here
		var marker = createTabMarker(point,icon,over,id,wxmap.mapType,dt,pave);
		markerbatch.push(marker);           
	}
	mgr.addMarkers(markerbatch,0);       
	mgr.refresh();
	closePopup();
}    

function deleteMarkers()
{
	for(var i = 0; i < markerbatch.length; i++)
	{
		GEvent.removeListener(markerbatch[i].clickhandle);
		delete(markerbatch[i]);
	}

	markerbatch = new Array();
}


/*close the dynamic popup window*/
function closePopup()
{
	document.getElementById("dwindow").style.display="none";
	document.getElementById("dwindow").style.visibility="hidden";

	if(document.getElementById("dwindow").style.display == "none")
		closewin();
}

/*show the dynamic popup window*/
function Popup(){
	document.getElementById("dwindow").style.display="block";
	document.getElementById("dwindow").style.visibility="visible";

}

// read the timestamp data for forecast display
function forecast_timestamp()
{	
var logic=false;
if (Tabbuttons["Forecast"]|| Tabbuttons["Alerts"]) logic=true;
if (!logic) return; // if current or stations display is not active, do nothing and stop the loop
	//debugger;
	// code for I
	
	if (window.ActiveXObject)	
	{
		theDataDoc = new ActiveXObject("microsoft.xmldom");
	}
	// code for Mozilla, Firefox, Opera, etc.
	else if (document.implementation && document.implementation.createDocument)
	{
		theDataDoc=document.implementation.createDocument("","",null);
	}
	else
	{
		alert('Your browser cannot handle this script');
	}

	theDataDoc.async = false;// this line is critical to make sure document is loaded before continuing
	theDataDoc.onreadystatechange = verify;
	theDataDoc.load(wxmap.weburl+"/TIMESTAMPS.xml"+ "?" + new Date().getTime());
	var  dateTimeObj = theDataDoc.getElementsByTagName("datetime");
	for (i = 1; i < dateTimeObj.length; i++)
	{
		forecastTimes[i-1]=dateTimeObj[i].firstChild.nodeValue;
	}
	dateTimeObj = theDataDoc.getElementsByTagName("gmttime");
	for (i = 0; i < dateTimeObj.length; i++)
	{
		forecastTimesGMT[i]=dateTimeObj[i].firstChild.nodeValue;
	}
	//if (Tabbuttons["Alerts"]) return;
	updateTimeDropDownMenu();
	setTimeout("forecast_timestamp()",period);
}

function current_timestamp()  //read and show timestamp on the html with interval of 5 minutes.
{
	if (!Tabbuttons["Current"] && !Tabbuttons["Stations"]) return; // if current or stations display is not active, do nothing and stop the loop
	//debugger;
	// code for I
	if (window.ActiveXObject)	
	{
		theDataDoc = new ActiveXObject("microsoft.xmldom");
	}
	// code for Mozilla, Firefox, Opera, etc.
	else if (document.implementation && document.implementation.createDocument)
	{
		theDataDoc=document.implementation.createDocument("","",null);
	}
	else
	{
		alert('Your browser cannot handle this script');
	}

	theDataDoc.async = false;// this line is critical to make sure document is loaded before continuing
	theDataDoc.onreadystatechange = verify;
	theDataDoc.load(wxmap.weburl+"/CurrentTime.xml");
	var dateTimeObj = theDataDoc.getElementsByTagName("datetime");
	wxmap.currentTime = dateTimeObj[0].childNodes[0].nodeValue;
	theDataDoc.load(wxmap.weburl+"/ahpstime.xml");
	dateTimeObj = theDataDoc.getElementsByTagName("ahpstime");
	if(dateTimeObj != null)
	{
		wxmap.ahpsTime = dateTimeObj[0].childNodes[0].nodeValue;
	}
        
    /* will read nwstime in getNDFDalert()
	theDataDoc.load(wxmap.weburl+"/nwstime.xml"+ "?" + new Date().getTime());
	dateTimeObj = theDataDoc.getElementsByTagName("nwstime");
	if(dateTimeObj != null)
	{
		wxmap.nwsTime = dateTimeObj[0].childNodes[0].nodeValue;
	}
	*/
	document.getElementById("mapName").innerHTML=wxmap.mapTitle+wxmap.currentTime;
	
	updateTimeDropDownMenu();
	setTimeout("current_timestamp()",period);
}

function verify()  //used for xml file ready check.   
{
	if (theDataDoc.readyState != 4)
	{
		return false;
	}
}

function rtrim(str) {
	return str.replace(/\s+$/, '');
}



function SaveThisLink()
{
	wxmap.lat=roundNumber(parseFloat(map.getCenter().lat()),3);
	wxmap.lng=roundNumber(parseFloat(map.getCenter().lng()),3);
	wxmap.z=map.getZoom();
	var Address=location.href.split('?');
	var URL=Address[0]+"?lat="+wxmap.lat.toString()+"&lng="+wxmap.lng.toString()+"&z="+wxmap.z.toString()+"&tb="+wxmap.tabSelected;
	// Save the Station ID if a marker popup is open - m
	if (openMarker)
	{
		URL +="&popup="+ openMarker.getTitle().split("Station ID:")[1];
	}	
	
	if (wxmap.tabSelected=="Current")
	{
	URL+="&i="+wxmap.CurrentSelected;
	} 
	else if (wxmap.tabSelected=="Forecast")
	{
	URL+="&i="+wxmap.ForecastSelected;
	}
	else if (wxmap.tabSelected=="Stations")
	{
	URL+="&i="+wxmap.StationsSelected;
	}
	else if(wxmap.tabSelected=="Alerts")
	{
		URL+="&i=0&alertType="+alertType+"&alertID="+alertID;



		if(alertID==2)
		{
			URL += "&adv=" + selectWind[0] + "&watch=" + selectWind[1] + "&warning=" + selectWind[2];
		}
	}
	//document.location=URL;
    document.getElementById("currentLocation").style.display="block";
	document.getElementById("currentLocation").style.zindex=204;
	inner_html_string="<FORM NAME=\"SaveLinkForm\">";
	inner_html_string+="<input type=\"text\" name=\"linkinput\" size=\"55\" value=\"";
	inner_html_string+=URL;
	inner_html_string+="\" />";
	inner_html_string+="</FORM>";
	document.getElementById("currentLocationContent").innerHTML=inner_html_string;
	document.SaveLinkForm.linkinput.focus();
	document.SaveLinkForm.linkinput.select();
	
}

function SaveAsBookmark()
{
    if(navigator.appName == "Netscape")
    {
//        var ios = Components.classes["@mozilla.org/network/io-service;1"]
//                        .getService(Components.interfaces.nsIIOService);
//        var uri = ios.newURI(document.SaveLinkForm.linkinput.value, null, null);
//        var newBkmkId = bmsvc.insertBookmark(newFolderId, uri, -1, "");
        window.sidebar.addPanel("WeatherShare", document.SaveLinkForm.linkinput.value, "");
    }
    else
    {
        window.external.AddFavorite(document.SaveLinkForm.linkinput.value, "WeatherShare");
    }
}

function CloseSaveLink()
{
	document.getElementById("currentLocation").style.display="none";
}


function zoomToCity(index) 
{
	resetDistrictZoom();
	resetCountyZoom();
	resetCountyRoadZoom();
	resetDistrictRoadZoom();
	
	map.setCenter(new GLatLng(CityArray[index][0],CityArray[index][1]),
					CityArray[index][2]);
	wxmap.zoomtoselected="City="+document.getElementById("selectCity").options[parseInt(index)+1].text;
}

function zoomToDistrictRoad(index)
{
	resetDistrictZoom();
	resetCityZoom();
	resetCountyZoom();
	resetCountyRoadZoom();
	
	map.setCenter(new GLatLng(DistrictRoadArray[index][0],DistrictRoadArray[index][1]),
					parseInt(DistrictRoadArray[index][2]));
	var selectedstring = document.getElementById("selectRoad2").options[parseInt(index)+1].text.match(/District (\d+) - \D+(\d+)/);
	wxmap.zoomtoselected="District="+selectedstring[1]+"&Highway="+selectedstring[2];
	
}


function zoomToCountyRoad(index)
{
	resetDistrictZoom();
	resetCityZoom();
	resetCountyZoom();
	resetDistrictRoadZoom();
	map.setCenter(new GLatLng(CountyRoadArray[index][0],CountyRoadArray[index][1]),
					CountyRoadArray[index][2]);
	var selectedstring = document.getElementById("selectRoad").options[parseInt(index)+1].text.match(/(\D+)-\D+(\d+)/);
	wxmap.zoomtoselected="County="+selectedstring[1]+"&Highway="+selectedstring[2];
	
}

function zoomToDistrict(district)
{
	resetCityZoom();
	resetCountyRoadZoom();
	resetDistrictRoadZoom();
	resetCountyZoom();
	switch(district)
	{
	case '1':
		map.setCenter(new GLatLng(40.387, -123.472), 7);
		break;
	case '2':
		map.setCenter(new GLatLng(40.766, -122.85), 8);
		break;
	case '3':
		map.setCenter(new GLatLng(39.188, -121.477), 8);
		break;
	case '4':
		map.setCenter(new GLatLng(37.959, -122.141), 8);
		break;
	case '5':
		map.setCenter(new GLatLng(35.791, -120.747), 7);
		break;
	case '6':
		map.setCenter(new GLatLng(36.385, -119.300), 7);
		break;
	case '7':
		map.setCenter(new GLatLng(34.350, -118.512), 9);
		break;
	case '8':
		map.setCenter(new GLatLng(34.7, -116.1), 8);
		break;
	case '9':
		map.setCenter(new GLatLng(36.982, -117.246), 7);
		break;
	case '10':
		map.setCenter(new GLatLng(37.812, -120.623), 8);
		break;
	case '11':
		map.setCenter(new GLatLng(33.033, -116.105), 8);
		break;
	case '12':
		map.setCenter(new GLatLng(33.711, -117.773), 10);
		break;
	default:
		map.setCenter(new GLatLng(37.000, -120.100), 6);
	}
	wxmap.zoomtoselected="District="+district;
}

function zoomToCounty(countyname) 
{
	resetDistrictZoom();
	resetCityZoom();
	resetCountyRoadZoom();
	resetDistrictRoadZoom();
	wxmap.zoomtoselected="County="+countyname;
	switch(countyname)
	{
	case 'Alameda':
		map.setCenter(new GLatLng(37.625, -121.96), 10);
		break    
	case 'Alpine':
		map.setCenter(new GLatLng(38.60, -119.88), 10);
		break
	case 'Amador':
		map.setCenter(new GLatLng(38.49, -120.57), 9);
		break
	case 'Butte':
		map.setCenter(new GLatLng(39.65, -121.61), 10);
		break
	case 'Calaveras':
		map.setCenter(new GLatLng(38.25, -120.53), 10);
		break
	case 'Colusa':
		map.setCenter(new GLatLng(39.18, -122.205), 10);
		break
	case 'Contra Costa':
		map.setCenter(new GLatLng(37.99, -121.98), 10);
		break
	case 'Del Norte':
		map.setCenter(new GLatLng(41.75, -123.89), 10);
		break
	case 'El Dorado':
		map.setCenter(new GLatLng(38.79, -120.49), 9);
		break
	case 'Fresno':
		map.setCenter(new GLatLng(36.72, -119.67), 8);
		break
	case 'Glenn':
		map.setCenter(new GLatLng(39.61, -122.37), 10);
		break
	case 'Humboldt':
		map.setCenter(new GLatLng(40.83, -123.76), 8);
		break
	case 'Imperial':
		map.setCenter(new GLatLng(33.05, -115.37), 9);
		break
	case 'Inyo':
		map.setCenter(new GLatLng(36.421, -117.334), 8);
		break
	case 'Kern':
		map.setCenter(new GLatLng(35.55, -119.01), 8);
		break
	case 'Kings':
		map.setCenter(new GLatLng(36.13, -119.89), 10);
		break
	case 'Lake':
		map.setCenter(new GLatLng(39.07, -122.82), 9);
		break
	case 'Lassen':
		map.setCenter(new GLatLng(40.66, -120.63), 9);
		break
	case 'Los Angeles':
		map.setCenter(new GLatLng(34.36, -118.21), 9);
		break
	case 'Madera':
		map.setCenter(new GLatLng(37.33, -119.73), 9);
		break
	case 'Marin':
		map.setCenter(new GLatLng(38.04, -122.63), 10);
		break
	case 'Mariposa':
		map.setCenter(new GLatLng(37.61, -119.95), 9);
		break
	case 'Mendocino':
		map.setCenter(new GLatLng(39.4, -123.49), 9);
		break
	case 'Merced':
		map.setCenter(new GLatLng(37.18, -120.73), 9);
		break
	case 'Modoc':
		map.setCenter(new GLatLng(41.6, -120.69), 9);
		break
	case 'Mono':
		map.setCenter(new GLatLng(37.82, -118.92), 9);
		break
	case 'Monterey':
		map.setCenter(new GLatLng(36.27, -121.275), 9);
		break
	case 'Napa':
		map.setCenter(new GLatLng(38.48, -122.34), 10);    
		break
	case 'Nevada':
		map.setCenter(new GLatLng(39.32, -120.68), 9);
		break
	case 'Orange':
		map.setCenter(new GLatLng(33.7, -117.77), 10);
		break
	case 'Placer':
		map.setCenter(new GLatLng(39.11, -120.77), 9);
		break
	case 'Plumas':
		map.setCenter(new GLatLng(39.985, -120.79), 9);
		break
	case 'Riverside':
		map.setCenter(new GLatLng(33.59, -116.18), 8);
		break
	case 'Sacramento':
		map.setCenter(new GLatLng(38.47, -121.39), 10);
		break
	case 'San Benito':
		map.setCenter(new GLatLng(36.6, -121.15), 9);
		break
	case 'San Bernardino': 
		map.setCenter(new GLatLng(34.990351, -116.233725), 8);
		break 
	case 'San Diego':
		map.setCenter(new GLatLng(33.07, -116.73), 9);
		break
	case 'San Francisco':
		map.setCenter(new GLatLng(37.747, -122.44), 11);
		break
	case 'San Joaquin':
		map.setCenter(new GLatLng(37.94, -121.33), 10);
		break
	case 'San Luis Obispo':
		map.setCenter(new GLatLng(35.34, -120.53), 9);
		break
	case 'San Mateo':
		map.setCenter(new GLatLng(37.413, -122.37), 10);
		break
	case 'Santa Barbara':
		map.setCenter(new GLatLng(34.733, -120.078), 9);
		break
	case 'Santa Clara':
		map.setCenter(new GLatLng(37.2, -121.72), 9);
		break
	case 'Santa Cruz': 
		map.setCenter(new GLatLng(37.08, -122), 10);
		break
	case 'Shasta':
		map.setCenter(new GLatLng(40.8, -122.14), 8);
		break
	case 'Sierra':
		map.setCenter(new GLatLng(39.57, -120.56), 9);
		break
	case 'Siskiyou':
		map.setCenter(new GLatLng(41.65, -122.64), 8);
		break
	case 'Solano':
		map.setCenter(new GLatLng(38.24, -122), 9);
		break
	case 'Sonoma':
		map.setCenter(new GLatLng(38.47, -122.98), 9);
		break
	case 'Stanislaus':
		map.setCenter(new GLatLng(37.62, -121), 9);
		break
	case 'Sutter':
		map.setCenter(new GLatLng(39.01, -121.69), 10);
		break
	case 'Tehama':
		map.setCenter(new GLatLng(40.13, -122.27), 8);
		break
	case 'Trinity':
		map.setCenter(new GLatLng(40.61, -123.34), 8);
		break
	case 'Tulare':
		map.setCenter(new GLatLng(36.242, -118.817), 9);
		break
	case 'Tuolumne':  
		map.setCenter(new GLatLng(38.04, -119.92), 9);
		break
	case 'Ventura':
		map.setCenter(new GLatLng(34.53, -119.12), 9);
		break
	case 'Yolo':
		map.setCenter(new GLatLng(38.72, -121.95), 9);
		break
	case 'Yuba':
		map.setCenter(new GLatLng(39.28, -121.318), 10);
		break
	default:
		map.setCenter(new GLatLng(37.0000, -120.100), 6);
	}
	//updateCountyOverlay(countyname);
}
function enforceMaxLength(obj, maxLength,label)
{
   if (obj.value.length > maxLength)
    obj.value = obj.value.substring(0,maxLength);
	// update the counter
	var elem = document.getElementById("textcounter");
	elem.innerHTML= maxLength - obj.value.length;	
	return true;
}
var tabContents=null;
function OpenUserComments(id,savetab)
{
	if(savetab)
	tabContents = map.getInfoWindow().getTabs(); // Save a reference to the current content
	var doc = "<div class='popup'><form onSubmit='javascript:SubmitComments(this,"+id+"); return false' action=''><b>Weather Station Problem Report Form</b><br><br>Classification:&nbsp;&nbsp;<select style='font-size:8pt; font-face:calibri' name='typeselect'><option>Wrong location</option><option>Wrong sensor data</option><option>Other</option></select><br><br>Email address: <br><input type='text' style='font-size:8pt; font-face:calibri' name='emailinput'><br><br>Description of the problem:<br><textarea style='font-size:8pt; font-face:calibri' name='feedback' cols='29' rows='10' onkeypress='return enforceMaxLength(this,295)' ></textarea><br><b><span id='textcounter'>295</span></b> characters remaining<br><br><input align='center' style='font-size:8pt; font-face:calibri' type='submit' value='Submit Feedback'></form><br><a href='javascript:CloseUserComments()'>Return back to sensor display</a></div>";
//	tab = ;
	map.updateInfoWindow(new Array(new GInfoWindowTab('General',doc)));							  
	//document.getElementById("UserComments").style.display="block";
	//document.getElementById("StationInfo").innerHTML="<strong>ID:</strong>"+id+"   <strong>Station:</strong>"+name;
}
function CloseUserComments()
{
	map.updateInfoWindow(tabContents);
}

function SubmitComments(form,id)
{
 	var para='id='+id+'&type='+form.typeselect.selectedIndex+'&msg='+form.feedback.value+'&email='+form.emailinput.value; 
	GDownloadUrl("error_report.php", 
                function(doc){					
						tab = new GInfoWindowTab('General',doc);
						map.updateInfoWindow(new Array(tab));
					},para
					); 
}

function markerPopup(StationID)
{
	// loop through the markerbatch to find the reference to the station marker we want 
	for (var i = 0; i < markerbatch.length; i++)
	{
		if (StationID == markerbatch[i].getTitle().split("Station ID:")[1])
		{
			GEvent.trigger(markerbatch[i],"click");
			return;
		}
	}	
	//alert("StationID "+ StationID+" couldn't be found"); 	
}

//Method to build icons that lay on top of NWS Observed 24 hour Precipitation overlays
function consHwPrecipMarkers (doc)
{
	var xmlDoc = GXml.parse(doc);
	var markers = xmlDoc.documentElement.getElementsByTagName("marker");
	deleteMarkers();
	var iconSize;
	mgr.clearMarkers();
	var desc,lat, lng, dt,data,mp,point,iconstr,county;
	for (var i = 0; i < markers.length; i++){
		desc = markers[i].getAttribute("desc");
		lat = parseFloat(markers[i].getAttribute("lat"));
		lng = parseFloat(markers[i].getAttribute("lng"));
		county = markers[i].getAttribute("c");
		dt = markers[i].getAttribute("dt");
		data = markers[i].getAttribute("data");
		mp = markers[i].getAttribute("mp");
		point = new GLatLng(lat, lng);
		iconstr = "DOTS/";
		//fix bug of value 9999 missing data
			if(data < 0)
			{
				iconstr += "Precip/-1.png";
				iconSize = 16;
				data="Missing data";
			}
			else if(data == 0)
			{
				iconstr += "Precip/0.png";
				iconSize = 16;
			}
			else if((data < 0.01) && (data > 0) )
			{
				iconstr += "Precip/0.001.png";
				iconSize = 16;
			}
			else if((data < 1.0) && (data >= 0.01) ) 
			{
				iconSize = 26;
				iconstr += "Precip/" + data + ".png";
			}
			//modified so that icons display exact value but all icons >3 have same color
			else if((data >= 1.0) && (data < 10.0))
			{		
				iconSize = 26;
				iconstr += "Precip/" + data + ".png";
			}
			// corner case
			else
			{
				iconSize = 26;
				iconstr += "Precip/10.0.png";
			}
		var htmlTag = "<font size=\"2\" face=\"calibri\"><b>Highway: " + desc + " County: "+county+" Milepost:" + mp + "</b><br>Latitude: " + lat + " Longitude: " + lng + "<br>NWS Observed 24 Precipitation for " + wxmap.ahpsTime +":</font><br><br><font size =\"4\">";

		if (data=="Missing data")	htmlTag += " " + data;
		else htmlTag += " " + data+" in.";

		var over = "Highway: " + desc + " County: "+county+" Milepost: " + mp + " NWS Observed 24 hour Precipitation for " + wxmap.ahpsTime ;
		var icon = new GIcon();
		icon.iconSize = new GSize(iconSize, iconSize);
		icon.iconAnchor = new GPoint(iconSize / 2, iconSize / 2);
		icon.infoWindowAnchor = new GPoint(iconSize / 4, iconSize / 4);
		icon.image = iconstr;
		var marker = createMarker(point, htmlTag, icon, over);
		markerbatch.push(marker);
	}

	mgr.addMarkers(markerbatch, 6, 17);
	mgr.refresh();
	closePopup();
}

//very simple controls for navigating through time list in forecast tab 
function FCNextTime(dir) {
	var obj=document.getElementById("selectTime");
    var total = obj.length - 1;
    var sel = obj.selectedIndex;
	document.getElementById("PrevTimeButton").onclick = null;
	document.getElementById("NextTimeButton").onclick = null;

    if (dir < 0) {
        if (sel > 0) {
            obj.selectedIndex = sel - 1;
            changeTime(obj.options[obj.selectedIndex].value,true);
			
        }
    } else {
        if (sel < total) {
            obj.selectedIndex = sel + 1;
            changeTime(obj.options[obj.selectedIndex].value,true);
        }
    }
}

//Create a context menu
function ContextMenu(oMap){this.initialize(oMap);}

//Construct the DOM tree of the menu
ContextMenu.prototype.initLink = function(oMap){
	var that=this;
	a_link = document.createElement("li");
	a_link.innerHTML="<a href='javascript:void(0);'>&raquo;Zoom In  </a>";
	GEvent.addDomListener(a_link, 'click', function() {
		that.map.zoomIn();
		that.contextmenu.style.display='none';
	});
	this.ul_container.appendChild(a_link);
	
	a_link = document.createElement("li");
	a_link.innerHTML="<a href='javascript:void(0);'>&raquo;Zoom Out  </a>";
	GEvent.addDomListener(a_link, 'click', function() {
		that.map.zoomOut();
		that.contextmenu.style.display='none';
	});
	this.ul_container.appendChild(a_link);
	
	a_link = document.createElement("li");
	a_link.innerHTML="<a href='javascript:void(0);'>&raquo;Zoom Here  </a>";
	GEvent.addDomListener(a_link, 'click', function() {
		var point = that.map.fromContainerPixelToLatLng(that.clickedPixel);
		that.map.zoomIn(point,true);
		that.contextmenu.style.display="none";
	});
	this.ul_container.appendChild(a_link);
	
	a_link = document.createElement("li");
	a_link.innerHTML="<a href='javascript:void(0);'>&raquo;Center Map Here  </a>";
	GEvent.addDomListener(a_link, 'click', function() {
		var point = that.map.fromContainerPixelToLatLng(that.clickedPixel);
		that.map.panTo(point);
		that.contextmenu.style.display="none";
	});
	this.ul_container.appendChild(a_link);
	
	/*a_link = document.createElement("li");
	a_link.innerHTML="<a href='javascript:void(0);'>&raquo;Drag Zoom  </a>";
	GEvent.addDomListener(a_link, 'click',  function(){});
	this.ul_container.appendChild(a_link);
    */
}
ContextMenu.prototype.bind = function(method) {
	var self = this;
	var opt_args = [].slice.call(arguments, 1);
	return function() {
		var args = opt_args.concat([].slice.call(arguments));
		return method.apply(self, args);
	}
}

//The object 'constructor'
ContextMenu.prototype.initialize = function(oMap){
	this.map = oMap;
	var that=this;
	
	this.contextmenu = document.createElement("div");
	this.contextmenu.style.display="none";
//CSS class name of the menu
	this.contextmenu.className="contextmenu";
	this.ul_container = document.createElement("ul");
	this.ul_container.id="context_menu_ul";
	this.contextmenu.appendChild(this.ul_container);	
	this.initLink();
	this.map.getContainer().appendChild(this.contextmenu);	

//Event listeners that will interact with our context menu
	GEvent.addListener(oMap,"singlerightclick",function(pixel,tile) {
		that.clickedPixel = pixel;
		var x=pixel.x;
		var y=pixel.y;
//Prevents the menu to go out of the map margins, in this case the expected menu size is 150x110
		if (x > that.map.getSize().width - 160) { x = that.map.getSize().width - 160 }
		if (y >that.map.getSize().height - 120) { y = that.map.getSize().height - 120 }

		var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));  
		pos.apply(that.contextmenu);
		that.contextmenu.style.display = "";
	});	
	GEvent.addListener(oMap, "move", function() {
		that.contextmenu.style.display="none";
	});
	GEvent.addListener(oMap, "click", function(overlay,point) {
		that.contextmenu.style.display="none";
	});	
}

function getSensorList(sel)
{
        if(document.getElementById("timelist"))
                document.getElementById("control_panel").removeChild(document.getElementById("timelist"));
	
	if(document.getElementById("adjustMenu"))
		document.getElementById("control_panel").removeChild(document.getElementById("adjustMenu"));

	var  County= sel.options[sel.selectedIndex].value;
	//document.getElementById('selectSensor').options.length = 0;	// Empty location select box
	if(County.length>0){
     var obj=document.getElementById('selectAlertType');
    	if(obj.options.length >0)
		{
		alertType=obj.options[obj.selectedIndex].value;
 		var para='type='+alertType+'&alertIDs=';
		if(alertInfos.match(/\d/g) != null)
			para+=alertInfos.match(/\d/g).toString();
		GDownloadUrl("alertSensors.php", 
                function(doc){				

						document.getElementById("selectAlertCriteria").innerHTML=doc;
						if(alertType=="Current" && parseInt(alertID) <=2 && parseInt(alertID) >0)
						{
							document.getElementById("selectSensor").options[alertID].selected=true;
							
							getSensorType(document.getElementById("selectSensor"));
						}
						else if(alertType=="Forecast" && parseInt(alertID) > 2 && parseInt(alertID) <= 7)
						{
							if(alertID == 3)
							    document.getElementById("selectSensor").options[1].selected=true;
                                                        else
							    document.getElementById("selectSensor").options[alertID - 3].selected=true;
							getSensorType(document.getElementById("selectSensor"));
						}
					},para
					); 
		}

		
		document.getElementById("zoomControlPanesBackground").style.height = "150px";
	}
        else
        {
            alertID = null;
            alertType = null;
            mgr.clearMarkers();
	    map.clearOverlays();
            document.getElementById("selectSensor").innerHTML = "<option selected=\"selected\" value=\"\">select a time frame</option>";
            wxmap.mapTitle = "Alerts";
            wxmap.mapTime=wxmap.currentTime;
            update_maptitle();
            document.getElementById("alertsTriggered").innerHTML = "0 triggered.";
        }
}

function getSensorType(sel)
{
	if(document.getElementById("selectTime"))
		document.getElementById("control_panel").removeChild(document.getElementById("timelist"));
        
	if(document.getElementById("adjustMenu"))
		document.getElementById("control_panel").removeChild(document.getElementById("adjustMenu"));


	document.getElementById("AlertsTab").style.background = "#FFFFFF";
	alertID= sel.options[sel.selectedIndex].value;

	if(alertID == 3 || alertID == 6 || alertID == 4)
	{
		var htmlstring = '<div id="timelist" class="timelist" style="margin-left: 27px; overflow: visible;"><table><tbody><tr><td>';
		htmlstring += '<select id="selectTime" style="width: 180px;" onchange="changeTime(this.selectedIndex, true)">';
		htmlstring += '<option selected="selected" value="0">' + forecastTimes[0] + '</option>';
		for(var i = 1; i < 8; i++)
		{
			htmlstring += '<option value="' + i + '">' + forecastTimes[i] + '</option>';
		}
		htmlstring += "</select></td><td><div id='PrevTimeButton' class='buttondisabled'><</div></td><td><div id='NextTimeButton' class='button' onclick='FCNextTime(1)'>></div></td></tr></tbody></table></div>";
		

	    var selected = document.getElementById("selectSensor").options.selectedIndex; 
	    document.getElementById("control_panel").innerHTML += htmlstring;
		document.getElementById("selectAlertType").options[2].selected=true;
		document.getElementById("selectSensor").options[selected].selected=true;
	    
	    wxmap.mapTime=forecastTimes[0];
	    
	    document.getElementById("zoomControlPanesBackground").style.height = "150px";
	}    

	// adjustable wind warning
	else if(alertID == 2)
	{
		//enable reload of NWSalert
		wxmap.nwsTime=null;
	
		// cookie will be null or have a 11,22,33 pair
	       var advisory=readCookie("Advisory");		
               var watch=readCookie("Watch"); 
               var warning=readCookie("Warning");
		// found a cookie
		if(advisory!=null &&watch!=null &&warning!=null)
		{
			selectWind[0] = readCookie("Advisory");
			selectWind[1] = readCookie("Watch");
			selectWind[2] = readCookie("Warning");
		}
		else if (!warningInURL)
		{
			selectWind[0] = 0;
			selectWind[1] = 0;
			selectWind[2] = 0;
		}



		var htmlstring = '<div id="adjustMenu" style="margin-left: 0px; overflow: visible; font-size:14px">';
		htmlstring += '<table border="0px"><tr align="center"><td>Advisory</td><td>Watch&nbsp&nbsp&nbsp</td><td>Warning</td></tr>';
		htmlstring += '<tr align="center">';
		
		// wind advisory change
		htmlstring += '<td width="90px"><select id="selectAdvisory" style="width: 80px;" onchange="adjustWind(this.selectedIndex + 9, 0)">';
		htmlstring += '</select></td>';
		htmlstring += '<td width="90px"><select id="selectWatch" style="width: 80px;" onchange="adjustWind(this.selectedIndex + 19, 1)">';
		htmlstring += '</select></td>';
		htmlstring += '<td width="90px"><select id="selectWarning" style="width: 80px;" onchange="adjustWind(this.selectedIndex + 29, 2)">';
		htmlstring += '</select></td>';


		document.getElementById("zoomControlPanesBackground").style.height = "180px";
		var selected = document.getElementById("selectSensor").options.selectedIndex;
		document.getElementById("control_panel").innerHTML += htmlstring;
		document.getElementById("selectAlertType").options[1].selected = true;
		document.getElementById("selectSensor").options[selected].selected=true;


		//alert("about");
		// wind advisory
		if(selectWind[0]==0)
		{
			document.getElementById("selectAdvisory").options[0] = new Option("( select )");
		}
		else
		{
			document.getElementById("selectAdvisory").options[0] = new Option(selectWind[0]);
		}
		for(var i = 10; i < 31; i++)
		{    
			document.getElementById("selectAdvisory").options[(i-9)] = new Option(i);
		}
		
		// wind watch
		if(selectWind[1]==0)
		{
			document.getElementById("selectWatch").options[0] = new Option("( select )");
		}
		else
		{
			document.getElementById("selectWatch").options[0] = new Option(selectWind[1]);
		}
		for(var i = 20; i < 41; i++)
		{  
			document.getElementById("selectWatch").options[(i-19)] = new Option(i);
		}

		// wind warning
		if(selectWind[2]==0)
		{
			document.getElementById("selectWarning").options[0] = new Option("( select )");
		}
		else
		{
			document.getElementById("selectWarning").options[0] = new Option(selectWind[2]);
		}
		for(var i = 30; i < 51; i++)
		{  
			document.getElementById("selectWarning").options[(i-29)] = new Option(i); 
		}
		

		// drop down the control panel box so it fits 
		//document.getElementById("zoomControlPanesBackground").style.height = "180px";
		//var selected = document.getElementById("selectSensor").options.selectedIndex;
		//document.getElementById("control_panel").innerHTML += htmlstring;		
		//document.getElementById("selectAlertType").options[1].selected = true;
		//document.getElementById("selectSensor").options[selected].selected=true;

		wxmap.mapTime=wxmap.currentTime;
	}
	else
	{
		wxmap.mapTime=wxmap.currentTime;
		document.getElementById("zoomControlPanesBackground").style.height = "150px";
	}
        
	
	// clear any overlays and markers showing
	map.clearOverlays();
	mgr.clearMarkers();

	callviewport_stations();

	if (alertType=="Current") //reload if alert type is current or crosswind alert
	{
		autorefreshed=true;	
	}
	else
	{
		autorefreshed=false;
	}

	alertHTML=document.getElementById("control_panel").innerHTML;
	if(alertType=="Forecast" && document.getElementById("alertsTriggered") && alertID != 3)
	{
		document.getElementById("alertsTriggered").innerHTML="";
		
	}

	//update_legend();
	
	wxmap.mapTitle = document.getElementById("selectAlertType").options[document.getElementById("selectAlertType").options.selectedIndex].text + ":";
	wxmap.mapTitle += document.getElementById("selectSensor").options[document.getElementById("selectSensor").selectedIndex].text+"  ";
	update_maptitle();
}

function adjustWind(val, form)
{
	//alert("AdjustWind: val=" + val + ",  form=" + form);

	// remember selection
	selectWind[form] = val;

	//var inner = '<option selected="selected">' + val + '</option>';

	// rewrite dropdown choices
	if(form==0)
	{
		var adv_menu = document.getElementById("selectAdvisory");
		adv_menu.options.length = 0;

		adv_menu.options[0] = new Option(val);

		for(i=10;i<31;i++)
			adv_menu.options[(i-9)] = new Option(i);
	}
	else if(form==1)
	{
		var watch_menu = document.getElementById("selectWatch");
		watch_menu.options.length = 0;

		watch_menu.options[0] = new Option(val);

		for(i=20;i<41;i++)
			watch_menu.options[(i-19)] = new Option(i);
	}
	else if(form==2)
	{
		var warning_menu = document.getElementById("selectWarning");
		warning_menu.options.length = 0;

		warning_menu.options[0] = new Option(val);

		for(i=30;i<51;i++)
			warning_menu.options[(i-29)] = new Option(i);
	}


	// when all 3 choices have been selected, then we pass it off for displaying
	if(selectWind[0] != 0 && selectWind[1] != 0 && selectWind[2] != 0)
	{
		if(selectWind[0] < selectWind[1] && selectWind[1] < selectWind[2])
		{
			//alert("Setting cookie: " + selectWind[0] + "," + selectWind[1] + "," + selectWind[2]);
			// remember user preference
			
			setCookie(selectWind[0], selectWind[1], selectWind[2]); 

			callviewport_stations();
		}
		else
		{
			alert("Advisory must be less than Watch value, and Watch value must be less than Warning.");
			if(document.getElementById("dwindow").style.display != "none")
				closePopup();
		}
	} 
}

function constructAdjustableWindMarkers(doc)
{
	var xmlDoc = GXml.parse(doc);
	var markers = xmlDoc.documentElement.getElementsByTagName("marker");
	var lat, lng, point, iconstr, over, iconSize, wsp, dir, latest, sensorName, name, source, cat;
	
	var numAdv = 0;
	var numWatch = 0;
	var numWarning = 0;

	// erase old markers
	mgr.clearMarkers();
	deleteMarkers();
	
	alertStations=markers.length;
	document.getElementById("alertsTriggered").innerHTML=alertStations + " triggered."
 	   document.getElementById("AlertsTab").style.background="#FFFFFF";
	
	for (var i = 0; i < markers.length; i++)
	{
		id  =parseFloat(markers[i].getAttribute("stationid"));
		lat = parseFloat(markers[i].getAttribute("lat"));
		lng = parseFloat(markers[i].getAttribute("lng"));	
		wsp = markers[i].getAttribute("wsp");
		//wsp = Math.round(wsp);
		wgust = markers[i].getAttribute("wgust");
		latest = markers[i].getAttribute("latest");
		sensorName = markers[i].getAttribute("sName");
		source = markers[i].getAttribute("source");
		cat = markers[i].getAttribute("category");
		pave = markers[i].getAttribute("r");
		iconSize = 30;
		
		// count alerts triggered
		if(cat == "Advisory")
		{
			numAdv++;
			iconstr = "DOTS/Alert/WINDADV.png";
		}
		else if(cat == "Watch")
		{
			numWatch++;
			iconstr = "DOTS/Alert/WINDWARN.png";
		}
		else if(cat == "Warning")
		{
			numWarning++;
			iconstr = "DOTS/Alert/HIGHWIND.png";
		}

		point = new GLatLng(lat, lng);

       // display string when mouseover
		var over = "Alert: " + cat;
		
		// create icon 
		var icon = new GIcon();
		icon.iconSize = new GSize(iconSize, iconSize);
		icon.iconAnchor = new GPoint(iconSize / 2, iconSize / 2);
		icon.infoWindowAnchor = new GPoint(iconSize / 4, iconSize / 4);
		icon.image = iconstr;

		// create marker and add it to the array we will display
		//var marker = createTabMarker(point, htmlTag, icon, over);
		var marker = createTabMarker(point,icon,over,id,"wspd",latest,pave);
		markerbatch.push(marker);		
	}

	// display markers and close the loading popup
	mgr.addMarkers(markerbatch, 6);
	mgr.refresh();
	
	closePopup();
}

function setCookie(val_1, val_2, val_3)
{
	// cookie that will expire in a month
	createCookie("Advisory",val_1,365) ;
	createCookie("Watch",val_2,365) ;
	createCookie("Warning",val_3,365) ;
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}


function testAlert()
{
	if(alertID == null ||alertID==5 ||alertID==7)
        {
            return;
        }
	
	docname = "alertgen.php?&NElat="+NElat0+"&NElng="+NElng0+
				"&SWlat=" +SWlat0 + "&SWlng="+SWlng0;
	if(parseInt(alertID) > 2)
	{
		docname+="&alertType=Forecast&start='"+ forecastTimesGMT[0] + "'" +
				"&ml=" + map.getZoom();
	}
	else
	{
		docname+="&alertType=Current";
	}
	docname+="&alertID="+alertID+"&alertTest=true";
	GDownloadUrl(docname, setAlertTriggered);

}

function setAlertTriggered(doc)
{
	var elements = doc.match(/\d/g);
	if (elements==null)
        {
            return;
        }
	
	if(!Tabbuttons["Alerts"] && parseInt(elements[1]) > 0)
	{
		document.getElementById("AlertsTab").style.background="#FF0000";
	}
        else
        {
            document.getElementById("AlertsTab").style.background="#FFFFFF";
        }
}


// read the station summary xml for stations tab display
function station_summary()
{	
if (!Tabbuttons["Stations"]) return; // if current or stations display is not active, do nothing and stop the loop
	//debugger;
	// code for I
	if (window.ActiveXObject)	
	{
		var theDataDoc = new ActiveXObject("microsoft.xmldom");
	}
	// code for Mozilla, Firefox, Opera, etc.
	else if (document.implementation && document.implementation.createDocument)
	{
		var theDataDoc=document.implementation.createDocument("","",null);
	}
	else
	{
		alert('Your browser cannot handle this script');
	}

	theDataDoc.async = false;// this line is critical to make sure document is loaded before continuing
	theDataDoc.onreadystatechange = verify;
	theDataDoc.load(wxmap.weburl+"/currentstations.xml");
	var  dataObj = theDataDoc.getElementsByTagName("Data");
	for (i = 0; i < dataObj.length; i++)
	{
		var name= dataObj[i].getAttribute("Name");
			eval('stationSummary.'+name+'[0]=dataObj[i].getAttribute("total")');
			eval('stationSummary.'+name+'[1]=dataObj[i].getAttribute("uptodate")');
			eval('stationSummary.'+name+'[2]=dataObj[i].getAttribute("outdated")');
	}
	
	tempHtml='<table class="summary" style="font-family:Verdana, Arial, Helvetica, sans-serif;font-size:10px" width="235"  cellspacing="0" cellpadding="0"> ';
	tempHtml+=' <tr> <td width="57"><strong>Source</strong></td><td width="40"><div align="center"><strong>Total</strong></div></td>';
	tempHtml+=' <td width="67"><strong>Up to date</strong></td><td width="61"><strong>Outdated</strong></td></tr><tr>';
	tempHtml+='<td>RWIS</td><td><div align="right">';
	tempHtml+=stationSummary.CALTRANS[0]+'</div></td><td><div align="right">'+stationSummary.CALTRANS[1]+'</div></td><td><div align="right">'+stationSummary.CALTRANS[2]+'</div></td></tr> <tr>';
	tempHtml+='<td>Madis</td><td><div align="right">';
	tempHtml+=stationSummary.MADIS[0]+'</div></td><td><div align="right">'+stationSummary.MADIS[1]+'</div></td><td><div align="right">'+stationSummary.MADIS[2]+'</div></td></tr> <tr>';
	tempHtml+='<td>Mesowest</td><td><div align="right">';
	tempHtml+=stationSummary.Mesowest[0]+'</div></td><td><div align="right">'+stationSummary.Mesowest[1]+'</div></td><td><div align="right">'+stationSummary.Mesowest[2]+'</div></td></tr> <tr>';
	tempHtml+='<td><strong>Total</strong></td>';
	var tmpTotal=parseInt(stationSummary.CALTRANS[0])+parseInt(stationSummary.MADIS[0])+parseInt(stationSummary.Mesowest[0]);
	tempHtml+=' <td><div align="right">'+tmpTotal+'</div></td>';
	var tmpTotal=parseInt(stationSummary.CALTRANS[1])+parseInt(stationSummary.MADIS[1])+parseInt(stationSummary.Mesowest[1]);
	tempHtml+=' <td><div align="right">'+tmpTotal+'</div></td>';
	var tmpTotal=parseInt(stationSummary.CALTRANS[2])+parseInt(stationSummary.MADIS[2])+parseInt(stationSummary.Mesowest[2]);
	tempHtml+=' <td><div align="right">'+tmpTotal+'</div></td>';	
	tempHtml+='</tr></table>';
	document.getElementById("stationsummary").innerHTML=tempHtml;
}

function StationsOverlay(name)
{
	var overlayName = wxmap.weburl+"/NDFD/plot/png/"+name+"station_highres.png";
	StationOverlay =  new GGroundOverlay (

		overlayName,  new GLatLngBounds(new GLatLng(32, -125),
		new GLatLng(42.5, -113.75)));

	map.clearOverlays();
	mgr.clearMarkers();
	map.addOverlay(StationOverlay);
	//CountyOverlay();
	//DistrictOverlay();
	//map.setCenter(new GLatLng(41.875696,-87.624207), 11);
	closePopup();
}

/* read the http://www.nws.noaa.gov/alerts/ca.cap for alert display

NWS PARTNERS AND USERS WILL NEED TO MAKE THE NECESSARY CHANGES TO 
THEIR COMMUNICATION SYSTEMS TO ACCOMMODATE THESE ZONE CHANGES.

SHAPE FILES OF THE NEW FIRE AND PUBLIC WEATHER ZONES FOR THE NWS 
OXNARD WEATHER FORECAST OFFICE ARE AVAILABLE FOR DOWNLOAD FROM 
THE FOLLOWING WEBSITE /USE LOWER CASE/:

 HTTP://WWW.NWS.NOAA.GOV/GEODATA/CATALOG/WSOM/HTML/FIREZONE.HTM

 http://www.weather.gov/geodata/catalog/wsom/html/pubzone.htm

FOR QUESTIONS REGARDING THESE PRODUCT CHANGES...PLEASE CONTACT: 

MARK JACKSON
METEOROLOGIST IN CHARGE
NATIONAL WEATHER SERVICE
520 NORTH ELEVAR
OXNARD, CA 93030
PHONE: 805-988-6615 X222
EMAIL: MARK.JACKSON@NOAA.GOV  */

function getNDFDAlert(type)
{        
	    //fix bug that time on NWS alert not updating. also reload/refresh if nwstime changed 2/3/09
		theDataDoc.load(wxmap.weburl+"/nwstime.xml"+ "?" + new Date().getTime());
		dateTimeObj = theDataDoc.getElementsByTagName("nwstime");
		if(dateTimeObj != null)
		{
			wxmap.nwsTime_tmp = dateTimeObj[0].childNodes[0].nodeValue;
		}
		if (wxmap.nwsTime_tmp==wxmap.nwsTime ) 
		{
			closePopup();
			return;  //do nothing if no new data
		}
		else {
		wxmap.nwsTime=wxmap.nwsTime_tmp;
		}
			wxmap.mapTitle = document.getElementById("selectAlertType").options[document.getElementById("selectAlertType").options.selectedIndex].text + ":";
		    wxmap.mapTitle += document.getElementById("selectSensor").options[document.getElementById("selectSensor").selectedIndex].text+"  ";
		    wxmap.mapTime = wxmap.nwsTime;
			update_maptitle();
			
    //var tilelayer = new GTileLayer(new GCopyrightCollection(), 6, 11, {tileUrlTemplate:'{X}-{Y}-{Z}', isPng:true, Opacity:0.5});
    //tilelayer.getTileUrl = function(a,b){alert(a.x + ", " + a.y + ", " + b);}
    //var overlay = new GTileLayerOverlay(tilelayer);
    //map.addOverlay(overlay);

	//prevents caching	
    var overlayName = wxmap.weburl+"/zone_overlay.png" + "?" + new Date().getTime();
    var  newOverlay =  new GGroundOverlay (
            overlayName,  new GLatLngBounds(new GLatLng(32, -125),
            new GLatLng(42.5, -113.75)));

    map.clearOverlays();
    map.addOverlay(newOverlay);      
    
	//prevents caching
	var docname="nwsdata.xml" + "?" + new Date().getTime();
	GDownloadUrl(docname, function(doc){
	var xmlDoc = GXml.parse(doc);
    var dataObj = xmlDoc.documentElement.getElementsByTagName('zone');

	for (var i = 0; i < dataObj.length; i++)
	{
		// check for subzones (lat/lng pairs)
		var subzones = dataObj[i].getElementsByTagName("lat").length;
		
		var info = new Object();
		info.areaDesc = GXml.value(dataObj[i].getElementsByTagName('area_desc')[0]);
		info.effective = GXml.value(dataObj[i].getElementsByTagName('effective')[0]);
		info.expires = GXml.value(dataObj[i].getElementsByTagName('expires')[0]);
		info.description = GXml.value(dataObj[i].getElementsByTagName('description')[0]);
		info.from = GXml.value(dataObj[i].getElementsByTagName('senderName')[0]);
		
		if(subzones > 1)
		{
			for(var j = 0; j < subzones; j++)
			{
				var lat = GXml.value(dataObj[i].getElementsByTagName('lat')[j]);
				var lng = GXml.value(dataObj[i].getElementsByTagName('lng')[j]);
		
				info.lat = lat;
				info.lng = lng;
				
				// create the marker (for j # of subzones)
				createAlertZoneMarker(map, info);
			}
		}
		else
		{
			var lat = GXml.value(dataObj[i].getElementsByTagName('lat')[0]);
			var lng = GXml.value(dataObj[i].getElementsByTagName('lng')[0]);
	
			info.lat = lat;
			info.lng = lng;
			
			// create the marker (no subzones)
			createAlertZoneMarker(map, info);
		}	
	}

	closePopup();

});
    wxmap.mapTitle = document.getElementById("selectAlertType").options[document.getElementById("selectAlertType").options.selectedIndex].text + ":";
    wxmap.mapTitle += document.getElementById("selectSensor").options[document.getElementById("selectSensor").selectedIndex].text+"  ";
    wxmap.mapTime = wxmap.nwsTime;
    update_maptitle();


}
        
function createAlertZoneMarker(map, info) {
    //var htmlcontent='<b>'+info.areaDesc+'</b><br>';
	var htmlcontent=info.from + '<br>';
    htmlcontent+="Effective:"+info.effective+'<br>';
    htmlcontent+="Expires:"+info.expires+'<br><br>';
    //htmlcontent+=replaceCarriageReturn(info.description, '<br>');
    //htmlcontent+=info.description;

	// chop up description marker popup by line feed
	var splitDesc = info.description.split("\n");
	for(var i = 0; i < splitDesc.length; i++)
	{
		htmlcontent+=splitDesc[i] + '<br>';	
	}

    center = new GLatLng(info.lat, info.lng);
    
    var marker = new GMarker(center,{title:info.areaDesc});
    GEvent.addListener(marker, 'click', function() {
            //marker.openInfoWindowHtml(htmlcontent,{maxWidth:maxWidth});
            warningInfowin(htmlcontent);
            });
    map.addOverlay(marker);
    }


function warningInfowin(html)
{
        var infocontext = document.getElementById("warninginfowin");
        if(infocontext != null)
        {
            infocontext.innerHTML='<img src="close.gif" style="position:relative; left:481px; top:2px; z-index:204; padding-bottom:4px;" onclick="javascript:closewarningInfo(this.parentNode);"><br>'+'<div class="warningInfo">'+html+'</div>' ;
            return;
        }
	infocontext = document.createElement("div");
	infocontext.style.display="none";
        infocontext.style.width="500px";
        infocontext.style.height="350px";
	infocontext.className="contextmenu";
        infocontext.id="warninginfowin";
	infocontext.style.cursor = 'pointer'; 
	infocontext.innerHTML='<img src="close.gif" style="position:relative; left:481px; top:2px; z-index:204; padding-bottom:4px;" onclick="javascript:closewarningInfo(this.parentNode);"><br>'+'<div class="warningInfo">'+html+'</div>' ;
	map.getContainer().appendChild(infocontext);
	var x=400;//map.getSize().width/2-140;
	var y=35;
	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));  
	pos.apply(infocontext);
	infocontext.style.display = "";	
}

function closewarningInfo(div)
{
        div.parentNode.removeChild(div);
}

function cycleTime()
	{
		if(playtimer == null)
		{
			document.getElementById("PlayButton").innerHTML="Stop";
			document.getElementById("PlayButton").onclick = function(){stopCycleTime();};
			playtimer = setInterval(cycleTime, 3000);
		}
		else
		{
			var obj=document.getElementById("selectTime");
		    var total = obj.length - 1;
    		var sel = obj.selectedIndex;
			
			if(sel == total)
				sel = 0;
			else
				sel = sel + 1;
				
			obj.selectedIndex = sel;
            changeTime(obj.options[obj.selectedIndex].value,true);
		}
		
	}
	
	function stopCycleTime()
	{
		clearInterval(playtimer);
		playtimer = null;
		
		document.getElementById("PlayButton").innerHTML="Play";
		document.getElementById("PlayButton").onclick = function(){cycleTime();};
	}

