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 initialSearch = null;  // this is used to make a distinction between the initial search and subsequent moves on the map
var visibleMarkerCount = 0;
var previousCenter = null;

var galleriesPerPage = 5;
var mMgr;
var maxZoom = 8;
var minZoom = 12;

/// <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(38.95940879245423, -94.921875), 3);
		map.enableScrollWheelZoom();
		map.addControl(new GLargeMapControl());
//		google.maps.Event.addListener(map, "zoomend", handleZoom);

		var mgrOptions = { borderPadding: 0 };
		mMgr = new MarkerManager(map, mgrOptions);
		
		//
		//	set a pointer to the move listener to null
		//
		
		map.listenerMoveEnd = null;

		//
		//	If a default address is passed in, have it go to it
		//
		
		if (defaultAddress != '' && defaultAddress != 'Enter Valid City and State or Zip'){

			SetOrigin(defaultAddress);
		}
	}
	
}

/// <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)
{
	if (mainDirections == null)
	{
		var directions = document.getElementById("directions");
		mainDirections = new google.maps.Directions(map, directions);
		
	}
	else
	{
		mainDirections.clear();
	}

	var galleriesPanel = document.getElementById("galleries");
	var directionsBox = document.getElementById("directionsBox");
	
	directionsBox.style.display = 'block';

	galleriesPanel.style.visibility = 'hidden';
	galleriesPanel.style.position = 'absolute';

	google.maps.Event.addListener(mainDirections, "error", handleErrors);
	mainDirections.load(origin + " to " + latitude + ", " + longitude);
	
	//Adjust meta tags
	var metas = document.getElementsByTagName("meta");
	
	var x=0;
	for(x=0; x<metas.length; x++){
		if(metas[x].getAttribute("name") == "WT.si_x"){
			metas[x].setAttribute("content",3);
		}
	}
}

/// <summary>handleMove kicks off the update process when the map is moved</summary>
///
/// <remarks></remarks>
function handleMove()
{

	if (map.getZoom() > minZoom || map.getZoom() < maxZoom)
	{

		//
		//	Clear left panel
		//

		document.getElementById('noLocations').style.display = 'block';
		document.getElementById('galleryContainer').style.display = 'none';
		
	}
	else if (previousCenter.distanceFrom(map.getCenter()) > 2000)
	{
		MapPoint(map.getCenter());
	}
	else
	{
		BindGalleries();
	}

}

