/////////////////////////////////
// Globals
/////////////////////////////////
var otaG = {
	oMap: "",
	pinIcon: "",
	locXml: "",
	miniImagesPath:"/assets/images/gmaps/mini/",
	tableimagesPath:"assets/images/gmaps/locations-page/",
	deployModeOn: true, // dev: deprecated. leave at true.
	mouseHoverModeOn: true,
	currentRegionName: "",
	regionsMenuTimeoutId: "",
	mapCenterAlertOnDragReleaseEnabled: false, // dev: set true to get easy map center coordinates
	markerHoverEnabled: true, // dev: set false to disable marker popups
	//centerMarker: null, // for dev purposes
	oLocations: [],
	oRegions: [] 
};


/////////////////////////////////
// Main Init
/////////////////////////////////

//google.load("maps", "2"); // moved to content for plugin initialization

function InitGMap() {
	otaG.oMap = new GMap2(document.getElementById("gMap"));
	otaG.oMap.setCenter(new GLatLng(39,-98), 4); // Center on USA 
	otaG.oMap.addControl(new GSmallMapControl());
	otaG.oMap.addControl(new GMapTypeControl());


	initMarkerIcon();
	initLocationsXml();

	if (otaG.mapCenterAlertOnDragReleaseEnabled) {
	    GEvent.addListener(otaG.oMap, "dragend", function(origZoom, newZoom) {
	        alert(otaG.oMap.getCenter() + " \n\nzoom = " + otaG.oMap.getZoom());
	    });	
    }
	
}      

google.setOnLoadCallback(InitGMap);


/////////////////////////////////
// Init Methods
/////////////////////////////////

function initLocationsXml()
{
	GDownloadUrl(OtaJsGlobals.clientAppRootNoBS + "/assets/xml/locations.xml", function(data, responseCode) {
		

		
		
		if(!otaG.deployModeOn) {
		
			otaG.locXml = GXml.parse(data);
			
			var locations = otaG.locXml.documentElement.getElementsByTagName("location");
			initializeLocationsObject(locations);
			
			var regions = otaG.locXml.documentElement.getElementsByTagName("region");
			initializeRegionObject(regions);
			
			setMapView();
			addMarkersToMap();
			injectLocationsTable();
			
			
			
		} else {
		
			//createRegionMenuClosed();
			

			// Error checking when on live server
			if(responseCode == 200) {
				
				otaG.locXml = GXml.parse(data);
				
				var locations = otaG.locXml.documentElement.getElementsByTagName("location");
				initializeLocationsObject(locations);
				
				var regions = otaG.locXml.documentElement.getElementsByTagName("region");
				initializeRegionObject(regions);
				
				setMapView();
				addMarkersToMap();
				injectLocationsTable();
				scrollPageToLocationsList(); // checks internally if scrolling was requested
				
				createRegionMenuClosed();
				
				// Zoom event subscription
				GEvent.addListener(otaG.oMap, "zoomend", function(origZoom, newZoom){
					map_zoom(origZoom, newZoom);
				});
				
			
			} 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);
			}
		}

	});
}


/////////////////////////////////
// Methods
/////////////////////////////////


function createRegionMenuClosed() {

	// create:
	var divRegionsClosed = document.createElement("div");
	otaG.divRegionsClosed = divRegionsClosed; // save to globals
	
	// customize:
	divRegionsClosed.style.visibility="visible";
	divRegionsClosed.style.backgroundImage = "url('assets/images/gmaps/gmap-region-menu-closed.png')";
	divRegionsClosed.style.position="absolute";
	divRegionsClosed.style.width = "201px";
	divRegionsClosed.style.height = "46px";
	
	divRegionsClosed.setAttribute("OnMouseOver", "regionsMenuClosed_MouseOver();");


	// positioning:
	var posX = otaG.oMap.getSize().width - 208;
	var posY = 36;
	
	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(posX, posY));
	pos.apply(divRegionsClosed);


	// add to the map:
	otaG.oMap.getContainer().appendChild(divRegionsClosed);
	
	// add opened menu in hidden mode to the map:
	createRegionsMenuOpen();
}


function regionsMenuClosed_MouseOver() {
	displayRegionsMenuOpen();
}



