// ========== GOOGLE MAP =================================================================================================
var GoogleMap = new Class({
	defaultOptions: {
		showtype: true,
		toggleTypeOnMouseover: true,
		controlsize: "large", // large or small
		maptype: 0, // [map:0,sat:1,hyb:2]
		zoom:3,
		minzoom: 3,
		maxzoom: 16,
		showzoom: true,
		showoverview: false,
		smoothzoom: true,
		scrollzoom: false,
		doubleclickzoom: false, 
		dragging: true,
		markerList: null,
		initialLoad: true
	},
	params: {
		zoom:3,
		lat: -95,
		lng: 34,
		minlat:false,
		maxlat:false,
		minlng:false,
		maxlng:false,
		activeMarker:null,
		startMarker:true
	},
	initialize: function(mapID, options) {
		this.setOptions($merge(this.defaultOptions, options));
		// ===== Check For Requirements =====
		if(GBrowserIsCompatible()){ 
			if(!$(mapID)) return;
			this.mapID = mapID;
			this.map = new GMap($(mapID));
			this.map.setMapType(G_DEFAULT_MAP_TYPES[this.options.maptype]);
			this.map.getPane(G_MAP_FLOAT_SHADOW_PANE).style.display = 'none'; //get rid of bubble shadow
			// ===== Set Options =====
			if(this.options.showzoom && this.options.controlsize == "small") this.map.addControl(new GSmallMapControl()); // Small Zoom Controls
			if(this.options.showzoom && this.options.controlsize == "large") this.map.addControl(new GLargeMapControl()); // Large Zoom Controls
			if(this.options.showscale) this.map.addControl(new GScaleControl()) // Map Scale
			if(this.options.showoverview) this.map.addControl(new GOverviewMapControl());
			if(this.options.doubleclickzoom) this.map.enableDoubleClickZoom();
			if(this.options.scrollzoom) this.map.enableScrollWheelZoom();
			if(this.options.smoothzoom) this.map.enableContinuousZoom();
			if(!this.options.dragging) this.map.disableDragging();
			// ===== If Everything is ready, load the map =====
			if(this.options.initialLoad){ this.initialSetup() } else { this.cachedSetup() };
			// ===== Restricting the range of Zoom Levels =====
			// Overwrite the getMinimumResolution() and getMaximumResolution() methods
			var mt = this.map.getMapTypes();
			for(var i=0; i<mt.length; i++){
				mt[i].getMinimumResolution = function(){return this.options.minzoom}.bind(this);
				mt[i].getMaximumResolution = function(){return this.options.maxzoom}.bind(this);
			}
			
			// ===== Add EventListeners To Map =====
			GEvent.addListener(this.map, "load", function() {
				this.zoomSlider.setMin(this.map.getZoom());
			}.bind(this));
			GEvent.addListener(this.map, "dragstart", function() {
				//storeLocator.vars.miles = false
			}.bind(this));
			GEvent.addListener(this.map, "movestart", function() {
				this.hideBubbleDialog();
			}.bind(this));
			GEvent.addListener(this.map, "moveend", function() {
				this.displayMarkers();
			}.bind(this));
			GEvent.addListener(this.map, "zoomstart", function(){
				this.hideBubbleDialog();
			}.bind(this));
			GEvent.addListener(this.map, "zoomend", function(){
				this.zoomSlider.setMin(this.map.getZoom());
			}.bind(this));
			GEvent.addListener(this.map, "maptypechanged", function() {
				var type = this.map.getCurrentMapType().getName();
				this.adjustMapButtons(type);
			}.bind(this));
			
			// ===== Toggle visibility of Map Controls =====
			if(this.options.toggleTypeOnMouseover){
				this.map.hideControls();
				GEvent.addListener(this.map, "mouseover", function(){
					this.map.showControls();
				}.bind(this));
				GEvent.addListener(this.map, "mouseout", function(){
					this.map.hideControls(); 
				}.bind(this));
			}
			
			// ===== Show standard "MAP | SAT | HYB" buttons =====
			if(this.options.showtype){
				this.map.addControl(new GMapTypeControl(3));
			} else {
			// ===== Add EventListeners To Graphic Buttons =====
				GEvent.addDomListener($('mapType_MAP'), "click", function() {
					this.map.setMapType(G_MAP_TYPE);
				}.bind(this));
				GEvent.addDomListener($('mapType_SAT'), "click", function() {
					this.map.setMapType(G_SATELLITE_TYPE);
				}.bind(this));
				GEvent.addDomListener($('mapType_HYB'), "click", function() {
					this.map.setMapType(G_HYBRID_TYPE);
				}.bind(this));
			}
			// ===== Init Slider Zoom Controls =====
			$('btnZoomPlus').addEvent('click',function(){
				this.zoomSlider.setMin(parseInt(this.params.zoom)+1);
			}.bind(this)).setStyle('cursor','pointer');
			$('btnZoomMinus').addEvent('click',function(){
				this.zoomSlider.setMin(parseInt(this.params.zoom)-1);
			}.bind(this)).setStyle('cursor','pointer');
			this.zoomSlider = new Slider($('zoomTrack'),$('btnThumb'),{
				start: this.options.minzoom,
				end: this.options.maxzoom,
				offset: 0,
				knobheight: 18,
				mode: 'horizontal', // vertical or horizontal;
				onComplete: function(pos){
					this.params.zoom = pos;
					this.map.setZoom(parseInt(pos));
				}.bind(this)
			}, null);
			// ===== Marker Array Containers =====
			this.startPoint = null;
			this.gmarkers = []; // full list of markers;
			this.inBounds = []; // track markers in bounds;
			this.htmls = [];
			this.count = 0;

			// ===== Directions API ======
			this.gRoute = new GDirections(this.map);
			GEvent.addListener(this.gRoute,"load", function() {
				(function () { this.showDirections() }.bind(this)).delay(1);
			}.bind(this));

			var reasons=[]; // === Array for decoding the failure codes ===
			reasons[G_GEO_SUCCESS]            = "Success";
			reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
			reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
			reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
			reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
			reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
			reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
			reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
			reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
			reasons[G_GEO_UNKNOWN_DIRECTIONS] = "The GDirections object could not compute directions between the points.";

			// === catch Directions errors ===
			GEvent.addListener(this.gRoute, "error", function() {
				var code = this.gRoute.getStatus().code;
				var reason="Code "+code;
				if (reasons[code]) reason = reasons[code];
				alert("Failed to obtain directions, "+reason);
			}.bind(this));
			
		} else { 
			alert("Sorry, the Google Maps API is not compatible with this browser");
			return;
		};
		// ===== Init Map (kludge to set zoom slider) =====
		GEvent.trigger(this.map,"load");
	},
	// =====[ Data Types ]=======================================================
	loadData: function(data,callback){
		var self = this;
		new Ajax(data, {
			method: 'get',
			onComplete:function(text,xml){
				callback(xml);
			}
		}).request();
	},
	initialSetup: function(){
		this.map.setCenter(new GLatLng(this.params.lng, this.params.lat), this.options.zoom);
	},
	cachedSetup: function(){
		this.map.setCenter(new GLatLng(this.params.lng, this.params.lat), this.params.zoom);
	},
	// =====[ Display Markers ]=====================================================
	resetMap: function(){
		//this.hideBubbleDialog();
		//this.hideMessageDialog();
	},
	updateMap: function(address){
		this.params.address = address;
		this.getLocation(address);
	},
	initLocation: function(address){
		this.removeAllMarkers();
		var geocoder = new GClientGeocoder();
		geocoder.getLatLng(address, function (point){
			if (point) {
				this.hideBubbleDialog();
				this.map.setCenter(point, this.params.zoom);
				this.setBounds();
			} else {
				this.removeAllMarkers();
				this.message('Unable to find the location. Please verify the address and submit again.');
				return false;
			}
		}.bind(this));
	},
	getLocation: function(address){
		this.removeAllMarkers();
		var geocoder = new GClientGeocoder();
		geocoder.getLocations(address, function (result){
			if (result.Status.code == G_GEO_SUCCESS) {
				var place = result.Placemark[0];
				var p = place.Point.coordinates;
				// ===== Store New Location =====
				this.params.lat = p[1];
				this.params.lng = p[0];
				// ====== Set Start Icon =====
				if($defined(this.startPoint)) this.removeMarker(this.startPoint)
				var marker = new GMarker(new GLatLng(p[1],p[0]),icon.self());
				this.startPoint = marker;
				this.map.addOverlay(marker);
				this.setLocation();
				// ===== Return to 'Original Location' =====
				if($('returnToLocation')){
					$('returnToLocation').addEvent('click',function(){
						this.params.lat = p[1];
						this.params.lng = p[0];
						this.setLocation(new GLatLng(p[1],p[0]));
						this.clearDirections();
					}.bind(this)).setStyles({
						'cursor':'pointer',
						'display':'block'
					});
				};
			} else {
				this.removeAllMarkers();
				this.message('Unable to find the location. Please verify the address and submit again.');
				return false;
			}
		}.bind(this));
	},
	setLocation: function(point){
		if(!point){
			var point = new GLatLng(this.params.lat,this.params.lng);
		}
		this.hideBubbleDialog();
		this.map.setCenter(point, 12);
		this.setBounds();
	},
	setBounds: function(){
		var bounds = this.map.getBounds();
		this.params.minlat = Math.min(bounds.getSouthWest().lat(),bounds.getNorthEast().lat());
		this.params.maxlat = Math.max(bounds.getSouthWest().lat(),bounds.getNorthEast().lat());
		this.params.minlng = Math.min(bounds.getSouthWest().lng(),bounds.getNorthEast().lng());
		this.params.maxlng = Math.max(bounds.getSouthWest().lng(),bounds.getNorthEast().lng());

		this.saveLocation();
	},
	saveLocation:function(){
		// setCookie;
		//storeLocator.setCookie();
		this.showMarkers();
	},
	// =====[ Display Markers ]=====================================================
	showMarkers: function(){
		this.createBubbleDialog();
		this.markerList.each(function(mark){
			this.setMarker(mark);
		}.bind(this));
		this.displayMarkers();
		// ===== Activate Checkboxes to Hide/Show Markers =====
		$E('.legend').setStyle('display','block');
		$$('.checkbox').each(function(checkbox){
			checkbox.addEvent('click',function(e){
				new Event(e).stop();
				var id = checkbox.getElement('img').getProperty('id').replace('chbx_','').toLowerCase();
				var box = checkbox.getElement('img');
				if(box.src.indexOf('_OFF')>-1){
					box.src = box.src.replace('_OFF','_ON');
				} else {
					box.src = box.src.replace('_ON','_OFF');
				}
				this.toggleMarkers(id);
			}.bind(this));
		}.bind(this));
	},
	setMarker: function(mark){
		var marker = new GMarker(new GLatLng(mark.lat,mark.lng),mark.icon);
		this.gmarkers[this.count] = marker;
		if (mark.type != null) { this.gmarkers[this.count].type = mark.type.toLowerCase() };
		// ===== AddEventListeners =====
		GEvent.addListener(marker, "click", function() {
			this.showBubbleDialog(marker,this.formatDialogText(mark,this.startPoint,marker));
			// ===== addEvent:Directions =====
			if($('getRoute')){
				$('getRoute').addEvent('click',function(e){
					new Event(e).stop();
					this.activeMarker = mark;
					this.getDirections(mark);
					$('getRoute').addClass('loading');
				}.bind(this));
			};
			// ===== addEvent:Switch StartPoint to Event Marker =====
			if($('setStartPoint')){
				$('setStartPoint').addEvent('click',function(e){
					new Event(e).stop();
					this.params.lat = mark.lat;
					this.params.lng = mark.lng;
					this.clearDirections();
					this.hideBubbleDialog();
				}.bind(this));
			}
		}.bind(this));
		this.count++;
	},
	addMarker: function(marker){
		this.map.addOverlay(marker);
	},
	removeMarker: function(marker){
		this.map.removeOverlay(marker)
	},
	removeAllMarkers: function(){
		if(this.gmarkers.length > 0){
			while(this.gmarkers.length > 0){
				this.map.removeOverlay(this.gmarkers.shift());
			}
		}
		this.inBounds = [];
		this.gmarkers = [];
		this.count = 0;
	},
	displayMarkers:function(){
		var total = 0;
		this.inBounds = [];
		// ===== Show markers ONLY if they're in bounds =====
		var bounds = this.map.getBounds();
		var mapBounds = new GLatLngBounds(bounds.getSouthWest(),bounds.getNorthEast());
		this.gmarkers.each(function(marker,i){
			this.removeMarker(marker);
			if(mapBounds.containsLatLng(marker.getPoint())){
				this.inBounds.include(marker);
				this.addMarker(marker);
				if($('totalMarkers')){
					// ===== Only show markers if checkbox is ON =====
					if(!this.isMarkerActive(marker.type)){
						marker.hide();
					} else {
						total++;
					}
				}
			};
			if($('totalMarkers')) $('totalMarkers').setHTML(total);
		}.bind(this));
	},
	toggleMarkers:function(type){
		var total = $('totalMarkers').getText();
		this.inBounds.each(function(marker){
			if(marker.type == type){
				if(!marker.isHidden()){
					marker.hide(); total--;
				} else {
					marker.show(); total++;
				}
			};
		});
		$('totalMarkers').setHTML(total);
	},
	isMarkerActive: function(type){
		var img = 'chbx_'+type.capitalize();
		return ($(img).getProperty('src').indexOf('_ON')>-1)? true : false;
	},
	// =====[ Custom Bubble Dialog ]================================================
	createBubbleDialog: function(){
		if(!$("bubble")) $('googleMap').adopt( new Element('div',{'id':'bubble', 'class':'mapBubble png'}).adopt( new Element('div',{'class':'info'}) ) );
	},
	hideBubbleDialog: function(){
		if($("bubble")) $("bubble").setStyle('display','none');
	},
	showBubbleDialog: function(marker,info){
		var pixels = this.positionBubbleTo(marker);
		var ico = {width:icon.display(marker.type).iconSize.width,height:icon.display(marker.type).iconSize.height};
		var size = {width:$('bubble').getStyle('width').toInt(),height:$('bubble').getStyle('height').toInt()};
		$('bubble').setStyles({
			'top': pixels.y-size.height+(ico.height/2)+10+'px',
			'left': pixels.x-(size.width/2)+(ico.width/2)+55+'px',
			'display':'block'
		});
		$E('#bubble .info').setHTML(info);
		if($('getRoute')){ $('getRoute').removeClass('loading'); }
		if (!$E('#bubble .close')){
			new Element('div',{'class':'close'}).addEvent('click',function(){ this.hideBubbleDialog() }.bind(this)).injectTop($E('#bubble'));
		}
	},
	positionBubbleTo: function(marker){
		var cornerTopLeft = this.map.fromContainerPixelToLatLng(new GPoint(0,0),true);
		var mapPos = this.map.fromLatLngToDivPixel(cornerTopLeft);
		var markerPos = this.map.fromLatLngToDivPixel(marker.getPoint());
		var markerPagePos = new GPoint(markerPos.x-mapPos.x, markerPos.y-mapPos.y);
		return {x:markerPagePos.x,y:markerPagePos.y}
	},
	// =====[ Alert Message Dialog ]================================================
	createMessageDialog: function(){
		//if(!$("bubble")) $('googleMap').adopt( new Element('div',{'id':'bubble', 'class':'mapBubble'}) );
	},
	hideMessageDialog: function(){
		// if($("bubble")) $("bubble").setStyle('display','none');
	},
	message: function(msg){
		alert(msg);
		/*
		var pixels = this.positionBubbleTo(marker)
		$("bubble").setStyles({
			'top': pixels.y-218+'px',
			'left': pixels.x-135+'px',
			'display':'block'
		});
		*/
	},
	positionMessageTo: function(marker){
		/*
		var cornerTopLeft = this.map.fromContainerPixelToLatLng(new GPoint(0,0),true);
		var mapPos = this.map.fromLatLngToDivPixel(cornerTopLeft);
		var markerPos = this.map.fromLatLngToDivPixel(marker.getPoint());
		var markerPagePos = new GPoint(markerPos.x-mapPos.x, markerPos.y-mapPos.y);
		//var pixels = cumulativeOffset(this.map.getContainer());
		var pixels = this.map.getContainer().getPosition();
		return {x:markerPagePos.x+pixels.x,y:markerPagePos.y+pixels.y}
		*/
	},
	// =====[ Format Strings ]======================================================
	formatDialogText: function(info,start,end){
		var newline = info.address.indexOf(', ')+1;
		var street = info.address.substring(0,newline);
		var state = info.address.substring(newline+1,info.address.length);
		var str = ''
			+ ((info.photo != "")? '<img src="'+info.photo+'" class="photo" />' : '')
			+ '<span>'+info.location+'</span><br />'
			+ street+'<br />'+state+'<br /><br />';
		if(this.params.startMarker){
			var mileage = Math.round(start.getPoint().distanceFrom(end.getPoint())/1609.344);
			str += 'approx. <span id="getDistance">'+mileage+((mileage==1)?' mile':' miles')+'</span>'
			str += '<a href="#" id="getRoute">Get Directions</a>'
		}
		return str;
	},
	validUSState: function(str){
		// TODO: autocomplete;
	},
	validUSZipCode: function(str){
	/* ==================================================*\
		DESCRIPTION: Validates that a string is a United
		States zip code in 5 digit format or zip+4 format.
		EXAMPLE: 99999 or 99999-9999
	\*===================================================*/
		var oRegExp  = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
		return oRegExp.test(str);
	},
	// =====[ External Map Controls ]===============================================
	adjustMapButtons: function(type){
		if(!this.options.showtype){ // if the buttons are graphics, switch the active/inactive states;
			$('mapType_MAP').setProperty('src',$('mapType_MAP').getProperty('src').replace('_active','_inactive'));
			$('mapType_SAT').setProperty('src',$('mapType_SAT').getProperty('src').replace('_active','_inactive'));
			$('mapType_HYB').setProperty('src',$('mapType_HYB').getProperty('src').replace('_active','_inactive'));
			switch(type){
				case 'Satellite':$('mapType_SAT').setProperty('src',$('mapType_SAT').getProperty('src').replace('_inactive','_active'));break;
				case 'Hybrid':$('mapType_HYB').setProperty('src',$('mapType_HYB').getProperty('src').replace('_inactive','_active'));break;
				default: $('mapType_MAP').setProperty('src',$('mapType_MAP').getProperty('src').replace('_inactive','_active'));break;
			}
		}
	},
	// =====[ Driving Directions ]================================================
	getDirections: function(end){
		this.clearDirections();
		this.gRoute.load("from: "+this.params.lat+","+this.params.lng+" to: "+end.lat+","+end.lng,{'getSteps':true,'preserveViewport':true,'getPolyline':true});
	},
	showDirections: function() {
		if($('dirSteps')) $('dirSteps').remove();
		new Element('table', {'id':'dirSteps'}).injectBefore($('directions').getElement('.summary'));
		var tbody = new Element('tbody').injectInside('dirSteps');
		tbody.adopt( new Element('tr').adopt(new Element('th',{'colspan':3}).setHTML(this.activeMarker.location+"<br />"+this.activeMarker.address)) );
		// === read through the GRoutes and GSteps ===
		for (var r=0,rl=this.gRoute.getNumRoutes(); r<rl; r++) {
			var route = this.gRoute.getRoute(r);
			for (var s=0,sl=route.getNumSteps(r); s<sl; s++) {
				var step = route.getStep(s);
				tbody.adopt(
					new Element('tr')
					.adopt(new Element('td').setHTML(s+1+'.'))
					.adopt(new Element('td').setHTML(step.getDescriptionHtml()+'<br /><em>'+step.getDistance().html+'</em>'))
				);
			}
		}
		// ===== Hide START / STOP / PAUSE icon(s) =====
		var numMarkers = this.gRoute.getNumGeocodes();
		for (var i = 0; i < numMarkers; i++) {
			var marker = this.gRoute.getMarker(i);
			if (marker != null) marker.hide();
		}
		// ===== Add Path Between Points =====
		this.map.addOverlay(this.gRoute.getPolyline());
		// ===== Mileage / Duration =====
		$E('#directions .summary').setHTML(this.gRoute.getSummaryHtml());
		// ===== Copyright =====
		$E('#printDirections .copyright').setHTML(this.gRoute.getCopyrightsHtml());
		// ===== Print Function =====
		$E('#printDirections a').addEvent('click',function(e){
			new Event(e).stop();
			this.printDirections();
		}.bind(this));
		$('directions').setStyle('display','block');
		this.hideBubbleDialog();
	},
	clearDirections: function(){
		this.gRoute.clear();
		$E('#directions .summary').setHTML('&nbsp;');
		$E('#printDirections .copyright').setHTML('&nbsp;');
		if($('dirSteps')) $('dirSteps').remove();
		if($('formatForPrint')) $('formatForPrint').remove();
		$('directions').setStyle('display','none');
	},
	printDirections: function(){
		// ===== Format Content for Print =====
		$E('body').adopt( new Element('div',{'id':'formatForPrint'}) )
		$('formatForPrint').setHTML($('directions').innerHTML);
		$E('#formatForPrint img').remove();
		$E('#formatForPrint a').remove();

		// ===== Add Content to popup window =====
		var str = '<html><head><title>Directions</'+'title>'
				+ '<link type="text/css" rel="stylesheet" href="css/directions.css" />'
				+ '<script type="text/javascript">window.print();</'+'script>'
				+ '</'+'head><body>'
				+ '<div id="formatForPrint">'+$('formatForPrint').innerHTML+'</div>'
				+ '</'+'body></'+'html>';
		var win = window.open("", "",'toolbar=no,scrollbars=yes,width=640,height=640');
		var doc = win.document.open("text/html", "replace");
		doc.writeln(str);
		doc.close();
	}
});
GoogleMap.implement(new Options);
window.addEvent('unload',GUnload);

