//<![CDATA[
//Global Variables
var map;  //The Google Maps map.
var mapType; //The current type of the GMap (satellite, hybrid, etc)
var geocoder; //Geocoder object
var distance = 0;
var totaldistance = 0;
var currentUnit = "Miles";
var param = "";
var street = "";
var city = "";
var state = "";
var zip = "";

var startMarker = null;
var endMarker = null;
var arrayMarkers = [];		//array of end point overlay Markers
var arrayRadPoints = [];	//array of clicked points in radians
var arrayDegPoints = [];	//array of clicked points in degrees
var arrayPolyLine = [];		//array of the polyline overlays that make up the line segaments on the map
var arrayPolyLineDistance = []; //array of the length of the polylines
var boundingBox = null; //GLatLngBounds to fit loaded routes into map

//function enableWindowResizeHandler()
//{
	if (window.attachEvent) window.attachEvent("onresize", WindowResize);
	else window.addEventListener("resize", WindowResize, false);
//}


function initEventHandlers()
{
	addClickHandler();	
}

function flashInstructions()
{
	var t1 = setTimeout("document.getElementById('instructions').style.color='red'",1000);
	var t2 = setTimeout("document.getElementById('instructions').style.color = 'black'",1500);
	t1 = setTimeout("document.getElementById('instructions').style.color='red'",2000);
	t2 = setTimeout("document.getElementById('instructions').style.color = 'black'",2500);
	
}

function addClickHandler()
{
	//Event handler to perform when the map is clicked
	GEvent.addListener(map, 'click', function(overlay, point) {
	if (overlay) 
	{
		//map.removeOverlay(overlay);
	} 
	else if (point) 
	{
		//create and add start marker to map
		if(startMarker===null)
		{
			var icon = new GIcon();
			icon.image = "http://www.google.com/intl/en_ALL/mapfiles/dd-start.png";
			icon.shadow = "http://www.google.com/intl/en_ALL/mapfiles/shadow50.png";
			icon.iconSize = new GSize(20, 34);
			icon.shadowSize = new GSize(37, 34);
			icon.iconAnchor = new GPoint(10, 34);
			startMarker = new GMarker(point,icon)
			map.addOverlay(startMarker);
		}

		if(document.getElementById("autoCenter").checked == true)
		{
		    map.panTo(point);
		}

		//update last Lat/Long point text
		var latLngStr = point.y.toFixed(6) + ',&nbsp;' + point.x.toFixed(6);
		document.getElementById("lastclicked").innerHTML = latLngStr;
		
		var radPointY = point.latRadians();
		var radPointX = point.lngRadians();
							
		arrayDegPoints.push(point);

		if(arrayDegPoints.length >= 2)
		{
			//law of cosines formula (Great circle formula)
			//d = acos( sin(lat1).sin(lat2)+cos(lat1).cos(lat2).cos(long2-long1) ).R
						
			//radius of the earth in km = 6371.01 +/-0.02km
			//radius of the earth in ft = 20,902,263.8 feet +/-65.6167979
			//radius of the earth in yd = 6,967,421.26 yards +/-21.872266
			//radius of the earth in miles = 3,958.76208 miles +/-0.0124274238
				
			var one = arrayDegPoints.length - 2;
			var two = arrayDegPoints.length - 1;
			
			//add a polypoint overlay between the last two points
			var line = [];
			line.push(arrayDegPoints[one]);
			line.push(arrayDegPoints[two]);
			var polyline = new GPolyline(line,"#FF0000",3,0.5);  //add a red line 2pixels thick
			map.addOverlay(polyline);
			arrayPolyLine.push(polyline);
		
			//calculate distance using the great circle formula
			var sinlat1 = Math.sin(arrayDegPoints[one].latRadians());
			var sinlat2 = Math.sin(arrayDegPoints[two].latRadians());
			var coslat2 = Math.cos(arrayDegPoints[two].latRadians());
			var coslat1 = Math.cos(arrayDegPoints[one].latRadians());
			var long2long1 = arrayDegPoints[two].lngRadians()-arrayDegPoints[one].lngRadians();
			var coslong = Math.cos(long2long1);
			distance = (sinlat1*sinlat2)+(coslat1*coslat2*coslong);
			distance = Math.acos(distance);
			
			distance = distance*3963.1676;//3958.76208; //distance in miles
			totaldistance = totaldistance + distance;	
			
			arrayPolyLineDistance.push(distance);
					
			var unitDistance;
			var unitTotalDistance;

			if(currentUnit=="Miles")
			{
				unitDistance = distance;
				unitTotalDistance = totaldistance;
			}
			else if (currentUnit=="Yards")
			{
				unitDistance = distance*1760.0;//distance in yards
				unitTotalDistance = totaldistance*1760.0;
			}
			else if (currentUnit=="Feet"){
				unitDistance = distance*5280;//distance in feet
				unitTotalDistance = totaldistance*5280;
			}
			else if(currentUnit=="Meters") { //convert miles to meters
				unitDistance = distance*1609.344;
				unitTotalDistance = totaldistance*1609.344;
			}
			else if(currentUnit=="Km") { //convert miles to km
				unitDistance = distance*1.609344;
				unitTotalDistance = totaldistance*1.609344;
			}
			
			document.getElementById("segmentdistance").innerHTML = getPrecision(unitDistance,4);//  + " " + currentUnit;
			document.getElementById("unitLabel1").innerHTML = currentUnit;
			document.getElementById("totaldistance").innerHTML = getPrecision(unitTotalDistance,4);//  + " " + currentUnit;
			document.getElementById("unitLabel2").innerHTML = currentUnit;
			
			document.getElementById("routeURL").innerHTML = " ";
		}
	}
	});	
}	

