var map;
var origin = null;
var destination;
var mainDirections = null;

var directionsDisplay = null;
var directionsService = 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 = 7;
var mMgr;
var maxZoom = 8;
var minZoom = 15;
var boundedGalleries = null;
var currentDealerNumber = null;

var isDirectionsMode = false;

var currentAddress = null;
var singleResult = false;
var mapRequest = null;

var infoWindow = null;
var pointOrigin = null;

/// <summary>GoogleMapLoad is the onLoad event to start rendering the map to the googleMap div</summary>
///But for some 
/// <remarks></remarks>
function GoogleMapLoad() {
	//if (google.maps.BrowserIsCompatible()) 
	//{

	//
	//	Set the map to the US by default
	//		
	var latlng = new google.maps.LatLng(38.95940879245423, -94.921875);
	var myOptions = {
		zoom: 9,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById("googleMap"), myOptions);
	//map.setCenter(new google.maps.LatLng(38.95940879245423, -94.921875), 9);
	//map.setZoom(13);


	var mgrOptions = { borderPadding: 0 };
	//mMgr = new MarkerManager(map, mgrOptions);

	//
	//	set a pointer to the move listener to null
	//

	//map.listenerMoveEnd = null;
	google.maps.event.addListener(map, 'dragend', function () {
	    //console.log('dragend');
	    handleMove();
	});
	google.maps.event.addListener(map, 'zoom_changed', function () {
	    handleMove();
	});

	//
	//	If a default address is passed in, have it go to it
	//

	if (defaultAddress != '') {
		var qs = new Querystring();
		if (qs.get("unserviced", "") == "yes") {
			document.getElementById('notServiced').style.display = 'block';
			setMetaInfo("3");
		} else {
			SetOrigin(defaultAddress);
			setMetaInfo("4");
		}
	}
	//}

}



function setMetaInfo(value) {
	//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", value);
		}
		if (metas[x].getAttribute("name") == "WT.si_n") {
			metas[x].setAttribute("content", "Extended Purchase");
		}
	}
}

/// <summary>handleMove kicks off the update process when the map is moved</summary>
///
/// <remarks></remarks>
function handleMove() {
	//map.clearOverlays();
    //UpdateIcons();
    
	if ((map.getZoom() > minZoom || map.getZoom() < maxZoom) && !isDirectionsMode) {

		//
		//	Clear left panel
		//

		document.getElementById('noLocations').style.display = 'block';
		document.getElementById('galleryContainer').style.display = 'none';

	}
//	else if (previousCenter.distanceFrom(map.getCenter()) > 2000) {
//		ShowPoint(map.getCenter());
//	}
	else {
	    //BindGalleries();
	    ShowPoint(map.getCenter());
	}


}

/// <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 (directionsDisplay != null) {
        directionsDisplay.setMap(null);
        directionsDisplay.setPanel(null);
    } else {

        directionsService = new google.maps.DirectionsService();
        directionsDisplay = new google.maps.DirectionsRenderer();

    }

	var galleriesPanel = document.getElementById("galleries");
	var directionsBox = document.getElementById("directionsBox");

	directionsBox.style.display = 'block';
	galleriesPanel.style.display = 'none';

	//directionsBox.innerHTML = "";

	directionsDisplay.setMap(map);
	directionsDisplay.setPanel(directionsBox);

    
	var start = document.getElementById("txtStartAddress").value;
	var end = document.getElementById("txtEndAddress").value;

	var request = {
	    origin: start,
	    destination: end,
	    travelMode: google.maps.TravelMode.DRIVING
	};
	directionsService.route(request, function (result, status) {
	    if (status == google.maps.DirectionsStatus.OK) {
	        directionsDisplay.setDirections(result);
            
	    }
	});


