var map; // Map object to be initialised by slLoadMap() function
var locationMarker = ''; // The marker for the address searched for
var stores = []; // Array of store information
var storeMarkers = []; // Array of store markers
var storesToDisplay = 5; // Number of results to display.
var decPoints = 0; // Number of decimal places to display for distances.

// Create new red pin icon for use as store location markers.
var icon = new GIcon();
icon.iconSize = new GSize(17, 23);
icon.shadowSize = new GSize(17, 23);
icon.iconAnchor = new GPoint(1, 33);
icon.infoWindowAnchor = new GPoint(1, 1);

// Create URL for directions links.
function slDirectionsUrl(fromAddress, toAddress, toLat, toLng){
	return ('http://maps.google.co.uk/maps?f=d&hl=en&ie=UTF8&saddr=' + fromAddress + ',+UK&daddr=' + toAddress + '&g=' + toAddress + '&ll=' + toLat + ',' + toLng + '&z=10');
}

// Function to create store location markers with info bubbles
function slCreateMarker(store, distance, latitude, longitude, storeName, postcode,storeNote){
	var point = new GLatLng(latitude, longitude);
	if (storeNote=='nessstores' || storeNote=='nessshop')
	{
		icon.image = "/public/images/ness.png";
		icon.shadow = "/public/images/ness_shadow.png";
	}
	else
	{
			icon.image = "/public/images/otherstores.png";
			icon.shadow = "/public/image/oherstores_shadow.png";
	}
	var marker = new GMarker(point, {icon: icon, title: storeName});
	var markerHtml = '<b>' + storeName + '</b><br/><br/>';
	if(locationMarker != ''){
		markerHtml = markerHtml + distance + ' miles from ' + document.getElementById('slAddress').value + '<br/>';
	}
	markerHtml = markerHtml + '<a href="' + slDirectionsUrl(document.getElementById('slAddress').value, postcode, latitude, longitude) + '" target="_blank">Get directions to this store</a>';
	GEvent.addListener(marker,"click",function(){
		marker.openInfoWindowHtml(markerHtml);
		slGetStoreInfo(store);
	});
	return marker;
}

// Loop through stores array to create markers.
function slAddMarkers(){
	for(i=0; i < stores.length; i++){		
		var storeSplit = stores[i].split("£$£$");		
		
		storeMarkers[i] = slCreateMarker(i, storeSplit[0], storeSplit[1], storeSplit[2], storeSplit[3], storeSplit[5],storeSplit[15]);
		map.addOverlay(storeMarkers[i]);
	}
}

// Create stores array from data in stores.xml file.
function slGetStores(){
	GDownloadUrl("/public/stores/stores.xml", function(data, responseCode){
		var xml = GXml.parse(data);
		var markers = xml.documentElement.getElementsByTagName("marker");
		if(markers.length > 0){
			for(var i=0; i < markers.length; i++){
				var marker = markers[i];
				stores[i] = '0£$£$' + marker.getAttribute("latitude") + '£$£$' + marker.getAttribute("longitude") + '£$£$' + marker.getAttribute("storeName") + '£$£$' + marker.getAttribute("storeAddress") + '£$£$' + marker.getAttribute("postcode") + '£$£$' + marker.getAttribute("telephone") + '£$£$' + marker.getAttribute("key") + '£$£$' + marker.getAttribute("openingTimesMonday") + '£$£$' + marker.getAttribute("openingTimesTuesday") + '£$£$' + marker.getAttribute("openingTimesWednesday") + '£$£$' + marker.getAttribute("openingTimesThursday") + '£$£$' + marker.getAttribute("openingTimesFriday") + '£$£$' + marker.getAttribute("openingTimesSaturday") + '£$£$' + marker.getAttribute("openingTimesSunday") + '£$£$' + marker.getAttribute("storeNote");
			}
			slAddMarkers();
		}
	});
}

// Initialise the google map and add controls and settings.
function slLoadMap(){		
	if(GBrowserIsCompatible()){		
		map = new GMap2(document.getElementById('slMap'));		
		map.setCenter(new GLatLng(54.5, -2.8), 6);
		map.addControl(new GLargeMapControl());
		map.addControl(new GScaleControl());
		map.addControl(new GHierarchicalMapTypeControl());
		//map.addControl(new GOverviewMapControl());
		map.addMapType(G_PHYSICAL_MAP);
		map.enableDoubleClickZoom();
		map.enableContinuousZoom();
		map.enableScrollWheelZoom();
		slGetStores();
	}
}

// Function to compare distance between two points.
function slCompareDistance(distanceA, distanceB){
	return (distanceA.substr(0,distanceA.indexOf("£$£$")) - distanceB.substr(0,distanceB.indexOf("£$£$")));
}

