// Global Variables
var map;
var geocoder;
var debugData;
var mapsTable;
var properties;
var routeBounds;
var viewportBoundary;

// Functions contained in this file:
// metCleanupURL(wam, webroutine, ml, partition, lang, debug, pageID) - replaces the standard lansa method of building URLs with our custom version
// metLoadMap(mapDivName, listName) - this is called on a new page load to set up the Google Map and place the markers for each location
// findSearchAddress() - this is called when the user hits the "Search" button. It converts their "search location" from an address or city to Latitude and Longitude coordinates
// jumpToProperty(pmplcd) - allows a button or link to submit the page and go to the given property page
// requireHttps() - reloads the current page in Https:// instead of Http://
// showJSPhotoGallery(jumpToPropertyOnClick, partition) - displays the javascript version of the slide show
// showJSAdRotator() - displays the javascript version of the ad rotator
// showEventGallery() - displays the event gallery

// This function cleans up the URLs that lansa generates to our preferred "clean" SEO-friendly version, which is either:
// www.metapts.com/WAM/WebRoutine.html?other=junk             OR
// www.metapts.com/WAM/WebRoutine/PageID.html?other=junk
function metCleanupURL(wam, webroutine, ml, partition, lang, debug, pageID)
{
	var url = "/" + wam + "/" + webroutine;
	var extra = "";

	if((wam.toUpperCase() == "CS_HOME") && (webroutine.toUpperCase() == "INDEX") && (partition == "FLX"))
	{
		url = "/";
	}
	else
	{
		if(pageID)
			url += "/" + pageID;

		if(partition == "FLX")
			url += ".html";
		else
			url += "." + partition;
	}

	if(ml != "LANSA:XHTML")
		extra += "+ml=" + ml;
	if(lang != "ENG")
		extra += "+language=" + lang;
	if(debug != undefined && debug != "")
		extra += "+debug=" + debug;

	// remove the first "+"
	if(extra != "")
	{
		url += extra.replace("+", "?");	// replace the first + with ?
	}

	return url;
}

// this is a way to jump to wam/webroutine/pageID and keep the rest of details as they were
function metBuildURL(wam, webroutine, pageID)
{
	return metCleanupURL(wam, webroutine, g_lxmlTs, g_lxmlPartition, g_lxmlLang, g_debug, pageID);
}

// Google API Keys:
// localhost:   ABQIAAAAIEG0uxScBK3gn1VQc-DCZRT2yXp_ZAY8_ufC3CFXhHIE1NvwkxSLvvP1nuaQO1gPPBvnKEHG8ZMm0g
// met.com:     ABQIAAAAIEG0uxScBK3gn1VQc-DCZRS3G5bKVZVr8egWZuaC0bMq5emYpBS1BAZvyLkDH6PgBIgTNsW8znyhkg
// metapts.com: ABQIAAAAIEG0uxScBK3gn1VQc-DCZRQXbnLPGEtPgLHGDOGny6MWBAqeKhTJpufYemBU_uHO_f6XWLJEGe684w
//
// metLoadMap(mapDivName, listName)
// This function takes the Lansa list of properties (listName) and their associated data,
// and uses the Google Maps div (mapDivName) to display markers at each property location.
function metLoadMap(mapDivName, listName)
{
	//alert(mapDivName);

	if(mapDivName != "")
	{
		var mapDiv = document.getElementById(mapDivName);
		if((mapDiv != null) && GBrowserIsCompatible())
		{
			map = new GMap2(mapDiv);
			map.addControl(new GLargeMapControl3D());
			map.addControl(new GScaleControl());
			map.addControl(new GMapTypeControl());
			//map.enableScrollWheelZoom();
			routeBounds = new GLatLngBounds();
			//var address = "1123 N Astor St, Milwaukee, WI 53202";
			var astorLoc = new GLatLng(43.045378, -87.900145);
			map.setCenter(astorLoc, 9);

			loadMarkers(listName);
		}
	}

	// this is setting up the basic borders around the area where Met has any properties
	// This prevents people from searching for properties in different states or different parts of WI.
	// Note that if we ever acquire a property outside of this general area, we would need to expand the box.
	geocoder = new GClientGeocoder();
	var sw = new GLatLng(42, -89);
	var ne = new GLatLng(44, -87);
	viewportBoundary = new GLatLngBounds(sw, ne);

	//SetFocus();
}