//	google.maps.event.addListener(mainDirections, "error", handleErrors);
//	//mainDirections.load(origin + " to " + latitude + ", " + longitude);
//	mainDirections.load(start + " to " + end)

	//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);
		}
	}

    isDirectionsMode = true;



    try {
        dcsMultiTrack('WT.si_n', 'Find a Store', 'WT.si_x', '3');
    } catch (ex) {
    }


}

/// <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 (directionsDisplay != null) {
        directionsDisplay.setMap(null);
        directionsDisplay.setPanel(null);
		isDirectionsMode = false;
	}
}

/// <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>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 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>MapPoint is a callback for the google geocoder call</summary>
///
/// <param/>
///
/// <remarks></remarks>

function MapPoint(results, status) {
	if (status != google.maps.GeocoderStatus.OK) return;
	pointOrigin = results[0].geometry.location;
	ShowPoint(pointOrigin);
}

/// <summary>ShowPoint retrieves the xml for the surrounding area</summary>
///
/// <param name="point">point on the map to retrieve addresses surrounding</param>
///
/// <remarks></remarks>

function ShowPoint(point) {

	previousCenter = point;

	if (!point) {
		document.getElementById('noLocations').style.display = 'block';
		document.getElementById('galleryContainer').style.display = 'none';

	}
	else {

		//
		//	get gallery xml
		//

	    //console.log(map.getBounds());

		if (mapRequest != null) {//clear any open requests
			mapRequest.abort();
			mapRequest = null;
			//mapRequest.onreadystatechange = function () { }; mapRequest.abort(); mapRequest = null;
		}

		
		//console.log(params);
		//mapRequest = GXmlHttp.create();


		var ne = map.getBounds().getNorthEast();
        var sw = map.getBounds().getSouthWest();

        var dist = Math.round(HaversineFormula(ne.lat(), ne.lng(), sw.lat(), sw.lng())) + 20;


        var params = "radius=" + dist + "&longitude=" + point.lng() + "&latitude=" + point.lat();


		if ($("#rightOptin").length > 0) {
			if (location.href.toLowerCase().indexOf("optindc") > -1) {
				params += "&optindc=1";
			} else if (location.href.toLowerCase().indexOf("optin") > -1) {
				params += "&optin=1";
			}
		}

		if ($("#chkFurnitureGallery:checked").val()) {
			params += "&FurnitureGallery=1";
		}
		if ($("#chkComfortStudio:checked").val()) {
			params += "&ComfortStudio=1";
		}
		if ($("#chkOther:checked").val()) {
			params += "&Other=1";
		}
		if ($("#chkParticipating:checked").val()) {
			params += "&Participating=1";
		}
		if ($("#chkOptin:checked").val()) {
			params += "&Optin=1";
		}


		var testing = querySt("testing");
		var addtoquerystring = "";
		if (testing) {
			addtoquerystring = "?testing=1";
		}

		var xhr = $.ajax(
		{
		    type: "POST",
		    url: applicationPath + "XML/Galleries.aspx" + addtoquerystring,
		    data: params,
		    dataType: "xml",
		    success: function (data) {

		        $(data).find("row").each(function () {
		            //
		            //	go over each gallery
		            //

		            var latitude = parseFloat($(this).attr("latitude"));
		            var longitude = parseFloat($(this).attr("longitude"));
		            var nfv5 = $(this).attr("nfv5");
		            var nfv6 = $(this).attr("nfv6");
		            var latlng = new google.maps.LatLng(latitude, longitude);


		            var directions = {};
		            directions.latlng = latlng;
		            directions.bizname = ($(this).attr("bizname"));
		            directions.add1 = ($(this).attr("add1"));
		            directions.city = ($(this).attr("city"));
		            directions.state = ($(this).attr("state"));
		            directions.zipcode = ($(this).attr("zip"));

		            directions.distance = Math.round(HaversineFormula(point.lat(), point.lng(), latitude, longitude));
		            
		            //console.debug(directions.distance);

		            directions.url = ($(this).attr("url"));
		            directions.phone = ($(this).attr("phone"));
		            directions.drawn = false;
		            directions.store_url = ($(this).attr("store_url"));
		            //directions.region = ($(this).attr("region"));
		            directions.activeAd = ($(this).attr("ActiveAd"));

		            var dealerNumber = ($(this).attr("dealer_number"));

		            if (dealerNumber != "") {
		                directions.dealerNumber = dealerNumber;
		            } else {
		                directions.dealerNumber = ($(this).attr("nfv15"));
		            }


		            if (nfv5 == '1') {
		                directions.icon = 'furnitureGalleries';
		            }
		            else if (nfv6 == '1') {
		                directions.icon = 'comfortStudios';
		            } else {
		                directions.icon = 'otherRetailers';
		            }

		            var existsAlready = false;

		            jQuery.each(galleriesArray, function () {
		                if (directions.latlng.lat() + '|' + directions.latlng.lng() == this.latlng.lat() + '|' + this.latlng.lng()) {
		                    existsAlready = true;

		                    return false;
		                }
		            });

		            if (!existsAlready) {
		                galleriesArray.push(directions);
		            }
		            else {
		                //
		            }


		            if (singleResult) return;

		        }
				);


		        singleResult = false;
		        pageNumber = 0;

		        //
		        //	recalculate all the distances
		        //

		        for (var i = 0; i < galleriesArray.length; i++) {

		            galleriesArray[i].distance = Math.round(HaversineFormula(point.lat(), point.lng(), galleriesArray[i].latlng.lat(), galleriesArray[i].latlng.lng()));

		        }

		        //Sort by 

		        //
		        //	Focus on the closest location
		        //

		        if (galleriesArray.length > 0) {
		            sortFunction = SortByService;
		            //galleriesArray.sort(SortByDistance); 


		            if (initialSearch) {

		                map.setCenter(galleriesArray[0].latlng, 9);
		            }

		            //
		            //	if galleriesArray is longer than 50 then trim it
		            //

//		            while (galleriesArray.length > 50) {
//		                var disappearingGallery = galleriesArray.pop();

//		                if ($("disappearingGallery.marker").length) {
//		                    //mMgr.removeMarker(disappearingGallery.marker);
//		                }
//		            }

		            BindGalleries();
		        }
		        else {
		            //
		            //	Display the no locations message
		            //

		            if (initialSearch)
		                map.setCenter(new google.maps.LatLng(38.95940879245423, -94.921875), 9);

		            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;
		        mapRequest = null;

		    }
		});


		//	    mapRequest.open("POST", applicationPath + "XML/Galleries.aspx" + addtoquerystring, true);
		//	    mapRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		//	    mapRequest.setRequestHeader("Content-length", params.length);

		//mapRequest.onreadystatechange = function () 

		//mapRequest.send(params);

	}
}
function querySt(ji) {
	hu = window.location.search.substring(1);
	gy = hu.split("&");
	for (i = 0; i < gy.length; i++) {
		ft = gy[i].split("=");
		if (ft[0] == ji) {
			return ft[1];
		}
	}
}
/// <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();
	if (infoWindow) infoWindow.close();

	//mMgr.clearMarkers();


	galleriesArray = new Array();

	document.getElementById('lblSearch').innerHTML = address;

	var geocoder = new google.maps.Geocoder(); // new google.maps.ClientGeocoder();

	geocoder.geocode({ 'address': address }, MapPoint);
}






