var configXML = "/var/www/includes/config/www_newfields_com.xml";
var jsonLocation;
var map;
var markers = [];
var gdir;
var sPDirectionsUrl ='';

$(document).ready(function()
{
	if (GBrowserIsCompatible()) {
		// Initialize the map.
		map = new GMap2(document.getElementById("map"), {size: new GSize(450, 400)});
		
        gdir = new GDirections(map, document.getElementById("directions"));
		GEvent.addListener(gdir, "addoverlay", onGDirectionsLoad);
		GEvent.addListener(gdir, "load", RealDirectionsLoad);
		
        GEvent.addListener(gdir, "error", handleErrors);

		map.addControl(new GSmallZoomControl3D());
		map.addControl(new GNavLabelControl());
		map.setCenter(new GLatLng(32.249974,-47.8125), 1);
	}
	GetLocationList();
});

function onGDirectionsLoad()
{
}

function RealDirectionsLoad()
{
	$("#directions #printlink").remove();
	$("#directions").prepend('<div id="printlink"><a target="map" href="locations_directions_printable.php?' + sPDirectionsUrl + '">Get Printable Directions</a></div>');
	map.closeInfoWindow();
}
function GetDirections(form) //start, end)
{
	start = form.d_start.value;
	end = $(form).find("span#destination_address").text();
	//alert(end)
	gdir.load("from: " + start + " to: " + end, {locale:"en_US"}); //, { "travelMode ": mode }
	sPDirectionsUrl = "fromAddress=" + start  + "&amp;toAddress=" + end; 

}

function GetLocationList()
{
	$.getJSON("/lib/Query.js.php",
	{
		XMLFile: configXML,
		QueryID: "Locations"
	},
	function(json){
		var sHtml = '<div class="loc_person"><a class="locationtitle" href="javascript:LocationChanged(0)">VIEW ALL</a></div>';
		var sCountry = '';
		if(json)
		{
			jsonLocation = json;
			//it's an array of records to loop through
			var sem = 0;
			$(jsonLocation).each(function(i)
			{
				var L = jsonLocation[i];
				var lat = parseFloat(L.lattitude);
				var lng = parseFloat(L.longitude);
				var point = new GLatLng(lat,lng);
				var marker = new GMarker(point);

				var txtAddress = (L.address1 ? L.address1 + '<br/>': '');
				txtAddress += (L.address2 ? ' ' + L.address2 + '<br/>': '');
				if (L.real_city){
					txtAddress += L.real_city;
				} else {
					txtAddress += L.city ? L.city : '';
				}
				txtAddress += L.state ? ', ' + L.state : '';
				txtAddress += (L.zip ? '  ' + L.zip : '') + '<br/>';
				txtAddress += (L.country ? '  ' + L.country + '<br/>': '') ;
				txtAddress += (L.phone ? L.phone + '<br/>' : '');
				txtAddress += L.url ? '<a href="' + L.url + '">website</a>' : '';
				
				var arrDirectionsForm = new Array();
				if (L.address1 ) arrDirectionsForm.push(L.address1);
				if (L.address2 ) arrDirectionsForm.push(L.address2);
				if (L.city ) arrDirectionsForm.push(L.city);
				if (L.state ) arrDirectionsForm.push(L.state);
				if (L.country ) arrDirectionsForm.push(L.country);
				//$("div#secretstash).attr('value', );
				
				//var txtDirectionsForm = $("div#secretstash").html();
				var txtDirectionsForm = document.getElementById('secretstash').innerHTML;
				
				if(sem==0){
					//alert(txtDirectionsForm);	
					sem =1;
				}
				txtDirectionsForm = txtDirectionsForm.replace(/\$destination\$/, arrDirectionsForm.join(', '));
				txtDirectionsForm = txtDirectionsForm.replace(/\$destination\$/, arrDirectionsForm.join(', '));


				//.replace(/\n/, '').replace(/\s/, '')
				txtAddress = '<div class="address">' + txtAddress + '</div>';		
				
				var infoTabs = new Array(
					new GInfoWindowTab("Address", txtAddress ),
					new GInfoWindowTab("Directions", txtDirectionsForm )
				);

				GEvent.addListener(marker, "click", function() {
					marker.openInfoWindowTabsHtml(infoTabs,{
						selectedTab:0,
						maxWidth:300
					});
				});
				
				if(L.lattitude)
					map.addOverlay(marker);				
				
				if(sCountry != L.country)
				{
					sHtml += '<div class="location" style="margin-top:8px;color:#036"><strong>' + L.country + '</strong><br></div>';
					sCountry = L.country;
				}
				var sTitle = L.state ? L.city + ', ' + L.full_name : L.city;
				sHtml += '<div class="loc_person"><a class="locationtitle" href="javascript:LocationChanged(' + (i + 1) + ')">' + sTitle + '</a></div>';
			});
			 
			//if (jsonRequest.locationID)
				//LocationChanged(ID2Index(jsonRequest.locationID));

			$("td#location_list").append(sHtml);
		}
		else
		{
			alert('Error getting names list');
		}
	});
}