function WindowResize()
{
	var frameWidth;
	var frameHeight;

	if (self.innerWidth)
	{
		frameWidth = self.innerWidth;
		frameHeight = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientWidth)
	{
		frameWidth = document.documentElement.clientWidth;
		frameHeight = document.documentElement.clientHeight;
	}
	else if (document.body)
	{
		frameWidth = document.body.clientWidth;
		frameHeight = document.body.clientHeight;
	}
	else return;
	
	if(frameHeight > 215) {
		document.getElementById("map").style.height = (frameHeight - 190) + "px";
	}
	if(frameHeight > 100) {
		document.getElementById("mapapp").style.height = (frameHeight - 55) + "px";
	}
	if(frameWidth > 240) {
		document.getElementById("map").style.width = (frameWidth - 135) + "px";
	}
	//map.onResize();
	if(map != null){
	    map.checkResize();
	}	
}

//resizes the map DIV
function WindowResizeFirstTime()
{
	var frameWidth;
	var frameHeight;

	if (self.innerWidth)
	{
		frameWidth = self.innerWidth;
		frameHeight = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientWidth)
	{
		frameWidth = document.documentElement.clientWidth;
		frameHeight = document.documentElement.clientHeight;
	}
	else if (document.body)
	{
		frameWidth = document.body.clientWidth;
		frameHeight = document.body.clientHeight;
	}
	else return;
	
	if(frameHeight > 215) {
		document.getElementById("map").style.height = (frameHeight - 215) + "px";
	}
	if(frameHeight > 100) {
		document.getElementById("mapapp").style.height = (frameHeight - 100) + "px";
	}
	if(frameWidth > 240) {
		document.getElementById("map").style.width = (frameWidth - 240) + "px";
	}	
}