/// <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() {
	//alert(this.m.dealerNumber);


	try {
		if (currentAddress == null || currentAddress != this.m.dealerNumber) {
			currentAddress = this.m.dealerNumber;
			map.setCenter(this.m.latlng);
			handleMove();//x*
		}

	} catch (err) {
		alert(err);
	}

	var divContent = document.createElement('div');
	var spanAddress = document.createElement('span');
	var lnkDirections = document.createElement('a');

//	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 lnkHours = document.createElement('a');
	var lnkAd = document.createElement('a');
//	var lnkClose = document.createElement('a');

	var spanLinks = document.createElement('span');


	divContent.style.paddingTop = '5px';
	//divContent.style.display = 'block';
	//divContent.style.height = '525px';
	//divContent.style.width = '525px';

//	divContent.appendChild(divLeft);
	divContent.appendChild(divRight);
	divContent.appendChild(divClear);

//	divLeft.appendChild(imgIcon);

	divRight.appendChild(spanAddress);
	spanLinks.appendChild(document.createElement('br'));
	if (this.m.store_url != '') {
	    spanLinks.appendChild(lnkWebsite);
	    if (this.m.store_url.indexOf('http')!=0) {
		    spanLinks.appendChild(lnkHours);
		    spanLinks.appendChild(document.createElement('br'));
			if (this.m.activeAd == '1' ) {
			    spanLinks.appendChild(lnkAd);
			}
		}
        
	}


    spanLinks.appendChild(lnkDirections);



    divRight.appendChild(spanLinks);

