        var map = null;
        var token="";
        var finding = false;
        var IsRouteByClick = false;
		var htPinID = new HashTable();
        
        var popuplat;
        var popuplon;
        
        var layerid=1;
        var iconUrl = "images/gasStationYB.gif";
        //var veLayer = new VEShapeLayer();
        var startpt;
        var endpt;
        
        function validate() { 
			var str = ""; 
			var elements = document.getElementsByTagName('input'); 

			// loop through all input elements in form 
			for(var i = 0; i < elements.length; i++) { 

				// check if element is mandatory; ie has a pattern  
				var pattern = elements.item(i).getAttribute('pattern'); 
				if (pattern != null) { 
					var value = elements.item(i).value; 

					// validate the value of this element, using its defined pattern 
					var offendingChar = value.match(pattern); 

					// if an invalid character is found 
					if(offendingChar != null) { 

					// add up all error messages 
					str += elements.item(i).getAttribute('errorMsg') + "\n" + 
							"Invalid character(s): '" + offendingChar + "' \n"; 

					// notify user by changing background color, in this case to red 
					//elements.item(i).style.background = "red";  
					} 
				} 
			}  

			if (str != "") { 
				// do not submit the form 
				alert("ERROR ALERT!!\n" +str);  
				return false; 
			} else { 
				// form values are valid; submit 
				return true; 
			} 
		}
		
        function GetMap()
        {
			token = document.getElementById('ClientToken');
            map = new VEMap('UKMap');
			map.SetClientToken(token);
            map.LoadMap(new VELatLong(54.928662,-3.006462),5);
            map.AttachEvent("onchangeview", ViewChange);
            map.AttachEvent("onclick", removepopupmenu);
	        map.AttachEvent("oncontextmenu", popupmenu);
	        
        }
        
/*        {
            map.DeleteAllPushpins();
            deleteRoute();
            var l = new VEShapeLayer();	
            var veLayerSpec = new VEShapeSourceSpecification(VEDataType.GeoRSS, "UKSitesRSS.xml", l);
            map.ImportShapeLayerData(veLayerSpec,onFeedLoad);
				
//            veLayerSpec.Type = VELayerType.GeoRSS;
//            veLayerSpec.ID = layerid;
//            veLayerSpec.LayerSource = "UKSites.xml";
//            veLayerSpec.Method = 'get';
//            veLayerSpec.IconUrl = iconUrl;
//            veLayerSpec.FnCallback = onFeedLoad;
//            map.AddLayer(veLayerSpec);
            layerid++;
        }
*/        
        function onFeedLoad(layer)
        {
            document.getElementById('searchForm').style.display = "none";
            document.getElementById('RESULTS').style.display = "none";
            var numShapes = layer.GetShapeCount();
            for(var i=0; i < numShapes; ++i)
			{
				var s = layer.GetShapeByIndex(i);
				s.SetCustomIcon("<img src='images/gasStationYB.gif'/>");
			}

        }
        
        function removepopupmenu(e)
        {
            var menu = document.getElementById('divPopupContainer').style.display='none';
            document.getElementById('routeForm').style.display = "none";
            document.getElementById('searchForm').style.display = "none";
            
        }
        
        

        function popupmenu(e)
        {
           var s = map.GetMapStyle();
           //alert(map.GetMapStyle());
           if (s == "o")
                return;
            var menu = document.getElementById('divPopupContainer');//'popupmenu');
            menu.style.display='block'; //Showing the menu

            popuplat = e.view.LatLong.Latitude;
            popuplon = e.view.LatLong.Longitude;
	
            var LLA = new VELatLong();
            LLA.Latitude = popuplat;
            LLA.Longitude = popuplon;
            var clickedPoint = map.LatLongToPixel(LLA); //Positioning the menu
            menu.style.left = clickedPoint.x + 234;
            menu.style.top = clickedPoint.y + 100;
        }
        
        function DeletePin(pinId)
        {  
            var len = map.pushpins.length;
            var pointSetUp = false;
            
            
            if (len > 0)
            {
                for (i=0; i<len; i++)
                {
                    if (map.pushpins[i].ID == pinId)
                        pointSetUp = true;
                }
                
                try {
                    if (pointSetUp)
                        map.DeletePushpin(pinId);
                    else
                    {}
                }              
                
                catch (err)
                {
                    alert(err.message);
                }
            
            }
            else
            {}
         } 
        
        function setStart()
        {
           //map.DeleteAllPushpins();
           DeletePin('start')
           
            var pin = new VEPushpin(
                'start',
                new VELatLong(popuplat,popuplon),
                'images/bluePin.gif',
                'Location Info',
                'This is your start point');
                map.AddPushpin(pin);
                
          
          startpt = new VELatLong();
          startpt.Latitude = popuplat;
          startpt.Longitude = popuplon;
        }

        function setEnd()
        {
          DeletePin('end');
           
            var pin = new VEPushpin(
                'end',
                new VELatLong(popuplat,popuplon),
                'images/redPin.gif',
                'Location Info',
                'This is your destination point');
                map.AddPushpin(pin); 

          endpt = new VELatLong();
          endpt.Latitude = popuplat;
          endpt.Longitude = popuplon;  
        }
            
        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 && typeof XMLHttpRequest != "undefined")
            {
                x = new XMLHttpRequest();
            }
            
            return x;
        }
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 ZoomTo(lat,lon,level)
{
	map.SetCenterAndZoom(new VELatLong(lat,lon),level);
}