// Property Location Class
// The loadMarkers() function will read in the data from the Lansa List, and create an array of propertyLoc objects,
// so that the data is in an easier format to work with.
function propertyLoc(dataArray)
{
	this.pmplcd = dataArray["PMPLCD"];
	this.pmplds = dataArray["PMPLDS"];
	this.pmpca1 = dataArray["PMPCA1"];
	this.pmpcct = dataArray["PMPCCT"];
	this.pmpcst = dataArray["PMPCST"];
	this.pmpczp = dataArray["PMPCZP"];
	this.pmltno = dataArray["PMLTNO"];
	this.pmlgno = dataArray["PMLGNO"];
	this.pmpllcd = dataArray["PMPLLCD"];
	this.distance = dataArray["DISTANCE"];
	this.visible = dataArray["VISIBLE"] == 1;
	this.url = metBuildURL("PA_Search", "View_Location", this.pmpllcd);
}

propertyLoc.prototype.getAddress = function()
{
	var address = this.pmpca1 + ", " + this.pmpcct + ", " + this.pmpcst + " " + this.pmpczp;
	return address;
}

propertyLoc.prototype.getHtml = function(loc)
{
	//var html = "<b><a href='javascript:jumpToProperty(\"" + this.pmplcd + "\");'>" + this.pmplds + "</a></b><br />"; 
	var html = "<b><a href='" + this.url + "'>" + this.pmplds + "</a></b><br />"; 
	html += this.pmpca1 + "<br />" ;
	html += this.pmpcct + ", " + this.pmpcst + " " + this.pmpczp + "<br />";
	if(this.distance)
	{
		html += this.distance + "<br />" ;
	}
	html += "<br /><a href='http://maps.google.com/maps?daddr=" + escape(this.getAddress()) + "' target='_new'>Get Directions</a><br />";
	return html;
}

// loadMarkers(listName)
// This function will go through the Lansa List "listName" and build an array of "propertyLoc" objects.
// Then it will use those to create the Markers on the Google Map.
function loadMarkers(listName)
{
	properties = new Array();
	mapsTable = document.getElementById(listName);
	if(!mapsTable)
	{
		return;
	}

	// do some setup to tell the Markers how they should look
	var houseIcon = new GIcon(G_DEFAULT_ICON);

	houseIcon.image = "/images/googlemaps/House.png";
	houseIcon.shadow = "/images/googlemaps/House.Shadow.png";
	houseIcon.iconSize = new GSize(56, 39); 
	houseIcon.shadowSize = new GSize(75, 39); 
	houseIcon.iconAnchor = new GPoint(28, 39); 
	houseIcon.infoWindowAnchor = new GPoint(45, 17); 

	// Old params with image copied from google:
	/*
	houseIcon.image = "/images/googlemaps/home.png";
	houseIcon.shadow = "/images/googlemaps/home.shadow.png";
	houseIcon.iconSize = new GSize(32, 32); 
	houseIcon.shadowSize = new GSize(59, 32); 
	houseIcon.iconAnchor = new GPoint(16, 30); 
	houseIcon.infoWindowAnchor = new GPoint(16, 4); 
	*/

	var markerOptions = { icon:houseIcon };
	var marker;

	// go through the Lansa List and pick out the data we need
	for(var rowNum in mapsTable.rows)
	{
		var curRow = mapsTable.rows[rowNum];

		// skip the header row and some random garbage that is there SOMETIMES
		if(rowNum == 0 || isNaN(rowNum))
			continue;

		var curRow = mapsTable.rows[rowNum];
		var rowData = new Array();

		// go through each Cell in the Lansa List, and try to find the info we're interested in
		for(var c=0; c<curRow.cells.length; c++)
		{
			var curCell = curRow.cells[c];
			var field = curCell.className;
			var value = curCell.firstChild.value;
			rowData[field] = value;
		}

		// use the array of data we found above to create a "propertyLoc" class object
		var prop = new propertyLoc(rowData);
		if(!prop.visible)
			continue;

		// set up a marker at the point where this property is
		var point = new GLatLng(prop.pmltno, prop.pmlgno);
		if(rowNum == 1)
		{
			map.setCenter(point, 10);
		}

		marker = new GMarker(point, markerOptions);
		//marker = new GMarker(point);
		map.addOverlay(marker);
		marker.bindInfoWindowHtml(prop.getHtml(point));

		// make sure that this property is visible on the map
		routeBounds.extend(point);
	}

	// if the user entered a "Desired Location," then we also want to show a marker at that location
	if(document.getElementById("F_SRCHLAT"))
	{
		var cachedLat = document.getElementById("F_SRCHLAT").value;
		var cachedLng = document.getElementById("F_SRCHLNG").value;

		if(cachedLat && cachedLng)
		{
			var srchPoint = new GLatLng(cachedLat, cachedLng);

			// Note: this marker is just the standard Google marker
			marker = new GMarker(srchPoint);
			map.addOverlay(marker);
			marker.bindInfoWindowHtml("My Search Location");

			// make sure the search location is visible on the map
			routeBounds.extend(srchPoint);
		}
	}

	var newZoom = map.getBoundsZoomLevel(routeBounds);
	// don't zoom in too far
	if(newZoom > 13)
		newZoom = 13;
	map.setCenter(routeBounds.getCenter(), newZoom);
}