// Function to reset the page for a new search.
function slNewSearch(){
	locationMarker = '';
	slLoadMap();
	document.getElementById('slStoreInfo').innerHTML = '';
	document.getElementById('slStoreInfo').style.display = 'none';
	document.getElementById('slResultsList').innerHTML = '';
	document.getElementById('slResults').style.display = 'none';
	document.getElementById('slSearch').style.display = 'block';
	document.getElementById('slAddress').value = '';
	document.getElementById('slAddress').focus();
}

// Function to replace all occurances of a string within another string.
function slReplaceStr(incomingText, str1, str2){
	while(incomingText.indexOf(str1) != -1){
		incomingText = incomingText.substring(0, incomingText.indexOf(str1)) + str2 + incomingText.substring(incomingText.indexOf(str1) + str1.length, incomingText.length);
	}
	return incomingText;
}

// Function to get store info and display in the storeInfo div.
function slGetStoreInfo(store){
	var storeSplit = stores[store].split("£$£$");
	var storeInfoHTML = '<span class="slHighlight">Store Address:</span><br/>' + storeSplit[3] + slReplaceStr(storeSplit[4], "|", "<br/>");
	storeInfoHTML = storeInfoHTML + '<br/><br/><span class="slHighlight">Telephone:</span><br/>' + storeSplit[6];
	if(document.getElementById('slAddress').value != ""){
		storeInfoHTML = storeInfoHTML + ' &nbsp;|&nbsp; <a href="javascript:slBackToResults();">Back to results list</a>';
	}
	storeInfoHTML = storeInfoHTML + '<br/><br/><span class="slHighlight">Facilities Available:</span>';
	if(storeSplit[7].indexOf("C") > -1){
		storeInfoHTML = storeInfoHTML + '<br/>Coffee Shop In Store';
	}
	if(storeSplit[7].indexOf("D") > -1){
		storeInfoHTML = storeInfoHTML + '<br/>Disabled Access';
	}	
	if(storeSplit[7].indexOf("P") > -1){
		storeInfoHTML = storeInfoHTML + '<br/>Free Parking On Site';
	}
	storeInfoHTML = storeInfoHTML + '<br/><br/><span class="slHighlight">Opening Hours:</span><table cellspacing="0" class="slTable"><tr><th>Day</th><th>Opening</th><th>Closing</th></tr>';
	storeInfoHTML = storeInfoHTML + '<tr><td>Monday</td><td>' + storeSplit[8].substring(0,(storeSplit[8].indexOf(";"))) + '</td><td>' + storeSplit[8].substring(storeSplit[8].indexOf(";") + 1) + '</td></tr>';
	storeInfoHTML = storeInfoHTML + '<tr><td>Tuesday</td><td>' + storeSplit[9].substring(0,(storeSplit[9].indexOf(";"))) + '</td><td>' + storeSplit[9].substring(storeSplit[9].indexOf(";") + 1) + '</td></tr>';
	storeInfoHTML = storeInfoHTML + '<tr><td>Wednesday</td><td>' + storeSplit[10].substring(0,(storeSplit[10].indexOf(";"))) + '</td><td>' + storeSplit[10].substring(storeSplit[10].indexOf(";") + 1) + '</td></tr>';
	storeInfoHTML = storeInfoHTML + '<tr><td>Thursday</td><td>' + storeSplit[11].substring(0,(storeSplit[11].indexOf(";"))) + '</td><td>' + storeSplit[11].substring(storeSplit[11].indexOf(";") + 1) + '</td></tr>';
	storeInfoHTML = storeInfoHTML + '<tr><td>Friday</td><td>' + storeSplit[12].substring(0,(storeSplit[12].indexOf(";"))) + '</td><td>' + storeSplit[12].substring(storeSplit[12].indexOf(";") + 1) + '</td></tr>';
	storeInfoHTML = storeInfoHTML + '<tr><td>Saturday</td><td>' + storeSplit[13].substring(0,(storeSplit[13].indexOf(";"))) + '</td><td>' + storeSplit[13].substring(storeSplit[13].indexOf(";") + 1) + '</td></tr>';
	storeInfoHTML = storeInfoHTML + '<tr><td>Sunday</td><td>' + storeSplit[14].substring(0,(storeSplit[14].indexOf(";"))) + '</td><td>' + storeSplit[14].substring(storeSplit[14].indexOf(";") + 1) + '</td></tr>';
	storeInfoHTML = storeInfoHTML + '</table>';
	
	if(storeSplit[15].length > 0){
		storeInfoHTML = storeInfoHTML + '<br/><span class="slHighlight">Additional Store Information:<br/></span>' + storeSplit[15];
	}
	
	storeInfoHTML = storeInfoHTML + '<br/><br/><span class="slHighlight">Actions:</span></a>';	
	storeInfoHTML = storeInfoHTML + '<br/><a href="' + slDirectionsUrl(document.getElementById('slAddress').value, storeSplit[5], storeSplit[1], storeSplit[2]) + '" target="_blank">Get directions to this store</a>';
	storeInfoHTML = storeInfoHTML + '<br/><a href="javascript:slNewSearch();">Start a new search</a>';

	document.getElementById('slSearch').style.display = 'none';
	document.getElementById('slResults').style.display = 'none';
	document.getElementById('slStoreInfo').style.display = 'block';
	document.getElementById('slStoreInfo').innerHTML = storeInfoHTML;
}

