﻿google.load("maps", "2", { "other_params": "sensor=false" });
var map;
var icon;
var markerArray = new Array();
var filterGroupArray = new Array();
var selectedFilters = new Array();

function initialize() {
	// unload the map on page unload
	$(window).unload(function() {
		GUnload();
	});

	$('#clearFiltersContainer').click(function() {
		clearFilters();
	});
	
	map = new google.maps.Map2(document.getElementById("map"));
	//map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 13);
	map.setUIToDefault();
	if (!_isUberMap) {
		map.disableDoubleClickZoom();
		map.disableScrollWheelZoom();
	}
	// get the data
	GDownloadUrl('/httphandlers/GoogleMapHandler.ashx?action=GetMap&mapId=' + _mapId, buildMap);
	
}
google.setOnLoadCallback(initialize);

function buildMap(data, responseCode) {
	var xml = GXml.parse(data);

	var docRootNode = xml.documentElement;

	switch (docRootNode.getAttribute("mapType")) {
		case "Hybrid":
			map.setMapType(G_HYBRID_MAP);
			break;
		case "Map":
			map.setMapType(G_NORMAL_MAP);
			break;
		case "Terrain":
			map.setMapType(G_PHYSICAL_MAP);
			break;
		case "Satellite":
			map.setMapType(G_SATELLITE_MAP);
			break;
	}
	
	var markers = docRootNode.getElementsByTagName("Marker");

	for (m = 0; m < markers.length; m++) {
		var thisMarker = markers[m];
		// TODO: add width/height to xml feed
		var markerWidth = thisMarker.getAttribute("markerImageWidth");
		var markerHeight = thisMarker.getAttribute("markerImageHeight");
		//var markerWidth = "";
		//var markerHeight = "";
		var markerImage = thisMarker.getAttribute("markerImage");

		var icon = buildIcon(markerImage, markerWidth, markerHeight);

		var marker = {
			title: thisMarker.getAttribute("title"),
			address: trim(GXml.value(thisMarker.getElementsByTagName("Address")[0])),
			description: trim(GXml.value(thisMarker.getElementsByTagName("Description")[0])),
			latitude: thisMarker.getAttribute("latitude"),
			longitude: thisMarker.getAttribute("longitude"),
			point: new GLatLng(parseFloat(thisMarker.getAttribute("latitude")), parseFloat(thisMarker.getAttribute("longitude"))),
			showDrivingDirections: thisMarker.getAttribute("showDrivingDirections"),
			currentlyDisplayed: true,
			allFilters: new Array()
		};
		
		// TODO: add phone

		var markerOptions = { icon: icon };
		var mapMarker = new GMarker(marker.point, markerOptions);
		
		marker.infoWindowHtml = createInfoWindow(marker);

		if (marker.showDrivingDirections != "false") {
			var tab1 = new GInfoWindowTab("Details", marker.infoWindowHtml);
			var tab2 = new GInfoWindowTab("Directions", buildDirectionsTab(marker)); // TODO: build this
			//var tab2 = new GInfoWindowTab("Directions", "");
			var arrTabs = new Array();
			arrTabs.push(tab1);
			arrTabs.push(tab2);
			mapMarker.bindInfoWindowTabsHtml(arrTabs);
			marker.hasTabs = true;
			marker.infoWindowTabs = arrTabs;
		}
		else {
			mapMarker.bindInfoWindowHtml(marker.infoWindowHtml);
			marker.hasTabs = false;
		}
		
		marker.mapMarker = mapMarker;
		
		if (_isUberMap) {
			// this marker has some filters associated with it
			marker.filterGroups = new Array();
			marker.currentlyDisplayed = false;
			/*
			<Filters>
				<FilterGroup title="Experiences" subTitle="Filter by Experience">
					<Filter title="National & State Parks; National Forests" checked="false" value="7152"/>
				</FilterGroup>
				<FilterGroup title="Services" subTitle="Filter by Services Provided">
					<Filter title="Food & Concessions" checked="false" value="7151"/>
					<Filter title="Lodging" checked="true" value="7180"/>
				</FilterGroup>
				<FilterGroup title="Locations" subTitle="Filter by Location">
					<Filter title="Alaska" checked="false" value="7133"/>
				</FilterGroup>
			</Filters>
			*/
			for (fg = 0; fg < thisMarker.getElementsByTagName("FilterGroup").length; fg++) {
				var thisFG = thisMarker.getElementsByTagName("FilterGroup")[fg];
				var objFG = {
					title: thisFG.getAttribute("title"),
					subTitle: thisFG.getAttribute("subTitle"),
					filters: new Array()
				};
				for (f = 0; f < thisFG.getElementsByTagName("Filter").length; f++) {
					var thisFilter = thisFG.getElementsByTagName("Filter")[f];
					var objF = {
						title: thisFilter.getAttribute("title"),
						checked: thisFilter.getAttribute("checked"),
						value: thisFilter.getAttribute("value")
					};
					objFG.filters.push(objF);
					marker.allFilters.push(objF.value);
				}
				marker.filterGroups.push(objFG);
			}
		}
		
		markerArray.push(marker);

		if (!_isUberMap) {
			map.addOverlay(mapMarker);
		}
	}

	if (_isUberMap) {
		buildFilterGroups();
		filterMarkers();
	}
	
	if (docRootNode.getAttribute("autoZoomAndCenter") === "true") {
		showAll();
	}
	else {
		// set the center
		map.setCenter(new GLatLng(parseFloat(docRootNode.getAttribute("centerLatitude")), parseFloat(docRootNode.getAttribute("centerLongitude"))), parseInt(docRootNode.getAttribute("defaultZoomLevel")));
	}
}

