// ****************************************************************
// ****************************************************************
// COPYRIGHT 2006, Vertex Software
// CREATED:  1/23/2006
// AUTHOR:   Ahmed
// ****************************************************************
// ****************************************************************
var gLocationPlotInfo = new Array();
var gCenterLatitude = "";
var gCenterLogitude = "";
var gCurrentZoomLevel = "";
var eZoomLevelToIconColorMapping = {
	2 : "black",
	3 : "orange",
	4 : "yellow",
	5 : "green",
	6 : "blue",
	7 : "brown",
	8 : "purple",
	9 : "red",
	10 : "orange"
	};
var gIconColorInMapView = "green";
var gIconColorOutOfMapView = "yellow";
var gColoredIconPrefix = "http://labs.google.com/ridefinder/images/mm_20_";
var gColoredIconExt = ".png";
var gZoomLevelToScaleMapping = {
	4 : { scale:100, distance:1 },
	5 : { scale:100, distance:2 },
	6 : { scale:123, distance:5 },
	7 : { scale:123, distance:10 },
	8 : { scale:123, distance:20 },
	9 : { scale:62, distance:20 }
	};
// zoom level 5 - 100px = 2mi; 
// zoom level 6 - 123px = 5mi;  - requires 246px for 5 mi radius, 492 px for 10 mi radius
// zoom level 7 - 123px = 10mi; - requires 246px for 10 mi radius, 492 px for 20 mi radius
// zoom level 8 - 123px = 20mi; - requires 246px for 20 mi radius, 492 px for 40 mi radius
var gLocationIDList = new Array();
var gLatLongExistingPairs = new Array();
var gCurrentMap = {};
var gMapSizeInPixels = 425;
var gUsingUniqueIconColors = false;
var gUsingNumberedIcons = false;
var gCurrentMarkerNumber = 0;
var gDefaultMapMarker = "http://labs.google.com/ridefinder/images/mm_20_green.png";
var gDefaultMapMarkersFolder = "/img/mapicons/";
var gLocationMarkerInfoWindowContent = "<div class=\"gPopupInfo\"><div style=\"vertical-align:middle\"><b><a href=\"{{PageURL}}\">{{LocationName}}</a></b><br />{{Address}}<br />{{City}}, {{State}} {{Zip}}</div><br clear=\"all\"/><span style=\"MARGIN-TOP: 8px; DISPLAY: block; MARGIN-BOTTOM: 8px\"><b>Start Address:</b><br /></span>{{StartAddressField}}<br /><a href=\"javascript:GetDirections()\">get directions</a><br />{{DestAddressField}}</div>";
var gAustinCenterPoint = new GPoint(-97.7427777777778,30.2669444444444);
var gLatLongBoundsInfo = "";
var gCurrentMapBounds = null;
var gDefaultIconObj = null;
var gDefaultIconSize = null;
var gDefaultShadowSize = null;
var gDefaultIconAnchor = null;
var gDefaultInfoWindowAnchor = null;
var gDefaultIconPropsLoaded = false;
var gNumberedIconSize = null;
var gNumberedShadowSize = null;
var gNumberedIconAnchor = null;
var gNumberedInfoWindowAnchor = null;
var gNumberedIconPropsLoaded = false;
var agt=navigator.userAgent.toLowerCase();
var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));

//****************************************************************
//SetMapSize
//****************************************************************
function SetMapSize( size ) {
	try {
		gMapSizeInPixels = size;
		}
	catch (error) {
		window.status = "SetMapSize: " + error.description;
		}
	}


//****************************************************************
//ClearLocationPlotInfo
//****************************************************************
function ClearLocationPlotInfo(  ) {
	try {
		gLocationPlotInfo = new Array();
		}
	catch (error) {
		window.status = "ClearLocationPlotInfo: " + error.description;
		}
	}


//****************************************************************
//InitializeMap
//****************************************************************
function InitializeMap( centerPoint, zoomLevel, mapDivID ) {
	var map = {};
	try {
		if (!mapDivID || typeof mapDivID!="string") mapDivID = "map";
		map = new GMap(document.getElementById(mapDivID));
		if (!map) return;
		gCurrentMap = map;
		map.addControl(new GSmallZoomControl());
		map.centerAndZoom(centerPoint, zoomLevel );
		}
	catch (error) {
		window.status = "InitializeMap: " + error.description;
		}
	return map;
	}


