var map = null;
var token="";
var finding = false;
var IsRouteByClick = false;
var IsInfo = false;
var popuplat;
var popuplon;
var startpt;
var endpt;
var layer = null;
var IsTraffic = false;
var contextShapes = new HashTable();
var htPinID = new HashTable();
var IsSPanelOpen = false;
var IsRPanelOpen = false;
var IsIPanelOpen = false;
var IsWPanelOpen = false;
var midPoints = new Array();
//var layer1 = new VEShapeLayer();

//Silverlight script
function createSilverlight()
		{
			var scene = new slAds.Page();
			Silverlight.createObjectEx({
				source: source, //"Page.xaml",
				parentElement: parentElement,//document.getElementById("silverlightControlHost"),
				id: id, //"SilverlightControl",
				properties: {
					width: "100%",
					height: "100%",
					background:"transparent",
					isWindowless:"true",
					version: "1.0"
				},
				events: {
					onLoad: Silverlight.createDelegate(scene, scene.handleLoad),
					onError: function(sender, args) {
						var errorDiv = document.getElementById("errorLocation");
						if (errorDiv != null) {
							var errorText = args.errorType + "- " + args.errorMessage;
									
							if (args.ErrorType == "ParserError") {
								errorText += "<br>File: " + args.xamlFile;
								errorText += ", line " + args.lineNumber;
								errorText += " character " + args.charPosition;
							}
							else if (args.ErrorType == "RuntimeError") {
								errorText += "<br>line " + args.lineNumber;
								errorText += " character " +  args.charPosition;
							}
							errorDiv.innerHTML = errorText;
						}	
					}
				}
			});
		}


		if (!window.Silverlight) 
			Silverlight = {};

		Silverlight.createDelegate = function(instance, method) {
			return function() {
				return method.apply(instance, arguments);
			}
		}
//		var IsPlayed = false;
		var host = "";
		var slEl = "";
		var mControl = "";
		var IsAccessed76 = false;
		var IsAccessed66 = false;
		var IsAccessedConoco = false;
		
		function showAd(p)
		{
		    var mode = map.GetMapMode();
		    if (mode == VEMapMode.Mode3D) {
				alert("This functionality is not available in 3D mode.");
				return;
			}
		    //alert(host + "-" + host.id + " = " + p);
		    if (host.id != p) {
		        switch (p) {
		            case "Div3":
		                host = document.getElementById("Div3");
		                slEl = document.getElementById("silverlightControl3");
		                mControl = "ad76";
		                if (IsAccessed76)
		                    slEl.content.findName(mControl).Play();
		                break;
		            case "Div1":
		                host = document.getElementById("Div1");
		                slEl = document.getElementById("silverlightControl1");
		                mControl = "ad66";
		                if (IsAccessed66)
		                    slEl.content.findName(mControl).Play();
		                break;
		            default:
		                host = document.getElementById("Div2");
		                slEl = document.getElementById("silverlightControl2");
		                mControl = "Conoco";
		                if (IsAccessedConoco)
		                    slEl.content.findName(mControl).Play();
		                break;
		        }
		    }
		    else
		        slEl.content.findName(mControl).Play();
		    $('Div4').style.display = "block";
		    host.style.display = "block";
		    

		}
		
		function hideAd(p)
		{
		    if (slEl)
				slEl.content.findName(mControl).Stop();
		    host.style.display = "none";
		    $('Div4').style.display = "none";
		    switch (p) {
		        case "Div3":
		            IsAccessed76 = true;
		            break;
		        case "Div1":
		            IsAccessed66 = true;
		            break;
		        default:
		            IsAccessedConoco = true;
		            break;
		    }
		    
		}
		
//End of Silverlight script

function OnTabClick(tabId)
{
	if ($(tabId).id == "tabHowTo") { 
		if ($(tabId).style.backgroundPosition == "0px -26px") {
			$('tabHowTo').style.backgroundPosition = "0px 0px";
			$('tabSearch').style.backgroundPosition = "-90px 0px";
			$('divResults').style.zIndex = -1;
		}
	
	}
	else if ($(tabId).id == "tabSearch") {
		if ($(tabId).style.backgroundPosition == "-90px 0px") {
			$('tabHowTo').style.backgroundPosition = "0px -26px";
			$('tabSearch').style.backgroundPosition = "-90px -26px";
			$('divResults').style.zIndex = 15;
		}
		
	}
}
var landZip = queryString("zip"); 

function GetMap()
{
    token = document.getElementById('ClientToken');
	map = new VEMap('myMap');
	map.SetClientToken(token);
	var options = new VEMapOptions();
	options.EnableBirdseye = true;
	if(queryString("state")!= 'false')
    {
		var coords = new VELatLong();
		coords = GetStateCoord(queryString("state"));
		map.LoadMap(coords,7,VEMapStyle.Shaded,false,VEMapMode.Mode2D,true,null,options);
	}
	else
		map.LoadMap(new VELatLong(40.369270,-95.436261),4,VEMapStyle.Shaded,false,VEMapMode.Mode2D,true,null,options);
    map.ShowMiniMap();
    $('MSVE_minimap').style.left = "563px";
    $('MSVE_minimap').style.top = "0px";
    $('MSVE_minimap_resize').style.display = "none";
    //YAHOO.util.Event.addListener($('MSVE_minimap_resize'), 'mousedown', handleResize);
	//map.AttachEvent("onchangeview", ViewChange);
	map.AttachEvent("oninitmode", changeUI);
    map.AttachEvent("onclick", popupmenu);
    setTimeout("moveMiniMap();",1000);
    
    if (landZip != "" && landZip != "false")
		FindNear();
    
}

function changeUI()
{
	var mode = map.GetMapMode();
	if (mode == VEMapMode.Mode3D)
		disableTopMenu();
	else
		enableTopMenu();
}

function disableTopMenu()
{
	$('mItem1').style.backgroundPosition = '0 -33px';
	$('mItem12').style.backgroundPosition = '-215px -33px';
	$('mItem13').style.backgroundPosition = '-369px -33px';
	$('mItem1').onmouseout = function() {return;};
	$('mItem12').onmouseout = function() {return;};
	$('mItem13').onmouseout = function() {return;};
	map.DetachEvent("onclick", popupmenu);
}