function buildFilterGroups() {
	for (m = 0; m < markerArray.length; m++) {
		var thisMarker = markerArray[m];
		for (fg = 0; fg < thisMarker.filterGroups.length; fg++) {
			var thisFG = thisMarker.filterGroups[fg];
			if ($.inArray(thisFG.title, filterGroupArray) == -1) {
				// not in array so add and build
				filterGroupArray.push(thisFG.title);
				var objFG = {
					filters: new Array(),
					filterTitles: new Array(),
					title: thisFG.title,
					subTitle: thisFG.subTitle
				};
				window[thisFG.title] = objFG;
			}
			// now we know for sure that the group is in memory
			// so let's check and see if we need to add the filter to memory as well
			for (f = 0; f < thisFG.filters.length; f++) {
				var thisFilter = thisFG.filters[f];
				if ($.inArray(thisFilter.title, window[thisFG.title].filterTitles) == -1) {
					// nope.  Add it.
					window[thisFG.title].filters.push(thisFilter);
					window[thisFG.title].filterTitles.push(thisFilter.title);
				}
			}
		}
	}
	// now sort our arrays
	for (fg = 0; fg < filterGroupArray.length; fg++) {
		var thisObj = window[filterGroupArray[fg]];
		thisObj.filters.sort(compareNames);

		// build the tab
		var tab = document.createElement("li");
		// <li><a href="#">Locations</a></li>
		var a = document.createElement("a");
		$(a).attr('href', '#');
		$(a).text(thisObj.title);
		$(tab).append(a);

		$('#tabsFilterGroups').append($(tab));

		// now build the checkboxes
		/*
		<div class="pane">
			<div style="position:relative">
				<div class="filterSubtitle">Search by Property</div>
				<div class="tooltip">
					<div><input type="checkbox" /> Colorado</div>
					<div><input type="checkbox" /> Colorado</div>
					<div><input type="checkbox" /> Colorado</div>
					<div><input type="checkbox" /> Colorado</div>
					<div><input type="checkbox" /> Colorado</div>
				</div>
				<img src="/images/btn-dropdown-arrow.gif" class="l"/>
			</div>
		</div>
		*/
		var pane = document.createElement("div");
		$(pane).attr('class', 'pane');

		var relPos = document.createElement("div");
		$(relPos).css('position', 'relative');

		var subTitle = document.createElement("div");
		$(subTitle).attr('class', 'filterSubtitle');
		$(subTitle).text(thisObj.subTitle);
		$(relPos).append($(subTitle));

		var tt = document.createElement("div");
		$(tt).attr('class', 'tooltip');

		// now loop over the filters themselves
		for (f = 0; f < thisObj.filters.length; f++) {
			var thisFilter = thisObj.filters[f];
			var filterDiv = document.createElement("div");

			var cb = document.createElement("input");
			$(cb).attr('type', 'checkbox');
			$(cb).attr('value', thisFilter.value);

			if (thisFilter.checked === "true") {
				$(cb).attr('checked', true);
				selectedFilters.push(thisFilter.value);
			}
			$(cb).click(function() {
				updateFilters(this);
			});
			
			$(filterDiv).append($(cb));
			
			var filterSpan = document.createElement("span");
			$(filterSpan).text(thisFilter.title);
			$(filterDiv).append($(filterSpan));
			$(tt).append($(filterDiv));
		}
		
		$(relPos).append($(tt));
		
		$(pane).append($(relPos));

		$('#containerFilters').append($(pane));
	}

	// finally, wire up the tabs and tooltips
	$(".filterSubtitle").tooltip({
		relative: true,
		position: 'bottom right',
		//offset: [21, 35],
		offset: [-1, -224],
		effect: 'slidedownup'
	});

	updateFilterCount();
	
	$(".css-tabs:first").tabs(".css-panes:first > div");

	// show the new tabs
	$('#boxHeadRight').show();
}