//****************************************************************
//InitializeMapAndPlotAllLocations
//****************************************************************
function InitializeMapAndPlotAllLocations( mapDivID ) {
	var map = {};
	try {
		var map = {};
		var centerPoint = "";
		var zoomLevel = "";
		if (gLocationIDList.length==0) BuildLocationIDList();
		if (gLocationIDList.length==0) {
			centerPoint = gAustinCenterPoint;
			zoomLevel = 9;
			}
		else if (gCenterLatitude!="" && gCenterLongitude!="") {
			centerPoint = new GPoint(gCenterLongitude,gCenterLatitude);
			zoomLevel = gCurrentZoomLevel || 9;
			}
		else {
			centerPoint = GetCenterPointFromLocations();
			zoomLevel = GetZoomLevelFromLocations();
			}
		map = InitializeMap( centerPoint, zoomLevel, mapDivID);
		for (var locationID in gLocationPlotInfo) {
			var locationMarker = CreateMarker(locationID,true);
			map.addOverlay(locationMarker);
			gLocationPlotInfo[locationID].Marker = locationMarker;
			}
		if (gLocationIDList.length==1) {
			FocusOnLocation(gLocationIDList[0]);
			}
		}
	catch (error) {
		window.status = "InitializeMapAndPlotAllLocations: " + error.description;
		}
	return map;
	}


//****************************************************************
//FocusOnLocation
//****************************************************************
function FocusOnLocation( locationID ) {
	try {
		var LocationInfo = gLocationPlotInfo[locationID];
		var LocationCoordinates = new GPoint(LocationInfo.Longitude, LocationInfo.Latitude);
		gCurrentMap.centerAndZoom(LocationCoordinates,3);
		var thisMarker = gLocationPlotInfo[locationID].Marker;
		// 02Mar06 - The following two lines are needed to address layering issue when multiple markers exist at exact same geocode.
		gCurrentMap.removeOverlay(thisMarker);
		gCurrentMap.addOverlay(thisMarker);
		GEvent.trigger(thisMarker,"click");	//grab marker object from global Info object and trigger its click event
		}
	catch (error) {
		window.status = "FocusOnLocation: " + error.description;
		}
	}


//****************************************************************
//GetDirections
//****************************************************************
function GetDirections() {
	try {
		var startAddress = document.getElementsByName("startAddr")[0].value;
		var destAddress = document.getElementsByName("destAddr")[0].value;
		var directionsWindow = window.open('http://maps.google.com/maps?saddr=' + startAddress + '&daddr=' + destAddress, "Printer", "width=760,height=600,resizable=yes,scrollbars=yes,menubar=yes");
		}
	catch (error) {
		window.status = "GetDirections:" + error.description;
		}
	}


//****************************************************************
//FindFacilitiesByAddress
//****************************************************************
function FindFacilitiesByAddress( ) {
	try {
		var address = document.getElementsByName("VisitorAddress")[0].value;
		var zipcode = document.getElementsByName("VisitorZip")[0].value;
		alert("ZIP: " + zipcode);
		if (zipcode=="") {
			document.getElementById("ZipError").innerHTML = "Please enter a valid zip code.";
			return;
			}
		else if (!zipcode.match(/^[0-9]{5}(\-[0-9]{4})?$/)) {
			document.getElementById("ZipError").innerHTML = "Please enter a valid zip code.";
			return;
			}
		else {
			document.getElementById("ZipError").innerHTML = "";
			}
		document.location.href = "/LocateFacilityByAddress/" + address + "/ZipCode/" + zipcode;
		}
	catch (error) {
		window.status = "FindFacilitiesByAddress: " + error.description;
		}
	}


//****************************************************************
//FindFacilitiesByService
//****************************************************************
function FindFacilitiesByService( ) {
	try {
		var ServiceID = document.getElementsByName("ServiceID")[0].value;
		if (ServiceID=="") {
			document.getElementById("ServiceError").innerHTML = "Please select a service area.";
			return;
			}
		document.location.href = "/LocateFacilityByService/" + ServiceID;
		}
	catch (error) {
		window.status = "FindFacilitiesByService: " + error.description;
		}
	}


//****************************************************************
//ClearInputField
//****************************************************************
function ClearInputField( element, defaultValue ) {
	try {
		if (element.value==defaultValue) element.value = "";
		}
	catch (error) {
		window.status = "ClearInputField: " + error.description;
		}
	}


//****************************************************************
//ResetInputField
//****************************************************************
function ResetInputField( element, defaultValue ) {
	try {
		if (element.value=="") element.value = defaultValue;
		}
	catch (error) {
		window.status = "ResetInputField: " + error.description;
		}
	}


