// Variable Declaration
var locations = {}; 	// Used to store all locations when drawing map. Useful for clustered Maps
var localSearch = new GlocalSearch(); // Used to get directions




// Check for variable definition
function isUndefined(x) { return x == null && x !== null; }

// Take postcode from Window.Name and populate postcode control
function loadPostcodeAndSearch() 
{
	 var passedPostcode  = window.name;
	 document.getElementById("postcode").value = passedPostcode;
	 setTimeout("loadPointandMarkers();",1000);
	 
}

// Redirect window to URL
function gotoURL (l) 
{
	window.location.href = l;
}

//proximity search for dealers
function getDistance(point1, point2) 
{
	var d=point1.distanceFrom(point2)/1000;
	return d.toFixed(1);
}

// Load the Map and draw location marker
function mapLoad() 
{
	if (GBrowserIsCompatible()) 
	{
		// Create the Map control
		map = new GMap2(document.getElementById("mapHolder"));
		map.addControl(new GLargeMapControl());
		// Centre map either on the middle of UK or the dealer if one is selected
		map.setCenter(new GLatLng(50.078568,-5.701191), 12);
		map.enableDoubleClickZoom();
		map.addOverlay(createMarkerWithDirections());
			
	}
	$('.sections').hAccordion();
}


// Create a marker to be painted with functions to fund directions
function createMarkerWithDirections() 
{
	var title = 'The Beach Restaurant';
	var address = 'Sennen Cove<br />Cornwall TR19 7BT';
	var lat = parseFloat(50.078568);
	var lng = parseFloat(-5.701191);
	var latlng = new GLatLng(lat, lng);
	var polperro = {latlng: latlng, title: title, address: address,lat:lat, lng:lng};
	var icon = new GIcon(G_DEFAULT_ICON,"http://www.trickboxmedia.com/polperro/img/google-maps/house_pacifica.png");
	icon.image = "http://www.trickboxmedia.com/polperro/img/google-maps/house_pacifica.png";
	icon.shadow = "http://www.trickboxmedia.com/polperro/img/google-maps/house_shadow.png";
	icon.iconSize = new GSize(25, 14);
	icon.shadowSize = new GSize(25, 14);
	icon.iconAnchor = new GPoint(9, 13);
	var marker = new GMarker(polperro.latlng, {icon: icon, title:title });		
	var thisHtml = "<span style='color:#000;'><b>The Beach Restaurant</b> <br />Sennen Cove<br />Cornwall TR19 7BT</span><div id='toHere' style=\"padding:5px 0px; color:#000;\"><strong>To here</strong> <a href='javascript:;' onclick='showFromHere();'>From here</a><br /><form action=\"javascript:getToDirections()\"><input name=\"daddr\" id=\"daddr\" value='50.078568,-5.697191' type=\"hidden\" /><input type='text' name=\"saddr\" id=\"saddr\" value='Enter your postcode' onfocus=\"this.value==this.defaultValue?this.value='':null\" /> <input type='submit' value='Go' /></form></div><div id='fromHere' style=\"display:none; padding:5px 0px;color:#000;\"><a href='javascript:;' onclick='showToHere()'>To here</a> <strong>From here</strong><form action=\"javascript:getFromDirections()\"><input name=\"saddr2\" id=\"saddr2\" value='50.078568,-5.697191' type=\"hidden\" /><input type='text' name=\"daddr2\" id=\"daddr2\" value='Enter your postcode' onfocus=\"this.value==this.defaultValue?this.value='':null\" /> <input type='submit' value='Go' /></form></div>" ;
	var gdir=new GDirections(map, document.getElementById("directions"));
	map.openInfoWindowHtml(map.getCenter(),(thisHtml));
	GEvent.addListener(marker, 'click', function() {								   
	marker.openInfoWindowHtml(thisHtml);
	});	
	return marker;
}


// Executes a search for a postcode and sets 1 callback functions to be called with the resulting point
function usePointFromPostcode(postcode, callbackFunction) {
	// Set the callback functions to be called with the result
	localSearch.setSearchCompleteCallback(null, 
		function() {
			
			if (localSearch.results[0])
			{		
				var resultLat = localSearch.results[0].lat;
				var resultLng = localSearch.results[0].lng;
				var point = new GLatLng(resultLat,resultLng);
				callbackFunction(point);

			}else{
				alert("Postcode not found!");
			}
		});	
		
	// Execute the postcode search	
	localSearch.execute(postcode + ", UK");
}


// Executes a search for a postcode and sets 2 callback functions to be called with the resulting point
function usePointFromPostcode2(postcode, callbackFunction,  callbackFunction2) {
	// Set the callback functions to be called with the result
	localSearch.setSearchCompleteCallback(null, 
		function() {
			
			if (localSearch.results[0])
			{		
				var resultLat = localSearch.results[0].lat;
				var resultLng = localSearch.results[0].lng;
				var point = new GLatLng(resultLat,resultLng);
				callbackFunction(point);
				callbackFunction2(point);
			}else{
				alert("Postcode not found!");
			}
		});	
	// Execute the postcode search	
	localSearch.execute(postcode + ", UK");
}