//	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.onclick = function () {
//	    //if (infoWindow) infoWindow.close();
//	    /* map.closeExtInfoWindow(); */
//	    console.log('asd');
//	    currentAddress = null;
//	    //currentmarker = null;
//	};
//	divContent.appendChild(lnkClose);

//	imgIcon.src = applicationPath + "images/storelocator/marker_" + this.m.iconimage + ".png";


	lnkWebsite.id = 'lnkWebsite';
	lnkWebsite.innerHTML = "Store Website";

	if (this.m.store_url != '') {

	    if (this.m.store_url.indexOf('http') != 0) {
	        lnkWebsite.href = this.m.store_url+"?WT.si_n=Find a Store&WT.si_x=2&WT.z_store_web=1";

	        lnkHours.id = 'lnkHours';
	        lnkHours.innerHTML = "Store Hours";
	        //lnkHours.setAttribute("class", "clearboth");
	        lnkHours.href = this.m.store_url + "Store-Info/?WT.z_store_hrs=1";

	        
	        lnkAd.id = 'lnkAd';
	        lnkAd.innerHTML = "View our ad";
	        //lnkAd.setAttribute("class", "clearboth");
	        lnkAd.href = this.m.store_url + "Sale/";

	    } else {
	        lnkWebsite.href = this.m.store_url;
	        lnkWebsite.setAttribute("target", "_blank");
	        lnkWebsite.onClick = function () {
	            try {
	                dcsMultiTrack('WT.si_n', 'Find a Store', 'WT.si_x', '2', 'WT.z_store_web', '1');
	            } catch (ex) {
	            }
	        }
	    }


//	    lnkHours.onClick = function () {
//	        try {
//	            dcsMultiTrack('WT.z_store_hrs', '1');
//	        } catch (ex) {
//	        }
//	    }
	}




	var dist = Math.round(HaversineFormula(pointOrigin.lat(), pointOrigin.lng(), this.m.latlng.lat(), this.m.latlng.lng()));
	//console.log(dist);

	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/>' +
		'~' + dist + ' miles&nbsp;';
	/**/
	



	lnkDirections.id = 'lnkDirections';
	lnkDirections.href = 'javascript:;';
	lnkDirections.innerHTML = 'Get Directions<br/>';
	lnkDirections.address = this.m.add1 + ' ' + this.m.city + ',  ' + this.m.state + ' ' + this.m.zipcode;
	lnkDirections.dealerNumber = this.m.dealerNumber;
	lnkDirections.onclick = function () {
		currentDealerNumber = this.dealerNumber;
		document.getElementById('divDirections').style.display = 'block';
		document.getElementById('txtEndAddress').value = this.address;
		try {
		    dcsMultiTrack('WT.z_store_dir', '1');
		} catch (ex) {
		}
	}