// =====[ Icon Graphics ]===================================================================================================
var icon = {
	display: function(type){
		switch(type){
			case 'location': return icon.location(); break;
		};
	},
	self: function(){
		var icon = new GIcon();
		icon.image = "/Style Library/images/LodgeNet/icon_YOU.png";
		icon.iconSize = new GSize(25, 27);
		icon.iconAnchor = new GPoint(8, 23);
		return icon;
	},
	location: function(){
		var icon = new GIcon();
		icon.image = "/Style Library/images/LodgeNet/icon_LOCATION.png";
		icon.iconSize = new GSize(48, 51);
		icon.iconAnchor = new GPoint(8, 51);
		return icon;
	}
}
// =====[ Google Map ]======================================================================================================

window.addEvent('domready',function(){
	var map = new GoogleMap('gmap',{
		showtype:true,
		showzoom:false,
		zoom:3
	});
	// ===== Add Events to Inputs =====
	$$('#googleMap .inputFields input').each(function(input){
		input.addEvent('keydown', function(event){
			var e = new Event(event);
			if (e.key=='enter'){ map.buildAddress(); e.stop(); };
		}).addEvent('focus',function(event){
			if(input.value == input.defaultValue){ input.value = ''; }
		}).addEvent('blur',function(event){
			if(input.value == ''){ input.value = input.defaultValue; }
		});
	});
	if ($('btnSearch')){
		$('btnSearch').addEvent('click',function(event){
			map.buildAddress(); new Event(event).stop();
		});
	}
	// ===== Format Address ======
	map.buildAddress = function(){
		var str = '';
		// ===== gather input values =====
		var address = ($E('#mapAddress input').value != $E('#mapAddress input').defaultValue)? $E('#mapAddress input').value.clean() : '';
		// ===== format =====
		str += (address)? address : '';
		// ===== validate input address =====
		var geocoder = new GClientGeocoder();
		geocoder.getLocations(str, function (result){
			if(result.Status.code == G_GEO_SUCCESS){
				map.params.startMarker = true;
				map.updateMap(str);
			} else {
				map.resetMap();
				map.message('Please enter a City and State OR a Zip Code.')
			}
		});
	};
	// ===== Load Data File ======
	map.parseXML = function(data){
		var markerList = [];
		var markers  = data.getElementsByTagName('marker');
		for(var x=0,xl=markers.length;x<xl;x++){
			var marker = markers[x];
			// ===== Format Address =====
			var address = "" +
			marker.getAttribute('address').replace('\\n','<br />') +", " +
			marker.getAttribute('city') +", " +
			marker.getAttribute('state') +", " +
			marker.getAttribute('zipcode') +'<br />' +
			marker.getAttribute('phone');
			// ===== Create Listing =====
			var locale = {
				type: marker.getAttribute('type'),
				icon: icon.display(marker.getAttribute('type')),
				location: marker.getAttribute('location'),
				address: address,
				photo: marker.getAttribute('photo') || '',
				lat: marker.getAttribute('lat'),
				lng: marker.getAttribute('lng')
			};
			markerList.include(locale);
		};
		map.markerList = markerList;
		// ===== Hide "You" marker =====
		map.params.startMarker = false;
		map.initLocation(map.params.lng+","+map.params.lat)
	};
	// ===== Parse Url ======//
		map.parsURL = function(){
			var xmlurl = '/_layouts/GetLocationXML.aspx';	
			if ( location.search != null ) {	
				var idx = location.search.indexOf('location=');
				
				if ( idx != -1 ) {		
					var kvploc = location.search.substring(idx);
					if ( kvploc != null )
						xmlurl += "?" + kvploc;
			}	
			return xmlurl;
		}
		
	};
	// ===== Init =====
	map.loadData(map.parsURL(),map.parseXML);
});
// =========================================================================================================================