// Places a default marker on the map
function placeMarkerAtPoint(point) {
	var icon = new GIcon(G_DEFAULT_ICON);
	var marker = new GMarker(point,icon);
	points.push(point);
	map.addOverlay(marker);
}

// Gets the postcode and fires off a search	
function loadPointandMarkers() {
	  var t = document.getElementById('postcode').value;
	  map.clearOverlays();
	  usePointFromPostcode2(t, placeMarkerAtPoint, showNearest); 
	  setTimeout("fitMap(map,points)",1000);
}

//show and hide to/from directions
function showFromHere () {
	document.getElementById("toHere").style.display="none";	
	document.getElementById("fromHere").style.display="block";
}

//show and hide to/from directions
function showToHere () {
	document.getElementById("toHere").style.display="block";	
	document.getElementById("fromHere").style.display="none";
}
// Fir the map to the visible dealers
function fitMap(map, points) 
{
	var bounds = new GLatLngBounds();
	for (var i=0; i< points.length; i++) 
	{
		bounds.extend(points[i]);
	}
	map.setZoom(map.getBoundsZoomLevel(bounds));
	map.setCenter(bounds.getCenter());
	Array.prototype.clear=function() 
	{
		this.length = 0;
	};
}

// Dealership sort function
function sortDealer(a,b)
{
	return (a[8] - b[8]);
}



// Do a Direction search and draw the results on the 'directions' div
function getToDirections() 
{
	// === create a GDirections Object ===
	var gdir=new GDirections(map, document.getElementById("directions"));
	G_END_ICON.image = "http://www.jaguardealeroffers.co.uk/uploads/images/jag-icon.png"; 

	// === Array for decoding the failure codes ===
	var reasons=[];
	reasons[G_GEO_SUCCESS]            = "Success";
	reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
	reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
	reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
	reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
	reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
	reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
	reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
	reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
	reasons[G_GEO_UNKNOWN_DIRECTIONS] = "The GDirections object could not compute directions between the points.";

	// === catch Directions errors ===
	GEvent.addListener(gdir, "error", function() 
	{
		var code = gdir.getStatus().code;
		var reason="Code "+code;
		if (reasons[code]) 
		{
			  reason = reasons[code]
		} 

		alert("Failed to obtain directions, "+reason);
	});																

        var saddr = document.getElementById("saddr").value;
        var daddr = document.getElementById("daddr").value;
	var dealerLatLng = usePointFromPostcode(saddr,showPointLatLng);
		
	function showPointLatLng(point)
	{
		dealerLatLng = point.lat() +","+ point.lng();
		gdir.load("from: "+dealerLatLng+" to: "+daddr);
	        $("#directions").slideDown("normal");
		map.closeInfoWindow();
	}
}

// Do a Direction search and draw the results on the 'directions' div
function getFromDirections() 
{
	// === create a GDirections Object ===
	var gdir=new GDirections(map, document.getElementById("directions"));
	G_START_ICON.image = "http://www.jaguardealeroffers.co.uk/uploads/images/jag-icon.png";

	// === Array for decoding the failure codes ===
	var reasons=[];
	reasons[G_GEO_SUCCESS]            = "Success";
	reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
	reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
	reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
	reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
	reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
	reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
	reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
	reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
	reasons[G_GEO_UNKNOWN_DIRECTIONS] = "The GDirections object could not compute directions between the points.";

	// === catch Directions errors ===
	GEvent.addListener(gdir, "error", function() 
	{
		var code = gdir.getStatus().code;
		var reason="Code "+code;
		if (reasons[code]) 
		{
			reason = reasons[code]
		} 

		alert("Failed to obtain directions, "+reason);
	});

	var saddr = document.getElementById("saddr2").value;
	var daddr = document.getElementById("daddr2").value;
	var homeLatLng = usePointFromPostcode(daddr,showPointLatLng);

	function showPointLatLng(point)
	{
		homeLatLng = point.lat() +","+ point.lng();
		gdir.load("from: "+saddr+" to: "+ homeLatLng);
		$("#directions").slideDown("normal");
		map.closeInfoWindow();
	}
}


	
// Adds the Window.Onload Function
function addLoadEvent(func) {
	  var oldonload = window.onload;
	  if (typeof window.onload != 'function') {
	    window.onload = func;
	  } else {
	    window.onload = function() {
	      oldonload();
	      func();
	    }
	  }
}

// Adds the Window.Onload Function
function addUnLoadEvent(func) 
{
	var oldonunload = window.onunload;
	if (typeof window.onunload != 'function') {
	  window.onunload = func;
	} else {
	  window.onunload = function() {
	    oldonunload();
	    func();
	  }
	}
}

addLoadEvent(mapLoad);
addUnLoadEvent(GUnload);