function enableTopMenu()
{
	$('mItem1').style.backgroundPosition = '0 0';
	$('mItem12').style.backgroundPosition = '-215px 0';
	$('mItem13').style.backgroundPosition = '-369px 0';
	$('mItem1').onmouseout = function() {this.style.backgroundPosition = '0 0';};
	$('mItem12').onmouseout = function() {this.style.backgroundPosition = '-215px 0';};
	$('mItem13').onmouseout = function() {this.style.backgroundPosition = '-369px 0';};
	map.AttachEvent("onclick", popupmenu);
}

function AddPin(lat,lon,imgPath,title,info)
{
	var pin = new VEShape(VEShapeType.Pushpin, new VELatLong(lat,lon));
	pin.SetCustomIcon(imgPath);
	pin.SetTitle(title);
	pin.SetDescription(info);
	map.AddShape(pin);
}
    
function AddPushpinCustom(lat,lon,num,title,info,addInfo,pinImage)
{
	
	var pin = new VEShape(VEShapeType.Pushpin, new VELatLong(lat,lon));
	var x = new VECustomIconSpecification(); //to use in 2D and 3D
	x.CustomHTML = "<div style=\"text-align:center; width:16px; height:25px; background-repeat:no-repeat; background-position:0px 0px; background-image: url(images/template.gif)\">" +
			"<span style=\"z-index:10; position:relative;top:12px;left:0px;FONT-SIZE: 7pt; COLOR: white; FONT-FAMILY: Arial\">" +
			num + "</span></div>";
	x.BackColor = "transparent";
	x.ForeColor = "White";
	x.Image = pinImage;
	x.TextContent = num;
	x.TextFont = "Arial";
	x.TextSize = "7pt";
	var offs = new VEPixel();
	offs.x = 0;
	offs.y = 12;
	x.TextOffset = offs;
	
	switch(title)
	{
		case "Found Location":
		case "Starting Point":
		case "Destination Point":
			pin.SetTitle(title);
			pin.SetCustomIcon(num);
			break;
		default:
			pin.SetCustomIcon(x);
			pin.SetDescription("<table width='100%'><tr><td><span style='font-size:x-small;'>" + 
			info + 
			"</span></td></tr><tr><td>" + 
			addInfo +
			"<br>Zoom to:<a href=\"javascript:void(0);\" onclick=\"ZoomTo(" + 
			lat + "," + lon +
			",16);\">street</a>" +
			"|" +
			"<a href=\"javascript:void(0);\" onclick=\"ZoomTo(" + 
			lat + "," + lon +
			",11);\">city</a>" +
			"|" +
			"<a href=\"javascript:void(0);\" onclick=\"ZoomTo(" + 
			lat + "," + lon +
			",6);\">region</a><br><br>" +
			"</td></tr><tr><td></td></tr></table>");
			pin.SetTitle(title);
			
			//var id = pin.GetID();
			//htPinID.put(num,id)
			break;	
	}
	//layer1.AddShape(pin);
	
	map.AddShape(pin);
	var id = pin.GetID();
	htPinID.put(num,id);
}
function AddPushpin(lat,lon,num,title,info,addInfo,imgPath)
{
	
	var pin = new VEShape(VEShapeType.Pushpin, new VELatLong(lat,lon));
	var x = new VECustomIconSpecification(); //to use in 2D and 3D
	switch (imgPath) {
	    case "images/pin_conoco.gif":
	        x.CustomHTML = "<div style=\"text-align:center; width:50px; height:32px; background-repeat:no-repeat; background-position:0px 0px; background-image: url(images/pin_conoco.gif)\"/>"
	        break;
	    case "images/pin_66.gif":
	        x.CustomHTML = "<div style=\"text-align:center; width:30px; height:32px; background-repeat:no-repeat; background-position:0px 0px; background-image: url(images/pin_66.gif)\"/>"
	        break;
	    case "images/pin_76.gif":
	        x.CustomHTML = "<div style=\"text-align:center; width:30px; height:32px; background-repeat:no-repeat; background-position:0px 0px; background-image: url(images/pin_76.gif)\"/>" 
	        break;
	    default:
	        break;
	} 
	x.BackColor = "transparent";
	x.ForeColor = "White";
	x.Image = "images/pin_76.gif";
	x.TextContent = num;
	x.TextFont = "Arial";
	x.TextSize = "7pt";
	var offs = new VEPixel();
	offs.x = 0;
	offs.y = 12;
	x.TextOffset = offs;

	switch (title) {
	    case "Found Location":
	    case "Starting Point":
	    case "Destination Point":
	        pin.SetTitle(title);
	        pin.SetCustomIcon(num);
	        break;
	    default:
	        pin.SetCustomIcon(x);
	        pin.SetDescription("<table width='100%'><tr><td><span style='font-size:x-small;'>" +
			info +
			"</span></td></tr><tr><td>" +
			addInfo +
			"<br>Zoom to:<a href=\"javascript:void(0);\" onclick=\"ZoomTo(" +
			lat + "," + lon +
			",16);\">street</a>" +
			"|" +
			"<a href=\"javascript:void(0);\" onclick=\"ZoomTo(" +
			lat + "," + lon +
			",11);\">city</a>" +
			"|" +
			"<a href=\"javascript:void(0);\" onclick=\"ZoomTo(" +
			lat + "," + lon +
			",6);\">region</a><br><br>" +
			"</td></tr><tr><td></td></tr></table>");
	        pin.SetTitle(title);

	        //var id = pin.GetID();
	        //htPinID.put(num,id)
	        break;
	}
	//layer1.AddShape(pin);

	map.AddShape(pin);
	var id = pin.GetID();
	htPinID.put(num, id);
}
	
	
function showInfo(title)
{
	var mode = map.GetMapMode();
	hideInfo();
	if (title.indexOf("*")>0)
		 title = title.replace("*","'");
	var pinId = htPinID.get(title);
	
	pin = map.GetShapeByID(pinId);
	
	var pts = pin.GetPoints();
	var arLL = new VELatLong();
	arLL.Latitude = pts[0].Latitude;
	arLL.Longitude = pts[0].Longitude;
	map.SetCenterAndZoom(arLL,16);
	
	if (mode != VEMapMode.Mode3D) {
		map.ShowInfoBox(pin,pin.GetPoints());
	}
	
}

