var otaG = {
	oMap: null,
	oGDir: null,
	oGeocoder: null,
	centerPoint: null,
	centerPointString: null,
	currentTargetString: "",
	pinIcon: null,
	centerMmarker: null,
	locXml: "",
	miniImagesPath:"/assets/images/gmaps/mini/",
	oLocations: [],
	currentLoc: null
};



google.setOnLoadCallback(InitGMap);

			
function InitGMap() {
	initLocationsXml();
}


function initializeGDirections() {
	if (GBrowserIsCompatible()) {      
		otaG.oGDir = new GDirections(otaG.oMap, document.getElementById("DirectionsInfoWrapper"));
		GEvent.addListener(otaG.oGDir, "load", onGDirectionsLoad);
		GEvent.addListener(otaG.oGDir, "error", handleErrors);
		
		// React on "Enter" button:
		var txtInput = document.getElementById("FromAddress");
		
		txtInput.onkeydown = function(e) {
			var e = window.event || e;
			
			if (e.keyCode === 13){
				setDirections();

				return false; // stop event bubbling - prevent postback here
			}
		};
		
	}
	
	renderToDirectionAddress();
	
}

function setDirections(strPresetAddress) {

//	if (otaG.oGDir.getStatus().code == G_GEO_SUCCESS) {
//		cleanMap();
//	}
	
	var fromAddress;
	var locale = "en";
	
	if ((strPresetAddress !== undefined) && (strPresetAddress.length > 0)) {
		otaG.currentTargetString = strPresetAddress;
	} else {
		otaG.currentTargetString = document.getElementById("FromAddress").value;
	}
	
	
	otaG.oGDir.load("from: " + otaG.currentTargetString + " to: " + otaG.centerPointString, { "locale": locale } );

}

function handleErrors() {
	setViewDirectionsERROR();
	alert("Error retrieving directions. Please check the address.");
}

function onGDirectionsLoad() { 
	if (otaG.oGDir.getStatus().code == G_GEO_SUCCESS) {
		setViewDirectionsOK();
		otaG.oMap.closeExtInfoWindow();
		otaG.centerMmarker.hide();
	}
}


function cleanMap() {
	otaG.oMap.clearOverlays();
}


function displayRoutePreset(linkNumber) {
	document.getElementById("FromAddress").value = "";
	setDirections(otaGInfo.targets[linkNumber].value);
}


function openPrintWindow() {

	var qString = "";
	
	var strFrom = otaG.currentTargetString;
	var strTo = otaG.centerPointString;
	
	var strOfficialName = otaG.currentLoc.officialName;
	var strAddress = otaG.currentLoc.address;
	var strAddress2 = otaG.currentLoc.address2;
	var strZipCode = otaG.currentLoc.zipCode;
	
	qString += "?";
	qString += "fr=" + escape(strFrom);
	qString += "&to=" + escape(strTo);
	qString += "&n=" + escape(strOfficialName);
	qString += "&a1=" + escape(strAddress);
	qString += "&a2=" + escape(strAddress2);
	qString += "&z=" + escape(strZipCode);
	
	var printWindow = window.open(OtaJsGlobals.clientAppRootNoBS + '/assets/html/GoogleMapsPrintPreview.aspx' + qString, '', 'width=795, height=600, menubar=1, resizable=0, scrollbars=1 ');

}



function initLocationsXml() {

	GDownloadUrl(OtaJsGlobals.clientAppRootNoBS + "/assets/xml/locations.xml", function(data, responseCode) {

		renderTargetLinks();
		
		
		// Error checking when on live server
		if(responseCode == 200) {
			
			otaG.locXml = GXml.parse(data);
			
			
			var locations = otaG.locXml.documentElement.getElementsByTagName("location");
			initializeLocationsObject(locations);
			
			otaG.currentLoc = getLocationById(otaGInfo.locationID);
			
			var infoMessage = getInfoWindowHtmlString(otaG.currentLoc);
			
			
			otaG.centerPoint = new GLatLng(otaG.currentLoc.lat, otaG.currentLoc.lng);
			otaG.centerPointString = otaG.currentLoc.lat + ', ' + otaG.currentLoc.lng;

			otaG.oMap = new GMap2(document.getElementById("GMap"));
			otaG.oMap.setCenter(otaG.centerPoint, otaGInfo.centerZoom);
			
			
			initMarkerIcon();
			
			otaG.centerMmarker = new GMarker(otaG.centerPoint, otaG.pinIcon);
			
			otaG.oMap.addOverlay(otaG.centerMmarker);
			
			
			GEvent.addListener(otaG.centerMmarker, "click", marker_click());
			
			
			otaG.centerMmarker.openExtInfoWindow(otaG.oMap, "otaInfoWindow", infoMessage, {beakOffset:2, paddingX:70, paddingY:40});
			
			otaG.oMap.addControl(new GSmallMapControl());
			otaG.oMap.addControl(new GMapTypeControl());
			
			initializeGDirections();
			
			

		} else if(responseCode == -1) {
			alert("Data request timed out. Please try later.");
		} else { 
			alert("Request resulted in error. Check XML file is retrievable. code: " + responseCode);
		}


	});
}