function createRegionsMenuOpen() {
	// create:
	
	var wrapperHeight = 250;
	
	var divRegionsOpen = document.createElement("div");
	otaG.divRegionsOpen = divRegionsOpen; // save to globals
	
	// customize:
	divRegionsOpen.style.visibility="visible";
	//divRegionsOpen.style.background="#ffffff"; //debug
	
	//divRegionsOpen.style.backgroundImage = "url('assets/images/gmaps/gmap-region-menu-closed.png')";
	
	divRegionsOpen.style.position="absolute";
	
	divRegionsOpen.style.width = "201px";
	divRegionsOpen.style.height = wrapperHeight + "px";
	divRegionsOpen.setAttribute("OnMouseOut", "regionsMenuOpen_MouseOut();");
	divRegionsOpen.setAttribute("OnMouseOver", "regionsMenuOpen_MouseOver();");
	
	
	// content - layout:
	
	var topHeight = 39;
	var bottomHeight = 15;
	var middleHeight = wrapperHeight - topHeight - bottomHeight;
	
	var divTop = document.createElement("div");
	divTop.style.visibility="visible";
	divTop.style.backgroundImage = "url('assets/images/gmaps/gmap-region-menu-open-top.png')";
	divTop.style.width = "201px";
	divTop.style.height = topHeight + "px";

	var divMiddle = document.createElement("div");
	divMiddle.style.visibility="visible";
	divMiddle.style.backgroundImage = "url('assets/images/gmaps/gmap-region-menu-open-middlerepeater.png')";
	divMiddle.style.backgroundRepeat = "repeat-y";
	divMiddle.style.width = "201px";
	divMiddle.style.height = middleHeight + "px";
	divMiddle.className = "RegionsMenuLinkContainer";

	var divBottom = document.createElement("div");
	divBottom.style.visibility="visible";
	divBottom.style.backgroundImage = "url('assets/images/gmaps/gmap-region-menu-open-bottom.png')";
	divBottom.style.width = "201px";
	divBottom.style.height = bottomHeight + "px";

	
	
	// content - links:
	var numberOfLinks = addLinksToRegionsMenu(divMiddle);
	
	
	divRegionsOpen.appendChild(divTop);
	divRegionsOpen.appendChild(divMiddle);
	divRegionsOpen.appendChild(divBottom);


	// menu height adjustment:
	
	//middleHeight = (numberOfLinks * 19) + 5; // 19 = font size + bottom margin
	middleHeight = (numberOfLinks * 16) + 5; // 19 = font size + bottom margin
	divMiddle.style.height = middleHeight + "px";
	
	wrapperHeight = topHeight + middleHeight + bottomHeight + 5;
	//alert(wrapperHeight); //debug
	divRegionsOpen.style.height = wrapperHeight + "px";

	// positioning:
	//var posX = otaG.oMap.getSize().width / 2;
	var posX = otaG.oMap.getSize().width - 208;
	var posY = 36;
	
	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(posX, posY));
	pos.apply(divRegionsOpen);

	
	// add to the map:
	otaG.oMap.getContainer().appendChild(otaG.divRegionsOpen);
	hideRegionsMenuOpen();
	
}


function displayRegionsMenuOpen() {
	otaG.divRegionsOpen.style.display = "block";
}

function hideRegionsMenuOpen() {
	otaG.divRegionsOpen.style.display = "none";

	if (otaG.regionsMenuTimeoutId !== "") {
		//console.log("cleared " + otaG.regionsMenuTimeoutId);
		otaG.regionsMenuTimeoutId = "";
	}
}

function regionsMenuOpen_MouseOver() {
	if (otaG.regionsMenuTimeoutId !== "") {
		clearTimeout(otaG.regionsMenuTimeoutId);
		
		//console.log("Menu In, " +"cleared " + otaG.regionsMenuTimeoutId);
		otaG.regionsMenuTimeoutId = "";
	}
}

function regionsMenuOpen_MouseOut() {
	if (otaG.regionsMenuTimeoutId === "") {
		otaG.regionsMenuTimeoutId = setTimeout("hideRegionsMenuOpen()", 500);
		//console.log("timer = " + otaG.regionsMenuTimeoutId);
	}
	
}



function regionsMenuLink_MouseOver() {
//	clearTimeout(otaG.regionsMenuTimeoutId);
}

function regionsMenuLink_MouseOut() {
//	clearTimeout(otaG.regionsMenuTimeoutId);
}



