/******************************************
Name:			findaretailer.js
Description:	Use to navigate between the options of the Find A Retailer system.

				Based loosely around ppk's form validation script concept:
				http://www.quirksmode.org
Date:			23/08/2006
Author:			Andrei Vais
******************************************/

//instanciate GoogleMap
if (GBrowserIsCompatible())
{
	var mapContainer = document.getElementById("LocationMap");
	
	var map = new GMap2(mapContainer);	
	var defaultMapLat = 55.9;
	var defaultMapLng = -5;
	var defaultMapZoomFactor = 5;
	
	//setup default latitude (North) and longitude (East)
	var defaultMapLocation = new GLatLng(defaultMapLat, defaultMapLng);
	//set map type - 0 (map), 1 (satellite), 2 (hybrid)
	var mapType = G_DEFAULT_MAP_TYPES[0];
	//add panning, zooming controls
	map.addControl(new GLargeMapControl());
	//add map type (map, sattelite, hybrid) control
	map.addControl(new GMapTypeControl());

	map.setCenter(defaultMapLocation, defaultMapZoomFactor, mapType);

	var actual;
	var icon = new GIcon();
	icon.image = "http://www.google.com/mapfiles/marker.png";


	//first create the master array for all retailer
	var vcards = getElementsByClassName(document.getElementById("PageContent"), "div", ["vcard"]);
	//console.log(vcards.length);
	//alert("basic setup done");
	//alert("vcards.length: " + vcards.length);
	//on inital load there will no vcards so no point in going through the whole map setup
	if (vcards.length != 0)
	{
		//console.log("start full setup");
		var retailerID = 0;
		var retailerHRef = "";
		var retailerName = "";
		var retailerAddress = "";
		var retailerLNG = 0;
		var retailerLTD = 0;
		var retailerTelephone = "";
		
		//now let's transform the array into a two dimensional one with the following setup
		//[i][0] - Retailer ID
		//[i][1] - Retailer HRef link
		//[i][2] - Retailer Name
		//[i][3] - Retailer Address
		//[i][4] - Retailer Latitude
		//[i][5] - Retailer Longitude
		//[i][6] - Retailer Contact Telephone

		//alert("before loop");
		//alert("retailerID childNodes: " + vcards[0].childNodes.length);
		for(var i = 0;  i <vcards.length; i++)
		{
			//get Retailer ID
			if (vcards[i].childNodes[0].childNodes[0].getAttribute("rel") != null)
			{
				retailerID = vcards[i].childNodes[0].childNodes[0].getAttribute("rel");
			}

			//get Retailer HRef link
			if (vcards[i].childNodes[0].childNodes[0].getAttribute("href") != null)
			{
				retailerHRef = vcards[i].childNodes[0].childNodes[0].getAttribute("href");
			}

			
			//get Retailer Name
			if (vcards[i].childNodes[0].childNodes[0].childNodes[0].nodeValue != null)
			{
				retailerName = "<h5>" + vcards[i].childNodes[0].childNodes[0].childNodes[0].nodeValue + "</h5>";
			}

			//get Retailer Address
			for(var j = 0; j < vcards[i].childNodes[1].childNodes.length; j++)
			{
				if (vcards[i].childNodes[1].childNodes[j].childNodes[0].nodeValue != null)
				{
					retailerAddress += vcards[i].childNodes[1].childNodes[j].childNodes[0].nodeValue + ", <br />";
				}
			}
			if (retailerAddress.lastIndexOf(", <br />") != -1)
			{
				retailerAddress = retailerAddress.substring(0,retailerAddress.length - 8);
			}

			//get Retailer Latitude
			if (vcards[i].childNodes[1].childNodes[5].childNodes[0].getAttribute("title") != null)
			{
				retailerLNG = vcards[i].childNodes[1].childNodes[5].childNodes[0].getAttribute("title");
			}

			//get Retailer Longitude
			if (vcards[i].childNodes[1].childNodes[5].childNodes[1].getAttribute("title") != null)
			{
				retailerLTD = vcards[i].childNodes[1].childNodes[5].childNodes[1].getAttribute("title");
			}

			//get Retailer Contact Telephone
			for(var k = 0; k < vcards[i].childNodes[2].childNodes.length; k++)
			{
				if (vcards[i].childNodes[2].childNodes[k].childNodes[0].nodeValue != null)
				{
					retailerTelephone += vcards[i].childNodes[2].childNodes[k].childNodes[0].nodeValue + " ";
				}
			}
			if (retailerTelephone.lastIndexOf(" ") != -1)
			{
				retailerTelephone = retailerTelephone.substring(0,retailerTelephone.length - 1);
			}
			
			vcards[i] = new Array(retailerID, retailerHRef, retailerName, retailerAddress, retailerLNG, retailerLTD, retailerTelephone);
			//console.log(vcards[i][0], " :: ", vcards[i][1], " :: ", vcards[i][2], " :: ", vcards[i][3], " :: ", vcards[i][4], " :: ", vcards[i][5], " :: ", vcards[i][6]);
			//alert(vcards[i][0] + "\n :: " + vcards[i][1] + "\n :: " + vcards[i][2] + "\n :: " + vcards[i][3] + "\n :: " + vcards[i][4] + "\n :: " + vcards[i][5] + "\n :: " + vcards[i][6]);
			
			//we need to reset the address and telephone to avoid appending multiple addresses/telephone numbers together
			retailerAddress = "";
			retailerTelephone = "";
		}
		//console.log("end full setup");
	}

	//removes temporary backogrund image now tha the map has fully loaded
	removeMapBackground(mapContainer);
}