currentBox = this.m.latlng.lat() + '|' + this.m.latlng.lng(); //$.toJSON(this.m.getLatLng());

	/*
	this.m.openExtInfoWindow(
	map,
	"extInfoWindow_coolBlues",
	divContent,
	{beakOffset: 0}//-1
	);
	*/
    if (infoWindow != null) {
        infoWindow.close();
    }
	infoWindow = new google.maps.InfoWindow(
	{
		content: divContent
	});

infoWindow.open(map, this.m); 

}

/// <summary>BindGalleries binds the galleries in the galleriesArray to the left list (divGalleries)</summary>
///
/// <remarks></remarks>
function BindGalleries() {
	galleriesArray.sort(sortFunction);

	//
	//	Generate left bar
	//



	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 == gallery.marker.latlng.lat() + '|' + gallery.marker.latlng.lng()) {/*$.toJSON(gallery.marker.getLatLng())*/
					currentBox = null;
					//map.closeExtInfoWindow()
					if (infoWindow) infoWindow.close();
				}
				//mMgr.removeMarker(gallery.marker);
				gallery.drawn = false;
			}

		}

	}
	BuildMarkers();
}

function BuildMarkers() {
	var divGalleries = document.getElementById('divGalleries');
	var previousPage = -1;
	var galleryPage = null;
	visibleMarkerCount = 0;

	divGalleries.innerHTML = "";

	for (var i = 0; i < boundedGalleries.length; i++) {

		var gallery = boundedGalleries[i];

		if (!gallery.drawn) {
			gallery.drawn = true;

			//
			//	Set up marker on map
			//

			var icon = new google.maps.MarkerImage();
			var shadow = new google.maps.MarkerImage();
			//if (i >= pageNumber * galleriesPerPage && i < pageNumber * galleriesPerPage + galleriesPerPage) {

			    
				icon.url = applicationPath + "images/storelocator/marker_" + gallery.icon + ".png";

				shadow.url = applicationPath + "images/storelocator/marker_shadow.png";
				shadow.size = new google.maps.Size(62, 43);

				icon.size = new google.maps.Size(25, 42);

				icon.anchor = new google.maps.Point(13, 37);
				//icon.infoWindowAnchor = new google.maps.Point(14, 0);
//			} else {

//    icon.url = applicationPath + "images/storelocator/marker_" + gallery.icon + "Dot.png";
//    
//				icon.size =  new google.maps.Size(10, 11);
//				icon.anchor =  new google.maps.Point(5, 5);
//				//icon.infoWindowAnchor = new GPoint(14, 0);
//				//icon.shadow = null;
//				//icon.shadow = applicationPath + "images/storelocator/marker_shadow.png";
//			}

			function orderOfCreation(marker, a) {//galleries and cs above other stores
				var z = -marker.getZIndex();  //-GOverlay.getZIndex(marker.getPoint().lat());
				if (marker.icon == 'furnitureGalleries') {
					z -= 50000;
				} else if (marker.icon == 'comfortStudios') {
					z -= 20000;
				}
				return -z;
			}
			var marker;

			//marker = new google.maps.Marker(gallery.latlng, { icon: icon, shadow: shadow/*, zIndexProcess: orderOfCreation*/ });
			var gll = gallery.latlng;
			marker = new google.maps.Marker({ 'map':map, 'position':gll, 'icon': icon, 'shadow': shadow });

			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.iconimage = gallery.icon;
			marker.shadowimage = gallery.shadow;
			marker.index = i;
			marker.url = gallery.url;
			marker.phone = gallery.phone;
			marker.store_url = gallery.store_url;
			//marker.region = gallery.region;
			marker.dealerNumber = gallery.dealerNumber;
			marker.activeAd = gallery.activeAd;


			marker.m = marker;

			gallery.marker = marker;

			google.maps.event.addListener(marker, "click", MarkerClick);

		}



		//
		//	if this gallery is within view, show it on the left nav
		//

        //var hover = (isTouchDevice() ? "" : "");//turn off hover for touch 

		var galleryBox = document.createElement('a');
		var galleryBox_text = document.createElement('div');
		var galleryBox_spacer = document.createElement('div');

		galleryBox.id = 'galleryBox' + i;
		galleryBox.href = 'javascript:void(0);';


		if (currentBox == gallery.latlng.lat() + '|' + gallery.latlng.lng()/*$.toJSON(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.onmouseover = function (e) { return false; };

		galleryBox_text.innerHTML = '<img class="galleryBox_icon" classname="galleryBox_icon" src="' + applicationPath + "images/storelocator/marker_" + gallery.icon + '.png" style="border: 0px none ;"/>'
                                    + '<div class="galleryBox_text" classname="galleryBox_text"><b>' + gallery.bizname + '</b><br/>' + gallery.add1 + '<br/>' + gallery.city + ', ' + gallery.state + ' ' + gallery.zipcode + '<br/>' + FormatPhoneNumber(gallery.phone) + '</div>'
                                    + '<div class="galleryBox_info" classname="galleryBox_info">More Info</div>';



		galleryBox.appendChild(galleryBox_spacer);
		galleryBox.appendChild(galleryBox_text);


		//
		//	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 = function () {
		    google.maps.event.trigger(this.m, "click");
		    dcsMultiTrack('WT.z_store_moreinfo', '1');
		};

		galleryPage.appendChild(galleryBox);

		visibleMarkerCount++;
	}

	if (currentAddress != null) {
		for (var i = 0; i < boundedGalleries.length; i++) {
			var gallery = boundedGalleries[i];
			if (currentAddress == gallery.marker.dealerNumber) {
				var addyPage = parseInt(i / galleriesPerPage);
				if (pageNumber != addyPage) {
					FlipGalleriesPageJump(addyPage);
				}

			}
		}
	}

	UpdatePaging();

	UpdateIcons();


	document.getElementById('noLocations').style.display = 'none';
	document.getElementById('galleryContainer').style.display = 'block';


}

function UpdateIcons() {
	var currentmarker = null;
	//mMgr.clearMarkers();



	for (var i = 0; i < boundedGalleries.length; i++) {
		var gallery = boundedGalleries[i];
		var marker = gallery.marker;

		var icon = marker.getIcon();
		var shadow = marker.getShadow();
//		if (i >= pageNumber * galleriesPerPage && i < pageNumber * galleriesPerPage + galleriesPerPage) {

			icon.url = applicationPath + "images/storelocator/marker_" + gallery.icon + ".png";
			icon.size = new google.maps.Size(25, 42);
			icon.anchor = new google.maps.Point(13, 37);
			//icon.infoWindowAnchor = new google.maps.Point(14, 0);

			if (shadow == null) {
				shadow = new google.maps.MarkerImage();
				marker.shadow = shadow;
			}
			shadow.url = applicationPath + "images/storelocator/marker_shadow.png";
			shadow.size = new google.maps.Size(62, 43);

//		} else {

//			icon.image = applicationPath + "images/storelocator/marker_" + gallery.icon + "Dot.png";
//			icon.size = new google.maps.Size(10, 11);
//			icon.anchor = new google.maps.Point(5, 5);
//			//icon.infoWindowAnchor = new google.maps.Point(14, 0);


//		}
			if (currentAddress != null) {
			    //console.log(currentAddress);
			//alert(currentAddress);
			if (currentAddress == marker.dealerNumber) {
				//currentAddress = null;
				document.getElementById('txtEndAddress').value = marker.add1 + ", " + marker.zipcode;
				currentmarker = marker;
			}
		}

		//mMgr.addMarker(marker, maxZoom, minZoom); -- TODO: FIX
	}
	if (currentmarker != null) {
	    
		google.maps.event.trigger(currentmarker, "click");
	    currentmarker = null;
	    currentAddress = null;
	}
}



/// <summary>UpdatePaging updates the left side list based on the page number</summary>
///
/// <remarks></remarks>
function UpdatePaging() {

	//
	//	update Paging
	//

	var pagination = document.getElementById('galleryPagination');
	pagination.innerHTML = "";

	var pager = document.createElement('div');
	pager.innerHTML = "";
	pager.setAttribute("class", "LocPaginationNum");
	pager.style.display = "block";
	pager.style.position = "absolute";
	pager.style.right = "10px";
	//pager.style.top = "355px";


	var results = document.createElement('div');
	//
	results.setAttribute("ID", "paginationResults");
	results.style.float = "right";
	results.style.display = "block";
	results.style.clear = "both";
	results.style.margin = "0 150px 0 10px";
	results.style.textAlign = "right";
	results.innerHTML = (pageNumber * galleriesPerPage + 1) + "-" + ((pageNumber * galleriesPerPage + galleriesPerPage) > visibleMarkerCount ? visibleMarkerCount : (pageNumber * galleriesPerPage + galleriesPerPage)) + " of " + visibleMarkerCount + " Results";



	//
	//	Make the next link inactive if this is the last page
	//
	var prevLink = null;
	if (pageNumber <= 0) {

		prevLink = document.createElement('a');
		prevLink.className = 'paginationBackDis';
		prevLink.innerHTML = 'Back';
	}
	else {
		prevLink = document.createElement('a');
		prevLink.className = 'paginationBack';
		prevLink.href = 'javascript:void(0);';
		prevLink.innerHTML = 'Back';
		prevLink.onclick = function () { FlipGalleriesPageBackward(); };
	}
	pager.appendChild(prevLink);

	//divider = document.createElement('span');
	//divider.innerHTML = '&nbsp;&nbsp;';
	//pager.appendChild(divider);
	//
	//	Make the next link inactive if this is the last page
	//
	var nextLink = null;
	if (pageNumber >= (Math.ceil(visibleMarkerCount / galleriesPerPage)) - 1) {

		nextLink = document.createElement('a');
		nextLink.className = 'paginationMoreDis';
		nextLink.innerHTML = 'More';
	}
	else {
		nextLink = document.createElement('a');
		nextLink.className = 'paginationMore';
		nextLink.href = 'javascript:void(0);';
		nextLink.innerHTML = 'More';
		nextLink.onclick = function () { FlipGalleriesPageForward(); };
	}

	//
	//	Add the objects to the pager div
	//
	pager.appendChild(nextLink);
	pagination.appendChild(pager);
	pagination.appendChild(results);


}




/// <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();
	UpdateIcons();

}

/// <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();
	UpdateIcons();

}
/// <summary>FlipGalleriesPageJump jumps the paging to a specific page</summary>
///
/// <remarks></remarks>
function FlipGalleriesPageJump(pageIndex) {

	var previousPage = document.getElementById('galleryPage_' + pageNumber);
	previousPage.style.display = 'none';
	pageNumber = pageIndex;
	var nextPage = document.getElementById('galleryPage_' + pageNumber);
	nextPage.style.display = 'block';
	UpdatePaging();
	UpdateIcons();

}
//
//	Add the google rendering function to the page load
//
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function () {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
}
function OpenMapPoint(address, dealerId) {

	isDirectionsMode = true;
	currentAddress = dealerId;
	currentDealerNumber = dealerId;
	singleResult = true;

	var geocoder = new google.maps.Geocoder(); // new google.maps.ClientGeocoder();

	geocoder.geocode({ 'address': address }, MapPoint);


}


function isTouchDevice() {
    try {
        var is_touch_device = 'ontouchstart' in document.documentElement;
        return is_touch_device;
    } catch (e) {
        return false;
    }
}
addLoadEvent(GoogleMapLoad);





