var map;
var origin = null;
var destination;
var mainDirections = null;
var galleriesArray = new Array();
var tileLayers = [];
var tileDesignatorLayer = [];
var pageNumber = 0;
var origin = null;
var sortFunction = null;
var currentBox = null;
var sylvania_latitude = 41.7105983165;
var sylvania_longitude = -83.7120437;
var errorGenerated = false;

var galleriesPerPage = 5;

/// <summary>GoogleMapLoad is the onLoad event to start rendering the map to the googleMap div</summary>
///
/// <remarks></remarks>
function GoogleMapLoad() 
{
	if (google.maps.BrowserIsCompatible()) 
	{
		
	  	//
		//	Set the map to the US by default
		//		

		map = new google.maps.Map2(document.getElementById("googleMap"));
		map.setCenter(new google.maps.LatLng(sylvania_latitude, sylvania_longitude), 12);
		map.enableScrollWheelZoom();
		map.addControl(new GLargeMapControl());

		//google.maps.Event.addListener(map, "moveend", function() {alert(map.getCenter());});

		//
		//	If a default address is passed in, have it go to it
		//
		
		if (locationid != '' && entryid != '' && name != '')
		{
			ExactLocation(entryid, locationid, name);
		}
	}
	
}

/// <summary>printdirections</summary>
///
/// <remarks>pops up a window with just the directions for printing</remarks>
function PrintDirections()
{

	myWindow = window.open('','','location=yes,menubar=yes,directories=yes,toolbar=yes,resizable=yes,scrollbars=yes,width=1000,height=800');
	myWindow.document.write('<a href="javascript:void(0);" onclick="print();">print</a><br/>' + document.getElementById('directions').innerHTML);
	myWindow.document.close();

}

/// <summary>CloseDirections</summary>
///
/// <remarks>closes the panel with the directions</remarks>
function CloseDirections()
{
	$('directionsBox').style.display = 'none';
	$('galleries').style.display = 'visible';
	mainDirections.clear();
	
}

/// <summary>SylvaniaDirectinos gets the directions to sylvania from the origin entered</summary>
///
/// <param name="origin">the address that is the origin for the directions</param>
///
/// <remarks></remarks>
function SylvaniaDirections(origin)
{
	origin = origin.replace("&", "&amp;");
	if (origin == "") alert('You must enter a location.');
	else GetDirections(origin, sylvania_latitude, sylvania_longitude);
}

/// <summary>GetDirections takes the origin and destination as parameters and kicks off the 
///	google method to map the directions between the two</summary>
///
/// <param name="origin">the address that is the origin for the directions</param>
/// <param name="latitude">the latitude of the destination</param>
/// <param name="longitude">the longitude of the destination</param>
///
/// <remarks></remarks>
function GetDirections(origin, latitude, longitude)
{
	$('galleryContainer').style.display = 'block';
	if (mainDirections == null)
	{
		var directions = document.getElementById("directions");
		mainDirections = new google.maps.Directions(map, directions);
		
	}
	else
	{
		mainDirections.clear();
	}

	var directionsBox = document.getElementById("directionsBox");
	
	directionsBox.style.display = 'block';

	errorGenerated = false;
	google.maps.Event.addListener(mainDirections, "error", handleErrors);
	mainDirections.load(origin + " to " + latitude + ", " + longitude);
	
}

/// <summary>name and description of function</summary>
///
/// <param name="paramname">description of parameter</param>
///
/// <remarks></remarks>
function handleErrors(){
	CloseDirections();
	if (!errorGenerated)
	{
		errorGenerated=true;
		
		if (mainDirections.getStatus().code == G_GEO_UNKNOWN_ADDRESS){
			alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + mainDirections.getStatus().code);
		}else if (mainDirections.getStatus().code == G_GEO_SERVER_ERROR){
			alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + mainDirections.getStatus().code);
		}else if (mainDirections.getStatus().code == G_GEO_MISSING_QUERY){
			 alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + mainDirections.getStatus().code)
		}else if (mainDirections.getStatus().code == G_GEO_BAD_KEY){
				 alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + mainDirections.getStatus().code);
		}else if (mainDirections.getStatus().code == G_GEO_BAD_REQUEST){
			alert("A directions request could not be successfully parsed.\n Error code: " + mainDirections.getStatus().code);
		}else{
			alert("An unknown error occurred.");
		}  
	}
}

/// <summary>name and description of function</summary>
///
/// <param name="paramname">description of parameter</param>
///
/// <remarks></remarks>
function onmainDirectionsectionsLoad(){ 
    // Use this function to access information about the latest load()
    // results.

    // e.g.
    // document.getElementById("getStatus").innerHTML = mainDirections.getStatus().code;
	// and yada yada yada...
}