/// <summary>name and description of function</summary>
///
/// <param name="paramname">description of parameter</param>
///
/// <remarks></remarks>
function handleErrors(){
	CloseDirections();
	
	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>MapPoint retrieves the xml for the surrounding area</summary>
///
/// <param name="point">point on the map to retrieve addresses surrounding</param>
///
/// <remarks></remarks>
function MapPoint(point)
{

	previousCenter = point;
	
	if (!point)
	{
			document.getElementById('noLocations').style.display = 'block';
			document.getElementById('galleryContainer').style.display = 'none';
	} 
	else
	{
		
		//
		//	get gallery xml
		//
		
		var request = GXmlHttp.create();
		var params = "longitude=" + point.x + "&latitude=" + point.y;

		request.open("POST", "../Components/XML/Galleries.xml.aspx", true);
		request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		request.setRequestHeader("Content-length", params.length);

		request.onreadystatechange = function() 
		{
			if (request.readyState == 4) 
			{
				var xml = google.maps.Xml.parse(request.responseText);
				var docEl = xml.documentElement;
				var galleries = docEl.getElementsByTagName("row");

				for (var i = 0; i < galleries.length; i++)
				{
					var latitude = parseFloat(google.maps.Xml.value(galleries[i].attributes.getNamedItem("latitude")));
					var longitude = parseFloat(google.maps.Xml.value(galleries[i].attributes.getNamedItem("longitude")));
					var bizname = google.maps.Xml.value(galleries[i].attributes.getNamedItem("bizname"));
					var add1 = google.maps.Xml.value(galleries[i].attributes.getNamedItem("add1"));
					var city = google.maps.Xml.value(galleries[i].attributes.getNamedItem("city"));
					var state = google.maps.Xml.value(galleries[i].attributes.getNamedItem("state"));
					var zipcode = google.maps.Xml.value(galleries[i].attributes.getNamedItem("zip"));
					var icon = 'otherRetailers';
					var url = google.maps.Xml.value(galleries[i].attributes.getNamedItem("url"));
					var phone = google.maps.Xml.value(galleries[i].attributes.getNamedItem("phone"));
					
					var nfv5 = google.maps.Xml.value(galleries[i].attributes.getNamedItem("nfv5"));
					var nfv6 = google.maps.Xml.value(galleries[i].attributes.getNamedItem("nfv6"));

					if (nfv5 == '1'){
						icon = 'furnitureGalleries';
					}
					else if (nfv6 == '1'){
						icon = 'comfortStudios';
					}

					var latlng = new google.maps.LatLng(latitude, longitude);
					
					var directions = {};//new Class();//Array();// = new google.maps.Directions();
					directions.latlng = latlng;
					directions.bizname = bizname;
					directions.add1 = add1;
					directions.city = city;
					directions.state = state;
					directions.zipcode = zipcode;
					directions.distance = Math.round(HaversineFormula(point.y, point.x, latitude, longitude));
					directions.icon = icon;
					directions.url = url;
					directions.phone = phone;
					directions.drawn = false;

					var existsAlready = false;
					existsAlready = galleriesArray.some(function(item, index)
													{
														return JSON.encode(directions.latlng) == JSON.encode(item.latlng);
													}
												);

					if (!existsAlready)
					{

						galleriesArray.push(directions);//({latlng:latlng, distance:dist, bizname: bizname, address:add1, city:city, state:state, zipcode:zipcode});
					}
					else
					{
						//
						//	Recalculate distance
						//
						
					}
				}

				pageNumber = 0;
				
				//
				//	recalculate all the distances
				//
				
				for (var i = 0; i < galleriesArray.length; i++)
				{

					galleriesArray[i].distance = Math.round(HaversineFormula(point.y, point.x, galleriesArray[i].latlng.lat(), galleriesArray[i].latlng.lng()));

				}
				
				//
				//	Focus on the closest location
				//

				if (galleriesArray.length > 0)
				{

					galleriesArray.sort(SortByDistance); 

					if (initialSearch)
					{

						map.setCenter(galleriesArray[0].latlng, 10);
					}

					//
					//	if galleriesArray is longer than 50 then trim it
					//
					
					while (galleriesArray.length > 50)
					{
						var disappearingGallery = galleriesArray.pop();

						if ($defined(disappearingGallery.marker))
						{
							//map.removeOverlay(disappearingGallery.marker);
							mMgr.removeMarker(disappearingGallery.marker);
						}
					}


					BindGalleries();

				}
				else
				{
					//
					//	Display the no locations message
					//
					
					if (initialSearch)
						map.setCenter(new google.maps.LatLng(38.95940879245423, -94.921875), 3);
					
					document.getElementById('noLocations').style.display = 'block';
					document.getElementById('galleryContainer').style.display = 'none';
					
				}
				
				if (initialSearch)
				{
					origin = point;
					map.listenerMoveEnd = google.maps.Event.addListener(map, "moveend", handleMove);
				}

				initialSearch = false;

			}
		}

		request.send(params);

	}
}

/// <summary>SetOrigin starts the process of mapping out from an origin based on an address</summary>
///
/// <param name="address">address to geocode to an origin and find locations from</param>
///
/// <remarks></remarks>
function SetOrigin(address)
{
	initialSearch = true;
	if (map.listenerMoveEnd != null)
		google.maps.Event.removeListener(map.listenerMoveEnd);

	sortFunction = SortByService;

	document.getElementById('noLocations').style.display = 'none';
	document.getElementById('galleryContainer').style.display = 'none';

	//map.clearOverlays();
	map.closeExtInfoWindow();
	mMgr.clearMarkers();
	
	galleriesArray = new Array();

	document.getElementById('lblSearch').innerHTML = address;

	var geocoder = new google.maps.ClientGeocoder();

	geocoder.getLatLng(
		address,
		MapPoint
	);

}

/// <summary>SortByDistance is a sorting method to allow sorting by distance amongst the results</summary>
///
/// <param name="a">an object that contains the gallery distance from the origin</param>
/// <param name="b">an object that contains the gallery distance from the origin</param>
///
/// <remarks></remarks>
function SortByDistance(a, b)
{
	return a.distance-b.distance;
}

/// <summary>SortByService is a sorting method to allow sorting by gallery type</summary>
///
/// <param name="a">an object that contains the gallery type and distance from the origin</param>
/// <param name="b">an object that contains the gallery type and distance from the origin</param>
///
/// <remarks></remarks>
function SortByService(a, b)
{
	var num1 = 0;
	var num2 = 0;

	var num = 1;
	
	if (a.icon == 'furnitureGalleries' && b.icon != 'furnitureGalleries')
		num = -1;

	if (a.icon == 'comfortStudios' && b.icon != 'comfortStudios')
	{
		if (b.icon == 'furnitureGalleries')
			num = 1;
		else
			num = -1;
	}

	if (a.icon == b.icon)
	{
		num = a.distance - b.distance;
	}
	
	return num;
}


/// <summary>MarkerClick is the event that handles when a marker is clicked either by the left side list of galleries or the icon</summary>
///
/// <remarks></remarks>
function MarkerClick()
{

	try{
		map.setCenter(this.m.getLatLng());
	}catch(err){

	}
	
	var divContent = document.createElement('div');
	var spanAddress = document.createElement('span');
	var lnkDirections = document.createElement('a');
	var divDirections = document.createElement('div');
	var txtDirections = document.createElement('input');
	var btnDirections = document.createElement('img');
	var divLeft = document.createElement('div');
	var divRight = document.createElement('div');
	var imgIcon = document.createElement('img');
	var divClear = document.createElement('div');
	var lnkWebsite = document.createElement('a');
	var lnkClose = document.createElement('a');
	
	divContent.style.paddingTop = '25px';
	divContent.appendChild(divLeft);
	divContent.appendChild(divRight);
	divContent.appendChild(divClear);
	
	divLeft.appendChild(imgIcon);
	
	divRight.appendChild(spanAddress);
	divRight.appendChild(lnkDirections);
	divRight.appendChild(divDirections);

	divLeft.setAttribute("class", "googleBubble_left");
	divLeft.setAttribute("className", "googleBubble_left");

	divRight.setAttribute("class", "googleBubble_right");
	divRight.setAttribute("className", "googleBubble_right");

	divClear.setAttribute("class", "clearboth");
	divClear.setAttribute("className", "clearboth");

	lnkClose.setAttribute("class", "bubbleClose");
	lnkClose.setAttribute("className", "bubbleClose");
	lnkClose.innerHTML = "close";
	lnkClose.onclick = function(){map.closeExtInfoWindow();};
	divContent.appendChild(lnkClose);

	imgIcon.src = "../images/findADealer/marker_" + this.m.icon + ".png";
	//imgIcon.src = 'markerIcon.aspx?type=' + this.m.icon + '&number=' + (this.m.index+1) + "&.png";

	divDirections.id = 'divDirections';
	divDirections.style.visibility = 'hidden';
	divDirections.appendChild(txtDirections);
	divDirections.appendChild(btnDirections);

	spanAddress.innerHTML = 
		'<span>' + this.m.bizname + '</span><br/>' +
		this.m.add1 + '<br/> ' + this.m.city + ',  ' + this.m.state + ' ' + this.m.zipcode + '<br/>' +
		'Tel: ' + FormatPhoneNumber(this.m.phone) + '<br/>' +
		'~' + this.m.distance + ' miles&nbsp;';

	lnkDirections.id = 'lnkDirections';
	lnkDirections.href = 'javascript:void(0);';
	lnkDirections.innerHTML = 'Get Directions<br/>';
	lnkDirections.onclick = function()
	{
		document.getElementById('lnkDirections').style.visibility = 'hidden';
		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.m.latlng.lat();
	txtDirections.longitude = this.m.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/home/directions_go.jpg';
	btnDirections.latitude = this.m.latlng.lat();
	btnDirections.longitude = this.m.latlng.lng();
	btnDirections.onclick = function()
	{
		GetDirections(document.getElementById('txtDirections').value, this.latitude, this.longitude);
		map.closeExtInfoWindow();
	}

	if (this.m.url != "")
	{
		lnkWebsite.href = this.m.url;
		lnkWebsite.target = "_blank";
		lnkWebsite.innerHTML = '<b>Store Website</b>';
		divRight.appendChild(lnkWebsite);	
	}

/*	

	//
	//	Highlight the box
	//
	
	if (currentBox != null)
	{
		if (currentBox.m.index % 2 == 1)
		{
			currentBox.setAttribute("class", "galleryBox_alternate");
			currentBox.setAttribute("className", "galleryBox_alternate");
		}
		else
		{
			currentBox.setAttribute("class", "galleryBox");
			currentBox.setAttribute("className", "galleryBox");
		}
		
	}
	
	this.m.box.className = "galleryBox_selected";
*/
	currentBox = JSON.encode(this.m.getLatLng());
	
	this.m.openExtInfoWindow(
              map,
              "extInfoWindow_coolBlues",
              divContent,
              {beakOffset: 0}
            ); 

}

/// <summary>BindGalleries binds the galleries in the galleriesArray to the left list (divGalleries)</summary>
///
/// <remarks></remarks>
function BindGalleries()
{	
	galleriesArray.sort(sortFunction); 

	//
	//	Generate left bar
	//

	var divGalleries = document.getElementById('divGalleries');
	var previousPage = -1;
	var galleryPage = null;
	visibleMarkerCount = 0;

	divGalleries.innerHTML = "";
	
	var boundedGalleries = new Array();
	for (var i = 0; i < galleriesArray.length; i++){
		var gallery = galleriesArray[i];
		var bounds = map.getBounds();
		
		//If the gallery/store/retailer is in the proper bounds
		if (bounds.contains(gallery.latlng)){
			boundedGalleries.push(gallery);
		}
		else{
		/*
			if ($("#gallery.marker").length)
			{
				if (currentBox == $.toJSON(gallery.marker.getLatLng()))
				{
					currentBox = null;
					map.closeExtInfoWindow()
				}
				mMgr.removeMarker(gallery.marker);
				gallery.drawn = false;
			}
			*/
		}	
	}
	
	for (var i = 0; i < boundedGalleries.length; i++)
	{

		var gallery = boundedGalleries[i];
		var bounds = map.getBounds();
		
		//if (bounds.contains(gallery.latlng))
		//{
			
			if (!gallery.drawn)
			{
				gallery.drawn = true;

				//
				//	Set up marker on map
				//

				var icon = new GIcon();
				icon.image = "../images/findADealer/marker_" + gallery.icon + ".png";
				//icon.image = "markerIcon.aspx?type=" + gallery.icon + "&number=" + (i+1) + "&.png";
				icon.shadow = "../images/findADealer/marker_shadow.png";
				icon.iconSize = new GSize(29, 38);
				icon.shadowSize = new GSize(62, 43);
				icon.iconAnchor = new GPoint(13, 37);
				icon.infoWindowAnchor = new GPoint(14, 0);

				function orderOfCreation(marker, a){
					return -GOverlay.getZIndex(marker.getPoint().lat());
				}
				var marker;
				
				//If  a gallery is close to a normal store, swap them
			
				if(boundedGalleries.length < i && gallery.icon == 'furnitureGalleries' && (boundedGalleries[i+1].icon == 'comfortStudios' || boundedGalleries[i+1].icon == 'otherRetailers' )){
					if(Math.round(HaversineFormula(gallery.latlng.lat(), gallery.latlng.lng(),boundedGalleries[i+1].latlng.lat(), boundedGalleries[i+1].latlng.lng())) < 5){
						marker = new google.maps.Marker(gallery.latlng, {icon:icon, zIndexProcess:orderOfCreation});
					}else{
						marker = new google.maps.Marker(gallery.latlng, icon);
					}
				}
				/*else if(gallery.icon == 'comfortStudios' && boundedGalleries[i+1].icon == 'otherRetailers' ){
					if(Math.round(HaversineFormula(gallery.latlng.lat(), gallery.latlng.lng(),boundedGalleries[i+1].latlng.lat(), boundedGalleries[i+1].latlng.lng())) < 5){
						marker = new google.maps.Marker(gallery.latlng, {icon:icon, zIndexProcess:orderOfCreation});
					}else{
						marker = new google.maps.Marker(gallery.latlng, icon);
					}
				}*/
				else{
					marker = new google.maps.Marker(gallery.latlng, icon);
				}
			
				marker.bizname = gallery.bizname;
				marker.add1 = gallery.add1;
				marker.city = gallery.city;
				marker.state = gallery.state;
				marker.zipcode = gallery.zipcode;
				marker.distance = gallery.distance;
				marker.latlng = gallery.latlng;
				marker.icon = gallery.icon;
				marker.index = i;
				marker.url = gallery.url;
				marker.phone = gallery.phone;

				marker.m = marker;

				gallery.marker = marker;

				google.maps.Event.addListener(marker, "click", MarkerClick);

				mMgr.addMarker(marker, 8, 12)

			}
			
			//
			//	if this gallery is within view, show it on the left nav
			//
		

			var galleryBox = document.createElement('a');
			var galleryBox_icon = document.createElement('img');
			var galleryBox_text = document.createElement('div');
			var galleryBox_info = document.createElement('div');
			var galleryBox_spacer = document.createElement('div');

			galleryBox.id = 'galleryBox' + i;
			galleryBox.href = 'javascript:void(0);';

			//alert(currentBox + ' ' + JSON.encode(gallery.latlng));
			if (currentBox == JSON.encode(gallery.latlng))
			{
				galleryBox.setAttribute("class", "galleryBox_selected");
				galleryBox.setAttribute("className", "galleryBox_selected");				
			}
			else if (visibleMarkerCount % 2 == 1)
			{
				galleryBox.setAttribute("class", "galleryBox_alternate");
				galleryBox.setAttribute("className", "galleryBox_alternate");
			}
			else
			{
				galleryBox.setAttribute("class", "galleryBox");
				galleryBox.setAttribute("className", "galleryBox");
			}

			galleryBox_spacer.setAttribute("class", "galleryBox_spacer");
			galleryBox_spacer.setAttribute("className", "galleryBox_spacer");
			galleryBox_spacer.innerHTML = '&nbsp;';

			galleryBox_icon.setAttribute("class", "galleryBox_icon");
			galleryBox_icon.setAttribute("className", "galleryBox_icon");
			galleryBox_icon.src = "../images/findADealer/marker_" + gallery.icon + ".png";
			//galleryBox_icon.src = "markerIcon.aspx?type=" + gallery.icon + "&number=" + (visibleMarkerCount+1) + "&.png";
			galleryBox_icon.style.border = '0px';

			galleryBox_text.setAttribute("class", "galleryBox_text");
			galleryBox_text.setAttribute("className", "galleryBox_text");

			galleryBox_text.innerHTML = '<b>' + gallery.bizname + '</b><br/>' + 
										gallery.add1 + '<br/>' +
										gallery.city + ', ' + gallery.state + ' ' + gallery.zipcode;

			galleryBox_info.setAttribute("class", "galleryBox_info");
			galleryBox_info.setAttribute("className", "galleryBox_info");

			galleryBox_info.innerHTML = 'Info';

			galleryBox.appendChild(galleryBox_spacer);
			galleryBox.appendChild(galleryBox_icon);
			galleryBox.appendChild(galleryBox_text);
			galleryBox.appendChild(galleryBox_info);

			//
			//	if new page, then add galleryBox to that new page
			//
			
			if (previousPage != Math.floor(visibleMarkerCount / galleriesPerPage))
			{

				previousPage = Math.floor(visibleMarkerCount / galleriesPerPage);
				galleryPage = document.createElement('div');
				galleryPage.id = 'galleryPage_' + previousPage;

				if (previousPage == 0)
					galleryPage.style.display = 'block';
				else
					galleryPage.style.display = 'none';
					
				divGalleries.appendChild(galleryPage);
				
			}


			//
			//	Set all my pointers to make life easy
			//

			gallery.marker.box = galleryBox;
			galleryBox.m = gallery.marker;
			galleryBox.onclick = MarkerClick;

			galleryPage.appendChild(galleryBox);

			visibleMarkerCount++;

		}
		

	//}

	//mMgr.refresh();

	UpdatePaging();

	document.getElementById('noLocations').style.display = 'none';
	document.getElementById('galleryContainer').style.display = 'block';


}

/// <summary>UpdatePaging updates the left side list based on the page number</summary>
///
/// <remarks></remarks>
function UpdatePaging()
{
	//
	//	update Paging
	//

	var pager = document.getElementById('galleryPagination');

	var previousLink = null;
	var nextLink = null;
	var results = document.createElement('div');
	var divider = document.createElement('span');
	var leftArrow = document.createElement('span');
	var rightArrow = document.createElement('span');

	results.setAttribute("ID","PaginationResults");
	results.innerHTML = "Displaying Results " + (pageNumber * 5 + 1) + "-" + ((pageNumber * 5 + 5) > visibleMarkerCount?visibleMarkerCount:(pageNumber * 5 + 5)) + " of " + visibleMarkerCount;
	
	leftArrow.innerHTML = "&lt;&nbsp;";
	rightArrow.innerHTML = "&nbsp;&gt;";

	pager.innerHTML = "";
	divider.innerHTML = '&nbsp;|&nbsp;';

	pager.appendChild(leftArrow);

	//
	//	Make the previous link inactive if this is the first page
	//
	
	if (pageNumber == 0)
	{
		previousLink = document.createElement('span');
		previousLink.innerHTML = 'Prev';
	}
	else
	{
		previousLink = document.createElement('a');
		previousLink.href = 'javascript:void(0);';
		previousLink.innerHTML = 'Prev';
		previousLink.onclick = function(){FlipGalleriesPageBackward();};
	}

	//
	//	Make the next link inactive if this is the last page
	//

	if (pageNumber >= (Math.ceil(galleriesArray.length / galleriesPerPage))-1 || galleriesArray.length < 5)
	{
		nextLink = document.createElement('span');
		nextLink.innerHTML = 'Next';
	}
	else
	{
		nextLink = document.createElement('a');
		nextLink.href = 'javascript:void(0);';
		nextLink.innerHTML = 'Next';
		nextLink.onclick = function(){FlipGalleriesPageForward();};
	}

	//
	//	Add the objects to the pager div
	//
	
	pager.appendChild(results);
	pager.appendChild(leftArrow);
	pager.appendChild(previousLink);
	pager.appendChild(divider);
	pager.appendChild(nextLink);
	pager.appendChild(rightArrow);
}

/// <summary>FlipGalleriesPageForward moves the paging forward a page</summary>
///
/// <remarks></remarks>
function FlipGalleriesPageForward()
{
	//
	//	hide last page
	//
	
	var previousPage = document.getElementById('galleryPage_' + pageNumber);
	previousPage.style.display = 'none';
	pageNumber++;
	var nextPage = document.getElementById('galleryPage_' + pageNumber);
	nextPage.style.display = 'block';
	UpdatePaging();
	
}

/// <summary>FlipGalleriesPageBackward moves the paging back a page</summary>
///
/// <remarks></remarks>
function FlipGalleriesPageBackward()
{
	var previousPage = document.getElementById('galleryPage_' + pageNumber);
	previousPage.style.display = 'none';
	pageNumber--;
	var nextPage = document.getElementById('galleryPage_' + pageNumber);
	nextPage.style.display = 'block';
	UpdatePaging();

}

//
//	Add the google rendering function to the page load
//

addLoadEvent(GoogleMapLoad);