﻿
// globally scoped variables
var map = null;
var geocoder = null;
var area = null;
var settings = null;

// load the google maps ajax library (version 2.x)
google.load("maps", "2.x");

// set the main initialization function to execute when the page loads
google.setOnLoadCallback(initialize);

function initialize()
{
	// check for compatibility
	if (!GBrowserIsCompatible())
		return false;

	// initialise the client-side settings from the embedded json written to the page
	var settingsJson = document.getElementById('settingsJson').firstChild.nodeValue;
	settings = eval("(" + settingsJson + ")");

	// initialise the map
	var mapDiv = document.getElementById("mapDiv");
	map = new google.maps.Map2(mapDiv);
    
	// add the standard controls
	map.addControl(new google.maps.LargeMapControl());
	map.addControl(new google.maps.MapTypeControl());
	map.addControl(new google.maps.OverviewMapControl());

	// enable zooming features
	map.enableDoubleClickZoom();
	map.enableContinuousZoom();
	map.enableScrollWheelZoom();

	// disable page from scrolling when zooming with scroll wheel
	google.maps.Event.addDomListener(mapDiv, "DOMMouseScroll", disableMapScrollWheel);
	mapDiv.onmousewheel = disableMapScrollWheel; // needed for IE?
	
	// set the starting position and zoom level
	map.setCenter(new google.maps.LatLng(settings.initialMapLatitude, settings.initialMapLongitude),
		settings.initialMapZoomLevel);	
    
	// initialise the geocoder
	geocoder = new google.maps.ClientGeocoder();
	geocoder.setBaseCountryCode(settings.baseCountry);
	 
	// set the input text box prompt
	var inputTextBox = document.getElementById('inputTextBox');
	showInputTextBoxPrompt(inputTextBox);
}


function processUserInput(input)
{
	/* display current viewing coords and zoom level
	var pos = google.maps.LatLng = map.getCenter();
	alert(pos.lat() + " " + pos.lng());
	alert(map.getZoom());
	*/
	
	// get the location that the user hopefully intended and show outlets near it
	if (geocoder)
	{
		geocoder.getLocations(input, function(response)
			{
				if (!response || response.Status.code != 200)
				{
					alert("Sorry, we were unable to find that address");
				}
				else
				{
					var location = response.Placemark[0]; // the first, best guess location
					var point = new google.maps.LatLng(location.Point.coordinates[1], location.Point.coordinates[0]);
					
					map.clearOverlays();
					prepareSidePanel();

					// initialise the "bounds" rectangle which will become the area to display
					area = new google.maps.LatLngBounds;

					showCurrentLocation(location);
					showNearestOutlets(point);
				}
			});
	}
}

function prepareSidePanel()
{
	// clear the outlet details side panel
	var outletDetailsPanelDiv = document.getElementById('outletDetailsPanelDiv');
	outletDetailsPanelDiv.innerHTML = "";
	
	// hide the bestsellers side panel
	var bestsellersPanelDiv = document.getElementById('bestsellersPanelDiv');
	bestsellersPanelDiv.style.display = "none";
}

function showCurrentLocation(location)
{
	var point = new google.maps.LatLng(location.Point.coordinates[1], location.Point.coordinates[0]);

	// create the marker
	var locationIcon = new google.maps.Icon(G_DEFAULT_ICON); // or could have used G_START_ICON
	locationIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";
	locationIcon.iconSize = new GSize(32, 32);
	var markerOptions = google.maps.MarkerOptions = { icon : locationIcon };	
	var marker = new google.maps.Marker(new google.maps.LatLng(point.lat(), point.lng()), markerOptions);
	
	// add the marker to the map
	map.addOverlay(marker);
	
	// bind an info window to the marker
	marker.bindInfoWindowHtml("<h1>" + location.address + "</h1>");

	// show the address of the location on the page
	var addressResultDiv = document.getElementById('addressResultDiv');
	var addressResultTextTemplate = document.getElementById('addressResultTextTemplate');
	addressResultDiv.innerHTML = addressResultTextTemplate.innerHTML.replace("<!--addressResultText-->", location.address);
	addressResultDiv.style.display = "inline";

	// extend the area to include the outlet
	area.extend(point);
}