var marker_click = function() {
	return function() {
	
		var oExtWindow = otaG.oMap.getExtInfoWindow();
		
		if (oExtWindow === null) {
			otaG.centerMmarker.openExtInfoWindow(otaG.oMap, "otaInfoWindow", getInfoWindowHtmlString(otaG.currentLoc), {beakOffset:2, paddingX:70, paddingY:40});
		}
		
	};
};



function initializeLocationsObject(locations) {

	for (var cLocation = 0; cLocation < locations.length; cLocation++ )	{
		var otaLoc = {};
		var currentLoc = locations[cLocation];
		
		// Info from XML
		otaLoc.id = currentLoc.getAttribute("id");
		otaLoc.lat =  parseFloat(currentLoc.getAttribute("lat"));
		otaLoc.lng =  parseFloat(currentLoc.getAttribute("lng"));
		otaLoc.showOnMap = currentLoc.getAttribute("showOnMap");
		otaLoc.region = currentLoc.getAttribute("region");
		otaLoc.territoryId = currentLoc.getAttribute("territoryId");
		
//		otaLoc.officialName = currentLoc.getElementsByTagName("officialName")[0].textContent; // doesnt work in IE...

		otaLoc.centerName = (currentLoc.getElementsByTagName("centerName")[0].firstChild) ? currentLoc.getElementsByTagName("centerName")[0].firstChild.data : "";
		otaLoc.officialName = (currentLoc.getElementsByTagName("officialName")[0].firstChild) ? currentLoc.getElementsByTagName("officialName")[0].firstChild.data : "";
		otaLoc.address = (currentLoc.getElementsByTagName("address")[0].firstChild) ? currentLoc.getElementsByTagName("address")[0].firstChild.data : "";
		otaLoc.address2 = (currentLoc.getElementsByTagName("address2")[0].firstChild) ? currentLoc.getElementsByTagName("address2")[0].firstChild.data : "";
		otaLoc.city = (currentLoc.getElementsByTagName("city")[0].firstChild) ? currentLoc.getElementsByTagName("city")[0].firstChild.data : "";
		otaLoc.state = (currentLoc.getElementsByTagName("state")[0].firstChild) ? currentLoc.getElementsByTagName("state")[0].firstChild.data : "";
		otaLoc.zipCode = (currentLoc.getElementsByTagName("zipCode")[0].firstChild) ? currentLoc.getElementsByTagName("zipCode")[0].firstChild.data : "";
		otaLoc.country = (currentLoc.getElementsByTagName("country")[0].firstChild) ? currentLoc.getElementsByTagName("country")[0].firstChild.data : "";
		otaLoc.linkToHomePage = (currentLoc.getElementsByTagName("linkToHomePage")[0].firstChild) ? currentLoc.getElementsByTagName("linkToHomePage")[0].firstChild.data : "";
		otaLoc.linkToHomeMap = (currentLoc.getElementsByTagName("linkToHomeMap")[0].firstChild) ? currentLoc.getElementsByTagName("linkToHomeMap")[0].firstChild.data : "";
		otaLoc.photoLink = (currentLoc.getElementsByTagName("photoLink")[0].firstChild) ? currentLoc.getElementsByTagName("photoLink")[0].firstChild.data : "";
		
		
		// Phones
		var phones = currentLoc.getElementsByTagName("phone");
		otaLoc.phones = [];

		for (var cPhone = 0; cPhone < phones.length; cPhone++) {
		
			if (phones[cPhone].firstChild) {
				var phone = {
					phoneType: phones[cPhone].getAttribute("type"),
					phoneNumber: phones[cPhone].firstChild.data
				};
			}
			
			otaLoc.phones[cPhone] = phone;
		}
		

		otaG.oLocations[cLocation] = otaLoc;
	
	}
}


function getLocationById(inLocationId) {

	for (var cLocation = 0; cLocation < otaG.oLocations.length; cLocation++) {
		if(otaG.oLocations[cLocation].id === inLocationId) {
			return otaG.oLocations[cLocation];
		}
	}
	
	return null;
}


function initMarkerIcon() {

	otaG.pinIcon = new GIcon(G_DEFAULT_ICON);
	otaG.pinIcon.image = OtaJsGlobals.clientAppRootNoBS + "/assets/images/gmaps/google-map-marker_ota.png";
	
	otaG.pinIcon.iconSize = new GSize(57, 55);
	otaG.pinIcon.iconAnchor = new GPoint(27, 53);
	otaG.pinIcon.infoWindowAnchor = new GPoint(57, 4);
	
	otaG.pinIcon.shadow = OtaJsGlobals.clientAppRootNoBS + "/assets/images/gmaps/google-map-marker_ota_shadow.png";
	otaG.pinIcon.shadowSize = new GSize(83, 55);


	otaG.pinIcon.imageMap = new Array(2, 1, 
									  54, 1, 
									  54, 43, 
									  2, 43);

}