function removeMapBackground(pMapContainer)
{
	if(pMapContainer)
	{
		pMapContainer.style.background = "none";
	}
}

function DisplayRetailers()
{
	//initialiaze required Google Map Api Objects
	var mapAddress = "";
	var mapCenterLat = 0;
	var mapCenterLng = 0;
	var mapMaxLat = 0;
	var mapMinLat = 0;
	var mapMaxLng = 0;
	var mapMinLng = 0;
	var mapLatDiff = 0;
	var mapLngDiff = 0;

	
	//set map latitude (North) and longitude (East)
	for(var i = 0;  i < vcards.length; i++)
	{
		mapCenterLat += Number(vcards[i][4]);
		mapCenterLng += Number(vcards[i][5]);
		//console.log("map center at: ", mapCenterLat, ", ", mapCenterLng);

		//get the Latitude range
		if(i == 0)
		{
			mapMaxLat =  Number(vcards[i][4]);
		}
		else
		{
			if (mapMaxLat < Number(vcards[i][4]))
			{
				mapMaxLat = Number(vcards[i][4]);
			}
		}
		
		if(i == 0)
		{
			mapMinLat =  Number(vcards[i][4]);
		}
		else
		{
			if (mapMinLat > Number(vcards[i][4]))
			{
				mapMinLat = Number(vcards[i][4]);
			}
		}

		//get the Longitude range
		if(i == 0)
		{
			mapMaxLng =  Number(vcards[i][5]);
		}
		else
		{
			if (mapMaxLng < Number(vcards[i][5]))
			{
				mapMaxLng = Number(vcards[i][5]);
			}
		}
		
		if(i == 0)
		{
			mapMinLng =  Number(vcards[i][5]);
		}
		else
		{
			if (mapMinLng > Number(vcards[i][5]))
			{
				mapMinLng = Number(vcards[i][5]);
			}
		}
	}

	mapCenterLat = mapCenterLat/vcards.length;
	mapCenterLng = mapCenterLng/vcards.length;
	mapLatDiff = mapMaxLat - mapMinLat;
	mapLngDiff = mapMaxLng - mapMinLng;
	
	//console.log("map center at: ", mapCenterLat, ", ", mapCenterLng)
	//console.log("mapMaxLat: ", mapMaxLat, " - mapMinLat: ", mapMinLat, " - mapLatDiff: ", mapLatDiff);
	//console.log("mapMaxLng: ", mapMaxLng, " - mapMinLng: ", mapMinLng, " - mapLngDiff: ", mapLngDiff);
	
	mapLocation = new GLatLng(mapCenterLat, mapCenterLng, mapType);
	
	//set map zoom factor - set the zoom factor depending how "spread out" there retailers are
	var mapZoomFactor;
	
	if ((mapLatDiff < 0.1) && (mapLngDiff < 0.01))
	{
		mapZoomFactor = 13;
	}		
	else if ((mapLatDiff < 0.1) && (mapLngDiff > 0.01))
	{
		mapZoomFactor = 12;
	}			
	else if ((mapLatDiff > 0.1) && (mapLngDiff < 0.2))
	{
		mapZoomFactor = 10;
	}		
	else if ((mapLatDiff < 1) && (mapLngDiff < 1))
	{
		mapZoomFactor = 9;
	}			
	else if ((mapLatDiff > 1) && (mapLngDiff > 1))
	{
		mapZoomFactor = defaultMapZoomFactor;
	}		
	else
	{
		//if this is the case then let's reset to display the whole UK
		mapLocation = defaultMapLocation;
		mapZoomFactor = defaultMapZoomFactor;
	}
	//console.log("mapZoomFactor: ", mapZoomFactor);
	map.setCenter(mapLocation, mapZoomFactor);
	
	addIcon(icon);

	for(var i = 0;  i < vcards.length; i++)
	{
		var point = new GLatLng(vcards[i][4], vcards[i][5]);
		
		mapAddress = "<div class='infowindow'>" + vcards[i][2] + "<br />" + vcards[i][3] + "<br /><br />" + vcards[i][6] + "</div>";
		//console.log("create marker: ", i, " lat: ", vcards[i][4], " lng: ", vcards[i][5], " mapAddress: ", mapAddress);
		
		map.addOverlay(createMarker(point, icon, mapAddress, i));
		mapAddress = "";
	}


	//now we created all the points on the map let's add the functionality to the list of results:
	//- each result will have 2 links which when clicked will open the corresponding Info window on the map
	//prepareVCardLinks();
}