function showNearestOutlets(point)
{	
	// build a url for querying the nearest outlets to the location
	var url = settings.dealersServiceUri
		+ "/NearestOutlets"
		+ "?lat=" + point.lat()
		+ "&lon=" + point.lng()
		+ "&groupId=" + settings.outletGroupId
		+ "&count=10";
	
	// hit the dealers web service using the url
	GDownloadUrl(url, function(data, responseCode)
		{
			if (responseCode != 200)
			{
				alert("Sorry, there was a problem finding dealers near that location");
			}
			else
			{
				// deserialize the outlets from the json
				var outlets = eval("(" + data + ")");
				
				// loop through the outlets
				for (var i = 0; i < outlets.length; i++)
				{
					var o = outlets[i]
					
					// display the outlets on the side panel
					addOutletToSidePanel(o, i);

					// display the outlet on the map
					addOutletToMap(o, i);

					// for the nearest six outlets, extend the area to include the outlet
					if (i < 6) area.extend(new google.maps.LatLng(outlets[i].Latitude, outlets[i].Longitude));
				}
				
				// pan to the area
				map.setCenter(area.getCenter());
				
				// zoom in to the optimum level
				var idealZoom = map.getBoundsZoomLevel(area);
				map.setZoom(idealZoom);
			}
		});
}

function addOutletToMap(outlet, index)
{
	// create a marker with an icon containing the letter
	var letterIcon = new google.maps.Icon(G_DEFAULT_ICON);
	letterIcon.image = getAlphabeticMarkerImageUrl(index);
	var markerOptions = google.maps.MarkerOptions = { icon : letterIcon };
	var marker = new google.maps.Marker(new google.maps.LatLng(outlet.Latitude, outlet.Longitude), markerOptions);
	
	// add a click event listener
	GEvent.addListener(marker, "click", function() {     
			//alert(index);
		});

	
	// add the marker to the map
	map.addOverlay(marker);
	
	// add an "info window" to display when clicked
	var infoWindowHtml = getInfoWindowHtml(outlet);
	marker.bindInfoWindowHtml(infoWindowHtml);

	marker.show();
}

function getInfoWindowHtml(outlet)
{
	// get the html template from a hidden element on the page
	var html = document.getElementById('infoWindowTemplate').innerHTML;

	html = html.replace("<!--name-->", outlet.DisplayName);
	html = html.replace("<!--address-->",   outlet.DisplayAddress == null ? "" : outlet.DisplayAddress);
	html = html.replace("<!--town-->",   outlet.Town);
	html = html.replace("<!--outletDetailsPageUri-->",  settings.outletDetailsPageUri.replace("{OutletId}", outlet.OutletId));
	
	return html;
}

function addOutletToSidePanel(outlet, index)
{
	// get the div to add the outlets to
	var div = document.getElementById('outletDetailsPanelDiv');

	// add the outlet details
	div.innerHTML += getOutletDetailsHtml(outlet, index);
}

function getOutletDetailsHtml(outlet, index)
{
	// get the html template from a hidden element on the page
	var html = document.getElementById('outletDetailsTemplate').innerHTML;

	html = html.replace("<!--markerImageUrl-->", getAlphabeticMarkerImageUrl(index));
	html = html.replace("<!--name-->", outlet.DisplayName);
	html = html.replace("<!--address-->", outlet.DisplayAddress == null ? "" : outlet.DisplayAddress);
	html = html.replace("<!--town-->",   outlet.Town);
	html = html.replace("<!--outletDetailsPageUri-->",  settings.outletDetailsPageUri.replace("{OutletId}", outlet.OutletId));
	
	return html;
}



function hideInputTextBoxPrompt(inputTextBox)
{
	if (inputTextBox.value == settings.userPromptText)
	{
		inputTextBox.value='';
		inputTextBox.className = '';
	}
}

function showInputTextBoxPrompt(inputTextBox)
{
	if (inputTextBox.value == '')
	{
		inputTextBox.value = settings.userPromptText; // 'enter your location'
		inputTextBox.className = 'textboxPrompt'; // make the text gray
	}
}

function disableMapScrollWheel(e)
{
	if (!e) e = window.event;
	if (e.preventDefault) e.preventDefault();
	e.returnValue = false;
}

function onPageUnload()
{
	GUnload();
}

// utilities

function getAlphabeticMarkerImageUrl(index)
{
	// get the letter (A, B, C etc.) corresponding to the position in the index
	var letter = String.fromCharCode("A".charCodeAt(0) + index);
	return "http://www.google.com/mapfiles/marker" + letter + ".png";
}