//-----------------------------------------------------------
//BuildLocationIDList
//-----------------------------------------------------------
function BuildLocationIDList( ) {
	try {
		for (var locationID in gLocationPlotInfo) {
			gLocationIDList.push(locationID);
			var locationInfo = gLocationPlotInfo[locationID];
			var latLongPairID = locationInfo.Latitude + ":" + locationInfo.Longitude;
			if (!gLatLongExistingPairs[latLongPairID]) {
				gLatLongExistingPairs[latLongPairID] = {};
				gLatLongExistingPairs[latLongPairID].incrementVal = 0.0001;
				}
			else {
				gLocationPlotInfo[locationID].Longitude = Number(gLocationPlotInfo[locationID].Longitude) + gLatLongExistingPairs[latLongPairID].incrementVal;
				gLocationPlotInfo[locationID].Latitude = Number(gLocationPlotInfo[locationID].Latitude) + gLatLongExistingPairs[latLongPairID].incrementVal;
				gLatLongExistingPairs[latLongPairID].incrementVal += 0.0001;
				}
			for (var attribute in locationInfo) {
				locationInfo[attribute] = unescape(locationInfo[attribute]);
				}
			}
		}
	catch (error) {
		window.status = "BuildLocationIDList: " + error.description;
		}
	}


//-----------------------------------------------------------
//BuildPopUpHTML
//-----------------------------------------------------------
function BuildPopUpHTML( locationID ) {
	var returnValue = "";
	try {
		var LocationInfo = gLocationPlotInfo[locationID];
		var templateHTML =  gLocationMarkerInfoWindowContent;
		if (LocationInfo.PopupHTML) templateHTML = LocationInfo.PopupHTML;
		templateHTML = templateHTML.replace(/\{\{/g,"||");
		templateHTML = templateHTML.replace(/\}\}/g,"||");
		for (var attribute in LocationInfo) {
			templateHTML = templateHTML.replace("||"+attribute+"||",LocationInfo[attribute]);
			}
		var destinationAddress = LocationInfo.Address + " " + LocationInfo.City + "," + LocationInfo.State + " " + LocationInfo.Zip;
		var startFieldHTML = "<input size=\"30\" maxlength=\"75\" name=\"startAddr\" value=\"\" />";
		var destFieldHTML = "<input type=\"hidden\" name=\"destAddr\" value=\"" + destinationAddress + "\"/>";
		templateHTML = templateHTML.replace("||StartAddressField||",startFieldHTML);
		templateHTML = templateHTML.replace("||DestAddressField||",destFieldHTML);
		returnValue = (templateHTML);
		}
	catch (error) {
		window.status = "BuildPopUpHTML: " + error.description;
		}
	return returnValue;
	}


//-----------------------------------------------------------
// LoadDefaultIconProps
//-----------------------------------------------------------
function LoadDefaultIconProps( ) {
	try {
		gDefaultIconSize = new GSize(12, 20);
		gDefaultShadowSize = new GSize(27, 24);
		gDefaultIconAnchor = new GPoint(9, 24);
		gDefaultInfoWindowAnchor = new GPoint(5, 10);
		gDefaultIconPropsLoaded = true;
		}
	catch (error) {
		window.status = "LoadDefaultIconProps: " + error.description;
		}
	}


//-----------------------------------------------------------
// LoadNumberedIconProps
//-----------------------------------------------------------
function LoadNumberedIconProps( ) {
	try {
		gNumberedIconSize = new GSize(20, 34);
		gNumberedShadowSize = new GSize(37, 34);
		gNumberedIconAnchor = new GPoint(9, 34);
		gNumberedInfoWindowAnchor = new GPoint(9, 20);
		gNumberedIconPropsLoaded = true;
		}
	catch (error) {
		window.status = "LoadNumberedIconProps: " + error.description;
		}
	}


//-----------------------------------------------------------
// LoadDefaultIconObj
//-----------------------------------------------------------
function LoadDefaultIconObj( ) {
	try {
		if (!gDefaultIconObj) {
			gDefaultIconObj = new GIcon();
			gDefaultIconObj.image = gDefaultMapMarker;
			gDefaultIconObj.shadow = "/img/mapicons/marker_shadow.png";
			gDefaultIconObj.iconSize = gDefaultIconSize;
			gDefaultIconObj.shadowSize = gDefaultShadowSize;
			gDefaultIconObj.iconAnchor = gDefaultIconAnchor;
			gDefaultIconObj.infoWindowAnchor = gDefaultInfoWindowAnchor;
			}
		}
	catch (error) {
		window.status = "LoadDefaultIconObj: " + error.description;
		}
	}