function updateFilters(cb) {
	if (cb.checked) {
		selectedFilters.push(cb.value);
	}
	else {
		var idx = $.inArray(cb.value, selectedFilters);
		if (idx != -1) {
			// remove it
			selectedFilters.splice(idx, 1);
		}
	}
	updateFilterCount();
	filterMarkers();
}
function clearFilters() {
	selectedFilters = new Array();
	$('#containerFilters').find('input[type=checkbox]').each(function() {
		$(this).attr('checked', false);
	});
	filterMarkers();
	updateFilterCount();
}
function updateFilterCount() {
	$('#filterCount').text("(" + selectedFilters.length + ")");

	if (selectedFilters.length == 0) {
		$('#clearFiltersContainer').hide();
	}
	else {
		$('#clearFiltersContainer').show();
	}
}
function filterMarkers() {
	for (m = 0; m < markerArray.length; m++) {
		var thisMarker = markerArray[m];
		var filtersMatched = 0;

		for (f = 0; f < selectedFilters.length; f++) {
			var thisFilter = selectedFilters[f];
			if ($.inArray(thisFilter, thisMarker.allFilters) != -1) {
				filtersMatched++;
			}
		}
		
		if (filtersMatched != selectedFilters.length && thisMarker.currentlyDisplayed) {
			map.removeOverlay(thisMarker.mapMarker);
			thisMarker.currentlyDisplayed = false;
		}
		else if (filtersMatched == selectedFilters.length && !thisMarker.currentlyDisplayed) {
			map.addOverlay(thisMarker.mapMarker);
			thisMarker.currentlyDisplayed = true;
		}
	}
}

function buildIcon(markerImage, width, height) {
	icon = new GIcon();

	if (markerImage && markerImage != "") {
		// assume, for now, we're using our 80x40 logo-based marker images
		icon.shadow = "/images/shadow.png";
		icon.image = markerImage;
	}
	else {
		icon.shadow = "/images/shadow50.png";
		icon.image = "/images/mm_20_red.png";
		width = "12";
		height = "20";
	}
	
	//icon.shadowSize = new GSize(22, 20);
	//icon.iconAnchor = new GPoint(6, 20);
	//icon.infoWindowAnchor = new GPoint(6, 2);
	//icon.infoShadowAnchor = new GPoint(22, 8);

	icon.shadowSize = new GSize(parseInt(width * 1.5), height);
	icon.iconAnchor = new GPoint(parseInt(width / 2), height);
	icon.infoWindowAnchor = new GPoint(parseInt(width / 2), 2);
	icon.infoShadowAnchor = new GPoint(22, parseInt(height / 2));
	icon.iconSize = new GSize(width, height);
	
	return icon;
}

function createInfoWindow(marker) {
	//var hasPhoto = (marker.photo && trim(marker.photo) != "") ? true : false;
	var hasPhoto = false;
	var detailsHTML = "<div class='popup'>";
	detailsHTML += "<div class='popupMarkerName'>" + marker.title + "</div>";
	detailsHTML += (hasPhoto == true) ? "<div class='popupMarkerDetails'>" : "<div class='popupMarkerDetailsNoPhoto'>";
	if (trim(marker.description) != "") {
		detailsHTML += "<div class='popupMarkerDescription'>" + marker.description + "</div>";
	}

	if (marker.address != "") {
		detailsHTML += marker.address + "<br />";
	}
	//detailsHTML += marker.phone;
	detailsHTML += "</div>"; // end popupMarkerDetails
	if (hasPhoto) {
		detailsHTML += "<div class='popupMarkerPhoto'><img src='" + marker.photo + "'></div>";
	}
	detailsHTML += "<br class='clear' />";
	detailsHTML += "</div>";
	return detailsHTML;
}