function undoLeg()
{
	if(arrayDegPoints.length > 1)
	{
		if(endMarker != null)
		{
			map.removeOverlay(endMarker);
		}
		arrayDegPoints.pop();
		if(arrayPolyLine.length >= 1)
		{
			map.removeOverlay(arrayPolyLine.pop() );
			var tempdistance = arrayPolyLineDistance.pop();
			totaldistance = totaldistance - tempdistance;
			if(arrayPolyLineDistance.length > 0)
			{
				distance = arrayPolyLineDistance[arrayPolyLineDistance.length-1];
			}
			else
			{
				distance = 0;
				totaldistance = 0;
			}
			convertToUnit(currentUnit);
		}
	}
	
	document.getElementById("routeURL").innerHTML = " ";
}

function clearRoute()
{
    document.getElementById("routeURL").innerHTML = " ";
    clearTrack();
}

function clearTrack()
{
	if(startMarker !== null)
	{
		map.removeOverlay(startMarker);
		startMarker = null;
	}
	
	if(endMarker !== null)
	{
		map.removeOverlay(endMarker);
		endMarker = null;
	}
	
	//remove polyline overlays from map
	var i = 0;
//	while (i <= arrayPolyLine.length && arrayPolyLine.length!=0)
//	{ 
//		map.removeOverlay(arrayPolyLine[i]);
//		i=i+1;
//	}

for(;i<arrayPolyLine.length && arrayPolyLine.length != 0; i++)
{
map.removeOverlay(arrayPolyLine[i]);

}

	
	//remove distance labels
	document.getElementById("segmentdistance").innerHTML = " ";
	document.getElementById("totaldistance").innerHTML = " ";

	//clear global variables and arrays
	distance = 0;
	totaldistance = 0;
	
	arrayPolyLineDistance.length = 0; //array of saved distances
	arrayDegPoints.length = 0;	//array of clicked points in degrees
	arrayPolyLine.length = 0;	//array of the polyline overlays that make up the line segaments on the map
} 

function convertToUnit(unit)
{
	var unitDistance;
	var unitTotalDistance;
	if(unit=="Miles") {
		unitDistance = distance;
		unitTotalDistance = totaldistance;
		currentUnit="Miles";
	}
	else if(unit=="Yards") { //convert miles to yards
		unitDistance = distance * 1760.0;
		unitTotalDistance = totaldistance * 1760.0;
		currentUnit="Yards";
	} 
	else if(unit=="Feet") { //convert miles to yards
		unitDistance = distance*5280;
		unitTotalDistance = totaldistance*5280;
		currentUnit="Feet";
	}
	else if(unit=="Meters") { //convert miles to meters
		unitDistance = distance*1609.344;
		unitTotalDistance = totaldistance*1609.344;
		currentUnit="Meters";
	}
	else if(unit=="Km") { //convert miles to km
		unitDistance = distance*1.609344;
		unitTotalDistance = totaldistance*1.609344;
		currentUnit="Km";
	}
	
	document.getElementById("segmentdistance").innerHTML = getPrecision(unitDistance,3);//  + " " + currentUnit;
	document.getElementById("unitLabel1").innerHTML = currentUnit;
	document.getElementById("totaldistance").innerHTML = getPrecision(unitTotalDistance,3);//  + " " + currentUnit;
	document.getElementById("unitLabel2").innerHTML = currentUnit;
}

function getPrecision(num,precision)
{
	var str = num.toString(10);
	var decimalPoint = str.indexOf(".");
	
	//make sure we don't extend beyond string length
	if(precision + decimalPoint + 1 <= str.length)
	{ 
		str = str.slice(0,decimalPoint+precision + 1);
	}
	return str;
}

function saveState()
{
	var p = map.getCenterLatLng();
	var type = map.getCurrentMapType();
	var zoom = map.getZoomLevel();

	document.getElementById("mapLongitude").value = p.x;
	document.getElementById("mapLatitude").value = p.y;
	document.getElementById("mapZoom").value = zoom;
}

function getData()
{
	saveState();
	var i = 0;
	var strValue = "";
	for(i=0; i < arrayDegPoints.length-1; i++)
	{
		strValue = strValue + arrayDegPoints[i].x + "," + arrayDegPoints[i].y + "\n";
	}
	strValue = strValue + arrayDegPoints[i].x + "," + arrayDegPoints[i].y;
	document.getElementById("mapTrackData").value = strValue;
	return true;
}