// Function to go back from store info to results.
function slBackToResults(){
	document.getElementById('slStoreInfo').style.display = 'none';
	document.getElementById('slResults').style.display = 'block';
}

// Function to call a stores marker click function.
function slClickStore(store){
	GEvent.trigger(storeMarkers[store], "click");
}

var localSearch = new GlocalSearch(); // Initialises the Google local search

// Function to geocode an address, plot a marker at the address,
// get distances from this address of the stores, sort the stores
// based on the distances, re-center and zoom the map to the address,
// open the location marker info bubble, create list of X nearest
// stores, hide search box and display stores list.
function slGetAddress(){
	address = document.getElementById('slAddress').value;
	localSearch.setSearchCompleteCallback(null, 
		function(){
			if(localSearch.results[0]){
				// Check point returned is within the UK (Lat: 50 to 61, Long: -11 to 2) as Google
				// can sometimes incorrectly recognise an address as being near San Francisco.
				if((localSearch.results[0].lat > 50) && (localSearch.results[0].lat < 61) && (localSearch.results[0].lng > -11) && (localSearch.results[0].lng < 2)){
					address = address.charAt(0).toUpperCase() + address.substr(1);
					document.getElementById('slAddress').value = address;
					map.clearOverlays();
					addressPoint = new GLatLng(localSearch.results[0].lat,localSearch.results[0].lng);
					locationMarker = new GMarker(addressPoint,{title: address});
					for(i=0; i < stores.length; i++){
						storeSplit = stores[i].split("£$£$");
						point = new GLatLng(storeSplit[1], storeSplit[2]);
						stores[i] = (point.distanceFrom(locationMarker.getLatLng()) / 1609).toFixed(decPoints) + '£$£$' + storeSplit[1] + '£$£$' + storeSplit[2] + '£$£$' + storeSplit[3] + '£$£$' + storeSplit[4] + '£$£$' + storeSplit[5] + '£$£$' + storeSplit[6] + '£$£$' + storeSplit[7] + '£$£$' + storeSplit[8] + '£$£$' + storeSplit[9] + '£$£$' + storeSplit[10] + '£$£$' + storeSplit[11] + '£$£$' + storeSplit[12] + '£$£$' + storeSplit[13] + '£$£$' + storeSplit[14] + '£$£$' + storeSplit[15];
					}
					stores.sort(slCompareDistance);
					nearestStoreSplit = stores[0].split("£$£$");
					GEvent.addListener(locationMarker,"click",function(){
						locationMarker.openInfoWindowHtml('<b>' + address + '</b><br/><br/>Your nearest store is <a href="javascript:slClickStore(0);">' + nearestStoreSplit[3] + ' - ' + nearestStoreSplit[0] + ' miles</a><br/><a href="' + slDirectionsUrl(address, nearestStoreSplit[5], nearestStoreSplit[1], nearestStoreSplit[2]) + '" target="_blank">Get directions to ' + nearestStoreSplit[3] + '</a>');
					});
					map.addOverlay(locationMarker);
					slAddMarkers();
					map.setCenter(addressPoint, 10);
					GEvent.trigger(locationMarker, "click");
					if(storesToDisplay > stores.length){
						storesToDisplay = stores.length;
					}
					var resultsListHTML = '';
					for(i=0; i < storesToDisplay; i++){
						storeSplit = stores[i].split("£$£$");
						resultsListHTML = resultsListHTML + '<li><a href="javascript:slClickStore(' + i + ');">' + storeSplit[3] + ' - ' + storeSplit[0] + ' miles</a></li>';
					}
					document.getElementById('slSearch').style.display = 'none';
					document.getElementById('slResults').style.display = 'block';
					document.getElementById('slResultsList').innerHTML = resultsListHTML;
				}else{
					alert("Address could not be found. Please search again.");
				}
			}else{
				alert("Address could not be found. Please search again.");
			}
		});	
	localSearch.execute(address + ", UK");
}

// Function to check if an address has been entered and call slGetAddress().
function slCheckForm(){
	if(document.getElementById('slAddress').value == ""){
		alert('Please enter an address');
		document.getElementById('slAddress').focus();
		return false;
	}else{
		slGetAddress();
		return false;
	}
}
//window.onload = slLoadMap;
window.onunload = GUnload;
