// Variable Declaration
var postcode2;		// Is used for .....
var locations = {}; 	// Used to store all locations when drawing map. Useful for clustered Maps
var localSearch = new GlocalSearch(); // Used to get directions
var points = new Array();	// Array to hold nearest dealers for proximity search

// Save postcode and redirect to results page
function findClosestDealers() 
{
	window.name = document.getElementById("postcode").value;
	window.location.href = "index.php?page=find-a-dealer-results";
}

// 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 all dealer markers
function mapLoad() 
{
	if (GBrowserIsCompatible()) 
	{
		// Create the Map control
		map = new GMap2(document.getElementById("map_canvas"));
		map.addControl(new GLargeMapControl());
		// Centre map either on the middle of UK or the dealer if one is selected
		if (typeof(dealerId)=='undefined')
		{
			map.setCenter(new GLatLng(52.75,-0.592773), 6);
		}
		else
		{
			map.setCenter(new GLatLng(parseFloat(Dealers[dealerId][0]), parseFloat(Dealers[dealerId][1])), 15);
		}
		map.enableDoubleClickZoom();

		for (var i = 0; i < Dealers.length; i++) 
		{	
			var id = i;
			var title = Dealers[i][2];
			var address = Dealers[i][3];
			var sales = Dealers[i][4];
			var aftersales = Dealers[i][5];
			var jagurl = Dealers[i][6];
			var website = Dealers[i][7];
			var lat = parseFloat(Dealers[i][0]);
			var lng = parseFloat(Dealers[i][1]);
			var latlng = new GLatLng(lat, lng);
			var dealer = {latlng: latlng, title: title, address: address,  sales:sales, aftersales:aftersales, jagurl:jagurl,website:website, id:id, lat:lat, lng:lng};
		
			var latlngHash = (latlng.lat().toFixed(6) + "" + latlng.lng().toFixed(6));
			latlngHash = latlngHash.replace(".","").replace(".","").replace("-","");
			
			if (locations[latlngHash] == null) 
			{
				locations[latlngHash] = []
			}
			
			// If a dealer is defined, only load that dealer otherwise load all
			if (typeof(dealerId)=='undefined')
			{
				// Load all dealers
				locations[latlngHash].push(dealer);
			}
			else
			{
				if (dealerId == dealer.id)
				{
					// Load all dealers
					locations[latlngHash].push(dealer);
				}
			}
		}

		for (var latlngHash in locations) 
		{
			// Only draw the marker if it's found in the Locations array		
			var dealers = locations[latlngHash];
			if (dealers.length > 1) 
			{
				map.addOverlay(createClusteredMarker(dealers));
			} 
			else if (dealers.length == 1)
			{
				if (typeof(dealerId)=='undefined')
				{
					map.addOverlay(createMarkerWithLink(dealers));
				}
				else
				{
					map.addOverlay(createMarkerWithDirections(dealers));
				}
			}
		}
	}
}

// Create a marker to be painted on the map
function createMarkerWithLink(dealers, title, icon, jagurl) 
{
	var dealer = dealers[0]; 
	var icon = new GIcon(G_DEFAULT_ICON,"http://www.jaguardealeroffers.co.uk/uploads/images/jag-icon.png");
	icon.image = "http://www.jaguardealeroffers.co.uk/uploads/images/jag-icon.png";
	icon.shadow = "http://www.jaguardealeroffers.co.uk/uploads/images/jag-icon-shadow.png";
	icon.iconSize = new GSize(31, 39);
	icon.shadowSize = new GSize(100, 40);
	icon.iconAnchor = new GPoint(15, 39);
	var marker = new GMarker(dealer.latlng, {icon: icon, title:title });
	var html = "<b>" + dealer.title + "</b> <br />" + dealer.address + "<br /> " + dealer.sales + "<br /><br /><a href='" + dealer.jagurl + "'>Click here for dealer <br />information and directions</a>" ;
	GEvent.addListener(marker, 'click', function() {								   
	marker.openInfoWindowHtml(html);
	});
	return marker;
}

// Create a marker to be painted with functions to fund directions
function createMarkerWithDirections(dealers, title, icon, jagurl,id, lat, lng) 
{
	var dealer = dealers[0];
	var icon = new GIcon(G_DEFAULT_ICON,"http://www.jaguardealeroffers.co.uk/uploads/images/jag-icon.png");
	icon.image = "http://www.jaguardealeroffers.co.uk/uploads/images/jag-icon.png";
	icon.shadow = "http://www.jaguardealeroffers.co.uk/uploads/images/jag-icon-shadow.png";
	icon.iconSize = new GSize(31, 39);
	icon.shadowSize = new GSize(100, 40);
	icon.iconAnchor = new GPoint(15, 39);
	var marker = new GMarker(dealer.latlng, {icon: icon, title:title });		
	var thisHtml = "<b>" + dealer.title + "</b> <br />" + dealer.address + "<br /> " + dealer.sales + "<br /><div id='toHere' style=\"padding:5px 0px;\"><strong>To here</strong> <a href='javascript:;' onclick='showFromHere();'>From here</a><br /><form action=\"javascript:getToDirections()\"><input name=\"daddr\" id=\"daddr\" value='" + dealer.lat+","+dealer.lng + "' 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;\"><a href='javascript:;' onclick='showToHere()'>To here</a> <strong>From here</strong><form action=\"javascript:getFromDirections()\"><input name=\"saddr2\" id=\"saddr2\" value='" + dealer.lat+","+dealer.lng + "' 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><a target=\"_blank\" href='" + dealer.website + "'>Visit the dealer website</a>" ;
	var gdir=new GDirections(map, document.getElementById("directions"));
	map.openInfoWindowHtml(map.getCenter(),(thisHtml));
	GEvent.addListener(marker, 'click', function() {								   
	marker.openInfoWindowHtml(thisHtml);});	
	return marker;
}