function addIcon(icon)
{ // Add icon attributes

	icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	icon.iconSize = new GSize(20, 34);
	icon.shadowSize = new GSize(37, 34);
	icon.iconAnchor = new GPoint(10, 34);
	icon.infoWindowAnchor = new GPoint(14, 34);
}

function createMarker(pPoint, pIcon, pAddress)
{
	// Set draggable markers
	var marker = new GMarker(pPoint, {icon:pIcon});

	GEvent.addListener(marker, "click", function()
	{
		// Open infowindow only if it's closed or the mouse moves over another marker
		if(map.getInfoWindow().isHidden() || actual != marker )
		{ 
			marker.openInfoWindowHtml(pAddress);
		}
		/* You can only open one info window at a time.
		* Store the marker of this info window.
		*/
		actual = marker;
	});

	return marker;
}

function prepareVCardLinks()
{
	var retailerVCardLinks = getElementsByClassName(document.getElementById("PageContent"), "a", ["RetailerLink"]);

	//console.log("retailerVCard: " + retailerVCardLinks.length);
	for(var i = 0;  i <retailerVCardLinks.length; i++)
	{
		retailerVCardLinks[i].onclick = function()
		{
			showMarker(this);
			return false;
		}
	}	
}

function showMarker(pLink)
{
	//console.log(pLink.getAttribute("rel"));
	for(var i = 0;  i < vcards.length; i++)
	{
		if (vcards[i][0] == pLink.getAttribute("rel"))
		{
			//console.log("get info for link at ", i);
			//get the details of the selected retailer
			//[i][0] - Retailer ID
			//[i][1] - Retailer HRef link
			//[i][2] - Retailer Name
			//[i][3] - Retailer Address
			//[i][4] - Retailer Latitude
			//[i][5] - Retailer Longitude
			//[i][6] - Retailer Contact Telephone
			var selectedRetailerID = vcards[i][0];
			var selectedRetailerAddress = "<div class='infowindow'>" + vcards[i][2] + "<br />" + vcards[i][3] + "<br /><br />" + vcards[i][6] + "</div>";
			var selectedRetailerLAT = vcards[i][4];
			var selectedRetailerLNG = vcards[i][5];

			//reset center of the map to the Lat/Lng coordinates of the selected retailer
			map.closeInfoWindow();
			mapLocation = new GLatLng(selectedRetailerLAT, selectedRetailerLNG, map.getCurrentMapType());
			map.panTo(mapLocation);

			var marker = new GMarker(mapLocation, {icon:icon});
			addIcon(icon);

			//console.log(marker.getLatLng());
			//map.clearOverlays();
			//map.addOverlay(createMarker(mapLocation, icon, selectedRetailerAddress, i));
		
			if(map.getInfoWindow().isHidden() || actual != marker ) { 
				//console.log("inside if");
				//console.log(selectedRetailerAddress);
				//console.log(marker);
				//map.getInfoWindow().show();
				//marker.openInfoWindowHtml("test");
			}
			actual = marker;
			
		}
	}
}