//function showInfo(num)
//{
//	hideInfo();
//	var pinId = htPinID.get(num);
//	var pin = map.GetShapeByID(pinId);
//	map.ShowInfoBox(pin,pin.GetPoints());
//}

function hideInfo()
{
	map.HideInfoBox();
}


function ZoomTo(lat,lon,level)
{
	map.SetCenterAndZoom(new VELatLong(lat,lon),level);
}

//initial move when the app started
function moveMiniMap()
{
	var myAnim = new YAHOO.util.Motion('MSVE_minimap', {points: { to: [852, 126] }} ); 
    myAnim.duration = 0.5;
    myAnim.onComplete.subscribe(handleResize);  
    myAnim.animate();       
    
}

function OnClick_MiniGlyph()
{
	if ($('MSVE_minimap').className == "minimap_collapsed")
	{
		var myAnim = new YAHOO.util.Motion('MSVE_minimap', {points: { to: [719,259] }} ); 
        myAnim.duration = 1.0;
        myAnim.onComplete.subscribe(handleResize1);  
        myAnim.animate();
    }
    else
    {
		$('MSVE_minimap_glyph').style.display = "none";
		var myAnim = new YAHOO.util.Motion('MSVE_minimap', {points: { to: [852, 126] }} ); 
        myAnim.duration = 1.0;
        myAnim.onComplete.subscribe(handleResize1);  
        myAnim.animate();
    }
}

function handleResize()
{
	$('MSVE_minimap_glyph').style.display = "block";
	$('MSVE_minimap').className = "minimap_collapsed";
	$('MSVE_minimap_glyph').style.backgroundPosition = "0px 0px";
		
}	

function handleResize1()
{
	if ($('MSVE_minimap').className != "minimap_collapsed")
	{
		$('MSVE_minimap_glyph').style.display = "block";
		$('MSVE_minimap').className = "minimap_collapsed";
		$('MSVE_minimap_glyph').style.backgroundPosition = "0px 0px";
		$('MSVE_minimap_glyph').style.top = "40px";
		$('MSVE_minimap_glyph').style.left = "703px";
		/*
		$('MSVE_minimap_glyph').style.top = "141px";
		$('MSVE_minimap_glyph').style.left = "957px";
		*/
	}
	else
	{
		$('MSVE_minimap').className = "expanded MSVE_smallMinimap MSVE_Minimap_V5";
		$('MSVE_minimap_glyph').style.backgroundPosition = "0px -30px";
		$('MSVE_minimap_glyph').style.top= "172px";
		$('MSVE_minimap_glyph').style.left= "570px";
		/*
		$('MSVE_minimap_glyph').style.top= "273px";
		$('MSVE_minimap_glyph').style.left= "824px";
		*/
	}
	
	
}

// Weather and traffic info based on Yahoo RSS feeds        
function getInfo()
{
    
    $('divInfo').style.display = "none";
    //map.DeleteAllShapes();
    
    deleteRoute();
    if ($('divPopupContainer').style.display == "block")
		$('divPopupContainer').style.display = "none";
    var zip = $('infoZip').value;
    GetData("WeatherHandler.ashx?zip=" + zip,"forecast");
    $('RESULTS').style.display = "none";
    if (IsIPanelOpen)
			closeInfoPanel();
	
}
       
                               
function popupmenu(e)
{
    if (e.rightMouseButton)
    {
		var s = map.GetMapStyle();
		if (s == "o")
			return;
		var menu = $('divPopupContainer');//popupmenu
		menu.style.display='block'; //Showing the menu
		
		var LLA = new VEPixel();
		LLA.x = e.mapX;
		LLA.y = e.mapY;
		var clickedPoint = map.PixelToLatLong(LLA);
		popuplat = clickedPoint.Latitude;
		popuplon = clickedPoint.Longitude;
		menu.style.left = e.clientX + "px";
		menu.style.top = e.clientY + "px";
    }
    else
    {
		var menu = $('divPopupContainer').style.display='none';
    }
}


function setStart()
{
    if (contextShapes.get('start') != null)
		map.DeleteShape(contextShapes.get('start'))
    
    var pin = new VEShape(VEShapeType.Pushpin,new VELatLong(popuplat,popuplon));
    pin.SetCustomIcon('images/bluePin.gif');
	pin.SetTitle('Location Info');
	pin.SetDescription('This is your start point');
	map.AddShape(pin);
	
	contextShapes.put('start',pin);  
    startpt = new VELatLong();
    startpt.Latitude = popuplat;
    startpt.Longitude = popuplon;
}

function setEnd()
{
    if (contextShapes.get('end') != null)
		map.DeleteShape(contextShapes.get('end'));
    
    var pin = new VEShape(VEShapeType.Pushpin,new VELatLong(popuplat,popuplon));
    pin.SetCustomIcon('images/redPin.gif');
	pin.SetTitle('Location Info');
	pin.SetDescription('This is your destination point');
	map.AddShape(pin);
    contextShapes.put('end',pin);
    endpt = new VELatLong();
    endpt.Latitude = popuplat;
    endpt.Longitude = popuplon;  
}

function setMidPoint()
{
    
    var pin = new VEShape(VEShapeType.Pushpin,new VELatLong(popuplat,popuplon));
    //pin.SetCustomIcon('images/greenPin.gif');
    
	//pin.SetTitle('Location Info');
	//pin.SetDescription('This is your destination point');
	map.AddShape(pin);
	pin.SetCustomIcon("<span onclick=\"DeleteViaPin('" + pin.GetID() + "')\"><img src=\"images/greenPin.gif\"/></span>");
	//alert("<span onclick=\"DeleteViaPin('" + pin.GetID() + "')\"><img src=\"images/greenPin.gif\"/></span>");
   // contextShapes.put(stopId,pin);
    midpt = new VELatLong();
    midpt.Latitude = popuplat;
    midpt.Longitude = popuplon;
    midPoints.push(midpt);  
}