function addLinksToRegionsMenu(container) {

	var numberOfLinks = 0;
	
	for (var i=0; i < otaG.oRegions.length; i++) {
	
		var regionName = otaG.oRegions[i].regionName;
	
		// manual filtering as in main menu
//		if (
//			(regionName === "USA and Canada") ||
//			(regionName === "Europe") ||
//			(regionName === "Middle East") ||
//			(regionName === "Asia Pacific")
//		) {
		
		if (regionName !== "USA and Canada") {
		//if (true) {
		
			var aLink = document.createElement("a");
			aLink.className = "RegionsMenuLink";
			aLink.setAttribute("href", "#");
			aLink.setAttribute("OnMouseOver", "regionsMenuLink_MouseOver('');");
			aLink.setAttribute("onClick", "gmddRegions_Click('" + regionName + "'); return false;");
			
			aLink.innerHTML = regionName;
			
			container.appendChild(aLink);
			numberOfLinks++;
			
			if (regionName.length > 27) {
				numberOfLinks++; // compensate word wrapping
			}

		}
		
	}



	// manual region list
//	addSingleLinkToRegionsMenu(container, "USA and Canada");
//	addSingleLinkToRegionsMenu(container, "Europe");
//	addSingleLinkToRegionsMenu(container, "Middle East");
//	addSingleLinkToRegionsMenu(container, "Asia Pacific");
//	numberOfLinks = 4;


	return numberOfLinks;
	
}


function addSingleLinkToRegionsMenu(container, regionName) {

	var aLink = document.createElement("a");
	aLink.className = "RegionsMenuLink";
	aLink.setAttribute("href", "#");
	aLink.setAttribute("OnMouseOver", "regionsMenuLink_MouseOver('');");
	aLink.setAttribute("OnMouseOut", "regionsMenuLink_MouseOut('');");
	aLink.setAttribute("onClick", "gmddRegions_Click('" + regionName + "'); return false;");
	aLink.innerHTML = regionName;
	
	container.appendChild(aLink);
}
	


	



/////////////////////////////////////////




function gmddRegions_Click(regionName) 
{
	
	otaG.oMap.closeExtInfoWindow();
	
	otaG.currentRegionName = regionName;
	setMapView();
	injectLocationsTable();
	
}




function addMarkersToMap()
{
	for (var cLocation = 0; cLocation < otaG.oLocations.length; cLocation++)
	{
		if(otaG.oLocations[cLocation].showOnMap === "True") {
			
			
			otaG.oMap.addOverlay(otaG.oLocations[cLocation].marker); // for all regions
			
			if (otaG.oLocations[cLocation].shiftMarker) {
				otaG.oMap.addOverlay(otaG.oLocations[cLocation].shiftMarker);
				otaG.oLocations[cLocation].shiftMarker.hide();
			}
			
			
			/* // only for current region
			if(
			   (otaG.currentRegionName == "") || 
			   (otaG.currentRegionName === otaG.oLocations[cLocation].region) || 
			   (IsPartOfSuperRegion(otaG.oLocations[cLocation]))
			   ){
				otaG.oMap.addOverlay(otaG.oLocations[cLocation].marker);
			}
			*/
		}
	}
}


function setMapView()
{
	var chosenRegion = getRegionByName(otaG.currentRegionName);
	
	if(otaG.currentRegionName != "") {
		otaG.oMap.setCenter(new GLatLng(chosenRegion.lat, chosenRegion.lng), chosenRegion.zoom);
	}
	else {
		otaG.oMap.setCenter(new GLatLng(31.353636941500987, -4.5703125), 2);
	}

}

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;
		}
		
		// Add Marker
		otaLoc.marker = new GMarker(new GLatLng(otaLoc.lat, otaLoc.lng), otaG.pinIcon);
		GEvent.addListener(otaLoc.marker, "click", marker_click(otaLoc.id));
		
		if(otaG.markerHoverEnabled) {
		    GEvent.addListener(otaLoc.marker, "mouseover", marker_mouseover(otaLoc.id));
		}
		
		
		// Add Shift-Marker
		otaLoc.isShifted = false; // indicates if the locations is on its original position on the map.

		

		otaLoc.shiftLat = (currentLoc.getElementsByTagName("shiftLat")[0]) ? currentLoc.getElementsByTagName("shiftLat")[0].firstChild.data : null;
		otaLoc.shiftLng = (currentLoc.getElementsByTagName("shiftLng")[0]) ? currentLoc.getElementsByTagName("shiftLng")[0].firstChild.data : null;

		if ((otaLoc.shiftLat !== null) && (otaLoc.shiftLng !== null)) {
			otaLoc.shiftMarker = new GMarker(new GLatLng(otaLoc.shiftLat, otaLoc.shiftLng), otaG.pinIcon);
			GEvent.addListener(otaLoc.shiftMarker, "click", marker_click(otaLoc.id));
			GEvent.addListener(otaLoc.shiftMarker, "mouseover", marker_mouseover(otaLoc.id));
		}
		
		
		
		// Add the new location to the global collection
		otaG.oLocations[cLocation] = otaLoc;
	
	}
}