function buildDirectionsTab(marker) {
	var addr = xreplace(trim(marker.address), "<br />", ", ");
	addr = xreplace(addr, "<br>", ", ");
	addr = xreplace(addr, "<br/>", ", ");

	var retHtml = "";
	//var retHtml = "<form action='#' onsubmit=''>";
	retHtml += "<div class='directionsContainer'>";
	retHtml += "<div class='dirHeader'>Get Directions ";
	retHtml += "<a id='dirTo' href='javascript:setDirectionsTo()'>To</a>";
	retHtml += "<span id='spnDirTo' class='dirSel'>To</span>";
	retHtml += " | ";
	retHtml += "<a id='dirFrom' href='javascript:setDirectionsFrom()'>From</a>";
	retHtml += "<span id='spnDirFrom' class='dirSel'>From</span>";
	retHtml += "&nbsp;&nbsp;" + marker.title + "</div>";
	retHtml += "<br class='clear' />";
	retHtml += "<div class='dirLabel'>From:</div>";
	retHtml += "<div class='dirInput' id='dirInputFromForm'><input type='text' class='directions' id='fromAddress' name='from' /></div>";
	retHtml += "<div class='dirInput' id='dirInputFromLabel'>" + marker.title + "</div>";
	retHtml += "<br class='clear'/>";
	retHtml += "<div class='dirLabel'>To:</div>";
	retHtml += "<div class='dirInput' id='dirInputToForm'><input type='text' class='directions' id='toAddress' name='to' /></div>";
	//retHtml += "<div class='dirInput'><input type='text' class='directions' id='toAddress' name='to' value='" + merchant.latitude + ", " + merchant.longitude + "'></div>";
	retHtml += "<div class='dirInput' id='dirInputToLabel'>" + marker.title + "</div>";
	retHtml += "<br class='clear' />";
	//retHtml += "<input type='submit' value='Get Directions'>";
	retHtml += "<input type='hidden' id='direction' value='To' />";
	//retHtml += "<input type='hidden' id='merchantGeocode' value='" + merchant.latitude + ", " + merchant.longitude + "' />";
	//710 N Summit Blvd # 101, Frisco, CO (Starbucks) @39.576783,-106.092512
	retHtml += "<input type='hidden' id='markerGeocode' value='";
	retHtml += jQuery.trim(xreplace(xreplace(xreplace(marker.address, "<br />", ", "), "&", "and"), " ", "+"));
	retHtml += "+(" + jQuery.trim(xreplace(xreplace(marker.title, '&', 'and')), ' ', '+') + ")+@" + marker.latitude + "," + marker.longitude + "' />";
	retHtml += "<br />";
	retHtml += "<a href='javascript:setDirections()' class='bullet'>Get Directions</a>";
	retHtml += "</div>";
	return retHtml;
}
function setDirectionsTo() {
	document.getElementById("dirTo").style.display = "none";
	document.getElementById("dirFrom").style.display = "inline";
	document.getElementById("spnDirTo").style.display = "inline";
	document.getElementById("spnDirFrom").style.display = "none";
	document.getElementById("direction").value = "To";
	document.getElementById("dirInputFromForm").style.display = "block";
	document.getElementById("dirInputToForm").style.display = "none";
	document.getElementById("dirInputFromLabel").style.display = "none";
	document.getElementById("dirInputToLabel").style.display = "block";
}
function setDirectionsFrom() {
	document.getElementById("dirTo").style.display = "inline";
	document.getElementById("dirFrom").style.display = "none";
	document.getElementById("spnDirTo").style.display = "none";
	document.getElementById("spnDirFrom").style.display = "inline";
	document.getElementById("direction").value = "From";
	document.getElementById("dirInputFromForm").style.display = "none";
	document.getElementById("dirInputToForm").style.display = "block";
	document.getElementById("dirInputFromLabel").style.display = "block";
	document.getElementById("dirInputToLabel").style.display = "none";
}

function setDirections() {
	var from;
	var to;
	if (document.getElementById("direction").value == "To") {
		to = document.getElementById("markerGeocode").value;
		from = document.getElementById("fromAddress").value;
	}
	else {
		from = document.getElementById("markerGeocode").value;
		to = document.getElementById("toAddress").value;
	}
	//gdir.load("from: " + from + " to: " + to, { "locale": "en_US" });
	
	//http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=FcjcXAIdzNuo-SkHz11RBXBqhzHEo5p-H8DMyQ%3BFUFo1gId-T2W-A&q=vail,+co+to+47.6058252,+-124.3714625+(Kalaloch+Lodge)&sll=37.0625,-95.677068&sspn=37.598824,80.859375&ie=UTF8&ll=44.056012,-116.433105&spn=8.541201,20.214844&z=6&saddr=vail,+co&daddr=47.6058252,+-124.3714625+(Kalaloch+Lodge)

	window.open('http://maps.google.com/maps?f=q&source=s_q&hl=en&q=' + from + '+to+' + to);
}

function showAll() {
	bounds = new GLatLngBounds();
	for (i = 0; i < markerArray.length; i++) {
		bounds.extend(markerArray[i].point);
	}
	map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
}

function trim(str) {
	if (str != "") {
		return str.replace(/^\s*|\s*$/g, "");
	}
	else {
		return "";
	}
}
function xreplace(checkMe, toberep, repwith) {
	var temp = checkMe;
	var i = temp.indexOf(toberep);
	while (i > -1) {
		temp = temp.replace(toberep, repwith);
		i = temp.indexOf(toberep, i + repwith.length + 1);
	}
	return temp;
}
function compareNames(a, b) {
	var nameA = a.title.toLowerCase();
	var nameB = b.title.toLowerCase();
	if (nameA < nameB) { return -1 }
	if (nameA > nameB) { return 1 }
	return 0;
}