function AddPushpin(lat,lon,num,title,info,addInfo)
{
	
	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/gasStationYB.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 = "images/gasStationYB.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 GetData(url,type) {
	var xmlhttp = GetXmlHttp();
	var sTemp = "";

	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 rightTrim(sString) 
         {
            while (sString.substring(sString.length-1, sString.length) == ' ')
            {
                sString = sString.substring(0,sString.length-1);
            }
            return sString;
         }
         
         function ResetFields()
         {
            document.getElementById('txtStreet').value = "";
            document.getElementById('txtCity').value = "";
            document.getElementById('txtZip').value = "";
            
            document.getElementById('txtStreetFrom').value = "";
            document.getElementById('txtCityFrom').value = "";
            document.getElementById('txtZipFrom').value = "";
            
            document.getElementById('txtStreetTo').value = "";
            document.getElementById('txtCityTo').value = "";
            document.getElementById('txtZipTo').value = "";
                     
         }
         
         function BuildAddress(street,city,zip)
         {
            var address = "";
            if (street != "") {
                address += street;
                if (city != "")
                    address += ", " + city;
                else
                    return;
                    
                if (zip != "")
                    address += " " + zip + ", UK";
                else
                    address += ", UK";
             }
             else {
                if (city != "")
                {
                    address += city;
                    if (zip != "")
                      address = zip + ", UK";
                    else
                      address = city + ", UK";
                            
                }
                else {
                    if (zip != "")
                      address = zip + ", UK";
                    else 
                      return address;
                } 
             }                   
             return address;
        }
         
			var txtWhere = "";
			function getAllStations()
			{
				var latLong = map.GetCenter();
					
				var street = "";
                var city = "Nottingham";
                var zip = "";
			    document.getElementById("searchForm").style.display = "none";
				map.DeleteAllPushpins();
				deleteRoute();
				txtWhere = "";
				
			    txtWhere = BuildAddress(street,city,zip);
			    try
			    {
					map.Find('',txtWhere, null, null, null, null, null, null, null, null, onAddressFoundAll);
                    //map.FindLocation(txtWhere);
                }
                catch(e)
                {
                    alert("The requested location cannot be found. Check your input.");
                }
                finding = true;				
				
/*				$('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();
*/
			}
            function FindNear()
            {
				var street = "";
                var city = "";
                var zip = "";
/*				if (document.getElementById('chkUKOutlets').checked) {
					city = "Nottingham";
				}
				else
				{*/
					street = document.getElementById('txtStreet').value;
					city = document.getElementById('txtCity').value;
					zip = document.getElementById('txtZip').value;
			    /*}*/
			    document.getElementById("searchForm").style.display = "none";
				map.DeleteAllPushpins();
				deleteRoute();
				txtWhere = "";
				
			    txtWhere = BuildAddress(street,city,zip);
			    try
			    {
/*				if (document.getElementById('chkUKOutlets').checked) 
				{
					map.Find('',txtWhere, null, null, null, null, null, null, null, null, onAddressFoundAll);
				}
				else
				{*/
					map.Find('',txtWhere, null, null, null, null, null, null, null, null, onAddressFound);
				/*}*/
					
                    //map.FindLocation(txtWhere);
                }
                catch(e)
                {
                    alert("The requested location cannot be found. Check your input.");
                }
                finding = true;
                
            }
            function onAddressFoundAll()
            {
				var latLong = map.GetCenter();
					
				var url = "UKSiteLocatorHandler.ashx?type=FindAll";
				url += "&street=" + "";
				url += "&city=" + "Nottingham";
				url += "&zip=" + "";
				url += "&range=250"
				
				GetData(url,"search");
				
				
				
			}
            
            
            
			function onAddressFound()
			{
				var latLong = map.GetCenter();
//				$('RESULTS').style.display = "block";
					
				var url = "UKSiteLocatorHandler.ashx?type=Find";
				url += "&street=" + document.getElementById('txtStreet').value;
				url += "&city=" + document.getElementById('txtCity').value;
				url += "&zip=" + document.getElementById('txtZip').value;
				url += "&range=" + document.getElementById('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();
				
			}
            
            function findCompleted()
            {
            finding = false;
            
            
            }

            function ViewChange()
            {
            if (finding)
                findCompleted();
            }
             
                                   
            
            
            function ShowPanel()
            {
                
                var e = window.event;
                if (e.srcElement.id == "imgRoute")
                {
                    document.getElementById("searchForm").style.display = "none";
                    document.getElementById("routeForm").style.display = "block";
                    
                }
                if (e.srcElement.id == "imgSearch")
                {
                    document.getElementById("searchForm").style.display = "block";
                    document.getElementById("routeForm").style.display = "none";
                   
                }
                
            }
            
            function GetARoute()
            {
                if (map.GetMapStyle() == VEMapStyle.Birdseye)
					map.SetMapStyle(VEMapStyle.Road);
                map.DeleteAllPushpins();
                document.getElementById('divPopupContainer').style.display = 'none';
                var e = window.event;
                var txtFrom = "";
                var txtTo = "";
                
                if (e.srcElement.id == "Button1")
                {
					var street0 = document.getElementById('txtStreetFrom').value;
                    var city0 = document.getElementById('txtCityFrom').value;
                    var zip0 = document.getElementById('txtZipFrom').value;
			        txtFrom = BuildAddress(street0,city0,zip0);
    			        			    
                    var street1 = document.getElementById('txtStreetTo').value;
                    var city1 = document.getElementById('txtCityTo').value;
                    var zip1 = document.getElementById('txtZipTo').value;
			        txtTo = BuildAddress(street1,city1,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;
			    }
			    
                map.GetRoute(txtFrom,txtTo,null,null,onGotRoute);
            }
           
			 
            function onGotRoute(route)
            {
                if (dd.elements["divDirections"] != null) {
                        dd.elements.divDirections.del();
                        document.getElementById("divDirections").style.display = "none";
                }
                document.getElementById("routeForm").style.display = "none";
                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 = "UKStoreLocatorVE.aspx?type=Route";
                url += "&latS=" + latStart;
                url += "&lonS=" + lonStart;
                url += "&latE=" + latEnd;
                url += "&lonE=" + lonEnd;
                //alert(url);
                var xmlhttp = GetXmlHttp();
                
                if (xmlhttp)
                {
                    document.getElementById('RESULTS').style.display = "block";
                    xmlhttp.onreadystatechange = function()
                    {
                        if (xmlhttp.readyState == 4)
                        {
                            //alert(xmlhttp.status);
                            if (xmlhttp.status == 200)
                            {
                                var result = xmlhttp.responseText;
                                var temp = result.split("<!");
                                result = temp[0];
                                                                
                                eval(result);
                                document.getElementById('RESULTS').style.display = "none";
                                //document.getElementById('progress').className = "off";
                                //document.getElementById('RESULTS').innerHTML = "<xmp>" + result + "</xmp>";
                            }
                        }
                    }
                    xmlhttp.Open("GET", url, true);
                    xmlhttp.send(null);
                 }
                 
                var steps="<table cellpadding='2' style=\"width: 350px; z-index:10;\" class=\"tblDirections\" border=\"0\"><tr><td colspan=\"3\"><span class='tblTitle'>Directions</span><span id=\"btnCloseDirections\" style=\"LEFT:255px\" onclick=\"Close();\"><img id=\"imgCloseD\" alt=\"Close\" src=\"images/TitleClose1.gif\"></td></tr>";
                var len = route.Itinerary.Segments.length;
                if (IsRouteByClick)
                {
                    steps += "<tr><td class='instruct' style=\"width: 19px\">1.</td>";
                    steps += "<td class='instruct' style=\"width: 280px\">" + route.Itinerary.Segments[0].Instruction + " Start Point</td>";
                    steps += "<td class='Num'>" + route.Itinerary.Segments[0].Distance + " " + 
                    route.Itinerary.DistanceUnit + "</td></tr>";
                    for(var i = 1; i<len-1 ;i++)
                    {
                        steps += "<tr><td class='instruct' style=\"width: 19px\">" + (i+1) + ".</td>";
                        steps += "<td class='instruct' style=\"width: 280px\">" + route.Itinerary.Segments[i].Instruction + "</td>";
                        steps += "<td class='Num'>" + route.Itinerary.Segments[i].Distance + " " + 
                        route.Itinerary.DistanceUnit + "</td></tr>";
                        
                    }
                    steps += "<tr><td class='instruct' style=\"width: 19px\">" + len + ".</td>";
                    steps += "<td class='instruct' style=\"width: 280px\">" + route.Itinerary.Segments[len-1].Instruction + " End Point</td>";
                    steps += "<td class='Num'>" + route.Itinerary.Segments[len-1].Distance + " " + 
                    route.Itinerary.DistanceUnit + "</td></tr>";
                }
                else
                {
                    
                    for(var i = 0; i<len ;i++)
                    {
                        steps += "<tr><td class='instruct' style=\"width: 19px\">" + (i+1) + ".</td>";
                        steps += "<td class='instruct' style=\"width: 280px\">" + route.Itinerary.Segments[i].Instruction + "</td>";
                        steps += "<td class='Num'>" + 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>";
                
                document.getElementById('divDir').innerHTML = steps;
                document.getElementById('forPrint').innerHTML = steps;
                document.getElementById('divDirections').style.display = "block";
                document.getElementById('divDir').style.display = "block";
                document.getElementById('divDirections').style.height = document.getElementById('divDir').style.height;
                ADD_DHTML("divDirections");               
            }
            
                                   
            function deleteRoute()
            {
                try  
                {  
                    map.DeleteRoute();
                }
                catch (err)     
                {
                    alert(err.message);
                } 
            }
            
         var opacityOn = false;
         
                
         function Close()
         {
            var eSrc = window.event.srcElement;
                
            if (eSrc.id == "imgClose")
            {
               ResetFields();
               document.getElementById('formPanel').style.display = "none";
            }
            else {
				document.getElementById('divDirections').style.display = "none";
				document.getElementById('forPrint').innerHTML = "";
				document.getElementById('divDir').style.display = "none";
				
                
            }
         }
         
         function window.onbeforeprint()
         {
			if (dd.elements["divDirections"] != null) {
              dd.elements.divDirections.hide();
            }
         }
         
         function window.onafterprint()
         {
			if (dd.elements["divDirections"] != null) {
              dd.elements.divDirections.show();
            }
         }
                 
         function printMap() {
           			
            if (window.print) {
                window.print();
                
            }
            else
                alert("Sorry, your browser doesn't support this feature.");
         }