function initializeRegionObject(regions)
{
	for (var cRegion = 0; cRegion < regions.length; cRegion++ )
	{
		var otaRegion = {};
		var currentRegion = regions[cRegion];
		
		otaRegion.regionName = currentRegion.getAttribute("regionName");
		otaRegion.lat = parseFloat(currentRegion.getAttribute("lat"));
		otaRegion.lng = parseFloat(currentRegion.getAttribute("lng"));

		otaRegion.zoom = +currentRegion.getAttribute("zoom");
		
		otaRegion.viewRegions = new Array();
		
		var additionalRegions = regions[cRegion].getElementsByTagName("showRegion");
		
		for (var cAdditionalRegions = 0; cAdditionalRegions < additionalRegions.length; cAdditionalRegions++) 
		{
			otaRegion.viewRegions[cAdditionalRegions] = additionalRegions[cAdditionalRegions].getAttribute("regionName");
		}
		
		otaG.oRegions[cRegion] = otaRegion;
		
	}
	
	
	// check Query String Region Name
	otaG.currentRegionName = getQuerystring("region");
	
	if (!regionNameIsValid(otaG.currentRegionName))
	{
		otaG.currentRegionName = "";
	}
	

}


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 getRegionByName(inRegionName)
{
	for (var cRegion = 0; cRegion < otaG.oRegions.length; cRegion++)
	{
		if(otaG.oRegions[cRegion].regionName === inRegionName)
		{
			return otaG.oRegions[cRegion];
		}
	}
	
	return null;
}


function IsPartOfSuperRegion(currentLoc)
{
	var currentRegion = getRegionByName(otaG.currentRegionName);
	
	for (var cSubRegion = 0; cSubRegion < currentRegion.viewRegions.length; cSubRegion++)
	{
		if(currentRegion.viewRegions[cSubRegion] === currentLoc.region)
		{
			return true;
		}
	}
	
	return false;
}


function regionNameIsValid(qsRegionName)
{
	for (var cRegion = 0; cRegion < otaG.oRegions.length; cRegion++ )
	{
		if (otaG.oRegions[cRegion].regionName === qsRegionName)
		{
			return true;
		}
	}
	
	return false;
}