// Function for Markers with multiple dealers on the same location
function createClusteredMarker(dealers) 
{
	var newIcon = MapIconMaker.createMarkerIcon({width: 62, height: 78, primaryColor: "#ff6600"});
	var marker = new GMarker(dealers[0].latlng, {icon: newIcon});
	var html = "";
	for (var i = 0; i < dealers.length; i++) {
	html += "<b>" + dealers[i].name + "</b> <br />" + dealers[i].address + "<br /><br /><a href='" + dealers[i].jagurl + "'>Click here for dealer <br />information and directions</a><br />";
	}
	GEvent.addListener(marker, 'click', function() {
	marker.openInfoWindowHtml(html);
	});
	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]);
}

// Function to show 3 nearest dealers
function showNearest(point)
{
	function createNearestMarker(point,icon,html) {
        var marker = new GMarker(point,icon);
        GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowHtml(html);
        });
        return marker;
  }
  
	Dealers[0][8] = getDistance(point, new GLatLng(Dealers[0][0],Dealers[0][1]));
	Dealers[1][8] = getDistance(point, new GLatLng(Dealers[1][0],Dealers[1][1]));
	Dealers[2][8] = getDistance(point, new GLatLng(Dealers[2][0],Dealers[2][1]));
	Dealers[3][8] = getDistance(point, new GLatLng(Dealers[3][0],Dealers[3][1]));
	Dealers[4][8] = getDistance(point, new GLatLng(Dealers[4][0],Dealers[4][1]));
	Dealers[5][8] = getDistance(point, new GLatLng(Dealers[5][0],Dealers[5][1]));
	Dealers[6][8] = getDistance(point, new GLatLng(Dealers[6][0],Dealers[6][1]));
	Dealers[7][8] = getDistance(point, new GLatLng(Dealers[7][0],Dealers[7][1]));
	Dealers[8][8] = getDistance(point, new GLatLng(Dealers[8][0],Dealers[8][1]));
	Dealers[9][8] = getDistance(point, new GLatLng(Dealers[9][0],Dealers[9][1]));
	Dealers[10][8] = getDistance(point, new GLatLng(Dealers[10][0],Dealers[10][1]));
	Dealers[11][8] = getDistance(point, new GLatLng(Dealers[11][0],Dealers[11][1]));
	Dealers[12][8] = getDistance(point, new GLatLng(Dealers[12][0],Dealers[12][1]));
	Dealers[13][8] = getDistance(point, new GLatLng(Dealers[13][0],Dealers[13][1]));
	Dealers[14][8] = getDistance(point, new GLatLng(Dealers[14][0],Dealers[14][1]));
	Dealers[15][8] = getDistance(point, new GLatLng(Dealers[15][0],Dealers[15][1]));
	
	Dealers.sort(sortDealer);

	var html = "<h4>Your three nearest dealers are:</h4>";
	var i=0;
	for (i=0;i<3;i++)	
	
	{
		html += "<div class=\"fod"+(i+1)+"Header\"><div><h4>" + Dealers[i][2] + " is " + Dealers[i][8] + "km away" + "</h4></div></div><div style=\"display: block;\" id=\"fod"+(i+1)+"Body\"><div class=\"fodHeading\"><p>CALL US ON <strong>" + Dealers[i][4] + "</strong></p></div><div><div class=\"fodAddress\"><strong>" + Dealers[i][2] + "</strong> <br />" + Dealers[i][3] + "</div><div class=\"fodTelephone\"><a href=\"" + Dealers[i][6] + "\" style=\"color:#fff;\">Click here for dealer details and directions</a></div></div></div> ";
		var markerHTML = "<b>" + Dealers[i][2] + "</b> <br />" + Dealers[i][3] + "<br />" + Dealers[i][4] + "<br /><br /><a href=\"" + Dealers[i][6] + "\">Click here for dealer <br />details and directions</a>";

		var point = new GLatLng(Dealers[i][0],Dealers[i][1]);
		points.push(point);
		var icon = new GIcon(G_DEFAULT_ICON,"http://www.jaguardealeroffers.co.uk/uploads/images/jag-icon-"+(i+1)+".png");
		icon.iconSize = new GSize(31, 39);
		icon.iconAnchor = new GPoint(15, 39);
		var marker = createNearestMarker(new GLatLng(Dealers[i][0],Dealers[i][1]),icon,markerHTML);
		map.addOverlay(marker);
	}
	 
	document.getElementById("info").innerHTML=html;

	var hdpost = document.getElementById('postcode').value;
	var hp = document.getElementById("postcoderesult");
	
	if (hp != null)
	{
		var pcr ="<h2 class=\"lower\">You searched for:</h2><h5 id=\"hdPost\">" + hdpost + "</h5>";
		hp.innerHTML = pcr;
		hp.setAttribute("class","");
	} 
	
	FLIR.replace( 'h4' , new FLIRStyle({ cFont:'stainreg'}) );
	FLIR.replace( 'h2.lower' , new FLIRStyle({ cFont:'stainreg'}) );
	FLIR.replace( '#hdPost' , new FLIRStyle({ cFont:'stainreg'}));
	
}


// 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);