// JavaScript Document
function doHowFarSubmit()
{
	//alert("doHowFarSubmit");

	// clear county value when coming from form
	var txt = document.getElementById("txtCounty");
	txt.value = "";
	
	hideStatus();
	
	// do calculation
	doHowFarCalculation();
}

function doHowFarCalculation()
{
	//alert("doHowFarCalculation");
	
	// validate form
	var txt = null;
	txt = document.getElementById("txtZip");
	var zip = txt.value;
	txt = document.getElementById("txtCity");
	var city = txt.value;
	txt = document.getElementById("txtCounty");
	var county = txt.value;
	
	if (zip.length == 0 && city.length == 0)
	{
		alert("Please enter a zip code or city and state.");
		return false;
	}

	// get state and destination
	var lst = null;
	lst = document.getElementById("lstState");
	var state = lst.options[lst.selectedIndex].value;
	lst = document.getElementById("lstDestination");
	var dest = lst.options[lst.selectedIndex].value;
	
	//alert(state);
	//alert(dest);
	
	// check for location
	getLocation(zip, city, state, county);
	
	//alert("Aloha");
}


function getLocation(zip, city, state, county)
{
	//alert("getLocation");
	
	var httpreq = getHTTPObject();
	
	showStatus("Status", "Finding your location...");
	
	var url = "geo.php?";
	if (zip != "")
	{
		url += "zip=" + zip;
	}
	else
	{
		url += "city=" + encodeURI(city) + "&state=" + state;
		if (county != "") url += "&county=" + county;
	}
	//alert("getting " + url);
	
    httpreq.open("GET", url, true);

    httpreq.onreadystatechange = function () {
			if (httpreq.readyState == 4)
			{
				//var div = document.getElementById(divName);
		
				if (httpreq.responseText)
				{
					last_text_response = httpreq.responseText;
					//format_news(last_text_response, div, divName);
					//alert(last_text_response);
					handleLocation(zip, city, state, county, last_text_response);
				}
				else 
				{		
					//div.innerHTML = "Data not available."; 
				}
			}
    }
    httpreq.send(null);			
}

function getDistance(id, lat, lng, home_id)
{
	//alert("getDistance");
	
	var httpreq = getHTTPObject();
	
	showStatus("Status", "Starting calculation...");
	
	var url = "dist.php?id=" + id + "&lat=" + lat + "&lng=" + lng + "&home_id=" + home_id;
	//alert("getting " + url);
	
    httpreq.open("GET", url, true);

    httpreq.onreadystatechange = function () {
			if (httpreq.readyState == 4)
			{
				//var div = document.getElementById(divName);
		
				if (httpreq.responseText)
				{
					last_text_response = httpreq.responseText;
					//format_news(last_text_response, div, divName);
					//alert(last_text_response);
					handleDistance(id, lat, lng, last_text_response);
				}
				else 
				{		
					//div.innerHTML = "Data not available."; 
				}
			}
    }
    httpreq.send(null);			
}

function showStatus(lbl_str, str)
{
	//alert("showStatus");
	
	var div = document.getElementById("status-wrapper");
	//alert("Got div: " + div);
	// clear existing text
	//alert("div.innerHTML (before) = " + div.innerHTML);
	div.innerHTML = "";
	//alert("div.innerHTML (after) = " + div.innerHTML);
	
	var para = document.createElement("p");
	// add status label
	var strong = document.createElement("strong");
	// add label
	var lbl = document.createTextNode(lbl_str + ": " );
	// add label to strong
	strong.appendChild(lbl);
	// add to paragraph
	para.appendChild(strong);
	// add text
	var txt = document.createTextNode(str);
	// add text to paragraph
	para.appendChild(txt);
	// add paragraph to div
	div.appendChild(para);
	// set div as visible
	//div.setAttribute("className", "show-div");
	setClass(div, "show-div");
	
	//alert("className = " + div.className);
	//alert("class = " + div.class);
	//alert("div.class = " + div.getAttribute("class"));
	//alert("div.className = " + div.getAttribute("className"));
	//alert("div.innerHTML (end) = " + div.innerHTML);
}

function hideStatus()
{
	//alert("hideStatus");
	
	var div = document.getElementById("status-wrapper");
	// set div as invisible
	//div.setAttribute("className", "hide-div");	
	setClass(div, "hide-div");
	// hide map as well
	div = document.getElementById("map-result");
	//div.setAttribute("className", "hide-div");	
	setClass(div, "hide-div");
	// hide milesign as well
	div = document.getElementById("milesign");
	//div.setAttribute("className", "hide-div");	
	setClass(div, "hide-div");
	// hide history
	div = document.getElementById("history");
	//div.setAttribute("className", "hide-div");	
	setClass(div, "hide-div");
}