function getLocationFields()
{
	street	= document.getElementById("txtStreet").value;
	//param = str.replace(/(\s)/g,"+");
	param = street;
}

function setLatLongOnMap(response)
{
	var lat = "";
	var lon = "";
	var zoom = "";
	var error = "";
	var i = 1;
	var c = '';
	
	if(response.indexOf("Error") >= 0)
	{
		alert("Error finding the location. Please check the address and correct any errors.");
		return;
	}
	
	//get latitude
	while( (c=response.charAt(i)) != '#' && i <= response.length)
	{
		lat = lat + c; 
		i++;
	}
	//get longitude
	i++;
	while( (c=response.charAt(i)) != '#' && i <= response.length)
	{
		lon = lon + c; 
		i++;
	}
	//get zoom
	i++;
	while( (c=response.charAt(i)) != '#' && i <= response.length)
	{
		zoom = zoom + c; 
		i++;
	}
	//alert("lat="+lat+ " ,lon="+lon+ " zoom="+zoom);
	map.setCenter(new GLatLng(lat,lon), parseInt(zoom,10) ); //map.centerAndZoom(new GPoint(lon, lat), parseInt(zoom,10) );
	
	if(parseInt(zoom,10)==17)
	{
		var strHtml = street + "<br/>" + city +", " + state;
		var point = new GLatLng(lat,lon);
		map.openInfoWindowHtml(point,strHtml);
		//var marker = new GMarker(point);
		//map.addOverlay(marker);
		//marker.openInfoWindowHtml(strHtml);
	}
}

function SetCookie(sName, sValue)
{
  date = new Date();
  document.cookie = sName + "=" + escape(sValue) + "; expires=" + date.toGMTString();
}

function DelCookie(sName)
{
  document.cookie = sName + "=" + escape(sValue) + "; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
}

function saveRoute()
{
	var divStyle = document.getElementById("saveRouteDialog").style;
	divStyle.position = "absolute";
	divStyle.display = "block";
	divStyle.visibility = "visible";
	divStyle.backgroundColor = "white";
}

function cancelRoute()
{
	var divStyle = document.getElementById("saveRouteDialog").style;
	divStyle.display = "none";
	//divStyle.visibility = "visible";
}

function closeRouteResult()
{
	var divStyle = document.getElementById("saveRouteResult").style;
	divStyle.display = "none";
	//divStyle.visibility = "visible";
}