function DeleteViaPin(pinGId)
{
	var viaPin = map.GetShapeByID(pinGId);
	var points = viaPin.GetPoints();
	p = new VELatLong();
	p.Latitude = points[0].Latitude;
	p.Longitude = points[0].Longitude;
	midPoints.removeLL(p); //ONLY for VELatLong objects
	map.DeleteShape(viaPin);
}

Array.prototype.removeLL=function(s){
  for(i=0;i<this.length;i++){
    if(s.Latitude==this[i].Latitude && s.Longitude==this[i].Longitude) this.splice(i, 1);
  }
}

function GetXmlHttp()
{
    var x = null;
    try
    {
        x = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
    {
            try
        {
            x = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (e)
        {
            x = null;
        }
        
    }
    
    if (x==null && window.XMLHttpRequest) // typeof XMLHttpRequest != "undefined")
    {
        x = new XMLHttpRequest();
    }
    
    return x;
}
    
function ResetFields()
{
	$('txtStreet').value = "";
	$('txtCity').value = "";
	$('ddlState').selectedIndex = 0;
	$('txtZip').value = "";

	$('txtStreetFrom').value = "";
	$('txtCityFrom').value = "";
	$('ddlStateFrom').selectedIndex = 0;
	$('txtZipFrom').value = "";

	$('txtStreetTo').value = "";
	$('txtCityTo').value = "";
	$('ddlStateTo').selectedIndex = 0;
	$('txtZipTo').value = "";

	$('infoZip').value = "";

}

function BuildAddress(street,city,state,zip)
{
	var address = "";
	if (street != "") {
		address += street;
		if (city != "")
			address += ", " + city;
		else
		{
			return;
		}
		if (state != "Select State")
		{
			address += ", " + state;
			if (zip != "")
				address += " " + zip + ", United States";
			else
				address += ", United States";
		}
		else {
			if (zip != "")
				address += " " + zip + ", United States";
			else
				address += ", United States";
		}
	}
	else {
		if (city != "")
		{
			address += city;
			if (state != "Select State") {
				address += ", " + state;
				if (zip != "")
					address += " " + zip + ", United States";
				else
					address += ", United States";
			}
			else {
				if (zip != "")
					address = zip;
				else
					address = city + ", United States";
			}        
		}
		else {
			if (state != "Select State")
			{
				if (zip != "")
					address = zip;
				else
					address = state + ", United States";
			}
			else {
				if (zip != "")
					address = zip;
				else {
					return address;
				}
			} 
		}                   
	}
	return address;
}


var xmlhttp;
function GetData(url,type) {
	var xmlhttp = GetXmlHttp();

	if (xmlhttp)
	{
		xmlhttp.onreadystatechange = function()
		{
			if (xmlhttp.readyState == 4)
			{
				if (xmlhttp.status == 200) 
				{
					switch(type) {
              			case "search":
              				GetStations(xmlhttp.responseText);
              				break;
              			case "trip":
              				GetRouteStores(xmlhttp.responseText);
              				break;
              			case "forecast":
              				GetCurWeather(xmlhttp.responseText);
              				break;
              			default:
              				OnGetTraffic(xmlhttp.responseText);
              				break;
					}
				}    
			}
		}
		xmlhttp.open("GET", url, true);
		xmlhttp.send(null);
	}

}

function OnGetTraffic(result)
{
	eval(result);
	map.LoadTraffic(true);
	map.ShowTrafficLegend(10,325);
    //map.SetTrafficLegendText("The traffic legend");
	$('RESULTS').style.display = "none";
}



function GetCurWeather(result) {
	var schema = {
		city: "cityname",
		time: "timestamp",
		curWeather: 
			{ image: "current_image_url",
			  condition: "current_condition",
			  temperature: "current_temp" },
		day: [
			{name: "day_name", condition: "day_forecast", high: "day_high", low: "day_low" }
		]
	};
	
	var resultAr = result.split("<WeatherApi>");
	resultAr = resultAr[1].split("</WeatherApi>");
    //var oXmlDom = createXMLDOM();
    var oXmlDom;
    if (window.ActiveXObject)
	{
		oXmlDom = new ActiveXObject("Microsoft.XMLDOM");
		oXmlDom.async = "false";
		oXmlDom.loadXML(resultAr[0]);
	}
	else
	{
		
		var parser = new DOMParser();
		oXmlDom = parser.parseFromString(resultAr[0],"application/xml");
	}
	
    
    var oXmlDoc = oXmlDom.documentElement;
    
    info = BuildCurWeather(oXmlDoc,schema);
    document.getElementById('forecast').innerHTML = info;
    openWeatherPanel();    
}

function BuildCurWeather(xmldoc,schema) {
	
	time = xmldoc.getElementsByTagName(schema.time)[0].childNodes[0].nodeValue;
	
	city = xmldoc.getElementsByTagName(schema.city)[0].childNodes[0].nodeValue;
	condDescr = xmldoc.getElementsByTagName(schema.curWeather.condition)[0].childNodes[0].nodeValue;
    temp = xmldoc.getElementsByTagName(schema.curWeather.temperature)[0].childNodes[0].nodeValue + "F";
    
    wImg = xmldoc.getElementsByTagName(schema.curWeather.image)[0].childNodes[0].nodeValue;
    day1forecast = (xmldoc.getElementsByTagName("day")[0]).getElementsByTagName("day_name")[0].childNodes[0].nodeValue;
    day1_cond = (xmldoc.getElementsByTagName("day")[0]).getElementsByTagName("day_forecast")[0].childNodes[0].nodeValue;
    day1_high = (xmldoc.getElementsByTagName("day")[0]).getElementsByTagName("day_high")[0].childNodes[0].nodeValue;
    day1_low = (xmldoc.getElementsByTagName("day")[0]).getElementsByTagName("day_low")[0].childNodes[0].nodeValue + "F";
                            
    day2forecast = (xmldoc.getElementsByTagName("day")[1]).getElementsByTagName("day_name")[0].childNodes[0].nodeValue;
    day2_cond = (xmldoc.getElementsByTagName("day")[1]).getElementsByTagName("day_forecast")[0].childNodes[0].nodeValue;
    day2_high = (xmldoc.getElementsByTagName("day")[1]).getElementsByTagName("day_high")[0].childNodes[0].nodeValue;
    day2_low = (xmldoc.getElementsByTagName("day")[1]).getElementsByTagName("day_low")[0].childNodes[0].nodeValue + "F";
    
    day3forecast = (xmldoc.getElementsByTagName("day")[2]).getElementsByTagName("day_name")[0].childNodes[0].nodeValue;
    day3_cond = (xmldoc.getElementsByTagName("day")[2]).getElementsByTagName("day_forecast")[0].childNodes[0].nodeValue;
    day3_high = (xmldoc.getElementsByTagName("day")[2]).getElementsByTagName("day_high")[0].childNodes[0].nodeValue;
    day3_low = (xmldoc.getElementsByTagName("day")[2]).getElementsByTagName("day_low")[0].childNodes[0].nodeValue + "F";
    
    var wInfo = "<table width=\"353px\"><tr><td align=\"left\"><img height=\"42\" width=\"42\" src=\"" + wImg + "\"/></td>" +
	"<td align=\"left\" class=\"curWeather\">" + condDescr + ", " + temp + "</td></tr></table><br />" + "<span class=\"wTitle\">Forecast</span><br />" +
	"<span class=\"wContent\">" + day1forecast + " - " + day1_cond + ". High: " + day1_high + " Low: " + day1_low + "</span><br />" + 
	"<span class=\"wContent\">" + day2forecast + " - " + day2_cond + ". High: " + day2_high + " Low: " + day2_low + "</span><br />" +
	"<span class=\"wContent\">" + day3forecast + " - " + day3_cond + ". High: " + day3_high + " Low: " + day3_low + "</span><br /><br /><br />" +
	"<span class=\"wLink\">" + city + "</span><br />" + "<span class=\"wNote\">" + time + "</span>";
                            
    
    return wInfo;
}


function GetStations(result)
{
	var IsFind = finding;
	var temp = result.split("<!");
	result = temp[0];
	                                                    
	try
	{
	if (!IsFind)
		map.DeleteAllPushpins();
	}
	catch (err)
	{
	alert(err.message);
	}

	eval(result);
	//if (layer1 != null)
		//map.AddShapeLayer(layer1);
	//$('RESULTS').style.display = "none";
}

function GetRouteStores(result) {

	var temp = result.split("<!");
	result = temp[0];
	                                                    
	eval(result);
	$('RESULTS').style.display = "none";
}

var captureEnter = function(e) {
    if(!e) var e = window.event;             // gets the event in ie or ns
    kCode = e.keyCode || e.which;   // gets the keycode in ie or ns
 
    if (kCode == 13) { // Enter key pressed
		if($('searchForm').style.display == "block")
			FindNear(); // another function that does something
		if($('routeForm').style.display == "block")
		{
			validate();
			if (!validate())return;
			GetARoute('form');
		}
		if($('divInfo').style.display == "block")
			FindNear();
		
       
    }
    else
		return false;
}

function FindNear()
{
	
	var zip = "";
	var street = "";
	var state = ""; 
	var city = "";
	 

		
	if ($('infoZip').value == "")
	{
		if ($('txtStreet').value == "" && $('txtCity').value == "" && $('txtZip').value == "" && queryString("zip") == 'false')
		{
			alert("Fill out the search form");
			return;
		}
		else
		{
			map.DeleteAllShapeLayers();
			$('divStores').innerHTML = "<IMG style='position:absolute; left:87px; top:194px;' src='images/ballIndicator.gif'>";
			$('tabHowTo').style.backgroundPosition = "0px -26px";
			$('tabSearch').style.backgroundPosition = "-90px -26px";
			$('divResults').style.zIndex = 15;
			
			street = $('txtStreet').value;
			city = $('txtCity').value;
			var list = $('ddlState').options;
			state = list[list.selectedIndex].text;
			if (landZip != "" && landZip != "false")
				zip = landZip;
			else
				zip = $('txtZip').value;
			
			//$("searchForm").style.display = "none";
			if (zip == "" && $('chkWeather').checked)
			{
				$('tabHowTo').style.backgroundPosition = "0px 0px";
				$('tabSearch').style.backgroundPosition = "-90px 0px";
				$('divResults').style.zIndex = -1;
				$('divStores').innerHTML = "<span id=\"noResults\">NO RESULTS</span>";
				alert("Enter a valid Zip Code");
				return;
			}
			IsTraffic = false;
		}
	}
	else
	{
		$('tabHowTo').style.backgroundPosition = "0px 0px";
		$('tabSearch').style.backgroundPosition = "-90px 0px";
		
		$('divStores').innerHTML = "<span id=\"noResults\">NO RESULTS</span>";
		$('divDir').innerHTML = "";
		$('divResults').style.zIndex = -1;
		map.DeleteAllShapeLayers();
		zip = $('infoZip').value;
		IsTraffic = true;
		
	}
				
	map.DeleteAllShapes();
	deleteRoute();
	var txtWhere = "";

	txtWhere = BuildAddress(street,city,state,zip);
	try
	{
		map.Find('',txtWhere, null, null, null, null, null, null, null, null, onAddressFound);
		
	}
	catch(e)
	{
		alert("The requested location cannot be found. Check your input.");
	}
	finding = true;

}

function onAddressFound()
{
	var latLong = map.GetCenter();
	$('RESULTS').style.display = "block";
	if (!IsTraffic)
	{
		if ($('chkWeather').checked)
		{
			GetData("WeatherHandler.ashx?zip=" + $('txtZip').value,"forecast");
			openWeatherPanel();
		}
		if ($('chkTraffic').checked)
		{
			//latLong = map.GetCenter();
			var url = "TrafficHandler.ashx?Lat=" + latLong.Latitude + "&Lng=" + latLong.Longitude;
			GetData(url,"traffic");
		}
		else
			map.ClearTraffic(); 
			
		var url = "USSiteLocatorHandler.ashx?type=Find";
		url += "&street=" + $('txtStreet').value;
		url += "&city=" + $('txtCity').value;
		url += "&state=" + $('ddlState').value;
		if (landZip != "" && landZip != "false") {
			url += "&zip=" + landZip;
			landZip = "";
		}
		else
			url += "&zip=" + $('txtZip').value;
		url += "&range=" + $('ddlRange').value;
		
		GetData(url,"search");
		
		
		$('divDir').style.display = "none";
		$('prntDir').style.display = "none";
		$('prntStores').style.left = "0px";
		$('prntStores').style.width = "100%";
		$('divStores').style.display = "block";
		if (IsSPanelOpen)
			closeSearchPanel();
		if (IsIPanelOpen)
			closeInfoPanel();
		
	}
	else
	{
		$('prntDir').innerHTML = "";
		$('prntStores').innerHTML = "";
		if (!$('Form1').rbInfo[0].checked)
		{
			//latLong = map.GetCenter();
			var url = "TrafficHandler.ashx?Lat=" + latLong.Latitude + "&Lng=" + latLong.Longitude;
			GetData(url,"traffic");
			if (IsIPanelOpen)
				setTimeout("closeInfoPanel();",1000);
		}
		else {
			getInfo();
		}
	}

}

function findCompleted()
{
	finding = false;
}

function ViewChange()
{
	if (finding)
		findCompleted();
}

function openSearchPanel() {
	
	var mode = map.GetMapMode();
	if (mode == VEMapMode.Mode3D) {
		alert("This functionality is currently available in 2D mode only.");
		return;
	}
	var sfAttrs = {   
            width: { to:212  },   
            height: { to: 242 }   
			};
	
	ResetFields();
	if (IsRPanelOpen)
		closeRoutePanel();
	if (IsIPanelOpen)
		closeInfoPanel();
	if(IsWPanelOpen)
		closeWeatherPanel();
	$("mItem1Sel").style.display = "block";
	$("frmSearch").style.display = "block";
	
	var myAnim = new YAHOO.util.Anim('divSearchBody', sfAttrs);   
	myAnim.duration = 0.5;
	//myAnim.onStart.subscribe(handleContent);
	myAnim.onComplete.subscribe(getSFContent);
	myAnim.animate();
	
	IsSPanelOpen = true;
	$("routeForm").style.display = "none";
	$("divInfo").style.display = "none";
}

function closeSearchPanel()
{
	var sfAttrs = {   
            width: { to:212  },   
            height: { to: 0 }   
			};
	
	$("searchForm").style.display = "none";
	var myAnim = new YAHOO.util.Anim('divSearchBody', sfAttrs);   
	myAnim.duration = 0.5;
	//myAnim.onStart.subscribe(handleContent);
	myAnim.onComplete.subscribe(getSFContentClosed);
	myAnim.animate();
	IsSPanelOpen = false;
}

function openRoutePanel() {
	var mode = map.GetMapMode();
	if (mode == VEMapMode.Mode3D) {
		alert("This functionality is currently available in 2D mode only.");
		return;
	}
	var sfAttrs = {   
            width: { to:406  },   
            height: { to: 205 }   
			};
	
	ResetFields();
	if (IsSPanelOpen)
		closeSearchPanel();
	if (IsIPanelOpen)
		closeInfoPanel();
	if(IsWPanelOpen)
		closeWeatherPanel();	
	$("mItem2Sel").style.display = "block";
	$("frmRoute").style.display = "block";
	
	var myAnim = new YAHOO.util.Anim('divRouteBody', sfAttrs);   
	myAnim.duration = 0.5;
	//myAnim.onStart.subscribe(handleContent);
	myAnim.onComplete.subscribe(getRFContent);
	myAnim.animate();
	IsRPanelOpen = true;
	
	
}

function closeRoutePanel()
{
	var rfAttrs = {   
            width: { to:0  },   
            height: { to: 0 }   
			};
	
	$("routeForm").style.display = "none";
	var myAnim = new YAHOO.util.Anim('divRouteBody', rfAttrs);   
	myAnim.duration = 0.5;
	//myAnim.onStart.subscribe(handleContent);
	myAnim.onComplete.subscribe(getRFContentClosed);
	myAnim.animate();
	IsRPanelOpen = false;
}

function openInfoPanel() {
	var mode = map.GetMapMode();
	if (mode == VEMapMode.Mode3D) {
		alert("This functionality is currently available in 2D mode only.");
		return;
	}
	var sfAttrs = {   
            width: { to:203  },   
            height: { to: 160 }   
			};
	
	ResetFields();
	if (IsSPanelOpen)
		closeSearchPanel();
	if (IsRPanelOpen)
		closeRoutePanel();
		
	$("mItem3Sel").style.display = "block";
	$("frmInfo").style.display = "block";
	
	var myAnim = new YAHOO.util.Anim('divInfoBody', sfAttrs);   
	myAnim.duration = 0.5;
	//myAnim.onStart.subscribe(handleContent);
	myAnim.onComplete.subscribe(getIFContent);
	myAnim.animate();
	IsIPanelOpen = true;
	
	
}

function closeInfoPanel()
{
	var rfAttrs = {   
            width: { to:203  },   
            height: { to: 0 }   
			};
	
	$("divInfo").style.display = "none";
	var myAnim = new YAHOO.util.Anim('divInfoBody', rfAttrs);   
	myAnim.duration = 0.5;
	//myAnim.onStart.subscribe(handleContent);
	myAnim.onComplete.subscribe(getIFContentClosed);
	myAnim.animate();
	IsIPanelOpen = false;
}

function openWeatherPanel()
{
	
	if (!IsWPanelOpen)
	{
		var wAttrs = {   
            width: { to:373  },   
            height: { to: 241 }   
			};
		
		$("shadow-container1").style.display = "block";
		$("forecast").style.display = "none";
		
		var myAnim = new YAHOO.util.Anim('bgrndWeather', wAttrs);   
		myAnim.duration = 0.5;
		//myAnim.onStart.subscribe(handleContent);
		myAnim.onComplete.subscribe(moveIt);
		myAnim.animate();
		IsWPanelOpen = true;
	}
	
}

function closeWeatherPanel()
{
	
	if (IsWPanelOpen)
	{
		var myAnim = new YAHOO.util.Motion('shadow-container1', {points:    
        { to: [249, 141] }    
		 });   
		myAnim.duration = 0.5;
		//myAnim.onStart.subscribe(handleContent);
		myAnim.onComplete.subscribe(closeIt);
		myAnim.animate();
		IsWPanelOpen = false;
	}
	
}

function moveIt()
{
	var myAnim = new YAHOO.util.Motion('shadow-container1', {points:    
        { to: [400, 250] }    
     }); 
    myAnim.duration = 0.5;  
	myAnim.animate();
	
	$("forecast").style.display = "block"; 
}

function closeIt()
{
	var wAttrs = {   
            width: { to:0  },   
            height: { to: 0 }   
			};
		
	//$("shadow-container1").style.display = "none";
	$("forecast").style.display = "none";
	
	var myAnim = new YAHOO.util.Anim('bgrndWeather', wAttrs); 
    myAnim.duration = 0.5;  
	myAnim.animate();
		 
}



function getSFContent()
{
	$("searchForm").style.display = "block";
}

function getSFContentClosed()
{
	$("frmSearch").style.display = "none";
	$("mItem1Sel").style.display = "none";
}

function getRFContent()
{
	$("routeForm").style.display = "block";
}

function getRFContentClosed()
{
	$("frmRoute").style.display = "none";
	$("mItem2Sel").style.display = "none";
}

function getIFContent()
{
	$("divInfo").style.display = "block";
}

function getIFContentClosed()
{
	$("frmInfo").style.display = "none";
	$("mItem3Sel").style.display = "none";
}

var locations;
function GetARoute(type)
{
	if (IsRPanelOpen)
		closeRoutePanel();
	$('divStores').innerHTML = "<IMG style='position:absolute; left:87px; top:194px;' src='images/ballIndicator.gif'>";
	$('tabHowTo').style.backgroundPosition = "0px -26px";
	$('tabSearch').style.backgroundPosition = "-90px -26px";
	$('divResults').style.zIndex = 15;
	$('RESULTS').style.display = 'block';
	$('routeForm').style.display = 'none';

	if (map.GetMapStyle() == VEMapStyle.Birdseye)
		map.SetMapStyle(VEMapStyle.Road);
	map.DeleteAllShapes();
	$('divPopupContainer').style.display = 'none';
	var e = window.event;
	var txtFrom = "";
	var txtTo = "";

	if (type == "form")
	{
		var street0 = $('txtStreetFrom').value;
		var city0 = $('txtCityFrom').value;
		var list = $('ddlStateFrom').options;
		var state0 = list[list.selectedIndex].text;
		var zip0 = $('txtZipFrom').value;
		txtFrom = BuildAddress(street0,city0,state0,zip0);
	    			        
		var street1 = $('txtStreetTo').value;
		var city1 = $('txtCityTo').value;
		list = $('ddlStateTo').options;
		var state1 = list[list.selectedIndex].text;
		var zip1 = $('txtZipTo').value;
		txtTo = BuildAddress(street1,city1,state1,zip1);
		
		if (txtTo == "" || txtFrom == "")
		{
			alert("Missing start or end address");
			return;
		}
		IsRouteByClick = false;
	}
	else
	{
		txtFrom = startpt;
		txtTo = endpt;
		if (txtTo == undefined || txtFrom == undefined)
		{
			alert("Missing start or end address");
			return;
		}
		IsRouteByClick = true;
	}
	if (IsRouteByClick && midPoints.length > 0)
	{
		var options = new VERouteOptions;

        // Otherwise what's the point?
        options.DrawRoute = true;

        // So the map doesn't change:
        options.SetBestMapView = false;

        // Call this function when map route is determined:
        options.RouteCallback  = ShowTurns;

        // Show as miles
        options.DistanceUnit = VERouteDistanceUnit.Mile;

        // Show the disambiguation dialog
        options.ShowDisambiguation = true;
		locations = new Array();
		var mPoint = new VELatLong();
		mPoint = startpt;
		locations.push(mPoint);
		//add mid points
		for (var k =0; k<midPoints.length; k++)
		{
			locations.push(midPoints[k]);
		}
		mPoint = endpt;
		locations.push(mPoint);
		map.GetDirections(locations,options);
		//alert("stop here");
	}
	else
		map.GetRoute(txtFrom,txtTo,null,null,onGotRoute);

}

function ShowTurns(route)
{
	
	map.DeleteAllShapes();
	var steps = "";
    var url = "USSiteLocatorHandler.ashx?type=MPRoute&soldTo=";
    for (var l=0; l<locations.length; l++)
    {
		url += "&lat" + l + "=" + locations[l].Latitude.toFixed(4);
		url += "&lon" + l + "=" + locations[l].Longitude.toFixed(4);
    }      
	var numTurns = 0;
           
	var displaySteps="<table cellpadding='0' style=\"width: 210px; z-index:10;\" class=\"tblDirections\" border=\"0\">";
	var prntSteps="<table cellpadding='0' style=\"width: 410px; z-index:10;\" class=\"tblDirections\" border=\"0\">";
	
	var legs = route.RouteLegs;
	var leg = null;
	var lenSum = 0;
	for (var i=0; i<legs.length; i++)
	{
		leg = legs[i];
		
		var turn = null; //The itinerary leg
		lenSum += leg.Itinerary.Items.length;		
		for (var j=0; j<leg.Itinerary.Items.length; j++)
		{
			turn = leg.Itinerary.Items[j];
			numTurns++;
			steps += "<tr><td valign=\"top\" class='instruct' style=\"width: 10px\">" + numTurns + ".</td>";
			steps += "<td valign=\"top\" class='instruct'>" + turn.Text + "</td>"; 
			steps += "<td valign=\"top\" class='instruct' style=\"width: 50px\">" + turn.Distance.toFixed(1) + " mi</td></tr>";
			
			
		}
	}
	GetData(url,"trip");
	
	steps += "<tr><td colspan=\"3\"><span class='tblTitle'>Total Distance: " + route.Distance.toFixed(1) + " mi</td></tr></table>";
	$('divDir').innerHTML = "<span class=tblTitle>Driving Directions</span><br>" + displaySteps + steps + "<br>";
	$('divDir').style.display = "block";
	$('divStores').style.display = "block";
	locations = new Array();
	midPoints = new Array();;
	
}
		
function onGotRoute(route)
{
	map.DeleteAllPushpins();
	var latStart = route.StartLocation.LatLong.Latitude;
    var lonStart = route.StartLocation.LatLong.Longitude;
    var latEnd = route.EndLocation.LatLong.Latitude;
    var lonEnd = route.EndLocation.LatLong.Longitude;
    //var url = "USStoreLocator.aspx?type=Route";
    var url = "USSiteLocatorHandler.ashx?type=Route";
    url += "&latS=" + latStart;
    url += "&lonS=" + lonStart;
    url += "&latE=" + latEnd;
    url += "&lonE=" + lonEnd;
	
	
	var len = route.Itinerary.Segments.length;
	//if (len > 50)
		//len = 50;
	//alert(len);
	
	
		
	
	//for (var i=0;i<len;i++)
	//{
		//var lat = route.Itinerary.Segments[i].LatLong.Latitude
		//url += "&lat" + i + "=" + route.Itinerary.Segments[i].LatLong.Latitude.toFixed(4);
		//url += "&lon" + i + "=" + route.Itinerary.Segments[i].LatLong.Longitude.toFixed(4);
	//}
	
	GetData(url,"trip");
	    
	var displaySteps="<table cellpadding='0' style=\"width: 210px; z-index:10;\" class=\"tblDirections\" border=\"0\">";
	var prntSteps="<table cellpadding='0' style=\"width: 410px; z-index:10;\" class=\"tblDirections\" border=\"0\">";
	var steps = "";
	if (IsRouteByClick)
	{
		steps += "<tr><td valign=\"top\" class='instruct' style=\"width: 10px\">1.</td>";
		steps += "<td valign=\"top\" class='instruct'>" + route.Itinerary.Segments[0].Instruction + " Start Point</td>";
		steps += "<td valign=\"top\" class='Num' style=\"width: 50px\">" + route.Itinerary.Segments[0].Distance + " " + 
		route.Itinerary.DistanceUnit + "</td></tr>";
		for(var i = 1; i<len-1 ;i++)
		{
			steps += "<tr><td valign=\"top\" class='instruct' style=\"width: 10px\">" + (i+1) + ".</td>";
			steps += "<td valign=\"top\" class='instruct'>" + route.Itinerary.Segments[i].Instruction + "</td>";
			steps += "<td valign=\"top\" class='Num' style=\"width: 50px\">" + route.Itinerary.Segments[i].Distance + " " + 
			route.Itinerary.DistanceUnit + "</td></tr>";
	        
		}
		steps += "<tr><td valign=\"top\" class='instruct' style=\"width: 10px\">" + len + ".</td>";
		steps += "<td valign=\"top\" class='instruct'>" + route.Itinerary.Segments[len-1].Instruction + " End Point</td>";
		steps += "<td valign=\"top\" class='Num' style=\"width: 50px\">" + route.Itinerary.Segments[len-1].Distance + " " + 
		route.Itinerary.DistanceUnit + "</td></tr>";
	}
	else
	{
	    
		for(var i = 0; i<len ;i++)
		{
			steps += "<tr><td valign=\"top\" class='instruct' style=\"width: 10px\">" + (i+1) + ".</td>";
			steps += "<td valign=\"top\" class='instruct'>" + route.Itinerary.Segments[i].Instruction + "</td>";
			steps += "<td valign=\"top\" class='Num' style=\"width: 50px\">" + route.Itinerary.Segments[i].Distance + " " + 
			route.Itinerary.DistanceUnit + "</td></tr>";
	        
		}
	    
	}
	steps += "<tr><td colspan=\"3\"><span class='tblTitle'>Total Distance: " + route.Itinerary.Distance + " " + 
	route.Itinerary.DistanceUnit + "</span></td></tr></table>";
	$('divDir').innerHTML = "<span class=tblTitle>Driving Directions</span><br>" + displaySteps + steps + "<br>";
	$('prntDir').innerHTML = "<span class=tblTitle>Driving Directions</span><br>" + prntSteps + steps;
	$('divDir').style.display = "block";
	$('divStores').style.display = "block";
	$('prntDir').style.display = "block";
	//$('prntDir').style.whiteSpace = "nowrap";
	$('prntDir').style.left = "0px";
	$('prntStores').style.left = "420px";
	//$('prntStores').style.width = "320px";
	$('prntStores').style.display = "block";
	
	            
}
	                                    
function deleteRoute()
{
	try  
	{  
		map.DeleteRoute();
	}
	catch (err)     
	{
		alert(err.message);
	} 
}

function Close()
{
	var eSrc = window.event.srcElement;
	//alert(eSrc.id);    
	if (eSrc.id == "imgCloseD")
	{
		ResetFields();
	    
		//$('divStores').innerHTML = "<span class='tblTitle'><IMG src='images/ballIndicator.gif'>";
	}
	else if (eSrc.id == "imgCloseF")
		$('shadow-container').style.display = "none";                                
	else {
		$('divStores').innerHTML = "<span class=\"tblTitle\"><IMG SRC=\"images/ballIndicator.gif\"></span>";
		$('divDir').innerHTML = "";
		$('prntStores').innerHTML = "";
		$('prntDir').innerHTML = "";
		$('divDir').style.display = "none";
		
	    
	}
}
          
function printMap() {
        
	if (window.print) {
		window.print();
	    
	}
	else
		alert("Sorry, your browser doesn't support this feature.");
}

function GetStateCoord(name)
{
	var coords = null;
	switch(name)
	{
		case "Illinois":
			coords = new VELatLong(39.739281,-89.504128);
			break;
		case "Missouri":
			coords = new VELatLong(38.304611,-92.436653);
			break;
		case "Kansas":
			coords = new VELatLong(38.498058,-98.320213);
			break;
		case "Oklahoma":
			coords = new VELatLong(35.308960,-98.716942);
			break;
		case "Texas":
			coords = new VELatLong(31.168989,-100.076790);
			break;
		case "New Mexico":
			coords = new VELatLong(34.166161,-106.026123);
			break;
		case "Arizona":
			coords = new VELatLong(34.168091,-111.930344);
			break;
		case "California":
			coords = new VELatLong(37.271832,-119.270203);
			break;
	}
	return coords;
}