/// <summary>Clear Directions clears the directions off of the map</summary>
///
/// <remarks></remarks>
function ClearDirections()
{
	if (mainDirections != null)
		mainDirections.clear();
}

/// <summary>FormatPhoneNumber formats a string phone number to a pretty string</summary>
///
/// <param name="number">the string number that needs to beautified</param>
///
/// <remarks></remarks>
function FormatPhoneNumber(number)
{
	
	//
	//	strip out all formatting
	//
	
	number = number.replace(/\(/gi, '');
	number = number.replace(/\)/gi, '');
	number = number.replace(/ /gi, '');
	number = number.replace(/-/gi, '');
	
	//
	//	put in brackets and dash
	//
	
	if (number.length == 10)
	{	
		number = '(' + number;
		number = number.substr(0, 4) + ') ' + number.substr(4);
		number = number.substr(0, 9) + '-' + number.substr(9);
	}
	return number;
}

/// <summary>toRads converts a value to radians</summary>
///
/// <param name="val">the value to be converted</param>
///
/// <remarks></remarks>
function toRad(val)
{
  return val * Math.PI / 180;
}

/// <summary>HaversineFormula returns the distance in miles between two lat/long points</summary>
///
/// <param name="lat1">latitude of the first point</param>
/// <param name="lon1">longitude of the first point</param>
/// <param name="lat2">latitude of the second point</param>
/// <param name="lon2">longitude of the second point</param>
///
/// <remarks>returns the distance as an integer</remarks>
function HaversineFormula(lat1, lon1, lat2, lon2)
{
				
	var R = 3956;
	var dLat = toRad(lat2-lat1);
	var dLon = toRad(lon2-lon1); 
	var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
			Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * 
			Math.sin(dLon/2) * Math.sin(dLon/2); 
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
	var d = R * c;					
					
	return d;
}

/// <summary>ProcessExactLocations processes the results from the webservice of a specific location</summary>
///
/// <param name="response">the webservice response envelope</param>
///
/// <remarks></remarks>
function ProcessExactLocation(response)
{
	//
	//	Get the result from the ws envelope
	//

	var envelopeDOM = Sarissa.getDomDocument();

	envelopeDOM = (new DOMParser()).parseFromString(response, "text/xml");

	Sarissa.setXpathNamespaces(envelopeDOM, "xmlns:b='http://tempuri.org/'");
	//envelopeDOM.setProperty("SelectionNamespaces", "xmlns:b='http://tempuri.org/' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'");
	
	var RetrieveExactLocationResult = envelopeDOM.selectSingleNode("//b:ExactLocationResult");
	
	var locationsXML = JH.Utilities.XmlDecode(RetrieveExactLocationResult.firstChild.nodeValue);

	var locationsDOM = Sarissa.getDomDocument();
	
	locationsDOM  = (new DOMParser()).parseFromString(locationsXML, "text/xml");
	
	//
	//	Get Result
	//

	var locations = locationsDOM.selectNodes("//location");
	var location;
	var locationid, entryid;
	var name, city, phone, state, zipcode, address;

	for (var i=0; i < locations.length; i++)
	{
		locationid = locations[i].attributes.getNamedItem('id').nodeValue;
		entryid = locations[i].attributes.getNamedItem('entryid').nodeValue;
		name = (locations[i].selectSingleNode('name').childNodes.length > 0?locations[i].selectSingleNode('name').firstChild.nodeValue:"");
		address = (locations[i].selectSingleNode('address').childNodes.length > 0?locations[i].selectSingleNode('address').firstChild.nodeValue:"");
		city = (locations[i].selectSingleNode('city').childNodes.length > 0?locations[i].selectSingleNode('city').firstChild.nodeValue:"");
		phone = (locations[i].selectSingleNode('phone').childNodes.length > 0?locations[i].selectSingleNode('phone').firstChild.nodeValue:"");
		state = (locations[i].selectSingleNode('state').childNodes.length > 0?locations[i].selectSingleNode('state').firstChild.nodeValue:"");
		zipcode = (locations[i].selectSingleNode('zipcode').childNodes.length > 0?locations[i].selectSingleNode('zipcode').firstChild.nodeValue:"");
		latitude = (locations[i].selectSingleNode('latitude').childNodes.length > 0?locations[i].selectSingleNode('latitude').firstChild.nodeValue:"");
		longitude = (locations[i].selectSingleNode('longitude').childNodes.length > 0?locations[i].selectSingleNode('longitude').firstChild.nodeValue:"");

		var latlng = new google.maps.LatLng(latitude, longitude);

		var marker = new google.maps.Marker(latlng);
		marker.name = name;
		marker.address = address;
		marker.city = city;
		marker.phone = phone;
		marker.state = state;
		marker.zipcode = zipcode;
		marker.latlng = latlng;

		marker.latlng = latlng;
		google.maps.Event.addListener(marker, "mouseover", MarkerClick);

		map.addOverlay(marker);
		
		map.setCenter(latlng);
		
		google.maps.Event.trigger(marker, "click");
		
	}
}