// findSearchAddress()
// When the user clicks the "Search" button, we need to translate the street address they typed in 
// into latitude and longitude so that we can figure out the distances to all properties.
// However, this has to be done on the client side, before the form actually gets submitted to our web server.
// So, if they have changed the search address, this function will prevent the form from submitting
// until we receive a response back from the Google servers.
function findSearchAddress()
{
	//alert("I'm in!");
	var searchLoc = document.getElementById("F_SRCHLOC").value;
	if(searchLoc == "")
	{
		// They haven't specified a search location, so nothing to translate
		document.getElementById("F_SRCHLAT").value = 0;
		document.getElementById("F_SRCHLNG").value = 0;
		document.getElementById("CACHEDLOC").value = "";
		return true;
	}

	if(isNaN(searchLoc) && searchLoc.toUpperCase().indexOf("WI") == -1)
	{
		// if they entered something that looks like an address or city, assume it is in WI
		searchLoc += ", WI";
		document.getElementById("F_SRCHLOC").value = searchLoc;
	}

	// if we've already translated this address, no need to do it again
	var cachedLoc = document.getElementById("CACHEDLOC").value;
	if(searchLoc == cachedLoc)
	{
		// they didn't change anything, so we already have the lat & lng
		return true;
	}
	else
	{
		// they changed their search address, we need to find the address
		// when we get a response from the Google servers, it will call the "searchAddressResponse()" function
		geocoder.setViewport(viewportBoundary);
		geocoder.getLatLng(searchLoc, searchAddressResponse);
		return false;
	}
}

// this is the callback function that will be called when we receive a response back from the Google servers
// when translating an address into Latitude and Longitude
function searchAddressResponse(point)
{
	// we received a response. update our "cache"
	document.getElementById("CACHEDLOC").value = document.getElementById("F_SRCHLOC").value;

	if(!point || !viewportBoundary.containsLatLng(point))
	{
		//alert("Viewport bounds: " + viewportBoundary.getSouthWest().lat() + "," + viewportBoundary.getSouthWest().lng() + " - " + viewportBoundary.getNorthEast().lat() + "," + viewportBoundary.getNorthEast().lng() );
		//alert("Search Point: " + point.y + "," + point.x);
		//alert("Address not found, or outside of Met's domain");
		document.getElementById("F_SRCHLAT").value = 0;
		document.getElementById("F_SRCHLNG").value = 0;
	}
	else
	{
		document.getElementById("F_SRCHLAT").value = point.y;
		document.getElementById("F_SRCHLNG").value = point.x;

		//map.setCenter(point, 10);
		/*
		map.addOverlay(new GMarker(point));
		routeBounds.extend(point);
		var newZoom = map.getBoundsZoomLevel(routeBounds);
		map.setCenter(routeBounds.getCenter(), newZoom);
		*/
	}

	// trick lansa so it doesn't think the user is clicking twice
	document.getElementById("SubmitButton").__lastClickedTime = 0;
	// since we prevented the form from submitting while we were waiting for the Google servers to respond,
	// we now need to re-submit the request.
	document.getElementById("SubmitButton").click();
}