function saveRouteToDatabase()
{
	map.draggableCursor = "wait";
    //debugger;
    var _name;
    _name = document.getElementById("routeName").value;
    if(_name==="") 
    {
		alert("Please enter a Route Name");
		return;
	}
    _name = _name.replace(/\<|\>|\"|\'|\%|\;|\(|\)|\&|\+|\-/g,"");
	
    var _description;
    _description = document.getElementById("routeDescription").value;
    _description = _description.replace(/\<|\>|\"|\'|\%|\;|\(|\)|\&|\+|\-/g,"");
    
    var _dist;// = ""; 
    _dist = totaldistance;//document.getElementById("totaldistance").innerHTML;
    if(!_dist) {_dist=0.0;}
    _dist = _dist.toFixed(3);
    var strXml = "<route>";
    strXml = strXml + "<name>" + _name + "</name>";
    strXml = strXml + "<description>"+_description+"</description>";
    strXml = strXml + xmlElementZoom( map.getZoom() );
    
    var objMapType = map.getCurrentMapType();
    var strMapType = objMapType.getName();
    
    strXml = strXml + xmlElementMapType(strMapType);
    var _c;
    for(_c=0; _c<arrayDegPoints.length;_c++ )
    {
        strXml = strXml + xmlElementPoint(_c.toString(),arrayDegPoints[_c].lat(),arrayDegPoints[_c].lng() );
    }
    
    strXml = strXml + "</route>";
   	if(!req)
	{
		req = createXmlRequestObject2();
	}
	//strXml = encodeURI(strXml);
	var SOAPEnvelope = "<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'><soap:Body><setRouteData xmlns='http://geodistance.com/'><routeName>"+_name+"</routeName><routeDescription>"+_description+"</routeDescription><routeData>"+strXml+"</routeData><lat>"+arrayDegPoints[0].lat()+"</lat><lon>"+arrayDegPoints[0].lng()+"</lon><routeDistance>"+_dist+"</routeDistance></setRouteData></soap:Body></soap:Envelope>";
	//req.open("POST", "http://www.geodistance.com/geodistance_ws.asmx", true);
	if(window.location.href.search(/http:\/\/geodistance.com/i) > -1)
    {
	    req.open("POST", "http://geodistance.com/geodistance_ws.asmx", true);
    }
    else if(window.location.href.search(/http:\/\/www.geodistance.com/i) > -1)
    {
	    req.open("POST", "http://www.geodistance.com/geodistance_ws.asmx", true);
    }
	//req.open("POST", "http://localhost:1644/GeoDistance/geodistance_ws.asmx", true);
	req.setRequestHeader('Content-Type',  "text/xml");
	req.onreadystatechange = cb_setRouteData;
	req.send(SOAPEnvelope);
	
    cancelRoute(); //close the window
}

function cb_setRouteData()
{
	if (req.readyState == 4) {
    // only if "OK"
		if (req.status == 200) {
			routeID = getRouteID();
			document.getElementById("savedRouteURL").innerHTML = "http://www.geodistance.com/?id="+routeID;
			var divStyle = document.getElementById("saveRouteResult").style;
			divStyle.position = "absolute";
			divStyle.display = "block";
			divStyle.visibility = "visible";
			divStyle.backgroundColor = "white";
			map.draggableCursor = "crosshair";
			document.getElementById("routeURL").innerHTML = "The URL for this route is <b>http://www.geodistance.com/?id="+routeID+"</b>";
		} 
		else {
			alert("There was a problem saving the Route to the database:\n");
			map.draggableCursor = "crosshair";
		}
	}
}

function getRouteID()
{
			var routeData;
			var routeID;
			
			//do IE specific XML processing
			if(window.ActiveXObject)
			{
				req.responseXML.setProperty("SelectionNamespaces", "xmlns:temp='http://geodistance.com/'");
				routeData = req.responseXML.selectNodes("//temp:setRouteDataResult");
				routeID = routeData[0].text;
			}
			
			//do Firefox, Netscape processing
			else if(window.XMLHttpRequest)
			{
				routeData = req.responseXML.getElementsByTagNameNS("http://geodistance.com/", "setRouteDataResult");
				routeID = routeData[0].textContent;
			}
			return routeID;
}

function loadRoute()
{
	//debugger;
	var divStyle = document.getElementById("findRouteDialog").style;
	divStyle.position = "absolute";
	divStyle.display = "block";
	divStyle.visibility = "visible";
	divStyle.backgroundColor = "white";
	
	//load table with data from DB
	//alert('loadRoute')
	fillTable();
}

function cancelLoadRoute()
{
	var divStyle = document.getElementById("findRouteDialog").style;
	divStyle.display = "none";
	//divStyle.visibility = "visible";
}

function loadRouteByName()
{
}

function loadRouteByID(routeID)
{
}

function addPointToRoute(lat, lng)
{
		point = new GLatLng(parseFloat(lat),parseFloat(lng) );
		arrayDegPoints.push(point);

		if(arrayDegPoints.length >= 2)
		{
				
			var one = arrayDegPoints.length - 2;
			var two = arrayDegPoints.length - 1;
			
			//add a polypoint overlay between the last two points
			var line = [];
			line.push(arrayDegPoints[one]);
			line.push(arrayDegPoints[two]);
			var polyline = new GPolyline(line,"#FF0000",3,0.5);  //add a red line 2pixels thick
			//map.addOverlay(polyline);
			arrayPolyLine.push(polyline);
		
			//calculate distance using the great circle formula
			var sinlat1 = Math.sin(arrayDegPoints[one].latRadians());
			var sinlat2 = Math.sin(arrayDegPoints[two].latRadians());
			var coslat2 = Math.cos(arrayDegPoints[two].latRadians());
			var coslat1 = Math.cos(arrayDegPoints[one].latRadians());
			var long2long1 = arrayDegPoints[two].lngRadians()-arrayDegPoints[one].lngRadians();
			var coslong = Math.cos(long2long1);
			distance = (sinlat1*sinlat2)+(coslat1*coslat2*coslong);
			distance = Math.acos(distance);
			
			distance = distance*3963.1676;//3958.76208; //distance in miles
			totaldistance = totaldistance + distance;	
			
			arrayPolyLineDistance.push(distance);
		}
}

function displayPolylines(strMapType,strZoom)
{
	//close the loadRoute Dialog
	cancelLoadRoute();
	
	var boxCenter = null;
	var boxZoom = null;
	
	if(arrayDegPoints.length > 0)
	{
		boundingBox = new GLatLngBounds(arrayDegPoints[0],arrayDegPoints[0]);
		for(var x=0;x<arrayDegPoints.length;x++)
		{
			boundingBox.extend(arrayDegPoints[x]);
		}
		boxCenter = boundingBox.getCenter();
		boxZoom = map.getBoundsZoomLevel(boundingBox);
		boundingBox = null;
	}
	
	switch(strMapType.toUpperCase())
	{
	case 'SATELLITE':
		map.setMapType(G_SATELLITE_MAP);
		break;
	case 'HYBRID':
		map.setMapType(G_HYBRID_MAP);
		break;
	case 'MAP':
		map.setMapType(G_NORMAL_MAP);
		break;
	default:
		map.setMapType(G_NORMAL_MAP);
		break;
	}
	
	if(boxZoom)
	{
		map.setZoom(boxZoom);
	}
	else
	{
		map.setZoom(parseInt(strZoom,10));
	}
	if(boxCenter)
	{
		map.panTo(boxCenter);
	}
	else
	{
		map.panTo(arrayDegPoints[0]);
	}
	
	//add polylines to the map
	for(var x=0;x<arrayPolyLine.length;x++)
	{
		map.addOverlay(arrayPolyLine[x]);
	}
	
	//add start finsh markers to the route
	if(startMarker===null)
	{
		var icon = new GIcon();
		icon.image = "http://www.google.com/intl/en_ALL/mapfiles/dd-start.png";
		icon.shadow = "http://www.google.com/intl/en_ALL/mapfiles/shadow50.png";
		icon.iconSize = new GSize(20, 34);
		icon.shadowSize = new GSize(37, 34);
		icon.iconAnchor = new GPoint(10, 34);
		if(arrayDegPoints.length > 0)
		{
			startMarker = new GMarker(arrayDegPoints[0],icon)
		}
	}
	map.addOverlay(startMarker);

	if(endMarker===null)
	{
		var icon2 = new GIcon();
		icon2.image = "http://www.google.com/intl/en_ALL/mapfiles/dd-end.png";
		icon2.shadow = "http://www.google.com/intl/en_ALL/mapfiles/shadow50.png";
		icon2.iconSize = new GSize(20, 34);
		icon2.shadowSize = new GSize(37, 34);
		icon2.iconAnchor = new GPoint(10, 34);
		if(arrayDegPoints.length > 0)
		{
			endMarker = new GMarker(arrayDegPoints[arrayDegPoints.length-1],icon2)
		}
	}
	map.addOverlay(endMarker);
						
	if(currentUnit=="Miles")
	{
		unitDistance = distance;
		unitTotalDistance = totaldistance;
	}
	else if (currentUnit=="Yards")
	{
		unitDistance = distance*1760.0;//distance in yards
		unitTotalDistance = totaldistance*1760.0;
	}
	else if (currentUnit=="Feet"){
		unitDistance = distance*5280;//distance in feet
		unitTotalDistance = totaldistance*5280;
	}
	else if(currentUnit=="Meters") { //convert miles to meters
		unitDistance = distance*1609.344;
		unitTotalDistance = totaldistance*1609.344;
	}
	else if(currentUnit=="Km") { //convert miles to km
		unitDistance = distance*1.609344;
		unitTotalDistance = totaldistance*1.609344;
	}
	
	document.getElementById("segmentdistance").innerHTML = getPrecision(unitDistance,4);//  + " " + currentUnit;
	document.getElementById("unitLabel1").innerHTML = currentUnit;
	document.getElementById("totaldistance").innerHTML = getPrecision(unitTotalDistance,4);//  + " " + currentUnit;
	document.getElementById("unitLabel2").innerHTML = currentUnit;
	
	document.getElementById("lastclicked").innerHTML = arrayDegPoints[arrayDegPoints.length-1].lat() + "," + arrayDegPoints[arrayDegPoints.length-1].lng();
		//}
}

function xmlElementPoint(nodeData, latitude, longitude)
{
	var _node;
    _node = "<point lat='" + latitude.toFixed(7) + "' lng='" + longitude.toFixed(7) + "'>" + nodeData + "</point>";
    
    return _node;
}

function xmlElementZoom(zoomLevel)
{
    var _node;
    _node = "<zoomlevel>" + zoomLevel + "</zoomlevel>";
    return _node; 
}

function xmlElementMapType(mapType)
{
    var _node;
    _node = "<maptype>" + mapType + "</maptype>";
    return _node; 
}


function GeoPoint()
{
    this.x = 0.0;
    this.y = 0.0;
}

var xmlhttp = null;

function submitGeocode()
{
    //debugger;
    var str = document.getElementById("txtStreet").value;
    document.getElementById("txtStreet").value = str;
    updateMap();
}

function updateMap()
{	
    //alert("updateMap()");
    //debugger;
	getLocationFields();
	geocoder.getLocations(param,function(response)
	{
	    if (!response || response.Status.code != 200) {
            alert(param + " not found");
        } 
        else {
            var lpoint = new GLatLng(response.Placemark[0].Point.coordinates[1],response.Placemark[0].Point.coordinates[0]);
            var zoom;
            switch(response.Placemark[0].AddressDetails.Accuracy)
            {
            case 1:
                zoom = 4;
                break;
            case 2:
                zoom = 5;
                break;
            case 3:
                zoom = 9;
                break;
            case 4:
                zoom = 13;
                break;
            case 5:
                zoom = 13;
                break;
            case 6:
                zoom = 17;
                break;
            case 7:
                zoom = 18;
                break;
            case 8:
                zoom = 18;
                break;
            default:
                zoom = 8;
            }
            map.setCenter(lpoint, zoom);
        }
	});
  
  return false;
}

function exportToKML()
{
	//check that there are at least 2 points
	if(arrayDegPoints.length < 2)
	{
		alert("Please create at least 2 points before exporting the route to a KML file.");
		return;
	}
	
	//note: Google KML file coordinate order is longitude,latitude,altitude
	var _tempStr = longlatToString();
	document.getElementById("dataKML").value = _tempStr;
	document.getElementById("geodistance").submit();
}

function longlatToString()
{
	var _x = 0;
	var _lonlatStr = "";
	for (_x=0; _x < arrayDegPoints.length; _x++)
	{
		_lonlatStr = _lonlatStr + arrayDegPoints[_x].lng() + "," + arrayDegPoints[_x].lat() + ",5\n ";
	}
	
	return _lonlatStr;
}
//]]>