/// <summary>ProcessSearchLocations processes the results from the webservice of a search for locations</summary>
///
/// <param name="response">the webservice response envelope</param>
///
/// <remarks></remarks>
function ProcessSearchLocations(response)
{

	//
	//	Get the result from the ws envelope
	//

	var envelopeDOM = Sarissa.getDomDocument();

	envelopeDOM = (new DOMParser()).parseFromString(response, "text/xml");

	Sarissa.setXpathNamespaces(envelopeDOM, "xmlns:b='http://tempuri.org/'");
	//envelopeDOM.setProperty("SelectionNamespaces", "xmlns:b='http://tempuri.org/' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'");
	
	var RetrieveSearchLocationsResult = envelopeDOM.selectNodes("//b:SearchLocationsResult");

	var locationsXML = "";	
//	document.write(RetrieveSearchLocationsResult.firstChild.nodeValue);

	for (var i=0; i < RetrieveSearchLocationsResult[0].childNodes.length; i++)
	{
		locationsXML += RetrieveSearchLocationsResult[0].childNodes[i].nodeValue;
	}

//	$each (RetrieveSearchLocationsResult[0].childNodes, function(node, index) {locationsXML += node.nodeValue;});
//	var locationsXML = JH.Utilities.XmlDecode(RetrieveSearchLocationsResult.firstChild.nodeValue);

	var locationsDOM = Sarissa.getDomDocument();
	
	locationsDOM  = (new DOMParser()).parseFromString(locationsXML, "text/xml");
	
	//
	//	Get Result
	//

	var locations = locationsDOM.selectNodes("//location");
	var location;
	var locationid, entryid;
	var name, city, phone, state, zipcode, address;
	var bounds = new google.maps.LatLngBounds();

	if (locations.length == 0)
	{
		alert("We could not find any locations that matched your search of `" + $('txtDoSomething').value +"`.");
		return;
	}
	
	for (var i=0; i < locations.length; i++)
	{
		locationid = locations[i].attributes.getNamedItem('id').nodeValue;
		entryid = locations[i].attributes.getNamedItem('entryid').nodeValue;
		name = (locations[i].selectSingleNode('name').childNodes.length > 0?locations[i].selectSingleNode('name').firstChild.nodeValue:"");
		address = (locations[i].selectSingleNode('address').childNodes.length > 0?locations[i].selectSingleNode('address').firstChild.nodeValue:"");
		city = (locations[i].selectSingleNode('city').childNodes.length > 0?locations[i].selectSingleNode('city').firstChild.nodeValue:"");
		phone = (locations[i].selectSingleNode('phone').childNodes.length > 0?locations[i].selectSingleNode('phone').firstChild.nodeValue:"");
		state = (locations[i].selectSingleNode('state').childNodes.length > 0?locations[i].selectSingleNode('state').firstChild.nodeValue:"");
		zipcode = (locations[i].selectSingleNode('zipcode').childNodes.length > 0?locations[i].selectSingleNode('zipcode').firstChild.nodeValue:"");
		latitude = (locations[i].selectSingleNode('latitude').childNodes.length > 0?locations[i].selectSingleNode('latitude').firstChild.nodeValue:"");
		longitude = (locations[i].selectSingleNode('longitude').childNodes.length > 0?locations[i].selectSingleNode('longitude').firstChild.nodeValue:"");
		
		var latlng = new google.maps.LatLng(latitude, longitude);

		var marker = new google.maps.Marker(latlng);
		marker.name = name;
		marker.address = address;
		marker.city = city;
		marker.phone = phone;
		marker.state = state;
		marker.zipcode = zipcode;
		marker.latlng = latlng;

		marker.latlng = latlng;
		google.maps.Event.addListener(marker, "mouseover", MarkerClick);

		map.addOverlay(marker);
		
		bounds.extend(marker.getPoint());
		
		
	}
	
	map.setZoom(map.getBoundsZoomLevel(bounds));
	map.setCenter(bounds.getCenter());
	
}