// This function will submit the current page and go to the specified property page.
// It exists just so that buttons and links can have a simple command to do this.
function jumpToProperty(pmplcd)
{
	var propField = document.getElementById("JUMPTOLOC");
	propField.value = pmplcd;
	var button = document.getElementById("GoToProp");
	button.click();
}

// This will force the current page to re-load in HTTPS instead of just HTTP
function requireHttps()
{
	var loc = document.location.toString();
	var index = loc.indexOf(":");
	var url = loc.substring(index,loc.length);
	if (index == "4") 
	{ 
         secureUrl = "https" + url;
         location.replace(secureUrl); // get rid of current page in history
         location.href = secureUrl;
	}
}

// JavaScript photo galleries - using HighSlide (http://highslide.com)

// Options for the in-page items
var photoGalleryOptions = 
{
	//slideshowGroup: 'group1',
	outlineType: null,
	allowSizeReduction: false,
	wrapperClassName: 'in-page controls-in-heading',
	useBox: true,
	width: 420,
	height: 280,
	//marginRight: 236,
	targetX: 'gallery-area',
	targetY: 'gallery-area',
	//numberPosition: 'caption',
	captionEval: 'this.thumb.alt'
}

function showJSPhotoGallery(jumpToPropertyOnClick, partition)
{
	hs.showCredits = false;
	hs.graphicsDir = '/images/highslide/graphics/';
	hs.transitions = ['expand', 'crossfade'];
	hs.restoreCursor = null;
	if(jumpToPropertyOnClick)
		hs.lang.restoreTitle = 'Click to view this apartment community';
	else
		hs.lang.restoreTitle = 'Click for next image';
	hs.captionEval = 'this.thumb.alt';
	//hs.marginRight = 236;
	hs.marginLeft = 0;
	hs.marginTop = 0;
	hs.marginBottom = 0;
	hs.useBox = true;
	hs.width = 420;
	hs.height = 280;
	hs.autoplay = true;
	hs.captionOverlay.position = 'top left';
	hs.captionOverlay.width = '420px';
	hs.captionOverlay.opacity = .55;
	hs.captionOverlay.className = 'photoGalleryCaption';
	hs.captionOverlay.offsetY = 20;
	hs.numberOfImagesToPreload = 1;

	// Add the slideshow providing the controlbar and the thumbstrip
	hs.addSlideshow({
		//slideshowGroup: 'group1',
		interval: 6000,
		repeat: true,
		useControls: false,
		/*
		overlayOptions: {
			position: 'bottom',
			offsetY: 50
		},
		*/
		thumbstrip: {
			//offsetX: 228,
			paddingLeft: 0,
			offsetX: 420,
			width: '236px',
			height: '280px',
			position: 'left',
			//position: 'middle rightpanel',
			relativeTo: 'expander',
			mode: 'vertical'
		}
	});

	// Open the first thumb on page load
	hs.addEventListener(window, 'load', function() {
		//if(confirm("load gallery?"))
			document.getElementById('PhotoGalleryThumb1').onclick();
		//hs.expand();
	});

	// Cancel the default action for image click and do next instead
	hs.Expander.prototype.onImageClick = function(sender) {
		if (/in-page/.test(this.wrapper.className))	
		{
			if(this.thumb.className)
			{
				//return parent.jumpToProperty(this.thumb.className);
				//figure out the page extension of the current page
				var ext = location.href.substring(location.href.lastIndexOf(".") );
				parent.location.href = "/PA_Search/View_Location/" + this.thumb.className + ext;
			}
			else

				return hs.next();
		}
	}

	// Under no circumstances should the static popup be closed
	hs.Expander.prototype.onBeforeClose = function() {
		if (/in-page/.test(this.wrapper.className))	return false;
	}
	// ... nor dragged
	hs.Expander.prototype.onDrag = function() {
		if (/in-page/.test(this.wrapper.className))	return false;
	}

	// Keep the position after window resize
    hs.addEventListener(window, 'resize', function() {
		var i, exp;
		hs.page = hs.getPageSize();

		for (i = 0; i < hs.expanders.length; i++) {
			exp = hs.expanders[i];
			if (exp) {
				var x = exp.x,
					y = exp.y;

				// get new thumb positions
				exp.tpos = hs.getPosition(exp.el);
				x.calcThumb();
				y.calcThumb();

				// calculate new popup position
		 		x.pos = x.tpos - x.cb + x.tb;
				x.scroll = hs.page.scrollLeft;
				x.clientSize = hs.page.width;
				y.pos = y.tpos - y.cb + y.tb;
				y.scroll = hs.page.scrollTop;
				y.clientSize = hs.page.height;
				exp.justify(x, true);
				exp.justify(y, true);

				// set new left and top to wrapper and outline
				exp.moveTo(x.pos, y.pos);
			}
		}
	});
}