function initMarkerIcon()
{
	otaG.pinIcon = new GIcon(G_DEFAULT_ICON);
	otaG.pinIcon.image = "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 = "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' onclick='infoWindowClick();' onMouseOver='infoWindowMouseOver();' onMouseOut='infoWindowMouseOut();'>";
    strHTML += "<div class='InfoWindowWrapper' onclick='infoWindowClick();'>";
    
	strHTML += "<div class=\"CenterName\">" + currentLoc.officialName +  "</div>";
//	strHTML += "<br />";
	
	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 id=\"bubbleLinkText\" 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 injectLocationsTable()
{
	var tableWrapper = document.getElementById("protect_table");
	
	var injectString = "";

	injectString += '<table class=\"location_table\" width=\"945\">' + "\n";

	// Table Header
	injectString += '<!-- Table header -->' + "\n";
	injectString += '<thead>' + "\n";
	injectString += '<tr>' + "\n";
	injectString += '<th scope=\"col\">Center Name and Address</th>' + "\n";
//	injectString += '<th scope=\"col\">Address</th>' + "\n";
	injectString += '<th scope=\"col\">Phone</th>' + "\n";
	injectString += '<th scope=\"col\">Links</th>' + "\n";
	injectString += '</tr>' + "\n";
	injectString += '</thead>' + "\n";

	// Table Body
	injectString += '<!-- Table body -->' + "\n";
	injectString += '<tbody>' + "\n";
	
	var displayLocCounter = 0;
	
	for (var cLocation = 0; cLocation < otaG.oLocations.length; cLocation++)
	{
		if(otaG.oLocations[cLocation].showOnMap === "True") {
			
			if(
			   (otaG.currentRegionName == "") || 
			   (otaG.currentRegionName === otaG.oLocations[cLocation].region) || 
			   (IsPartOfSuperRegion(otaG.oLocations[cLocation]))
			   ){
				injectString += getTableRowInjectString(otaG.oLocations[cLocation], displayLocCounter);
				displayLocCounter++;
			}
			
		}
	}
	
	
	injectString += '</tbody>' + "\n";
	
	injectString += '<!-- Table footer -->' + "\n";
	injectString += '<tfoot></tfoot>' + "\n";
	injectString += '</table>' + "\n";

	
	tableWrapper.innerHTML = injectString;
	
	
}


function getTableRowInjectString(currentLoc, displayLocCounter)
{
	var srtRow = "";
	
	if ( (displayLocCounter % 2) === 0 ) {
		srtRow += '<tr class=\"vcard\">' + "\n";
	} else {
		srtRow += '<tr class=\"vcard darkrow\">' + "\n";
	}
	
	// Center Name and Address
	srtRow += '<td class="CenterNameCell">' + "\n";

//	srtRow += '</td>' + "\n";
	
	// Address
//	srtRow += '<td>' + "\n";

	
	srtRow += '<div class=\"loc-image\">' + "\n";



	srtRow += '<a href=\"#\" onclick="tableLocClick(&quot;' + currentLoc.id + '&quot;)" >';
	
	srtRow += '<img alt=\"\" class=\"LocImage\" src=\"';
	srtRow += otaG.tableimagesPath + currentLoc.photoLink;
	srtRow += '\" ></img>';
	
	srtRow += '</a>';


	
	srtRow += '</div>' + "\n";


	srtRow += '<span class=\"adr\">' + "\n";
	
	srtRow += '<p class="center_name"><span class="CenterNameClick" onclick="tableLocClick(&quot;';
	srtRow += currentLoc.id;
	srtRow += '&quot;)">';
	srtRow += currentLoc.centerName;
	//srtRow += " id = " + currentLoc.id;
	srtRow += '</span></p>' + "\n";
	
	srtRow += '<p>' + "\n";
	
	srtRow += '<span class=\"fn org\">' + currentLoc.officialName + '</span><br />' + "\n";
	//srtRow += '<span class=\"fn org\">' + currentLoc.officialName + " id = " + currentLoc.id + '</span><br />' + "\n";
	srtRow += '<span class=\"street-address\">' + currentLoc.address + '</span><br />' + "\n";
	
	if(currentLoc.address2) {
		srtRow += '<span class=\"extended-address-2\">' + currentLoc.address2 + '</span><br>' + "\n";
	}
	
	srtRow += '<span class=\"locality\">' + currentLoc.city + '</span>' + "\n";
	srtRow += '<span class=\"region\">' + currentLoc.state + '</span>' + "\n";
	srtRow += '<span class=\"postal-code\">' + currentLoc.zipCode + '</span> - ' + "\n";
	srtRow += '<span class=\"country-name\">' + currentLoc.country + '</span>' + "\n";
	
	srtRow += '</p>' + "\n";
	srtRow += '</span>' + "\n";
	srtRow += '</td>' + "\n";
	
	// Phone	
	srtRow += '<td class="PhoneCell">' + "\n";
	srtRow += '<p>';
	
	for (var cPhone = 0; cPhone < currentLoc.phones.length; cPhone++)
	{
		srtRow += '<span class=\"tel\">' + "\n";
		srtRow += '<span class=\"type\">' + currentLoc.phones[cPhone].phoneType + '</span>: ';
		srtRow += '<span class=\"value\">' + currentLoc.phones[cPhone].phoneNumber + '</span>' + "\n";
		srtRow += '<br />' + "\n";
		srtRow += '</span>' + "\n";
	}


	
	srtRow += '</p>' + "\n";
	srtRow += '</td>' + "\n";

	// Links
	srtRow += '<td class="LinksCell">' + "\n";
	srtRow += '<span class=\"location_table_info_icon\">' + "\n";
	
	srtRow += '<p><a href=\"' + OtaJsGlobals.clientAppRootNoBS + currentLoc.linkToHomePage + '\" class=\"fn url\">Center Information</a></p>' + "\n";
	
	srtRow += '</span>' + "\n";
	
	srtRow += '<span class=\"location_table_pin_icon\">' + "\n";
	
	srtRow += '<p><a href=\"' + OtaJsGlobals.clientAppRootNoBS + currentLoc.linkToHomeMap + '\" class=\"fn url\">Map and driving directions</a></p>' + "\n";
	
	srtRow += '</span>' + "\n";
	srtRow += '</td>' + "\n";

	srtRow += '</tr>' + "\n";
	
	
	return srtRow;
}


/////////////////////////////////
// Event Handlers
/////////////////////////////////


function tableLocClick(locId)
{
	window.scrollBy(0, -50000);
	window.scrollBy(0, 180);
	otaG.mouseHoverModeOn = false; // switch marker hover bubbles off.
	marker_popUp(locId)();
}

var marker_click = function(locationId){
	return function(){
	
		if (otaG.oMap.getExtInfoWindow() === null) {
			// if bubble is closed
			otaG.mouseHoverModeOn = true;
			marker_popUp(locationId)();
		}
		else if (locationId !== otaG.oMap.getExtInfoWindow().bubbleLocId) {
			// if bubble is open for a different marker
			otaG.mouseHoverModeOn = true;
			marker_popUp(locationId)();
		}
		else {
			// if bubble is open for current marker
			var currentLoc = getLocationById(locationId);
			var absHomeUrl = OtaJsGlobals.clientAppRootNoBS + currentLoc.linkToHomePage;
			
			//alert(absHomeUrl);
			window.location.href = absHomeUrl;
		}
		
	};
};



var marker_popUp = function(locationId){
	return function(){
		var currentLoc = getLocationById(locationId);
		//currentLoc.marker.openInfoWindowHtml(getInfoWindowHtmlString(currentLoc)); // default Google bubble
		
		if (this.openExtInfoWindow !== undefined) {
			// respond to the Marker clicks
			otaG.mouseHoverModeOn = true; // switch marker hover bubbles on.
			this.openExtInfoWindow(otaG.oMap, "otaInfoWindow", getInfoWindowHtmlString(currentLoc), {beakOffset:2, paddingX:70, paddingY:40});
		}
		else {
			//respond to the Location Table clicks
			currentLoc.marker.openExtInfoWindow(otaG.oMap, "otaInfoWindow", getInfoWindowHtmlString(currentLoc), {beakOffset:2, paddingX:70, paddingY:40});
		}
		
		// attach location ID to the current bubble object:
		otaG.oMap.getExtInfoWindow().bubbleLocId = locationId;

	};
};


function infoWindowClick() {
	var currentLocId = otaG.oMap.getExtInfoWindow().bubbleLocId;
	marker_click(currentLocId)();
}


var marker_mouseover = function(locationId){
	return function(){
		var currentLoc = getLocationById(locationId);
		
		if (otaG.mouseHoverModeOn != false) {
			if (this.openExtInfoWindow !== undefined) {
				this.openExtInfoWindow(otaG.oMap, "otaInfoWindow", getInfoWindowHtmlString(currentLoc), {beakOffset:2, paddingX:70, paddingY:40});
				
				// attach location ID to the current bubble object:
				otaG.oMap.getExtInfoWindow().bubbleLocId = locationId;
			}
		}
		
		
	};
};


function map_zoom(origZoom, newZoom) {

	for (var cLocation = 0; cLocation < otaG.oLocations.length; cLocation++) {
	
		var currLoc = otaG.oLocations[cLocation];
		var currMarker = currLoc.marker;
		var currShiftMarker = currLoc.shiftMarker;
		
	
		if (currLoc.shiftMarker !== undefined) {
		
			if ((newZoom > 4) && (newZoom < 9)) {
				if (!currLoc.isShifted) {
				
					currMarker.hide();
					currShiftMarker.show();
					
					currLoc.isShifted = true;
				}
			}
			else {
				if (currLoc.isShifted) {
				
					currMarker.show();
					currShiftMarker.hide();
					currLoc.isShifted = false;
				}
			}
		}
		
	} // end for
	

}


function scrollPageToLocationsList() {
	var currentAddress = window.location.toString();
	if (currentAddress.indexOf("#list_of_locations") > -1 ) {
		//alert("found!");
		
		window.scrollBy(0, -50000);
		window.scrollBy(0, 740);
		
	}
}


function infoWindowMouseOver() {
    // JP 4/13/2010: remove hover un-underlining
	//var bubbleLinkText = document.getElementById("bubbleLinkText");
	//bubbleLinkText.style.textDecoration = "none";
	
}

function infoWindowMouseOut() {
    // JP 4/13/2010: remove hover un-underlining
	//var bubbleLinkText = document.getElementById("bubbleLinkText");
	//bubbleLinkText.style.textDecoration = "underline";

}


////////////////////////
// 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;
}

function getQuerystring(key, default_)
{
	if (default_==null) default_="";
	key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
	var qs = regex.exec(window.location.href);
	
	if(qs == null) {
		return default_;
	}
	else {
		var result = qs[1];
		
		while (result.indexOf("%20") != -1)
		{
			result = result.replace("%20", " ");			
		}

		return result;
	}
} 