function handleLocation(zip, city, state, county, response)
{
	//alert("handleLocation");
	
	if (response == "Not Found")
	{
		hideStatus();
		alert("Sorry, but we can't find your location. Please try another.");
		return;
	}
	
	// parse response first
	var lines = response.split("\r\n");
	//alert(lines.length);
	// show location list if needed
	var div_list = document.getElementById("multiple-locations");
	var ul_list = document.getElementById("location-list");
	if (lines.length == 1)
	{
		// hide multiple locations
		//div_list.setAttribute("className", "hide-div");
		setClass(div_list, "hide-div");
		showStatus("Status", "Location found, preparing calculation...");		
		displayLocation(zip, city, state, county, response);
	}
	else
	{
		hideStatus();
		// show multiplie locations
		//div_list.setAttribute("className", "show-div");
		setClass(div_list, "show-div");
		// populate list
		ul_list.innerHTML = "";
		for (i = 0; i < lines.length; i++)
		{
				// create list item from line
				var line = lines[i];
				// split line to get country and zip
				var parts = line.split("|");
				var li = document.createElement("li");
				// add text
				var thisId = parts[0];
				var thisZip = parts[4];
				var thisCounty = parts[2];
				var bZipFound = false;
				var msg = "";
				if (thisCounty.length > 0)
				{
					msg = "County: " + thisCounty;
				}
				if (Number(thisZip) > 0) 
				{
					if (msg.length > 0) msg += ", ";
					msg += "Zip Code: " + thisZip;
					bZipFound = true;
				}
				// create link tag
				var lnk = document.createElement("a");
				// set link properties
				if (bZipFound)
				{
					// use zip code in link
					lnk.setAttribute("href", "javascript:selectZip(" + thisZip + ");");
				}
				else
				{
					// use county in link
					lnk.setAttribute("href", "javascript:selectCounty(\"" + thisCounty + "\");");
				}
				var txt = document.createTextNode(msg);
				// add message to link
				lnk.appendChild(txt);
				
				// add link to li item
				li.appendChild(lnk);
				// add li to list
				ul_list.appendChild(li);
		}
	}
}

function handleDistance(id, lat, lng, response)
{
	//alert("handleDistance");
	
	// parse response to get distance and dest coordinates
	var parts = response.split("|");
	var miles = parts[0];
	var point = parts[1].split(",");
	var dest_lat = point[0];
	var dest_lng = point[1];
	
	// get city, state, and destination
	var txt = document.getElementById("txtCity");
	var city = txt.value;
	var lst = document.getElementById("lstState");
	var state = lst.options[lst.selectedIndex].value;
	lst = document.getElementById("lstDestination");
	var dest = lst.options[lst.selectedIndex].text;
	// show number of miles
	showStatus("Result", "Your distance is " + miles + " miles from " + city + ", " + state + " to " + dest + ".");
	
	// show mile sign
	var milesign = document.getElementById("milesign");
	var signbody = document.getElementById("milesign-body");
	// set name and miles
	signbody.innerHTML = "";	
	var para = document.createElement("p");
	//para.setAttribute("className", "milesign-dest");
	setClass(para, "milesign-dest");
	para.appendChild(document.createTextNode(dest));
	signbody.appendChild(para);

	para = document.createElement("p");
	//para.setAttribute("className", "milesign-miles");
	setClass(para, "milesign-miles");
	para.appendChild(document.createTextNode(miles));
	signbody.appendChild(para);
/*
	var ms_name = document.getElementById("milesign-dest");
	var ms_miles = document.getElementById("milesign-miles");
	// clear values
	ms_name.innerHTML = "";
	ms_miles.innerHTML = "";
	// set values
	ms_name.appendChild(document.createTextNode(dest));
	ms_miles.appendChild(document.createTextNode(miles));
*/
	// show milesign
	//milesign.setAttribute("className", "show-div");
	setClass(milesign, "show-div");
	
	// set map coordinates here
	var div = document.getElementById("map-result");
	div.innerHTML = "";
	//div.setAttribute("className", "show-div");
	setClass(div, "show-div");
	
	var divMap = document.createElement("div");
	//alert("before style: " + divMap.getAttribute("style"));
	//alert("before divMap.style: " + divMap.style);
	setWidthHeight(divMap, "500px", "300px");
	divMap.setAttribute("id", "map");
//	divMap.setAttribute("style", "width: 500px; height: 300px;");
	//alert("style: " + divMap.getAttribute("style"));
	//alert("divMap.style: " + divMap.style);
	div.appendChild(divMap);
	var map = document.getElementById("map");
	
	// find center
	var center = findCenter(lat, lng, dest_lat, dest_lng);	
	//alert(center.lat() + ", " + center.lng());
	map = new GMap2(document.getElementById("map"));
	var zoomLevel = 3;
	if (state == "AK") zoomLevel = 2
	map.setCenter(center, zoomLevel);
//		map.addControl(new GMapTypeControl());
	map.addControl(new GSmallMapControl());
	map.addControl(new GScaleControl());
	
	// add points
	var points = new Array( new GLatLng(lat, lng), new GLatLng(dest_lat, dest_lng));
	map.addOverlay(new GMarker(points[0]));
	map.addOverlay(new GMarker(points[1]));
	var line = new GPolyline(points, "#FF0000");
	map.addOverlay(line);
/*
	// add coordinates for now
	var para = null;
	var txt = null;
	para = document.createElement("p");
	txt = document.createTextNode("Start: " + lat + ", " + lng);
	para.appendChild(txt);
	div.appendChild(para);
	para = document.createElement("p");
	txt = document.createTextNode("End: " + dest_lat + ", " + dest_lng);
	para.appendChild(txt);
	div.appendChild(para);
	para = document.createElement("p");
	txt = document.createTextNode("Center: " + center);
	para.appendChild(txt);
	div.appendChild(para);
*/

	// move to status
	window.location.href = "#status";
}
	