// Options for the in-page items
var adRotatorOptions = 
{
	//slideshowGroup: 'group1',
	outlineType: null,
	allowSizeReduction: false,
	wrapperClassName: 'in-page controls-in-heading',
	useBox: true,
	width: 250,
	height: 300,
	//marginRight: 236,
	targetX: 'gallery-area',
	targetY: 'gallery-area',
	//numberPosition: 'caption',
	captionEval: 'this.thumb.alt'
}

function showJSAdRotator()
{
	hs.graphicsDir = '/images/highslide/graphics/';
	hs.transitions = ['expand', 'crossfade'];
	hs.restoreCursor = null;
	hs.lang.restoreTitle = 'Click to view this apartment community';
	hs.captionEval = 'this.thumb.alt';
	//hs.marginRight = 236;
	hs.marginRight = 0;
	hs.marginLeft = 0;
	hs.marginTop = 0;
	hs.marginBottom = 0;
	hs.useBox = true;
	hs.width = 250;
	hs.height = 300;
	hs.autoplay = true;
	hs.captionOverlay.position = 'top left';
	hs.captionOverlay.width = '250px';
	hs.captionOverlay.opacity = .55;
	hs.captionOverlay.className = 'adRotatorCaption';
	hs.captionOverlay.offsetY = 20;
	hs.numberOfImagesToPreload = 1;

	// Add the slideshow providing the controlbar and the thumbstrip
	hs.addSlideshow({
		//slideshowGroup: 'group1',
		interval: 4000,
		repeat: true,
		useControls: false,
		/*
		overlayOptions: {
			position: 'bottom',
			offsetY: 50
		},
		*/
		thumbstrip: {
			//offsetX: 228,
			paddingLeft: 0,
			offsetY: 0,
			width: '250px',
			//height: '120px',
			position: 'bottom',
			//position: 'middle rightpanel',
			//relativeTo: 'expander',
			mode: 'horizontal'
		}
	});

	// Open the first thumb on page load
	hs.addEventListener(window, 'load', function() {
		document.getElementById('AdRotatorThumb1').onclick();
	});

	// Cancel the default action for image click and do next instead
	hs.Expander.prototype.onImageClick = function(sender) {
		if (/in-page/.test(this.wrapper.className))	
		{
			if(this.thumb.className)
			{
				//return parent.jumpToProperty(this.thumb.className);
				//figure out the page extension of the current page
				var ext = location.href.substring(location.href.lastIndexOf(".") );
				parent.location.href = "/PA_Search/View_Location/" + this.thumb.className + ext;
			}
			else
				return hs.next();
		}
	}

	// Under no circumstances should the static popup be closed
	hs.Expander.prototype.onBeforeClose = function() {
		if (/in-page/.test(this.wrapper.className))	return false;
	}
	// ... nor dragged
	hs.Expander.prototype.onDrag = function() {
		if (/in-page/.test(this.wrapper.className))	return false;
	}
}

function showEventGallery()
{
	hs.showCredits = false;
	hs.graphicsDir = '/images/highslide/graphics/';
	hs.transitions = ['expand', 'crossfade'];
	hs.outlineType = 'rounded-white';
	hs.align = 'center';
	hs.fadeInOut = true;
	hs.zIndexCounter = 10001;
	//hs.restoreCursor = null;
	//hs.lang.restoreTitle = 'Click to view this apartment community';
	hs.captionEval = 'this.thumb.alt';

	// Add the slideshow providing the controlbar and the thumbstrip
	hs.addSlideshow({
		//slideshowGroup: 'group1',
		interval: 4000,
		//repeat: true,
		useControls: true,
		fixedControls: 'fit',
		overlayOptions: {
			opacity: .75,
			position: 'bottom center',
			hideOnMouseOut: true
		}
	});
}