function getInfoWindowHtmlString(currentLoc) {
	var strHTML = "";
	strHTML += "<div class='InfoWindowWrapper'>";

	strHTML += "<div class=\"CenterName\">" + currentLoc.officialName +  "</div>";
	
	strHTML += "<table style=\"width:100%;\">";
	strHTML += "<tr>";
	strHTML += "<td>";
			
	strHTML += currentLoc.address;
	strHTML += "<br />";
	
	if (currentLoc.address2) {
		strHTML += currentLoc.address2;
		strHTML += "<br />";
	}

	
	strHTML += currentLoc.city + " ";
	strHTML += currentLoc.state + " ";
	strHTML += currentLoc.zipCode + " ";
	strHTML += "<br />";
	strHTML += "<br />";


	for (var cPhone = 0; cPhone < currentLoc.phones.length; cPhone++) {
		strHTML += currentLoc.phones[cPhone].phoneType;
		strHTML += ": ";
		strHTML += currentLoc.phones[cPhone].phoneNumber;
		strHTML += "<br />";
	}

	
	strHTML += "</td>";
	strHTML += "<td style=\"width:98px;\">";



	var strPhotoLinkPath = OtaJsGlobals.clientAppRootNoBS + otaG.miniImagesPath + currentLoc.photoLink;
	


	if (isFile(strPhotoLinkPath)) {
		strHTML += "<div class=\"LocImageWrapper\"><img alt=\"\" class=\"LocImage\" src=\"";
		strHTML += strPhotoLinkPath;
		strHTML += "\"></img>";
	}
	

	strHTML += "</td>";
	strHTML += "</tr>";
	strHTML += "</table>";

//	strHTML += "<br />";
//	strHTML += "<a class=\"HomepageLink\" alt=\"\" href=\"" + OtaJsGlobals.clientAppRootNoBS + currentLoc.linkToHomePage + "\">";
//	strHTML += "Click here to visit the " + currentLoc.centerName + " home page &gt;</a>";


	strHTML += "</div>";
	return strHTML;
}


function setViewDirectionsOK() {
	var printButtonDisabled = document.getElementById("PrintDirectionsButtonDisabled");
	printButtonDisabled.style.display = "none";
	
	var printButton = document.getElementById("PrintDirectionsButton");
	printButton.style.display = "inline";
	
	var divDirectionsInfoWrapper = document.getElementById("DirectionsInfoWrapper");
	divDirectionsInfoWrapper.style.display = "block";
	
	var h2DirectionsInfoTitle = document.getElementById("DirectionsInfoTitle");
	h2DirectionsInfoTitle.style.display = "block";

}


function setViewDirectionsERROR() {

	var printButtonDisabled = document.getElementById("PrintDirectionsButtonDisabled");
	printButtonDisabled.style.display = "inline";
	
	var printButton = document.getElementById("PrintDirectionsButton");
	printButton.style.display = "none";

	var divDirectionsInfoWrapper = document.getElementById("DirectionsInfoWrapper");
	
	var h2DirectionsInfoTitle = document.getElementById("DirectionsInfoTitle");
	h2DirectionsInfoTitle.style.display = "none";
	
}


function renderToDirectionAddress() {
	var toDirectionAddress = document.getElementById("ToDirectionAddress");
	toDirectionAddress.innerHTML = otaG.currentLoc.officialName + "<br />" + otaG.currentLoc.address + "<br />" + otaG.currentLoc.city + " " + otaG.currentLoc.state + " " + otaG.currentLoc.zipCode;
}


function renderTargetLinks() {
	var targetLinksWrapper = document.getElementById("TargetLinksWrapper");

	if (targetLinksWrapper !== null) {
		var htmlString = "";
		
		for (var i = 0; i < otaGInfo.targets.length; i++) {
			htmlString += "<a href='#' onclick='displayRoutePreset(" + i + "); return false;'>" + otaGInfo.targets[i].text + "</a><br />";
		}
		
		targetLinksWrapper.innerHTML = htmlString;
	}
	
}



////////////////////////
// Helper functions
//

function isFile(str) {

	var O = AJ();
	if(!O) return false;
	try	
	{
		O.open("HEAD", str, false);
		O.send(null);
		return (O.status==200) ? true : false;
	}
	catch(er) 
	{
		return false;
	}
}

function AJ() {

	var obj;
	
	if (window.XMLHttpRequest) {
		obj= new XMLHttpRequest();
	}
	else if (window.ActiveXObject) {
		try
		{
			obj= new ActiveXObject('MSXML2.XMLHTTP.3.0');
		}
		catch(er)
		{
			obj=false;
		}
	}
	
	return obj;
}