function findCenter(lat, lng, dest_lat, dest_lng)
{
	//alert("findCenter");
	
	// get average lat
	var avg_lat = (Number(lat) + Number(dest_lat)) / 2;
	var avg_lng = (Number(dest_lng) + Number(lng)) / 2;
	
	// return center
	return new GLatLng(avg_lat, avg_lng);
}

function displayLocation(zip, city, state, county, response)
{
	//alert("displayLocation");
	
	//alert("Display Location");
	//alert(response);
		
	// get destination id
	var lst = document.getElementById("lstDestination");
	var dest = lst.options[lst.selectedIndex].value;
	var destName = lst.options[lst.selectedIndex].text;
	
	// get lat and lng from response
	var parts = response.split("|");
	var id = parts[0];
	var point = parts[1].split(",");
	var lat = point[0];
	var lng = point[1];
	
	// get city and state from location
	var location = "";
	if (zip > 0)
	{
		// zip look up only have lat/lng and location
		location = parts[2];
		// split and get city and state
		var loc = location.split(", ");
		city = loc[0];
		state = loc[1];
		
		setCityState(city, state);
	}
		
	//alert(location);
	//alert(response);
	
	// call calculation
	getDistance(dest, lat, lng, id);
	
	// show history
	getHistory(dest, destName);
}

function selectZip(zip)
{
	//alert("selectZip");
	
	// set zip on form
	var txt = document.getElementById("txtZip");
	txt.value = zip;
	
	// resubmit form
	doHowFarCalculation();
}

function selectCounty(county)
{
	//alert("selectCounty");
	
	// set zip on form
	var txt = document.getElementById("txtCounty");
	txt.value = county;
	
	// resubmit form
	doHowFarCalculation();
}

function setCityState(city, state)
{
	//alert("setCityState");
	
	var txt = document.getElementById("txtCity");
	txt.value = city;
	
	// select state in drop down
	var lst = document.getElementById("lstState");
	for (i = 0; i < lst.options.length; i++)
	{
		// get option and value
		var st = lst.options[i].value;
		if (st == state)
		{
			// select and exit
			lst.selectedIndex = i;
			break;
		}
	}
}

function getHistory(destId, destName)
{
	//alert("getHistory");
	
	var httpreq = getHTTPObject();
	
	var url = "dist_history.php?id=" + destId;
	
    httpreq.open("GET", url, true);

    httpreq.onreadystatechange = function () {
			if (httpreq.readyState == 4)
			{
				if (httpreq.responseXML)
				{
					last_xml_response = httpreq.responseXML;
					//format_news(last_text_response, div, divName);
					//alert(last_text_response);
					handleHistory(destName, last_xml_response);
				}
				else 
				{		
					//div.innerHTML = "Data not available."; 
				}
			}
    }
    httpreq.send(null);			
}

function handleHistory(destName, response)
{
	//alert("handleHistory");
	
	// get history div to show
	var div = document.getElementById("history");
	// get h2 to update destination name
	var h2 = document.getElementById("history-h2");
	
	// set h2 text
	h2.innerHTML = "";
	h2.appendChild(document.createTextNode("Recent Searches for " + destName));
	
	// get body for history results
	var signbody = document.getElementById("milesign-body-history");
	// set name and miles
	signbody.innerHTML = "";	
	
/* run in loop */
    var doc = response.documentElement;

	if (doc == null) return false;

	// get list of items
	var items = doc.getElementsByTagName('item');
	// loop through each item
	for (i = 0; i < items.length; i++)
	{
		var location = items[i].getElementsByTagName('location')[0];
		var miles = items[i].getElementsByTagName('miles')[0];

		var para = document.createElement("p");
		var city = location.firstChild.data;
		if (city.length < 14)
		{
			//para.setAttribute("className", "milesign-dest");
			setClass(para, "milesign-dest");
		}
		else
		{
			//para.setAttribute("className", "milesign-dest-small");
			setClass(para, "milesign-dest-small");
		}
		para.appendChild(document.createTextNode(city));
		signbody.appendChild(para);
	
		para = document.createElement("p");
		//para.setAttribute("className", "milesign-miles");
		setClass(para, "milesign-miles");
		para.appendChild(document.createTextNode(miles.firstChild.data));
		signbody.appendChild(para);

	}
	
	// show history div
	//div.setAttribute("className", "show-div");
	setClass(div, "show-div");								   
}