// TEST FUNCTIONS
// These functions were set up at some point for testing or setup, but are not used any more.
// I just kept them around to aid in test/debugging in the future.
function getLatLngFromAddr(addr)
{
	geocoder.getLatLng(addr, function(point)
	{

		if(!point)
		{
			alert(prop.pmplds + ":" + addr + " not found");
		}
		else
		{
			var houseIcon = new GIcon(G_DEFAULT_ICON);
			houseIcon.image = "/images/googlemaps/home.png";
			houseIcon.shadow = "/images/googlemaps/home.shadow.png";
			houseIcon.iconSize = new GSize(32, 32); 
			houseIcon.shadowSize = new GSize(59, 32); 
			houseIcon.iconAnchor = new GPoint(16, 30); 
			houseIcon.infoWindowAnchor = new GPoint(16, 4); 
			
			var markerOptions = { icon:houseIcon };
			//alert(markerOptions.icon.image);
			var marker = new GMarker(point, markerOptions);
			map.addOverlay(marker);
			marker.bindInfoWindowHtml(prop.getHtml(point));
			
			routeBounds.extend(point);
			if(rowNum == mapsTable.rows.length - 1)
			{
				var newZoom = map.getBoundsZoomLevel(routeBounds);
				map.setCenter(routeBounds.getCenter(), newZoom);
			}

		}

	});

}

function OLDmetCleanupURL(wam, webroutine, ml, partition, lang)
{
	var url = "/" + wam + "/" + webroutine + "/";
	if(ml != "LANSA:XHTML")
		url += "+ml=" + ml;
	//if(partition != "FLX")
		url += "+part=" + partition;
	if(lang != "ENG")
		url += "+language=" + lang;

	// remove the first "+"
	if(url.indexOf("+") == url.lastIndexOf("+"))
		url = url.replace("+", "");	// there is only one, remove it
	else
		url = url.replace("+", "?+");	// there is more than one, add a ? in front

	return url;
}

// this was used just to turn different Style Sheets on and off so that we could pick which style to go with
function toggleLansaCSS(srchStr)
{
	var i=0;
	var srchStr;
	var outputDiv = srchStr + "CSSstate";
	if(document.styleSheets.length>0)
	{
		for(i=0;i<document.styleSheets.length;i++) 
		{
			var isRelevant = (document.styleSheets[i].href.indexOf(srchStr) != -1);
			//alert(document.styleSheets[i].href + '\ndisabled=' + document.styleSheets[i].disabled + '\nnotMet=' + isMet);
			if(isRelevant)
			{
				document.styleSheets[i].disabled = !document.styleSheets[i].disabled;
				document.getElementById(outputDiv).innerHTML = document.styleSheets[i].disabled ? "Off" : "On";
				//var cell = document.getElementById("lansaCSSstate");
			}
		}
	}
}
//setTimeout('toggleLansaCSS("std")', 50);
//setTimeout('toggleLansaCSS("override")', 50);

// This was used to test the idea of soft-coding form validation, and doing form validation in javascript, rather than submitting a form, and having lansa check if it is valid.  I believe this was working ok, but it never was used in production code.
function metCheckForm()
{
 //alert(window.location.host);
 var returnVal = true;
 var form = document.forms["LANSA"];
 //alert(form.elements.length);

 //alert(form.elements["REQUIRED"].value);
 var required = form.elements["REQUIRED"].value.split(",");
 //alert(required.length);
 for(var i = 0; i<required.length; i++)
 {
  var curID = required[i].trim();
  
  var node = form.elements[curID];
  
  if (node != null)
  {
    //alert(curID + " is a " + node.type);
    if(node.type == "text")
    {
      if(node.value == "") 
      {
       if(returnVal)
       {
        alert(node.id + " cannot be blank");
        node.focus();
        returnVal = false;
       }
      }
    }
  }
  
 }

/*
 for(var i = 0; i<form.elements.length; i++)
 {
  var node = form.elements[i];
  if(node.type == "text")
  {
   //alert(node.id + " = " + node.value);
   if(node.value == "") 
   {
    alert(node.id + " cannot be blank");
    node.focus();
    returnVal = false;
   }
  }
 }
*/

 return returnVal;
}

