var map;
var geocoder;
var debugData;
var mapsTable;
var properties;
var routeBounds;
var viewportBoundary;

// This function cleans up the URLs that lansa generates to our preferred "clean" SEO-friendly version
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;
}

function metBuildURL(wam, webroutine, pageID)
{
	return metCleanupURL(wam, webroutine, g_lxmlTs, g_lxmlPartition, g_lxmlLang, g_debug, pageID);
}

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;
}

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);

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;
}

// Google API Keys:
// localhost:   ABQIAAAAIEG0uxScBK3gn1VQc-DCZRT2yXp_ZAY8_ufC3CFXhHIE1NvwkxSLvvP1nuaQO1gPPBvnKEHG8ZMm0g
// met.com:     ABQIAAAAIEG0uxScBK3gn1VQc-DCZRS3G5bKVZVr8egWZuaC0bMq5emYpBS1BAZvyLkDH6PgBIgTNsW8znyhkg
// metapts.com: ABQIAAAAIEG0uxScBK3gn1VQc-DCZRQXbnLPGEtPgLHGDOGny6MWBAqeKhTJpufYemBU_uHO_f6XWLJEGe684w
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);
		}
	}

	geocoder = new GClientGeocoder();
	var sw = new GLatLng(42, -89);
	var ne = new GLatLng(44, -87);
	viewportBoundary = new GLatLngBounds(sw, ne);

	//SetFocus();
}

//Property Location Class
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;
}

propertyLoc.prototype.doAlert = function(text)
{
	alert(text + " " + this.pmplcd);
}

propertyLoc.prototype.createMarker = function(point)
{
	alert(this.pmplcd);

			/*
			if(!point)
			{
				alert(address + " not found");
			}
			else
			{
				var marker = new GMarker(point);
				map.addOverlay(marker);
				marker.bindInfoWindowHtml(html);
			}
			*/
}

function findSearchAddress()
{
	//alert("I'm in!");
	var searchLoc = document.getElementById("F_SRCHLOC").value;
	if(searchLoc == "")
	{
		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)
	{
		searchLoc += ", WI";
		document.getElementById("F_SRCHLOC").value = searchLoc;
	}

	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
		geocoder.setViewport(viewportBoundary);
		geocoder.getLatLng(searchLoc, searchAddressResponse);
		return false;
	}
}

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;
	document.getElementById("SubmitButton").click();
}

function loadMarkers(listName)
{
	properties = new Array();
	mapsTable = document.getElementById(listName);
	if(!mapsTable)
	{
		return;
	}

	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 stolen 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;

	for(var rowNum in mapsTable.rows)
	{
		// skip the header row and some random garbage that is there SOMETIMES
		var curRow = mapsTable.rows[rowNum];

		if(rowNum == 0 || isNaN(rowNum))
			continue;

		var curRow = mapsTable.rows[rowNum];
		var rowData = new Array();

		//var rowData;
		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;
		}

		var prop = new propertyLoc(rowData);
		if(!prop.visible)
			continue;

		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));

		/*
		GEvent.addListener(marker,"mouseover", 
			function()
			{
				//alert("XXX");
				//marker.infoWindow.restore();
			});    

		GEvent.addListener(marker,"mouseout", 
			function()
			{
				marker.closeInfoWindow();
			});    
		*/

		routeBounds.extend(point);
	}

	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);

			marker = new GMarker(srchPoint);
			map.addOverlay(marker);
			marker.bindInfoWindowHtml("My Search Location");

			routeBounds.extend(srchPoint);
		}
	}

	var newZoom = map.getBoundsZoomLevel(routeBounds);
	// don't zoom in too far
	if(newZoom > 13)
		newZoom = 13;
	map.setCenter(routeBounds.getCenter(), newZoom);
}

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 jumpToProperty(pmplcd)
{
	var propField = document.getElementById("JUMPTOLOC");
	propField.value = pmplcd;
	var button = document.getElementById("GoToProp");
	button.click();
}

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
		}
	});
}