function ID2Index(id)
{
	for (i=0; i < jsonLocation.length; i++){
		if (jsonLocation[i].id == id) 
			return i + 1;
	}
}

function LocationChanged(index) 
{
	L = jsonLocation[index - 1];
	map.closeInfoWindow();
	if (index <= 0){
		map.setCenter(new GLatLng(24.686952,-81.210937), 2);
		//http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=usa&sll=33.830123,-84.264793&sspn=0.009376,0.015471&ie=UTF8&z=2
		$("div#search_title").html('SHOWING ALL');
		$("div#location_info").html('');
	}
	else
	{
		//alert(L.name);
		map.setCenter(new GLatLng(L.lattitude,L.longitude), 9);
		$("div#search_title").html((L.city ? L.city : '') + (L.state ? ', ' + L.state : '') + (L.country ? ', ' + L.country : ''));
		var txtAddress = L.address1 + '<br/>';
		txtAddress += L.address2 ? L.address2 + '<br/>' : '';
		if (L.real_city){
			txtAddress += L.real_city;
		} else {
			txtAddress += L.city ? L.city : '';
		}
		txtAddress += L.state ? ', ' + L.state : '';
		txtAddress += (L.zip ? '  ' + L.zip : '') + '<br/>';
		txtAddress += L.country + '<br/>';
		txtAddress += (L.phone ? L.phone + '<br/>' : '');
		$("div#location_info").html(txtAddress);
	}
}


function ShowSelection()
{
	var sHtml='';
	var searchString = '';
	
//	$("table#partner_list").html(sHtml);
}

function handleErrors(){
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
		alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_BAD_KEY)
		alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
		alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	else alert("An unknown error occurred.");
}

function NONONOonGDirectionsLoad(){ 
	var poly = gdir.getPolyline();
	/*
	if (poly.getVertexCount() > 100) {
		alert("This route has too many vertices");
		return;
	}
	*/
	var baseUrl = "http://maps.google.com/staticmap?";
	
	var params = [];
	var markersArray = [];
	markersArray.push(poly.getVertex(0).toUrlValue(5) + ",greena");
	markersArray.push(poly.getVertex(poly.getVertexCount()-1).toUrlValue(5) + ",greenb");
	params.push("markers=" + markersArray.join("|"));
	
	var polyParams = "rgba:0x0000FF80,weight:5|";
	var polyLatLngs = [];
	for (var j = 0; j < poly.getVertexCount(); j++) {
		polyLatLngs.push(poly.getVertex(j).lat().toFixed(5) + "," + poly.getVertex(j).lng().toFixed(5));
	}
	params.push("path=" + polyParams + polyLatLngs.join("|"));
	params.push("size=300x300");
	params.push("key=" + gKey);
	
	baseUrl += params.join("&");
	
	var extraParams = [];
	extraParams.push("center=" + map.getCenter().lat().toFixed(6) + "," + map.getCenter().lng().toFixed(6));
	extraParams.push("zoom=" + map.getZoom());
	addImg(baseUrl + "&" + extraParams.join("&"), "staticMapOverviewIMG");
	
	var extraParams = [];
	extraParams.push("center=" + poly.getVertex(0).toUrlValue(5));
	extraParams.push("zoom=" + 15);
	addImg(baseUrl + "&" + extraParams.join("&"), "staticMapStartIMG");
	
	var extraParams = [];
	extraParams.push("center=" + poly.getVertex(poly.getVertexCount()-1).toUrlValue(5));
	extraParams.push("zoom=" + 15);
	addImg(baseUrl + "&" + extraParams.join("&"), "staticMapEndIMG");	
}

function addImg(url, id) {
 var img = document.createElement("img");
 img.src = url;
 document.getElementById(id).innerHTML = "";
 document.getElementById(id).appendChild(img);
}