/// <summary>MarkerClick opens an info box with the location's details</summary>
///
/// <remarks></remarks>
function MarkerClick()
{
	var divContent = document.createElement('div');
	var divAddress = document.createElement('div');
	var divDirections = document.createElement('div');
	var txtDirections = document.createElement('input');
	var btnDirections = document.createElement('img');
	var lnkDirections = document.createElement('a');
	var divClear = document.createElement('div');

	divClear.style.clear = "both";

	divContent.appendChild(divAddress);
	divContent.appendChild(divClear);
	divContent.appendChild(lnkDirections);
	divContent.appendChild(divDirections);

	divAddress.innerHTML = 
		'<span>' + this.name + '</span><br/>' +
		this.address + '<br/> ' + this.city + ',  ' + this.state + ' ' + this.zipcode + '<br/>' +
		'Tel: ' + FormatPhoneNumber(this.phone);


	divDirections.id = 'divDirections';
	divDirections.style.visibility = 'hidden';
	divDirections.appendChild(txtDirections);
	divDirections.appendChild(btnDirections);

	lnkDirections.id = 'lnkDirections';
	lnkDirections.href = 'javascript:void(0);';
	lnkDirections.innerHTML = 'Get Directions<br/>';
	lnkDirections.onclick = function()
	{
		document.getElementById('lnkDirections').style.display = 'none';
		document.getElementById('divDirections').style.visibility = 'visible';
	}
	
	txtDirections.id = 'txtDirections';
	txtDirections.type = 'text';
	txtDirections.value = 'Enter start address';
	txtDirections.onfocus = function() {if (this.value=='Enter start address'){this.value=''};};

	txtDirections.latitude = this.latlng.lat();
	txtDirections.longitude = this.latlng.lng();

	txtDirections.onkeypress = function(e) {
		var key;

		if(window.event)
			key = window.event.keyCode;     //IE
		else
			key = e.which;     //firefox

		if(key == 13)
		{
			GetDirections(this.value, this.latitude, this.longitude);
			map.closeExtInfoWindow();
			return false;
		}

		return true;
	};

	btnDirections.id = 'btnDirections';
	btnDirections.src = 'images/searchbutton.jpg';
	btnDirections.latitude = this.latlng.lat();
	btnDirections.longitude = this.latlng.lng();
	btnDirections.onclick = function()
	{
		GetDirections(document.getElementById('txtDirections').value, this.latitude, this.longitude);
		map.closeInfoWindow();
	}

	map.openInfoWindow(this.latlng, divContent, {suppressMapPan:true});
}

/// <summary>SetOrigin starts the process of mapping out from an origin based on an address</summary>
///
/// <param name="address">address to map to an origin and find locations from</param>
///
/// <remarks></remarks>
function SearchLocations(search)
{
	if (search == "") 
	{
		return;
	}

	map.clearOverlays();
	galleriesArray = new Array();

	search = search.replace("&", "&amp;");
	var envelope = getSoapEnvelope('SearchLocations', 'http://tempuri.org/', new Hash({search: search, siteID: siteID}));

	var wsCall = new Request(
		{
			method: 'post',
			urlEncoded: false,
			url:applicationPath + '/Services/Sylvania.asmx', 
			headers: {'Content-Type': 'text/xml; charset="utf-8"', 'Host':host, 'SOAPAction': 'http://tempuri.org/SearchLocations', 'Content-Length': envelope.length},
			onComplete: ProcessSearchLocations,
			onFailure:	function()
						{
							alert('ajax failure');
						}
		}
	);

	wsCall.send(envelope);

}

/// <summary>SetOrigin starts the process of mapping out from an origin based on an address</summary>
///
/// <param name="address">address to map to an origin and find locations from</param>
///
/// <remarks></remarks>
function ExactLocation(entryid, directoryid, name)
{

	map.clearOverlays();
	galleriesArray = new Array();
	name = name.replace("&", "&amp;");
	var envelope = getSoapEnvelope('ExactLocation', 'http://tempuri.org/', new Hash({entryid: entryid, directoryid: directoryid, name: name}));

	var wsCall = new Request(
		{
			method: 'post',
			urlEncoded: false,
			url:applicationPath + '/Services/Sylvania.asmx', 
			headers: {'Content-Type': 'text/xml; charset="utf-8"', 'Host':host, 'SOAPAction': 'http://tempuri.org/ExactLocation', 'Content-Length': envelope.length},
			onComplete: ProcessExactLocation,
			onFailure:	function()
						{
							alert('ajax failure');
						}
		}
	);

	wsCall.send(envelope);

}

//
//	Add the google rendering function to the page load
//

addLoadEvent(GoogleMapLoad);