//-----------------------------------------------------------
// ApplyNumberedIconProps
//-----------------------------------------------------------
function ApplyNumberedIconProps( iconObj ) {
	try {
		iconObj.iconSize = gNumberedIconSize;
		iconObj.shadowSize = gNumberedShadowSize;
		iconObj.iconAnchor = gNumberedIconAnchor;
		iconObj.infoWindowAnchor = gNumberedInfoWindowAnchor;
		}
	catch (error) {
		window.status = ": " + error.description;
		}
	return iconObj;
	}


//-----------------------------------------------------------
//CreateIcon
//-----------------------------------------------------------
function CreateIcon( locationID ) {
	var iconObj = "";
	try {
		if (!gDefaultIconPropsLoaded) {
			LoadDefaultIconProps();
			}
		if (!gNumberedIconPropsLoaded) { 
			LoadNumberedIconProps(); 
			}
		if (!gDefaultIconObj) { 
			LoadDefaultIconObj(); 
			}
		iconObj = new GIcon(gDefaultIconObj);
		if (gUsingNumberedIcons && gLocationPlotInfo[locationID].MarkerColor) {//Used for colored/numbered markers
			var color = gLocationPlotInfo[locationID].MarkerColor;
			var markerNumber = gLocationPlotInfo[locationID].MarkerNumber;
			iconObj.image = gDefaultMapMarkersFolder + "marker_" + color + "_" + markerNumber + (is_ie ? ".gif" :".png");
			iconObj = ApplyNumberedIconProps(iconObj);
			}
		else if (gLocationPlotInfo[locationID].MarkerNumber && gLocationPlotInfo[locationID].MarkerNumber==0) {	//for Visitor's location
			var color = "red";
			iconObj.image = gColoredIconPrefix + color + gColoredIconExt;
			}
		else if (gUsingNumberedIcons) {//Used for default color numbered markers
			iconObj.image = gDefaultMapMarkersFolder + "marker_green_" + gLocationPlotInfo[locationID].MarkerNumber + ".png";
			iconObj = ApplyNumberedIconProps(iconObj);
			}
		}
	catch (error) {
		window.status = "CreateIcon: " + error.description;
		}
	return iconObj;
	}


//-----------------------------------------------------------
//CreateMarker
//-----------------------------------------------------------
function CreateMarker( locationID, withPopupHTML ) {
	var marker = "";
	try {
		var locationInfo = gLocationPlotInfo[locationID];
		var point = new GPoint(locationInfo.Longitude, locationInfo.Latitude);
		marker = new GMarker( point, CreateIcon(locationID) );
		if (withPopupHTML) {
			var popupHTML = BuildPopUpHTML(locationID);
			GEvent.addListener(marker,'click',function() {
				marker.openInfoWindowHtml(popupHTML);
				}
			);
		}
		}
	catch (error) {
		window.status = "CreateMarker: " + error.description;
		}
	return marker;
	}


//-----------------------------------------------------------
//GetCenterPointFromLocations
//-----------------------------------------------------------
function GetCenterPointFromLocations( locationIDList, defaultCenter) {
	var pointToReturn = defaultCenter || gAustinCenterPoint;
	try {
		if (!locationIDList ) locationIDList = gLocationIDList;
		if (locationIDList.length==1) {
			var centerLocation = gLocationPlotInfo[locationIDList[0]];
			pointToReturn = new GPoint(centerLocation.Longitude,centerLocation.Latitude);
			}
		else {
			var latLongBoundsInfo = GetBoundsOfPlots( locationIDList );
			var middleLatitude = Number(latLongBoundsInfo.minLatBound + latLongBoundsInfo.maxLatBound)/2;
			var middleLongitude = Number(latLongBoundsInfo.minLongBound + latLongBoundsInfo.maxLongBound)/2;
			pointToReturn = new GPoint(middleLongitude,middleLatitude);
			}
		}
	catch (error) {
		window.status = "GetCenterPointFromLocations: " + error.description;
		}
	return pointToReturn;
	}


//-----------------------------------------------------------
//GetZoomLevelFromLocations
//-----------------------------------------------------------
function GetZoomLevelFromLocations( locationIDList ) {
	var zoomLevel = 10;
	try {
		if (!locationIDList ) locationIDList = gLocationIDList;
		if (locationIDList.length==1) return 4;
		var latLongBoundsInfo = GetBoundsOfPlots( locationIDList );
		//One deg diff equals 69.04 miles
		var latitudeDiff = Math.abs(latLongBoundsInfo.minLatBound - latLongBoundsInfo.maxLatBound);
		var latitudeDifferenceInMiles = latitudeDiff * 69.04;
		//One deg diff equals 59.96 miles
		var longitudeDiff = Math.abs(latLongBoundsInfo.minLongBound - latLongBoundsInfo.maxLongBound);
		var longitudeDifferenceInMiles = longitudeDiff * 59.96;
		for (var level=4; level<10; level++) {
			var maxDistanceAtThisLevel = (gMapSizeInPixels/gZoomLevelToScaleMapping[level].scale) * gZoomLevelToScaleMapping[level].distance;
			if (latitudeDifferenceInMiles<maxDistanceAtThisLevel && longitudeDifferenceInMiles<maxDistanceAtThisLevel) {
				return level;
				}
			}
		}
	catch (error) {
		window.status = "GetZoomLevelFromLocations: " + error.description;
		}
	return zoomLevel;
	}


//-----------------------------------------------------------
//GetBoundsOfPlots
//-----------------------------------------------------------
function GetBoundsOfPlots( locationIDList ) {
	var record = { minLatBound:null, maxLatBound: null, minLongBound:null, maxLongBound:null };
	try {
		if (gLatLongBoundsInfo) return gLatLongBoundsInfo;
		var minLatBound = null;
		var maxLatBound = null;
		var minLongBound = null;
		var maxLongBound = null;
		for (var item=0; item<locationIDList.length-1; item++) {
			var locationInfo = gLocationPlotInfo[locationIDList[item]];
			var nextLocationInfo = gLocationPlotInfo[locationIDList[item+1]];
			if (item==0) {
				minLatBound = Math.min(locationInfo.Latitude,nextLocationInfo.Latitude);
				maxLatBound = Math.max(locationInfo.Latitude,nextLocationInfo.Latitude);
				minLongBound = Math.min(locationInfo.Longitude,nextLocationInfo.Longitude);
				maxLongBound = Math.max(locationInfo.Longitude,nextLocationInfo.Longitude);
				}
			else {
				minLatBound = Math.min(minLatBound,nextLocationInfo.Latitude);
				maxLatBound = Math.max(maxLatBound,nextLocationInfo.Latitude);
				minLongBound = Math.min(minLongBound,nextLocationInfo.Longitude);
				maxLongBound = Math.max(maxLongBound,nextLocationInfo.Longitude);
				}
			}
		if (locationIDList.length==1) {
			minLatBound = gLocationPlotInfo[locationIDList[0]].Latitude;
			maxLatBound = minLatBound;
			minLongBound = gLocationPlotInfo[locationIDList[0]].Longitude;
			maxLongBound = minLongBound;
			}
		else if (locationIDList.length==0) {
			minLatBound = gAustinCenterPoint.y;
			maxLatBound = minLatBound;
			minLongBound = gAustinCenterPoint.y;
			maxLongBound = minLongBound;
			}
		record.minLatBound = Number(minLatBound);
		record.maxLatBound = Number(maxLatBound);
		record.minLongBound = Number(minLongBound);
		record.maxLongBound = Number(maxLongBound);
		gLatLongBoundsInfo = record;
		}
	catch (error) {
		window.status = "GetBoundsOfPlots: " + error.description;
		}
	return record;
	}


//-----------------------------------------------------------
// IncrementMarkerCount
//-----------------------------------------------------------
function IncrementMarkerCount( locationID ) {
	try {
		gCurrentMarkerNumber++;
		gLocationPlotInfo[locationID].MarkerNumber = gCurrentMarkerNumber;
		}
	catch (error) {
		window.status = "IncrementMarkerCount: " + error.description;
		}
	}


//-----------------------------------------------------------
//IsLocationWithinBounds
//-----------------------------------------------------------
function IsLocationWithinBounds( locationID ) {
	var result = false;
	try {
		var LocationInfo = gLocationPlotInfo[locationID];
		if (!gCurrentMapBounds) gCurrentMapBounds = gCurrentMap.getBoundsLatLng();
		if (LocationInfo.Longitude > gCurrentMapBounds.minX && LocationInfo.Longitude < gCurrentMapBounds.maxX && LocationInfo.Latitude > gCurrentMapBounds.minY && LocationInfo.Latitude < gCurrentMapBounds.maxY) {
			result = true;
			}
		}
	catch (error) {
		window.status = "IsLocationWithinBounds: " + error.description;
		}
	return result;
	}
