/*
Copyright (c) 2008-2011, Teranet Inc. All rights reserved.
*/

/*************************************************
 *             BANNER AD FUNCTIONS
 **************************************************/
function showHideBannerAd(bannerAdColId, showAd) {
	var bannerAdCol;
	bannerAdCol = document.getElementById(bannerAdColId);
	if (bannerAdCol && bannerAdCol != null) {
		if (showAd) {
			if (bannerAdColId == 'leftbanneradcolumn') {
				resizeViewportForMinRes(showAd, 1024, 768, "58%", "42%", "leftcolumnwithbanner", "rightcolumnwithbanner");
				bannerAdCol.className = 'leftbanneradcolshow';
			} else if (bannerAdColId == 'topbanneradcolumn') {
			}
		} else {
			if (bannerAdColId == 'leftbanneradcolumn') {
				resizeViewportForMinRes(showAd, 1024, 768, "53%", "47%", "leftcolumn", "rightcolumn");//restore the orig viewport size
				bannerAdCol.className = 'leftbanneradcolhide';
			} else if (bannerAdColId == 'topbanneradcolumn') {
			}
		}
	}
}

function showHideAllBannerAds(showAd, targetWindow) {
	targetWindow.showHideBannerAd("leftbanneradcolumn", showAd);
}

function retrieveBannerAd(pageType, municipality, targetWindow, resultCallback) {
	if (targetWindow == null) {
		if (pageType == 'ENHANCED_REPORT') {
			targetWindow = window;
		}
		else {
			targetWindow = getMainWindow(window);
		}
	}
	if (getMainWindow(window) != window) {
		getMainWindow(window).retrieveBannerAd(pageType, municipality, targetWindow, resultCallback);
		return;
	}
	// the following code runs in the main window
	var lro = "";
	if (document.getElementById('lro')) {
		lro = document.getElementById('lro').options[document.getElementById('lro').selectedIndex].value;
	}

	if (!municipality) {
		municipality = '';
	}
	getBannerAd(pageType, targetWindow, lro, municipality, resultCallback);
}

function getBannerAd(pageType, targetWindow, lro, municipality, resultCallback) {
	var browserWidth = screen.width;
	var browserHeight = screen.height;
	if (screen.height == 'undefined' || screen.width == 'undefined') {
		browserWidth = 1024;
		browserHeight = 768;
	}

	var bannerAjaxURL = '/gwhweb/bannerAd.do?screenWidth=' + browserWidth
						+ "&screenHeight=" + browserHeight
						+ "&pageType=" + encodeURIComponent(pageType)
						+ "&lro=" + encodeURIComponent(lro)
						+ "&municipality=" + encodeURIComponent(municipality);

    // make an AJAX call and replace wait indicator with retrieved HTML content
	var callback = {
	   success: function(o) {
	   	  //alert(o.responseText);
	      updateAd( eval('(' +  o.responseText + ')'), targetWindow, pageType == 'ENHANCED_REPORT_CONFIG' ? 'reportConfigAd': 'leftbannerad', resultCallback);
	   },
	   failure: function(o) {
	   	  if (pageType != 'ENHANCED_REPORT_CONFIG') {
	      	  targetWindow.showHideBannerAd("leftbanneradcolumn", false);//hide ads
	      }
	      if (resultCallback) resultCallback('FAILURE');
	   }
	}
	try {
		YAHOO.util.Connect.asyncRequest('POST', bannerAjaxURL, callback, null);
	} catch (exception){ 
        if (resultCallback) resultCallback('ERROR');
	}	
}

function updateAd(jsonAd, targetWindow, idPrefix, resultCallback) {
	if (jsonAd && jsonAd['adFileUrl']) {
		var img = targetWindow.document.createElement('img');
		img.onload = function(){
		
			try {			
				img.onload = null; //IE fires onload() when image is loaded... and when it starts showing every frame sequence in animated GIFs
				var link = targetWindow.document.getElementById(idPrefix + 'hlid');
	
				link.innerHTML = '';
				link.appendChild(img);
				if (jsonAd['clickThroughURL']) {
					link.href = jsonAd['clickThroughURL'];
					link.onclick = function(){ reportAdClick(jsonAd); return true;};
					link.target='_blank';
				}
				else {
					link.href = 'javascript:void(1)';
					link.target = '';
					link.onclick = '';
				}
				targetWindow.showHideBannerAd(idPrefix + "column", true);//show ads
				if (targetWindow.adSuccess_callback) {
					targetWindow.adSuccess_callback(jsonAd, img);
				}
		        if (resultCallback) {
		         	resultCallback('SUCCESS', jsonAd);
		        } 
				reportAdSuccess(jsonAd);
	        }
	        catch (e) {
	        	if (resultCallback) resultCallback('ERROR');
	        }
		};
		img.onerror = function(){ targetWindow.showHideBannerAd(idPrefix + "column", false);
								  if (resultCallback) resultCallback('ERROR');
								  reportAdError(jsonAd);};
		img.onabort = function(){ targetWindow.showHideBannerAd(idPrefix + "column", false);
								  if (resultCallback) resultCallback('ERROR');	
								  reportAdError(jsonAd);};
		img.src = jsonAd['adFileUrl'];
	}
	else {
		targetWindow.showHideBannerAd(idPrefix + "column", false);//hide ads
	}
}
function reportAdSuccess(jsonAd) { reportAdAction(jsonAd, "IMPRESSION"); }
function reportAdClick(jsonAd)   { reportAdAction(jsonAd, "CLICK"); }
function reportAdError(jsonAd)   { reportAdAction(jsonAd, "ERROR"); }

function reportAdAction(jsonAd, adActionType) {
	// notify server via AJAX about the ad event
	var params = new Array();
	for (var i in jsonAd) {
		params.push(encodeURIComponent(i));
		params.push('=');
		params.push(encodeURIComponent(jsonAd[i]));
		params.push('&');
	}
	params.push('counterType');
	params.push('=');
	params.push(encodeURIComponent(adActionType));
	YAHOO.util.Connect.asyncRequest('POST', "/gwhweb/bannerCounter.do", new Object(), params.join(''));
	trackParamsGoogleAnalytics(jsonAd, adActionType);
}

function trackParamsGoogleAnalytics(jsonAd, adActionType) {

	//AD_CAMPAIGN_NAME
	var adCampaignValue = jsonAd.adCampaignName;
	var advertiserName = jsonAd.advertiserName
	_gaq.push(['_setCustomVar', 1,  'AD_CAMPAIGN_NAME', adCampaignValue + '_' + advertiserName,1]);

	//NAME_BEID
	var companyNameBeidValue = jsonAd.companyName + '_' +encodeURIComponent(jsonAd.beid);
	_gaq.push(['_setCustomVar', 2,  'NAME_ID', companyNameBeidValue,1]);

	var municipality = jsonAd.municipality;
	var lro = jsonAd.lro;
	

	var adActionTypeValue = googleEventTypeTranslatedValue(adActionType);
	_gaq.push(['_setCustomVar', 3,  'EVENT_TYPE', adActionTypeValue,1]);

	//adCampaignType
	var adCampaignTypeValue = encodeURIComponent(jsonAd.pageType);
	_gaq.push(['_setCustomVar', 4,  'REPORT_TYPE', adCampaignTypeValue,1]);

		var mun = getLROText(lro);
		_gaq.push(['_setCustomVar', 5,  'LRO', mun,1]);

//let's log the real url
var pageURL;
if(adCampaignTypeValue == 'ENHANCED_REPORT') {
//todo - do this better
	pageURL = '/gwhweb/propertyReport.do';
}
else {
	pageURL = parent.document.getElementById('PropertySearchResultsID').src;
}
//This is done here because the pageURL returns in IE without URI prefix (host:port) and sometimes withour the gwhweb.
var customURL = splitURL(pageURL);
//google analytics : let's log the url
_gaq.push(['_trackPageview', customURL]);

}

var splitURL = function(url) {
	var gwhweb = '/gwhweb';
	var url;//the url to built for google analytics
	//split url up to params list.
	var myArray = url.split('?');
	var zero = myArray[0];
	var params = myArray[1];
	var str;
	if(zero) {
		var tmp = zero.lastIndexOf('/');
		if(tmp>0) {//we have slashes
			str = zero.substring(tmp+1);
		} else {
			str = zero;
		}
	}
	if(!params) {
		str = lastValue(url);
		url = gwhweb + '/' + str;
	} else {
		url = gwhweb + '/' + str + '?' + params;
	}
//	alert('URL: ' + url);
	return url;
}

var lastValue = function(url) {
	var str;
		var tmp = url.lastIndexOf('/');
		if(tmp>0) {//we have slashes
			str = url.substring(tmp+1);
		} else {
			str = url;
		}
	return str;
}

var googleEventTypeTranslatedValue = function (eventTypeValue) {
	//all backend possible values for event type are: IMPRESSION, CLICK, ERROR
	//the requirements for values that go into google analitics are:
	// IMPRESSION -> AD_IMPRESSION
	// CLICK -> AD_CLICK
	// ERROR -> AD_FAIL
	if(eventTypeValue == 'IMPRESSION') return 'AD_IMPRESSION';
	if(eventTypeValue == 'CLICK') return 'AD_CLICK';
	if(eventTypeValue == 'ERROR') return 'AD_FAIL';
	return eventTypeValue;
}

function getLROText(lro) {

var x = parent.document.getElementById('lro');
var value='';
var i;
	for (i=0;i<x.length;i++)
	{
		value = x.options[i].value;
		if(lro == value) return x.options[i].text;
	}
}

function resizeViewportForMinRes(showAd, scrnWidth, scrnHeight, iframeColWidth, mapColWidth, iframeColClass, mapColClass) {

	//if (screen.width == scrnWidth && screen.height == scrnHeight) {
		var iframeCol = document.getElementById("leftcolumn");
		var mapCol = document.getElementById("rightcolumn");
		var mapLayersDiv = document.getElementById("maplayers");

		var mapTopCtrlDiv = document.getElementById("maptopctrl");
		var mapNavActionDiv = document.getElementById("MSVE_navAction_topBar");

		if (iframeCol && iframeCol != null) {
			if (BrowserDetect.browser == "Firefox") iframeCol.style.width = iframeColWidth;
			if (BrowserDetect.browser == "Explorer") iframeCol.classname = iframeColClass;
		}
		if (mapCol && mapCol != null) {
			if (BrowserDetect.browser == "Firefox") mapCol.style.width = mapColWidth;
			if (BrowserDetect.browser == "Explorer") iframeCol.classname = mapColClass;
		}

		//reposition the map layers div
		if (mapLayersDiv && mapLayersDiv != null) {
			if (showAd && scrnWidth == "1024" && scrnHeight == "768") {
				mapLayersDiv.style.left = "-100px";
			} else {
				mapLayersDiv.style.left = "0px";
			}
			/*
			var newMapLayersTopPos = 0;
			if (mapTopCtrlDiv & mapTopCtrlDiv != null) {
				newMapLayersTopPos = mapTopCtrlDiv.offsetHeight;
			}
			if (mapNavActionDiv && mapNavActionDiv != null) {
				newMapLayersTopPos = newMapLayersTopPos + mapNavActionDiv.offsetHeight;
			}
			*/
		}
	//}
}
 /*************************************************
 *               GENERAL FUNCTIONS
 **************************************************/

var __GENERAL_FUNCTIONS__; 

/*
 * Registers a module with the GWH object
 * @method register
 */
function registerNamespace(ns)
{
 var nsParts = ns.split(".");
 var root = window;

 for(var i=0; i<nsParts.length; i++)
 {
  if(typeof root[nsParts[i]] == "undefined")
   root[nsParts[i]] = new Object();

  root = root[nsParts[i]];
 }
}
registerNamespace("GWH.Ajax");
registerNamespace("GWH.Util");

GWH.Util.GetParam=function(name ){
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null )    return "";
	else    return results[1];
}

GWH.Util.Constants=function( ){  }
GWH.Util.Constants.SEARCH_RESULT = "SEARCH_RESULT";
GWH.Util.Constants.NHOOD_RECORD = "NHOOD_RECORD";
GWH.Util.Constants.HOUSE_VIEW_MODE = 0;
GWH.Util.Constants.DRIVE_BY_VIEW_MODE = 1;

function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1)
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }

  function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }

/*
 * Hash Map Implementation
 */
function KeyValue( key, value )
{
    this.key = key;
    this.value = value;
}

function HMap()
{
    this.array = new Array();
}

HMap.prototype.put = function( key, value )
{
    if( ( typeof key != "undefined" ) && ( typeof value != "undefined" ) )
    {
    	var found = false;

	    for( var k = 0 ; k < this.array.length ; k++ )
	    {
	        if( this.array[k].key == key ) {
	        	this.array[k] = new KeyValue( key, value );
	            found = true;
	            break;
	        }
	    }

	    if ( found == false ) {
	        this.array[this.array.length] = new KeyValue( key, value );
	    }
    }
}

HMap.prototype.get = function( key )
{
    for( var k = 0 ; k < this.array.length ; k++ )
    {
        if( this.array[k].key == key ) {
            return this.array[k].value;
        }
    }
    return "";
}

HMap.prototype.getkeys = function()
{
	var keysArray = new Array();
    for( var k = 0 ; k < this.array.length ; k++ )
    {
        keysArray[k] = this.array[k].key;
    }
    return keysArray;
}

HMap.prototype.length = function()
{
    return this.array.length;
}

HMap.prototype.remove = function( key )
{
	if( ( typeof key == "undefined" ) || key == null ) {
		return;
	}

	var foundValue = this.get(key);

	if ( foundValue == null || foundValue == "" ) {
		return;
	}

	var newArray = new Array();
	var i = 0;

    for( var k = 0 ; k < this.array.length ; k++ )
    {
        if( this.array[k].key != key ) {

        	newArray[i] = new KeyValue( this.array[k].key, this.array[k].value );
        	i = i + 1;
        }
    }

	this.array = newArray;

	foundValue = i = newArray = null;
}


function showMessageDialog(title, msg)
{
	if (printDialog.wait)
	{
		printDialog.wait.hide();
		printDialog.wait.destroy();
	}

	if (title == null) {
		title = "";
	}

	printDialog.wait =
               new YAHOO.widget.Dialog("wait",
                                               { width: "350px",
                                                 fixedcenter: true,
                                                 close: true,
                                                 draggable: true,
                                                 zindex:1000,
                                                 modal: true,
                                                 visible: false
                                               }
                                           );
	printDialog.wait.setHeader(title);
    var dialogHtml = "<div id='printDialog'>";

	dialogHtml += "<p>";
	dialogHtml += "<div align='center'>";
	dialogHtml += msg + "<p>";
	dialogHtml += "<input class='formbtn' type='button' name='ok' value='   OK   ' onclick='printDialog.wait.hide();'>";
	dialogHtml += "</div>";
	dialogHtml += "</div>";

	printDialog.wait.setBody(dialogHtml);
	printDialog.wait.render(document.body);

	// Show the message dialog
	printDialog.wait.show();
}

/*
 *   Disabling keys - start
 */

/*
 * This is to disable the F5 (116) key for the transactional flow
 */
function disableKey(event) {
  if (!event) event = window.event;
  if (!event) return;

  var keyCode = event.keyCode;// ? event.keyCode : event.charCode;

  //window.status = keyCode;

  // keyCode for F% on Opera is 57349 ?!

  if (keyCode == 116) {
   //window.status = "F5 key detected! Attempting to disabling default response.";
   window.setTimeout("window.status='';", 2000);

   // Standard DOM (Mozilla):
   if (event.preventDefault) event.preventDefault();

   //IE (exclude Opera with !event.preventDefault):
   if (document.all && window.event && !event.preventDefault) {
     event.cancelBubble = true;
     event.returnValue = false;
     event.keyCode = 0;
   }

   return false;
  }
}

/*
 * This is to disable the following key for the main page (transaction flow)
 * - F5 (116)
 * - Enter (13)
 * - TAB (9)
 * - Space (32)
 * - Page-up (33)
 * - Page-down (34)
 * - Backspace (8)
 */
function disableMainPageKey(event) {
  if (!event) event = window.event;
  if (!event) return;

  var keyCode = event.keyCode;// ? event.keyCode : event.charCode;

  //window.status = keyCode;

  // keyCode for F% on Opera is 57349 ?!

//  if (keyCode == 116 || keyCode == 13 || keyCode == 9) {
   //window.status = "F5 key detected! Attempting to disabling default response.";
   window.setTimeout("window.status='';", 2000);

   // Standard DOM (Mozilla):
   if (event.preventDefault) event.preventDefault();

   //IE (exclude Opera with !event.preventDefault):
   if (document.all && window.event && !event.preventDefault) {
     event.cancelBubble = true;
     event.returnValue = false;
     event.keyCode = 0;
   }

   return false;
//  }
}

function setEventListener(eventListener) {

	// This is to detact keypress
	if (document.addEventListener) document.addEventListener('keypress', eventListener, true);
	else if (document.attachEvent) document.attachEvent('onkeydown', eventListener);
	else document.onkeydown = eventListener;

	if (!document.getElementById) return;
	var el = document.getElementById("Msg");
	if (el) el.innerHTML = "Event handler added.";


  	// This is to detact right click
	if (document.layers){
		document.captureEvents(Event.MOUSEDOWN);
		document.onmousedown=clickNS4;
	}
	else if (document.all&&!document.getElementById){
		document.onmousedown=clickIE4;
	}

	document.oncontextmenu=new Function("return false")
}

function unsetEventListener(eventListener) {
  if (document.removeEventListener) document.removeEventListener('keypress', eventListener, true);
  else if (document.detachEvent) document.detachEvent('onkeydown', eventListener);
  else document.onkeydown = null;

  if (!document.getElementById) return;
  var el = document.getElementById("Msg");
  if (el) el.innerHTML = "Event handler removed.";
}

function clickIE4(){
	if (event.button==2){
		return false;
	}
}

function clickNS4(e){
	if (document.layers||document.getElementById&&!document.all){
		if (e.which==2||e.which==3){
			return false;
		}
	}
}

/*
 *   Disabling keys - end
 */


/*
 * Browser Detection Object - Start
 *
 * The following properties are exposed
 *		Browser name: BrowserDetect.browser
 *		Browser version: BrowserDetect.version
 *		OS name: BrowserDetect.OS
 *
 *		Browser can be 'Explorer', 'Firefox', 'Safari', 'Chrome', etc.
 *
 */
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

/*
 * Browser Detection Object - Start
 */

 /*************************************************
 *               MENU RELATED FUNCTIONS
 **************************************************/

var __MENU_FUNCTIONS__;


/*
 *	Used by:
 *		MenuHeader.jsp
 *
 *	Usage:
 *	- Open GeoLearn/E-Learning
 */
function openGeoLearnWindow()
{
	if(geoLearnwindow!=null)
	{
		if(geoLearnwindow.closed == true)
		{
			geoLearnwindow = window.open("/gwhweb/geoLearn.jsp","EDUCATION","height=660,RESIZABLE=yes, screenX=50, screenY= 50, width=850,scrollbars=yes, status=no,toolbar=no,menubar=no,location=no,titlebar=0");
		}
		else
		{
			setTimeout('geoLearnwindow.focus();',250);
		}
	}
	else
	{
		geoLearnwindow = window.open("/gwhweb/geoLearn.jsp","EDUCATION","height=660,RESIZABLE=yes, screenX=50, screenY= 50, width=850,scrollbars=yes,status=no,toolbar=no,menubar=no,location=no,titlebar=0");
    	setTimeout('geoLearnwindow.focus();',250);
	}
}


/*
 *	Used by:
 *		MenuHeader.jsp
 *
 *	Usage:
 *	- Proxy to open GeoLearn/E-Learning
 */
function geoLearn_function()
{
	openGeoLearnWindow();
}


/*
 *	Used by:
 *		MenuHeader.jsp
 *
 *	Usage:
 *	- Open RealNet
 *
 *	Note:
 *	- This function can actually be more generic so that it can used to call GeoLearn, Zoom2It, etc
 */
function openThirdPartyProductWindow(prodURL, prodTitle)
{
	var screenwidth = screen.width-20;
	var screenheight = screen.height-80;
	var movetoX = 20;
	var movetoY = 50;
	if(screenwidth > 850)
	{
		screenwidth = 850;
	}

	if(screenheight > 950)
	{
		screenheight =950;
	}

	if(thirdPartyProductWindow != null)
	{
		if(thirdPartyProductWindow.closed == true)
		{
			thirdPartyProductWindow = window.open("",prodTitle,"height=500,width=500,RESIZABLE=yes, scrollbars=yes, status=yes,toolbar=no,menubar=no,location=no");
			thirdPartyProductWindow.moveTo(movetoX,movetoY);
			thirdPartyProductWindow.resizeTo(screenwidth,screenheight);
		}
		else
		{
			setTimeout('thirdPartyProductWindow.focus();',250);
		}
	}
	else
	{
		thirdPartyProductWindow = window.open("",prodTitle,"height=600,width=800,RESIZABLE=yes, scrollbars=yes, status=yes,toolbar=no,menubar=no,location=no");
	   	setTimeout('thirdPartyProductWindow.focus();',250);
	    try
	    {
			thirdPartyProductWindow.moveTo(movetoX,movetoY);
	    	thirdPartyProductWindow.resizeTo(screenwidth,screenheight);
	    }
		catch (e)
		{
		}

	}
	thirdPartyProductWindow.location=prodURL;
}


/*
 *	Used by:
 *		MenuHeader.jsp
 *
 *	Usage:
 *	- Proxy to open RealNet
 *
 *	Note:
 *	- This function can actually be more generic so that it can used to call GeoLearn, Zoom2It, etc
 */
function thirdPartyProduct_function(prodURL, prodTitle)
{
	openThirdPartyProductWindow(prodURL, prodTitle);
}


/*
 *	Used by:
 *		MenuHeader.jsp
 *
 *	Usage:
 *	- Open Zoom2ItPlus
 */
function openzoom2itpluswindow()
{
	if(zoom2itpluswindow != null)
	{
		if(zoom2itpluswindow.closed == true)
		{
			zoom2itpluswindow = window.open("","ZOOM2ITPLUS","height=682,RESIZABLE=yes, screenX=100, screenY= 100, width=670,scrollbars=yes, status=no,toolbar=no,menubar=no,location=no,titlebar=0");
		}
		else
		{
			setTimeout('zoom2itpluswindow.focus();',250);
		}
	}
	else
	{
		zoom2itpluswindow = window.open("","ZOOM2ITPLUS","height=682,RESIZABLE=yes, screenX=100, screenY= 100, width=670,scrollbars=yes,status=no,toolbar=no,menubar=no,location=no,titlebar=0");
		setTimeout('zoom2itpluswindow.focus();',250);
	}
}

/*
 *	Used by:
 *		MenuHeader.jsp
 *
 *	Usage:
 *	- Proxy to open Zoom2ItPlus
 */
function zoom2itPlus()
{
  zoom2itPlusWPL(getPropertyPIN(),getPropertyLRO(),'false');
}

function zoom2itPlusPurchaseTrue(pin,lro)
{
  zoom2itPlusWPL(pin,lro,'true');
}

/*
 *	Used by:
 *	  Map and ...
 *
 *	Usage:
 *	- Proxy to open Zoom2ItPlus
 */
function zoom2itPlusWPL(pin,lro,purchase)
{
    parent.document.getElementById('zoom2it').action = "/gwhweb/zoom2itplus.jsp";
	parent.document.getElementById('zoom2it').method = "post";
    // Global property attributes available
    if(document.forms['propertyAttributesVOForm']) {
    if(pin.length==8)
        	pin="0"+pin;
     	parent.document.getElementById('zoom2it').pinvalue.value = pin;
     	parent.document.getElementById('zoom2it').lrovalue.value = lro;
        parent.document.getElementById('zoom2it').purchasevalue.value = purchase;
 	} else {
        // Global property attributes not available, default to province level
        parent.document.getElementById('zoom2it').pinvalue.value = '999999999';
        parent.document.getElementById('zoom2it').lrovalue.value = '99';
        parent.document.getElementById('zoom2it').purchasevalue.value = 'false';
    }
	openzoom2itpluswindow();
	parent.document.getElementById('zoom2it').target = "ZOOM2ITPLUS";
    parent.document.getElementById('zoom2it').submit();
}

/*
 *	Used by:
 *		MenuHeader.jsp
 *
 *	Usage:
 *	- Go to Store Catalogue page
 */
function storeCatalogue()
{
	parent.document.getElementById('storeCatalogueForm').action = "/gwhweb/storeCatalogue.do";
	parent.document.getElementById('storeCatalogueForm').method = "post";
    if(document.forms['propertyAttributesVOForm'])
    {
    	tempPIN = getPropertyPIN();
    	if (tempPIN == '999999999') {
	        parent.document.getElementById('storeCatalogueForm').pin.value = '';
	    }
	    else {
	    	parent.document.getElementById('storeCatalogueForm').pin.value = tempPIN;
	    }
    }
    else
    {
        // Global property attributes not available, default to province level
        parent.document.getElementById('storeCatalogueForm').pin.value = '';
    }
	parent.document.getElementById('storeCatalogueForm').submit();
}


/*
 *	Used by:
 *		MenuHeader.jsp
 *
 *	Usage:
 *	- Open the FAQ window
 */
function openFAQWindow(url) {

	if (faqWindow != null) {
		if (faqWindow.closed == true) {
			faqWindow = window.open (url, 'FAQ', 'toolbar=no, menubar=no, scrollbars=yes, resizable=yes,location=no, directories=no, status=no, width=750, height=500');
			setTimeout('faqWindow.focus();',250);
		}
		else {
			setTimeout('faqWindow.focus();',250);
		}
	}
	else {
	  faqWindow = window.open (url, 'FAQ', 'toolbar=no, menubar=no, scrollbars=yes, resizable=yes,location=no, directories=no, status=no, width=750, height=500');
	  faqWindow.focus();
	}
}


/*
 *	Used by:
 *		MenuHeader.jsp
 *
 *	Usage:
 *	- Show the More Menu from the menu bar
 */
function showMoreMenu(){
	mopen('m1')
}


/*
 *	Used by:
 *		MenuHeader.jsp
 *
 *	Usage:
 *	- open hidden layer
 */
function mopen(id){
	// cancel close timer
	mcancelclosetime();

	// close old layer
	if (ddmenuitem) {
		ddmenuitem.style.visibility = 'hidden';
	}

	//hide More link if desired
	moreLinkElement=document.getElementById("moreLink");

	// get new layer and show it
	ddmenuitem = document.getElementById(id);
	if (ddmenuitem) {
		ddmenuitem.style.visibility = 'visible';
	}

	//hide reportType selectList in reactrTemplate page.
	hideShowSelectList("ratreporttype","hide")
}


/*
 *	Used by:
 *		MenuHeader.jsp
 *
 *	Usage:
 *	- close showed layer
 */
function mclose(){

	if (ddmenuitem) {
		ddmenuitem.style.visibility = 'hidden';
	}
	moreLinkElement=document.getElementById("moreLink");
	hideShowSelectList("ratreporttype","show");
}


/*
 *	Used by:
 *		MenuHeader.jsp
 *
 *	Usage:
 *	- go close timer
 */
function mclosetime(){
	closetimer = window.setTimeout(mclose, timeout); // time to remove the dd menu on mouse out.
}


/*
 *	Used by:
 *		MenuHeader.jsp
 *
 *	Usage:
 *	- cancel close timer
 */
function mcancelclosetime(){
	if(closetimer){
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}


/*
 *	Used by:
 *		MenuHeader.jsp
 *
 *	Usage:
 *	- hide reportType selectList in reactrTemplate page for dd to display.
 */
function hideShowSelectList(selectName,flag){
	reportTypeElement= document.getElementById(selectName);
	reportLabelElement=document.getElementById("ratreporttypeLabel");
	if (reportTypeElement && flag=='hide') {
		reportTypeElement.style.display='none';
		reportLabelElement.style.display='none';	}
	else if (reportTypeElement && flag=='show') {
		reportTypeElement.style.display='';
		reportLabelElement.style.display='';
	}
}

/*
 *	Used by:
 *		MenuHeader.jsp
 *
 *	Usage:
 *	- Opens a window to the Conduit applicaiton
 */
function openGenericConduitWindow()
{
	var conduitURL = "/gwhweb/conduit.do";
	openConduitWindow(conduitURL);
}


 /*************************************************
 *                 AJAX FUNCTIONS
 **************************************************/
var __AJAX_FUNCTIONS__;

/*
 * The GWH Ajax Library
 *
 * @module Ajax
 * @requires
 * @optional
 * @namespace GWH.Ajax
 * @title Ajax Controls for autocomplete
 */

/* Global Variable - cached for reuse*/
var asXmlHttp;

/*
 * Following functionalities are required for auto suggestion
 */

var oResponse;
GWH.Ajax.getDataset=function(datasetType,key,lro) {
	var URL='/gwhweb/autosuggest.do?datasetType='+datasetType+'&key='+key+'&lro='+lro;
	try {
	  	var asXmlHttp = GWH.Ajax.getXmlHttpRequest();
		asXmlHttp.open("GET",URL,false);
		asXmlHttp.send(null);
		if (asXmlHttp.readyState==4) {
			// alert("xmlHttp.responseText:"+toHtml(asXmlHttp.responseText));
			if (asXmlHttp.status==200||asXmlHttp.status == 0) {
			      var suggestion=eval('(' + toHtml(asXmlHttp.responseText) + ')');
				//oResponse= suggestion.postalcodearray;
			 	if (datasetType=="pcode") {
					oResponse= suggestion["FsaLroVO-array"];
				} else if (datasetType=="municipality") {
					oResponse= suggestion["MunicipalityVO-array"];
				} else if (datasetType=="streetname") {
					 oResponse= suggestion["StreetNameInfoVO-array"];
				} else {
				     	oResponse={};
				     	 window.status="Problem retrieving  data["+asXmlHttp.statusText+"]";
		     	}
   			}
	    }
  	}catch (e) {
  		//alert('source=' + e.source + '\nname=' + e.name + '\nmessage=' + e.message);
  		window.status='source=' + e.source + ' name=' + e.name + ' message=' + e.message;
		return null;
	}
};


GWH.Ajax.getPostalCodes=function(sQuery) {
     var aResults = [];
     sQuery=sQuery.toUpperCase();
	 if (sQuery && sQuery.length > 0) {
        var key = sQuery.substring(0, 2); //use first 2 chars
        var lro=document.forms['propertySearchForm'].lro.value;
         if (isNumber(sQuery.charAt(1))==1) {
	    	// it is a postal code
	    	  GWH.Ajax.getDataset("pcode",key,lro); // call to ajax library
    	     if (oResponse) {
        	    for (var i = oResponse.length - 1; i >= 0; i--) {
            	    var sKey = oResponse[i].fsa;
                	var sKeyIndex = encodeURI(sKey.toLowerCase()).indexOf(sQuery.toLowerCase());
	                if (sKeyIndex === 0) {
    	                aResults.unshift([sKey,oResponse[i].lro, oResponse[i].lroName,oResponse[i].municipalityName]);
        	        }
            	}
        	}
    	} else {
    	  //it is a municipality
    	  GWH.Ajax.getDataset("municipality",key,lro); // call to ajax library
    	     if (oResponse) {
        	    for (var i = oResponse.length - 1; i >= 0; i--) {
            	    var sKey = oResponse[i].municipalityName;
                	var sKeyIndex = encodeURI(sKey.toLowerCase()).indexOf(sQuery.toLowerCase());
	                if (sKeyIndex === 0) {
    	                aResults.unshift([sKey, oResponse[i].lro, oResponse[i].lroName]);
        	        }
            	}
        	}
    	 }
    }
 	return aResults;
}

GWH.Ajax.getStreetNames=function(sQuery) {
     var aResults = [];
     sQuery=sQuery.toUpperCase();
	 if (sQuery && sQuery.length > 0) {

        var key = sQuery.substring(0, 2); //use first 2 chars
        var lro=document.forms['propertySearchForm'].lro.value;

	      GWH.Ajax.getDataset("streetname",key,lro); // call to ajax library
    	     if (oResponse) {
        	    for (var i = oResponse.length - 1; i >= 0; i--) {


            	    var sKey = oResponse[i].id ;
                	var sKeyIndex = encodeURI(sKey.toLowerCase()).indexOf(sQuery.toLowerCase());
	                if (sKeyIndex === 0) {
    	                aResults.unshift([sKey,oResponse[i].streetName]);
        	        }
            	}
        	}
       }

 	return aResults;
}

GWH.Ajax.getReportCountDefault=function()
{
	GWH.Ajax.getReportCount(3000,1,2000);
}

var responseTimeoutID = 0;
var retryInterval = 0;
var retryCount = 0;
var responseTimeout = 0;
var bUsedTimeout = false;
var bShowError = true;
var xhreq;
GWH.Ajax.getReportCount=function(retryInt, retryCnt, respTimeout)
{
	//alert('Inside getReportCount');
  	//Get XMLHttpRequest instance
  	xhreq = GWH.Ajax.getXmlHttpRequest();

  	// Set the handler function which will receive callback notifications
  	// from the XMLHttpRequest object and also pass the handle to function to process results
  	//"specificPageHelperFunction" is passed to the xhreq to be called to process the XML response from server
  	var handlerFunction = getReadyStateHandler(xhreq, GWH.Ajax.reportCountResponseHandler, false, '');
  	xhreq.onreadystatechange = handlerFunction;
	responseTimeout = respTimeout;
	retryCount = ++retryCnt; // increment 1 to compensate for first try
	retryInterval = retryInt;
	GWH.Ajax.sendReportCountReq();
  	//alert('Exiting getReportCount()');
}

GWH.Ajax.sendReportCountReq=function()
{
	//alert('Inside sendReq()');
	var srvURL="/gwhweb/getUserCounterInfo.jsp?ts=" + new Date().getTime();
	//alert(srvURL);
	// check retry count if reached
	if(retryCount > 0)
		retryCount--;

	// Open an HTTP POST (or GET) connection.
	// Third parameter specifies request is asynchronous.
	xhreq.open("POST", srvURL, true);
	// Send request for report count information
	xhreq.send(null);
	// set timeout on response handler here; also disable pop-up error (silent)
	bShowError = false;
	bUsedTimeout = true;
	responseTimeoutID = setTimeout("GWH.Ajax.responseTimedOut()", responseTimeout);
}

GWH.Ajax.responseTimedOut=function()
{
	// Abort the send
	xhreq.abort();
	//alert('Inside responseTimedOut()...aborting request');

	if(retryCount > 0)
		setTimeout("GWH.Ajax.sendReportCountReq()", retryInterval);
	else
	{
		//alert('Error: retrieving report counter information');
		// Retry count reached, stop retrying
		// Show error after number of retries reached
		// An HTTP problem has occurred
		var repViewed = document.getElementById("repViewed");
		repViewed.innerHTML = "-!- ";
        repViewed.title = "Please refresh page to get latest report usage count.";
	    var repcnt = document.getElementById("repcnt");
		repcnt.className = "repcntwarn";
        //window.status='Error: unable to retrieve report count information';
	}
}

GWH.Ajax.reportCountResponseHandler=function(responseText, params)
{
	clearTimeout(responseTimeoutID); // didn't timed out

	//alert('Inside reportCountResponseHandler()');
	//alert(responseText);
	var repCntResponse = responseText.split('^');
	var retcnt = repCntResponse.length;
	//For debugging only
	//if(retcnt == 0)
	//	alert('Response is empty!');

	if(retcnt == 1)
		window.status = repCntResponse[0]; // error message will show
	else
	{
		// everything's ok, retrieve other report count info
		var reportViewed = repCntResponse[1];
		var reportTotal = repCntResponse[2];
		var	isBelowThreshold;
		if(repCntResponse[3] == "y")
			isBelowThreshold = true;
		else
			isBelowThreshold = false;

		GWH.Ajax.updateReportCounterView(reportViewed, reportTotal, isBelowThreshold);
	}
}

GWH.Ajax.updateReportCounterView=function(reportViewed, reportTotal, isBelowThreshold)
{
	//alert("Inside updateReportCounterView");
	var repViewed = document.getElementById("repViewed");
	repViewed.innerHTML = reportViewed+" ";
	repViewed.title = "";
	var repTotal = document.getElementById("repTotalcnt");
	repTotal.innerHTML = reportTotal+" ";
	var repcnt = document.getElementById("repcnt");
	if(isBelowThreshold)
	{
		//alert("BELOW threshold");
		repcnt.className = "repcntwarn";
		return;
	}
	repcnt.className = "repcntok";
}

GWH.Ajax.getXmlHttpRequest=function(){
	var xhr=null;
	if(window.XMLHttpRequest) xhr= new XMLHttpRequest; //native
	else if(window.ActiveXObject) //native unsupported, try ActiveX
		try{
			xhr=new ActiveXObject("Msxml2.XmlHttp.6.0")
			}
		catch(e1){
			try{
				xhr=new ActiveXObject("Msxml2.XmlHttp.3.0")
				}
			catch(e2){
				try{
					xhr=new ActiveXObject("Msxml2.XMLHTTP")
					}
				catch(e3){
						try{
							xhr=new ActiveXObject("Microsoft.XMLHTTP")
							}
						catch(e4){
							// Unable to create an XMLHttpRequest with ActiveX
							}
						}
					}
				}
		else throw	"Unsupported browser (no XMLHTTP object).";
	return xhr;
}


/*
 * Example function
 * Specific functions will be created following this pattern
 * These functions will be called by the page components
 * params - an array of parameters for the call.
 */
GWH.Ajax.specificFunction = function (params,srvUrl) {

  //Get XMLHttpRequest instance
  var xhreq = GWH.Ajax.getXmlHttpRequest();

  // Set the handler function which will receive callback notifications
  // from the XMLHttpRequest object and also pass the handle to function to process results
  //"specificPageHelperFunction" is passed to the xhreq to be called to process the XML response from server
  var handlerFunction = getReadyStateHandler(xhreq, specificPageHelperFunction, xmlflag, params);
  xhreq.onreadystatechange = handlerFunction;

  // Open an HTTP POST (or GET) connection.
  // Third parameter specifies request is asynchronous.
  if (srvURL && srvURL!='')
	  xhreq.open("POST", srvUrl, true);
  else return;

  // Specify that the body of the request contains form data (if params are submitted)
  xhreq.setRequestHeader("Content-Type",
                       "application/x-www-form-urlencoded");

  // Send form encoded data stating that I want to add the
  // specified item to the cart.
  xhreq.send("param0="+ params[0] + "&param1="+params[1]);
}

/*
 * Returns a function that waits for the specified XMLHttpRequest
 * to complete, then passes its XML response
 * to the given handler function.
 * req - The XMLHttpRequest whose state is changing
 * responseXmlHandler - Function to pass the XML response to
 */
function getReadyStateHandler(req, responseHandler, isXML, params) {

  // Return  anonymous function that listens to the XMLHttpRequest instance
  return function () {

	// Check if timeout is used. If so, then response came back before timing out
	if(bUsedTimeout)
	{
		clearTimeout(responseTimeoutID);
		bUsedTimeout = false; // reset
	}

    // If the request's status is "complete"
    if (req.readyState == 4) {
      // Check successful server response was received
      if (req.status == 200||req.status == 0 ){

        // Pass the payload of the response to the  handler function based on type
        if(isXML) responseHandler(req.responseXML, params);
        else responseHandler(req.responseText, params);

      } else {
      	responseHandler(null, params);
      	// Show or silent failure
		if(bShowError)
      	{
	        // An HTTP problem has occurred
    	    window.status='HTTP error:=' + req.status;
    	}
      }
    }
  }
}


 /*************************************************
 *        PAGE / IFRAME / WINDOW FUNCTIONS
 **************************************************/
var __PAGE_WINDOW_FUNCTIONS__;

/* ========= */
/* iframe.js */
/* ========= */
//the occupiedDivs array contains all possible first-level divs (children of body node)
//that are taking up vertical space within an iframe document
var occupiedDivs = new Array('announcementdiv', 'paginationctrl', 'piisummarydiv', 'producttabsdiv', 'propdtls_piidiv', 'propdtls_surveydiv', 'propdtls_condoinfodiv', 'propdtls_assessmentdiv', 'planlist_searchdiv','srprplanlist_searchdiv', 'compsreporthdr', 'compsreportlist');
var divsArrayLength = occupiedDivs.length;
var divBuffer = 5; //old value is 20;
var iframeDocDivToResize;
var iframeDocDivToResizeAdjust = 5; // old value is 60;
var iframeToResize;
var iframeDebug = false;
var iframeObjName;
var iframeParentPage;

function setIframeHeight(iframeName, parentPage) {
	iframeObjName = iframeName;
	iframeParentPage = parentPage;
	if (iframeDocDivToResize == "swfdiv") return;	//exclude SWF pages as behaviour in IE7 is affected by the way onresize event is fired in IE7.

	var newIFrameHeight = getNewIFrameHeight();
	if (newIFrameHeight > 0) {
		iframeToResize.style.height = newIFrameHeight + "px";
		if (iframeDebug) alert("in iframe.js: setIframeHeight(): \niframeToResize.style.height=" + iframeToResize.style.height);
		if (null != iframeDocDivToResize) resizeIFrameDocument();
	}
}

/*
   Returns the iframe height which is determined from the browser's current view port and
   divs occupying vertical spaces on the iframe's parent page.
*/
function getNewIFrameHeight() {
	iframeToResize = getIFrameToResize();
	var allowance = 0;
	var newIFrameHeight = 0;
	var occupiedHeight = 0;

	if (iframeToResize) {
		iframeToResize.style.height = "auto";

		if (iframeParentPage == 'PropertyView') {
			//first-level div containers (children of body node) presently in PropertyView.jsp
			var div1OffsetHeight = document.getElementById('tophdr').offsetHeight;
			var div2OffsetHeight = document.getElementById('srchbar').offsetHeight;
			var div3OffsetHeight = document.getElementById('gwhfooter').offsetHeight;
			var div4OffsetHeight = document.getElementById('infoandmapcontent').offsetHeight;
//			console.debug('tophdr='+div1OffsetHeight);
//			console.debug('srchbar='+div2OffsetHeight);
//			console.debug('gwhfooter='+div3OffsetHeight);
//			console.debug('infoandmapcontent='+div4OffsetHeight);
			//sum up all divs which are taking up vertical space on the page
			occupiedHeight = div1OffsetHeight + div2OffsetHeight + div3OffsetHeight + allowance;
			occupiedHeight = occupiedHeight - 55;

		} else if (iframeParentPage == 'MyGeoWarehouse') {
			//first-level div containers (children of body node) presently in MyGeoWarehouse.jsp
			var div1OffsetHeight = document.getElementById('tophdr').offsetHeight;
			var div2OffsetHeight = document.getElementById('myGWH_returndiv').offsetHeight;
			var div3OffsetHeight = document.getElementById('gwhfooter').offsetHeight;
			var div4OffsetHeight = document.getElementById('infoandmapcontent').offsetHeight;

			//sum up all divs which are taking up vertical space on the page
			occupiedHeight = div1OffsetHeight + div2OffsetHeight + div3OffsetHeight + allowance;

		} else if (iframeParentPage == 'StoreCatalogue') {
			//first-level div containers (children of body node) presently in StoreCatalogue.jsp
			var div1OffsetHeight = document.getElementById('tophdr').offsetHeight;
			var div2OffsetHeight = document.getElementById('catalogue_returndiv').offsetHeight;
			var div3OffsetHeight = document.getElementById('gwhfooter').offsetHeight;

			//sum up all divs which are taking up vertical space on the page
			occupiedHeight = div1OffsetHeight + div2OffsetHeight + div3OffsetHeight + allowance;

		} else if (iframeParentPage == 'UserProfileInitialEdit') {
			//first-level div containers (children of body node) presently in MyGeoWarehouse.jsp
			var div1OffsetHeight = document.getElementById('tophdr').offsetHeight;
			var div2OffsetHeight = document.getElementById('myGWH_returndiv').offsetHeight;
			var div3OffsetHeight = document.getElementById('gwhfooter').offsetHeight;
			var div4OffsetHeight = document.getElementById('infoandmapcontent').offsetHeight;

			//sum up all divs which are taking up vertical space on the page
			occupiedHeight = div1OffsetHeight + div2OffsetHeight + div3OffsetHeight + allowance;
		}
		var bodyHeight = getBodyHeight();
		//console.debug('bodyHeight = ' + bodyHeight);
		newIFrameHeight = (bodyHeight - occupiedHeight);
		//console.debug('newIFrameHeight = ' + newIFrameHeight);
	}
	if (iframeDebug) alert("in iframe.js: getNewIFrameHeight(): newIFrameHeight=" + newIFrameHeight);
	return newIFrameHeight;
}

/* Set iframe height to a pre-defined value */
function resetIframeHeight(iframeName, height, div) {
	setIFrameDocDivToResize(div);
	var iframeToResize = getIFrameToResize();
	iframeToResize.style.height = height + "px";
	if (iframeDebug) alert("in iframe.js: resetIframeHeight(): \niframeName="+iframeName + "\niframeToResize.style.height=" + iframeToResize.style.height);
}

/* Returns the iframe object to resize */
function getIFrameToResize() {
	if (null == iframeToResize) {
		iframeToResize = document.getElementById? document.getElementById(iframeObjName): document.all? document.all[iframeObjName]: null;
	}
	if (iframeDebug) alert("in iframe.js: getIFrameToResize(): \niframeToResize=" + iframeToResize);
	return iframeToResize;
}

/* Returns the height of the current browser view port */
function getBodyHeight() {
	var bodyHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
	  //non-IE
	  bodyHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	  //IE 6+ in 'standards compliant mode'
	  bodyHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	  //IE 4 compatible
	  bodyHeight = document.body.clientHeight;
	}
	return bodyHeight;
}

function setIFrameDocDivToResize(div) {
	iframeDocDivToResize = div;
}

/*
   Resizes the current iframe document.
   This method is invoked from the iframe document itself when it is loaded onto the iframe.
*/
function resizeIFrameDoc(div) {
iframeDebug = false;
	if (iframeDebug) alert("in iframe.js: resizeIFrameDoc(): \ndiv="+div + "\niframeObjName=" + iframeObjName + "\niframeParentPage=" + iframeParentPage);
	setIFrameDocDivToResize(div);
	//re-compute and re-size the iframe in case it has been resized to a predefined height (i.e., if resetIframeHeight method was invoked)
	var newIFrameHeight = getNewIFrameHeight();
	if (newIFrameHeight > 0) {
		iframeToResize.style.height = newIFrameHeight + "px";
		resizeIFrameDocument();
	}
}

/*
   Resizes the current iframe document.
   This method is invoked from the iframe's parent page.
*/
function resizeIFrameDocument() {
	var frameObj = getIFrameToResize();
	if (iframeDebug) alert("in iframe.js: resizeIFrameDocument(): \nframeObj=" + frameObj + "\nframeObj.id=" + frameObj.id + "\niframeDocDivToResize=" + iframeDocDivToResize + "\ndivBuffer=" + divBuffer);
	if (null != frameObj) {
		var frameObjHeight = frameObj.offsetHeight;
		var divToResize = frameObj.contentWindow.document.getElementById(iframeDocDivToResize);
		var totalOccupiedHeight = 0;
		var debugMsg = "in iframe.js: resizeIFrameDocument(): \n";
		//console.debug('B4 for loop totalOccupiedHeight =' + totalOccupiedHeight);
		//console.debug('B4 for loop frameObjHeight =' + frameObjHeight);
		for (var i=0; i < divsArrayLength; ++i) {
			var divObj = frameObj.contentWindow.document.getElementById(occupiedDivs[i]);
			if (null != divObj) {
				debugMsg = debugMsg + divObj.id + " = " + divObj.offsetHeight + "\n";
				totalOccupiedHeight = totalOccupiedHeight + divObj.offsetHeight;
				//console.debug('debugMsg =' + debugMsg);
				//console.debug('totalOccupiedHeight =' + totalOccupiedHeight);
			}
		}

		totalOccupiedHeight = totalOccupiedHeight + divBuffer;
		debugMsg = debugMsg + "\ndivToResize=" + divToResize + "\nframeObjHeight=" + frameObjHeight + "\ntotalOccupiedHeight = " + totalOccupiedHeight;
		var frameDocObjHeight = frameObjHeight - totalOccupiedHeight;
		debugMsg = debugMsg + "\nframeDocObjHeight=" + frameDocObjHeight;
		if (iframeDebug) alert(debugMsg);

		//console.debug('iframeDocDivToResizeAdjust =' + iframeDocDivToResizeAdjust);
		//console.debug('frameDocObjHeight =' + frameDocObjHeight);

		if (frameDocObjHeight > 0 && null != divToResize) {
			divToResize.style.height = Math.max(0, frameDocObjHeight - iframeDocDivToResizeAdjust) + "px";
			if (iframeDebug) alert("in iframe.js: resizeIFrameDocument(): \nframeObjHeight=" + frameObjHeight + "\ntotalOccupiedHeight=" + totalOccupiedHeight + "\nframeDocObjHeight=" + frameDocObjHeight + "\ndivToResize.style.height="+divToResize.style.height);
		}
		//console.debug('divToResize.style.height =' + divToResize.style.height);
		//Property Details: Sales history header and data are on separate DIVs; need to sync them.
		var saleshisthdrdiv = frameObj.contentWindow.document.getElementById('saleshisthdrdiv');
		var saleshistdatadiv = frameObj.contentWindow.document.getElementById('contentdiv');
		if (null != saleshisthdrdiv && null != saleshistdatadiv) {
			saleshisthdrdiv.style.width = saleshistdatadiv.offsetWidth + "px";
		}
	}
}

/*
 *	Used by:
 *		cartviews/ccerror.jsp (function actually not used in the jsp)
 *		errMessage.jsp
 *		infoMessage.jsp
 *
 *	Usage:
 *	- This is to detect whether the header and footer of the page needs to be hidden
 */
function detectParentIFrame() {
	frameObj = window.frameElement;
	if (frameObj != null) {
		frameId = frameObj.id;
		if (frameId != null &&
			(frameId == 'PropertySearchResultsID' || frameId == 'userprofile' ||
				frameId == 'passwordchange' || frameId == 'reportcount' || frameId == 'transactionhistory')) {
			//alert('This page is within iframe ' + frameId + '.');
			document.getElementById('errorpageheaderdiv').className = 'headerdivhidden';
			document.getElementById('errorpagefooterdiv').className = 'footerdivhidden';
		}
	} else {
		//alert('This page is not within an iframe.');
		document.getElementById('errorpageheaderdiv').className = 'headerdivvisible';
		document.getElementById('errorpagefooterdiv').className = 'footerdivvisible';
	}
}


/*
 *	Used by:
 *		error pages/template.jsp (function original name: detectParentIFrame())
 *
 *	Usage:
 *	- This is to detect whether the header and footer of the page needs to be hidden
 *	- This is the same as detectParentIFrame() except that it will hide the header
 *	  and footer when the page is a "https"
 */
function errTemplate_detectParentIFrame() {
	if (window.location.protocol == "https:") {
		document.getElementById('errorpageheaderdiv').className = 'headerdivhidden';
		document.getElementById('errorpagefooterdiv').className = 'footerdivhidden';
		return;
	}
	frameObj = window.frameElement;
	if (frameObj != null) {
		frameId = frameObj.id;
		if (frameId != null &&
			(frameId == 'PropertySearchResultsID' || frameId == 'userprofile' ||
				frameId == 'passwordchange' || frameId == 'reportcount' || frameId == 'transactionhistory')) {
			//alert('This page is within ' + frameId + '.');
			document.getElementById('errorpageheaderdiv').className = 'headerdivhidden';
			document.getElementById('errorpagefooterdiv').className = 'footerdivhidden';
		}
	} else {
		//alert('This page is not within an iframe.');
		document.getElementById('errorpageheaderdiv').className = 'headerdivvisible';
		document.getElementById('errorpagefooterdiv').className = 'footerdivvisible';
	}
}

/*
 *	Used by:
 *		cartviews/ccerror.jsp (function original name: closeWindow())
 *		cartviews/orderreceipt.jsp (function original name: closeWindow(); function actually not used in the jsp)
 *		cartviews/paymentoptions.jsp (function original name: closeWindow())
 *		cartviews/viewcart.jsp (function original name: closeWindow())
 *		estore/ProductDetailScreen.jsp (function original name: closeWindow())
 *		parcelregister/PRNonTransDetailScreen.jsp (function original name: closeWindow())
 *
 *	Usage:
 *	- To close the page's parent window
 */
function closeParentWindow() {
	parent.close();
}


/*
 *	Used by:
 *		GenericHeader.jsp (function original name: closeWindow())
 *
 *	Usage:
 *	- To close the own window
 */
function closeOwnWindow() {
	self.close();
}


/*
 *	Used by:
 *		cartviews/ccerror.jsp (function actually not used in the jsp)
 *		errMessage.jsp
 *		infoMessage.jsp
 *
 *	Usage:
 *	- ???
 */
function verifyTopAndSetUrl(errPageUrl)
{
	if (self != top)
	{
		window.top.location.href=errPageUrl;
	}
}


/*
 *	Used by:
 *		cartviews/ccerror.jsp (function actually not used in the jsp)
 *
 *	Usage:
 *	- Go back to the preivious page
 *
 *	Note:
 *	- This function can actually removed, as nobody is using it
 */
function goBack()
{
	window.history.back()
}


/*
 *	Used by:
 *		cartviews/paymentoptions.jsp
 *		parcelregister/PRNonTransDetailScreen.jsp
 *		MPAC REPORT NON TRANSACTIONAL FULFILLMENT page
 *
 *	Usage:
 *	- A function call by the onkeypress event to avoid user to press the <Enter> key
 */
function noenter() {
	return !(window.event && window.event.keyCode == 13);
}

// Function to get the ProeprtyView window.
// It is used by reports to get Property View to update the Report Counter Display
// - Returns the PropertyView window handle if it is found
// - Returns a null if the PropertyView cannot be found
function getMainWindow(currentWindow) {
	if (currentWindow == null || currentWindow.closed ) {
		// Won't be able to find the main window
		return null;
	}

	// Check if the current window is the main window
	var reportForm = currentWindow.document.getElementById('propertyReportForm');

	if ( reportForm	!= 'undefined' && reportForm != null) {
		return currentWindow;
	}

	// If this is a pop-up window, try to get the opener
	var popupParent = currentWindow.opener;

	if ( popupParent != null && popupParent.closed == false ) {
		currentWindow =  popupParent;
	}

	// No try to get the topmost ancestor window and conrirm that it is the main window
	currentWindow = currentWindow.top;

	// Check if the current window is the main window
	var reportForm = currentWindow.document.getElementById('propertyReportForm');

	if ( reportForm	!= 'undefined' && reportForm != null) {
		return currentWindow;
	} else {
		return null;
	}
}


function openExtWnd(url) {
	newWindow = window.open (url, 'extwnd', 'toolbar=no, menubar=no, scrollbars=yes, resizable=yes,location=no, directories=no, status=no, width=750, height=500');
	newWindow.focus();
}


 /*************************************************
 *                AGREEMENT FUNCTIONS
 **************************************************/
var __AGREEMENT_FUNCTIONS__;
function f_cancel() {
   var form = document.getElementById("form1");
   form.action = "/gwhweb/login/la.do";
   form.legalAccepted.value="false";
   //alert(form1.legalAccepted.value);
   form.submit();
}

function f_submit() {
 	var form = document.getElementById("form1");
    form.action = "/gwhweb/login/la.do";
    form.submit();
}


 /*************************************************
 *                LPP HOME FUNCTIONS
 **************************************************/
var __LPP_HOME_FUNCTIONS__;
function verifyTop() {
	if (self != top) {
		window.open(location.href, '_top');
	}
}

function changeLogo(){
	var img1 = "<img src=\"../images/geowarehouse.jpg\" border=\"0\"  width=\"721px\" >";
	document.getElementById("header1").innerHTML=img1;
	changeItem();
}

function changeMenuItem() {
	menuItem1.className='leftSideBarVisited';
}

function Logout() {
    if(logoutstatus == 'hide') {
        return;
    }
	document.location.href="logout.jsp";
}

function imgRoll(imgName) {
	theImg = document.images[imgName];
	srcStr = theImg.src;
	if (srcStr.search("def") != -1)
		theImg.src = eval ("'"+srcStr.replace("def","roll")+"'");
	if (srcStr.search("roll") != -1)
		theImg.src = eval ("'"+srcStr.replace("roll","def")+"'");
}

//used to open standard windows for pop-up information (CSC only)
function openWin(href) {
	var newWindow = window.open(href,'popup','toolbar=no,menubar=no,location=no,directories=no,scrollbars=yes,resizable=yes,width=500,height=400')
}
<!--detect browser and make adjustments-->
function browserDetect() {
	if (document.layers) thisbrowser="NN4";
	if (document.all) thisbrowser="ie"
	if (!document.all && document.getElementById) thisbrowser="NN6";
}

function getElement(name) {
	if (thisbrowser == 'ie') return document.all[name];
	else if (thisbrowser == 'NN6') return document.getElementById(name);
	if (thisbrowser == 'NN4') return eval("document."+name);
}
<!--end detect browser-->

function doCheck(f) {
	var ok = false;
	for (var i=0; i<f.searchWords.value.length; i++) {
		if (f.searchWords.value.charAt(i) != " ") ok = true;
	}
	if (ok) {
		//if (f.site[1].checked) {
		//	f.redirect.value = "/csc/cscSearch.html";
		//	f.csc.value = "true";
		//}
		return true;
	} else {
		alert("Please enter a word to search for.")
		return false;
	}
}

function checkInput(f) {
	if (doCheck(f)) f.submit();
}


/** Renamed from handlerKey() due to name conflict **/
function loginHandlerKey(evt) {
	var enterKeyCode=13;
	evt = (evt) ? evt : ((window.event) ? window.event : "")
	if (evt && evt.keyCode == enterKeyCode) {
		loginsubmit();
	}
}


function openLinkInPopUp(url) {
	var popUpWindow = window.open(url,"_blank","height=600,width=750,RESIZABLE=yes, scrollbars=yes, status=yes,toolbar=yes,menubar=yes,location=yes");
}

function loginsubmit() {
    document.getElementById("form1").submit();
}


 /*************************************************
 *             PROPERTY VIEW FUNCTIONS
 **************************************************/
var __PROPERTY_VIEW_FUNCTIONS__;

function ToggleMapLayers(){
	var layerctrl = document.getElementById("maplayers");
	if (layerctrl.style.visibility =='visible') layerctrl.style.visibility =='hidden';
	if (layerctrl.style.visibility =='hidden') layerctrl.style.visibility =='visible';
}
function ToggleLayerControl(e){
	var layerctrl = document.getElementById("maplayers");
	if (layerctrl.style.visibility =='visible') layerctrl.style.visibility =='hidden';
	if (layerctrl.style.visibility =='hidden') layerctrl.style.visibility =='visible';
}
function ToggleLayer(ll) {	  	
	if(ll.checked) gwhmap.DoHideShowLayerByID(ll.id,true);
	else gwhmap.DoHideShowLayerByID(ll.id,false);
}
function ToggleThematicLayer(tl, ln){
	var thlegend = document.getElementById("thematiclegend");
	if (tl.checked) {
		gwhmap.showHideThematicLayer(tl.id, true);
		thlegend.style.display="block";
		thlegend.style.visibility="visible";
	} else {
		gwhmap.showHideThematicLayer(tl.id,  false);
		thlegend.style.display="none";
		thlegend.style.visibility="hidden";
	}
	thlegend=null;

	//persist layer selection state
	persistMapLayerState(ln, tl.checked);
}
function persistMapLayerState(ln, lstate) {
	var mapLayerAjaxURL = '/gwhweb/mapLayer.do?layerName=' + ln + "&selected=" + lstate;
	var callback = {
		success: function(o) {
			//alert("Map layer state persisted");
		},
		failure: function(o) {
			//alert("Map layer state not persisted");
		}
	}
	try {
		YAHOO.util.Connect.asyncRequest('GET', mapLayerAjaxURL, callback, null);
	} catch (e){ 
		window.status = 'ToggleThematic...e.src=' + e.source + '\ne.n=' + e.name + '\ne.m=' + e.message;
	}
}
function hideThematicLayers(id){
    gwhmap.showHideThematicLayer(id, false);
}

function SetOpacityValue4Thematic(transluncencyValue) {
	 gwhmap.SetOpacity4Thematic(transluncencyValue);
}
function KeyDownHandler(evt, btn){ 	var enterKeyCode=13;
	evt = (evt) ? evt : ((window.event) ? window.event : "")
	if (evt && evt.keyCode == enterKeyCode) {
	    evt.returnValue=false;
	    evt.cancel = true;
            btn.click();
        }
 }
<!-- Scripts to get and set a specific property global attributes that is in active -->
function getPropertyPIN() {
    return document.forms['propertyAttributesVOForm'].propertyPIN.value;
}
function setPropertyPIN(pinvalue) {
    document.forms['propertyAttributesVOForm'].propertyPIN.value = pinvalue;
}

function getPropertyLRO() {
	if(document.forms['propertySearchForm'] && document.forms['propertySearchForm'].lro && document.forms['propertyAttributesVOForm'].propertyLRO.value=="99"){
		return document.forms['propertySearchForm'].lro.options[document.forms['propertySearchForm'].lro.selectedIndex].value;
	}else{
    return document.forms['propertyAttributesVOForm'].propertyLRO.value;
    }
}
function setPropertyLRO(lrovalue) {
    document.forms['propertyAttributesVOForm'].propertyLRO.value = lrovalue;
}
function resetPropertyAttributesToDefault() {
    document.forms['propertyAttributesVOForm'].propertyPIN.value = "999999999";
    document.forms['propertyAttributesVOForm'].propertyLRO.value = "80";
}
function resetPropertyPIN() {
    document.forms['propertyAttributesVOForm'].propertyPIN.value = "999999999";
}
function resetPropertyLRO() {
    document.forms['propertyAttributesVOForm'].propertyLRO.value = "80";
}
function setPropertyPINandLRO(pinval,lroval) {
    document.forms['propertyAttributesVOForm'].propertyPIN.value = pinval;
    document.forms['propertyAttributesVOForm'].propertyLRO.value = lroval;
}
function directToHouseView(pinToHouseView) {
	if (pinToHouseView != "") {
		DisplayHouseView(pinToHouseView);
	}
}


 /*************************************************
 *             PROPERTY SEARCH FUNCTIONS
 *
 * Java script functions for the Search Form and the Back to Search Results link
 **************************************************/
var __PROPERTY_SEARCH_FUNCTIONS__;

	function submitSearchBlock(pin){
		var pinStr=pin.toString();
		var block=pinStr.substring(0,5);
		parent.document.forms['propertySearchForm'].pin.value=block;
		parent.document.forms['hiddenSearchForm'].searchType.value ="SEARCH_BY_BLOCK";
		parent.setSearchType('SEARCH_BY_BLOCK');
		parent.submitSearchForm (parent.document);
	}

	function submitSearchForm (document){
		if( validateAllSearchFileds(document) ){
			populateHiddenForm(document);
			//alert("hiddenParams: searchType="+document.forms['hiddenSearchForm'].searchType.value+", lro="+document.forms['hiddenSearchForm'].lro.value+", pcode="+document.forms['hiddenSearchForm'].postalCode.value+", streetNo="+document.forms['hiddenSearchForm'].streetNumber.value+", streetName="+document.forms['hiddenSearchForm'].streetName.value+", streeNumberFrom="+document.forms['hiddenSearchForm'].streetNumberFrom.value+
				//", streetNumberTo="+document.forms['hiddenSearchForm'].streetNumberTo.value +", fname="+document.forms['hiddenSearchForm'].firstName.value+",lastName="+document.forms['hiddenSearchForm'].lastOrCompName.value+", inst="+document.forms['hiddenSearchForm'].instrument.value+",pin="+document.forms['hiddenSearchForm'].pin.value);

			//var uriStr = "/gwhweb/getpropertysearchresults.do";
			//var uriSrch = "searchType="+document.forms['hiddenSearchForm'].searchType.value+"&lro="+document.forms['hiddenSearchForm'].lro.value+
			//"&postalCode="+document.forms['hiddenSearchForm'].postalCode.value+"&streetNumber="+document.forms['hiddenSearchForm'].streetNumber.value+
			//"&streetName="+document.forms['hiddenSearchForm'].streetName.value+"&pin="+document.forms['hiddenSearchForm'].pin.value+
			//"&firstName="+document.forms['hiddenSearchForm'].firstName.value+"&lastOrCompName="+document.forms['hiddenSearchForm'].lastOrCompName.value+
			//"&unitNo="+document.forms['hiddenSearchForm'].unitNo.value+"&instrument="+document.forms['hiddenSearchForm'].instrument.value+
			//"&streetNumberFrom="+document.forms['hiddenSearchForm'].streetNumberFrom.value+"&streetNumberTo="+document.forms['hiddenSearchForm'].streetNumberTo.value;

			//updateTargetHash(uriStr, uriSrch);
			//updateBackLastSearchUri(uriStr + "?" + uriSrch);

            resetPropertyPIN();
            if (searchCounter != null && searchCounter==0){
				submitHiddenForm(document);
				disableSearchButton();
				clearHiddenForm(document);
				searchCounter=searchCounter+1;
			}
		}
		else{
			;
		}
		setTimeout('enableSearchButton();',5000);
		messageCounter();
	}

	function updateBackLastSearchUri(uri)
	{
		parent.document.getElementById("lastSearchUri").value = uri;
	}

	function validateAllSearchFileds (document){
		var searchType=document.forms['hiddenSearchForm'].searchType.value;
		if(searchType =='SEARCH_BY_EXACT_NAME')
			return true;
		if(searchType =='SEARCH_BY_BLOCK'){
			document.forms['hiddenSearchForm'].searchType.value="SEARCH_BY_PIN";
			return true;
		}
		if(searchType=='SEARCH_BY_EXACT_ADDRESS'	){
			document.forms['hiddenSearchForm'].searchType.value="SEARCH_BY_ADDRESS";
			return true;
		}

		if(searchType =='SEARCH_BY_ADDRESS'){
			passStNo= validateSearchFileds('field_stno');
			passStName= validateSearchFileds('field_stname');
			passUnitNo=validateSearchFileds('field_unitno');
			passPCode=validateSearchFileds('field_pcode');
			if(passStNo==false || passStName==false||passUnitNo==false||passPCode==false){return false;}
			else return true;
		}
		if(searchType =='SEARCH_BY_ADDRESS_RANGE'){passFrom= validateSearchFileds('field_stfrom');passTo=validateSearchFileds('field_stto');passStName=validateSearchFileds('field_stname');passPCode=validateSearchFileds('field_pcode');if(passFrom==false || passTo==false || passStName==false||passPCode==false) return false ; else return true;}
		if(searchType =='SEARCH_BY_NAME'){passlname= validateSearchFileds('field_lname');passPCode=validateSearchFileds('field_pcode');if(passlname==false||passPCode==false)return false ; else return true;}
		if(searchType =='SEARCH_BY_PIN'){passpin= validateSearchFileds('field_pin');passPCode=validateSearchFileds('field_pcode'); if(passpin==false||passPCode==false)return false; else return true;}
		if(searchType =='SEARCH_BY_INSTRUMENT'){passinstrument= validateSearchFileds('field_instrument');passPCode=validateSearchFileds('field_pcode'); if(passinstrument==false||passPCode==false) return false ; else return true;}
		if(searchType =='SEARCH_BY_LOT'){passTown= validateSearchFileds('field_select_township');passConc=validateSearchFileds('field_select_concession');passLot=validateSearchFileds('field_select_lot');if(passTown==false || passConc==false || passLot==false) return false ; else return true;}
		//TODO validate search_by_arn
		if(searchType =='SEARCH_BY_ARN')
			return validateSearchFileds('field_arn');
	}

	function validateSearchFileds(field){

   	if(true){ //TODO
   		var passTest='Y'
   		var searchType=document.forms['hiddenSearchForm'].searchType.value;

   		if(field=='field_pcode'){
		 	if((isName(trim(document.forms['propertySearchForm'].postalCode.value)) == -1) ){
		        	document.getElementById("errordiv0").style.display='block';
		        	writeText("errorConsole0", "error", 'Special Characters including !@#$%^&*(,{}|:"<> are not allowed. Please try again.');
			      	//document.getElementById("label0").style.color='#ff0000'
			      	unhighlightLabelErr(document.getElementById("label0"));
		        	var passTest='N';
		    }
		    else{
			 		 writeText("errorConsole0", "error", "");
			     	//document.getElementById("label0").style.color='black';
			     	unhighlightLabelErr(document.getElementById("label0"));
			     	document.getElementById("errordiv0").style.display='none';
			     	var passTest='Y';
			 }
		}

   		if(searchType=='SEARCH_BY_ADDRESS'){

   			//****************** Search Type is Address ***************

	    	if(field=='field_stno'){
	    		if(trim(document.forms['propertySearchForm'].streetNumber.value) =="" ){
			     	document.getElementById("errordiv1").style.display='block';
			     	writeText("errorConsole1", "error", "Please specify a Street Number in the 'streetNumber' field");
			     	//document.getElementById("label1").style.color='#ff0000'
			     	highlightLabelErr(document.getElementById("label1"));
			     	var passTest='N';
			 	}

		 		else if(isNumber(trim(document.forms['propertySearchForm'].streetNumber.value)) == -1){
		        	document.getElementById("errordiv1").style.display='block';
		        	writeText("errorConsole1", "error", 'Letters and Special Characters including !@#$%^&*(,.{}|:"<> are not allowed in the Street Number. Please try again.');
			     	//document.getElementById("label1").style.color='#ff0000'
			     	highlightLabelErr(document.getElementById("label1"));
			     	var passTest='N';
		    	}
		    	else{
			 		 writeText("errorConsole1", "error", "");
			 		 unhighlightLabelErr(document.getElementById("label1"));
			     	//document.getElementById("label1").style.color='black';
			     	document.getElementById("errordiv1").style.display='none';
			     	var passTest='Y';
			 		}
		    }
		 	if(field=='field_stname'){
		 		if((document.forms['propertySearchForm'].streetName.value =="") ){
		        	document.getElementById("errordiv2").style.display='block';
		        	writeText("errorConsole2", "error", "Please specify a 'Street Name'");
			      	//document.getElementById("label2").style.color='#ff0000'
			      	highlightLabelErr(document.getElementById("label2"));
		        	var passTest='N';
		    	}
		    	else if (isName(document.forms['propertySearchForm'].streetName.value)== -1){
		    		document.getElementById("errordiv2").style.display='block';
		        	writeText("errorConsole2", "error", 'Special Characters including !@#$%^&*(,{}|:"<> are not allowed in the Street name. Please try again.');
			      	//document.getElementById("label2").style.color='#ff0000'
			      	highlightLabelErr(document.getElementById("label2"));
		        	var passTest='N';
		    	}
		    	else if ((document.forms['propertySearchForm'].streetName.value.length < 2)){
		    		document.getElementById("errordiv2").style.display='block';
		        	writeText("errorConsole2", "error", 'Street Name must have at least 2 characters. Please try again.');
			      	//document.getElementById("label2").style.color='#ff0000'
			      	highlightLabelErr(document.getElementById("label2"));
		        	var passTest='N';
		    	}
		    	else{
			 		 writeText("errorConsole2", "error", "");
			     	//document.getElementById("label2").style.color='black';
			     	unhighlightLabelErr(document.getElementById("label2"));
			     	document.getElementById("errordiv2").style.display='none';
			     	var passTest='Y';
			 	}
			 }
			 if(field=='field_unitno'){
		 		if((isName(trim(document.forms['propertySearchForm'].unitNo.value)) == -1) ){
		        	document.getElementById("errordiv3").style.display='block';
		        	writeText("errorConsole3", "error", 'Special Characters including !@#$%^&*(,{}|:"<> are not allowed in the Suite #. Please try again.');
			      	//document.getElementById("label3").style.color='#ff0000'
				highlightLabelErr(document.getElementById("label3"));
		        	var passTest='N';
		    	}
		    	else{
			 		 writeText("errorConsole3", "error", "");
			     	//document.getElementById("label3").style.color='black';
				unhighlightLabelErr(document.getElementById("label3"));
			     	document.getElementById("errordiv3").style.display='none';
			     	var passTest='Y';
			 	}
			 }
		    if(passTest=='N'){return false;}
		    else{return true;}
	    }


   		if(searchType =='SEARCH_BY_NAME'){
	   		//*************** Search type is Name ****************
	   		if(field=='field_lname'){
	   			if((document.forms['propertySearchForm'].lastOrCompName.value.length < 2)){
		       	document.getElementById("errordiv4").style.display='block';
		       	writeText("errorConsole4", "error", "Last Name or Company Name must have at least 2 characters. Please try again.");
			      //document.getElementById("label2").style.color='#ff0000'
			      highlightLabelErr(document.getElementById("label2"));
		        passTest='N';
		 	 		}
		 	 		else{
			 		 writeText("errorConsole2", "error", "");
			     //document.getElementById("label2").style.color='black';
			     unhighlightLabelErr(document.getElementById("label2"));
			     document.getElementById("errordiv4").style.display='none';
			     passTest='Y';
			 		}
      	}
      	if(passTest=='N'){return false;}
		    else{return true;}
	   	}


   		if(searchType =='SEARCH_BY_ARN'){
   		//alert('validat arn: '+trim(document.forms['propertySearchForm'].arn.value));
   			if(field=='field_arn'){
   				var arnReg= new RegExp("^\\d{15}$");
   				var match = arnReg.exec(trim(document.forms['propertySearchForm'].arn.value));
   				if(match==null){
   					document.getElementById("errordiv3").style.display='block';
   					writeText("errorConsole3", "error", "Assessment Roll Number must be 15 digits");
   					highlightLabelErr(document.getElementById("label1"));
   					return false;
   				}
   				else{
	   				writeText("errorConsole3", "error", "");
			        unhighlightLabelErr(document.getElementById("label1"));
			    	document.getElementById("errordiv3").style.display='none';
			    	return true;
			    }
   			}
   			return true;
   		}

   		if(searchType =='SEARCH_BY_PIN'){

   			// **********  SearchType is PIN  ********************
	    	if(field=='field_pin'){
	    		p = isPIN(trim(document.forms['propertySearchForm'].pin.value));
	    		if(p == -2){
		        document.getElementById("errordiv3").style.display='block';
		       	writeText("errorConsole3", "error", "Property Identification Number must have 9 digits (i.e. 112660139). Block Number must have 5 digits (i.e. 11266).");
			      //document.getElementById("label1").style.color='#ff0000'
			      highlightLabelErr(document.getElementById("label1"));
		        passTest='N';
		    	}
	    		else if(p == -1){
		        document.getElementById("errordiv3").style.display='block';
		       	writeText("errorConsole3", "error", 'Letters and Special Characters including !@#$%^&*(,.{}|:+-"<> are not allowed in the PIN. Please try again.');
			      //document.getElementById("label1").style.color='#ff0000'
			      highlightLabelErr(document.getElementById("label1"));
		        passTest='N';
		    	}
		    	else{
			 		 writeText("errorConsole3", "error", "");
			     //document.getElementById("label1").style.color='black';
			     unhighlightLabelErr(document.getElementById("label1"));
			     document.getElementById("errordiv3").style.display='none';
			     passTest='Y';
			 		}
		  	}
		  	if(passTest=='N'){return false;}
		    else{return true;}
	   }

		if(searchType =='SEARCH_BY_INSTRUMENT'){
			// **********  SearchType is Instrument  ********************
	    if(field=='field_instrument'){
	    	if((document.forms['propertySearchForm'].instrument.value.length == 0 )){
		       document.getElementById("errordiv3").style.display='block';
		       writeText("errorConsole3", "error", "Please insert a valid value for the Instrument/Plan field");
			     //document.getElementById("label1").style.color='#ff0000'
			     highlightLabelErr(document.getElementById("label1"));
		       passTest='N';
		    }
		    else if(isInstrument(document.forms['propertySearchForm'].instrument.value)== -1){
		     	document.getElementById("errordiv3").style.display='block';
		       	writeText("errorConsole3", "error", 'Special Characters including !@;#$%^&*(,{}|:+-"<> are not allowed in the Instrument/Plan field. Please try again.');
			    //document.getElementById("label1").style.color='#ff0000'
			    highlightLabelErr(document.getElementById("label1"));
		       passTest='N';
		  }
		  else{
			 		 writeText("errorConsole3", "error", "");
			     //document.getElementById("label1").style.color='black';
			     unhighlightLabelErr(document.getElementById("label1"));
			     document.getElementById("errordiv3").style.display='none';
			     passTest='Y';
			 		}
		 }
		 if(passTest=='N'){return false;}
		 else{return true;}
		}
	//************** SearchType is lot *****************
		if(searchType =='SEARCH_BY_LOT'){
			if(field=='field_select_township'){
	    		if(document.forms['propertySearchForm'].select_township.disabled== false&&(document.forms['propertySearchForm'].select_township.value == 0 )){
		       		document.getElementById("errordiv1").style.display='block';
		       		writeText("errorConsole1", "error", "Please select a township");
			     	highlightLabelErr(document.getElementById("label1"));
		       		passTest='N';
		       	}

		  		else{
		  			if(document.forms['propertySearchForm'].select_township.disabled== true){
		  				document.getElementById("errordiv1").style.display='block';
		       			writeText("errorConsole1", "error", "No Townships Available For This LRO");
			     		highlightLabelErr(document.getElementById("label1"));
		       			passTest='N';
		  			}
		  			else{
			 	 		writeText("errorConsole1", "error", "");
			     		unhighlightLabelErr(document.getElementById("label1"));
			     		document.getElementById("errordiv1").style.display='none';
			     		passTest='Y';
			     		}
			 	}
			}
			if(field=='field_select_concession'){
	    		if(document.forms['propertySearchForm'].select_concession.disabled== false&&(document.forms['propertySearchForm'].select_concession.value == 0 )){
		       		document.getElementById("errordiv2").style.display='block';
		       		writeText("errorConsole2", "error", "Please select a concession");
			     	highlightLabelErr(document.getElementById("label2"));
		       		passTest='N';
		    	}
		  		else{
			 	 	writeText("errorConsole2", "error", "");
			     	unhighlightLabelErr(document.getElementById("label2"));
			     	document.getElementById("errordiv2").style.display='none';
			     	passTest='Y';
			 	}
			 }
			 if(field=='field_select_lot'){
	    	 	if(document.forms['propertySearchForm'].select_lot.disabled==false &&(document.forms['propertySearchForm'].select_lot.value == 0 )){
		       		document.getElementById("errordiv3").style.display='block';
		       		writeText("errorConsole3", "error", "Please select a lot");
			     	highlightLabelErr(document.getElementById("label3"));
		       		passTest='N';
		    	}
		  		else{
			 		 writeText("errorConsole3", "error", "");
			     	unhighlightLabelErr(document.getElementById("label3"));
			     	document.getElementById("errordiv3").style.display='none';
			     	passTest='Y';
			 	}
			 }
		 	if(passTest=='N'){return false;}
		 	else{return true;}
		}
	//----------- End lot -------

		if(searchType =='SEARCH_BY_ADDRESS_RANGE'){
			// **********  SearchType is addressRange  ********************

			if(field=='field_stfrom'){
				if(trim(document.forms['propertySearchForm'].streetNumberFrom.value) =="" ){
			     	document.getElementById("errordiv1").style.display='block';
			     	writeText("errorConsole1", "error", "Please specify a Street Number in the 'From' field");
			     	//document.getElementById("label1").style.color='#ff0000'
			     	highlightLabelErr(document.getElementById("label1"));
			     	var passTest='N';
			 	}
			 	else if (isNumber(trim(document.forms['propertySearchForm'].streetNumberFrom.value)) == -1) {
		        	document.getElementById("errordiv1").style.display='block';
		        	writeText("errorConsole1", "error", 'Letters and Special Characters including !@#$%^&*(,.{}|:"<> are not allowed in the From Street Number. Please try again.');
			      	//document.getElementById("label1").style.color='#ff0000'
			      	highlightLabelErr(document.getElementById("label1"));
		        	passTest='N';
		   		}

			 	else{
			 		writeText("errorConsole1", "error", "");
			     	//document.getElementById("label1").style.color='black';
			     	unhighlightLabelErr(document.getElementById("label1"));
			     	document.getElementById("errordiv1").style.display='none';
			     	var passTest='Y';
			 	}
			 }

			 if(field=='field_stto'){
				if (isNumber(trim(document.forms['propertySearchForm'].streetNumberTo.value)) == -1) {
		        	document.getElementById("errordiv2").style.display='block';
		        	writeText("errorConsole2", "error", 'Letters and Special Characters including !@#$%^&*(,.{}|:"<> are not allowed in the To Street Number. Please try again.');
			      	//document.getElementById("label2").style.color='#ff0000'
			      	highlightLabelErr(document.getElementById("label2"));
		        	passTest='N';
		   		}
				else if( parseInt(trim(document.forms['propertySearchForm'].streetNumberTo.value),10) < parseInt(trim(document.forms['propertySearchForm'].streetNumberFrom.value),10) ){
      				document.getElementById("errordiv2").style.display='block';
		  			writeText("errorConsole2", "error", 'To # should be greater than From #. Please try again.');
					//document.getElementById("label2").style.color='#ff0000'
					highlightLabelErr(document.getElementById("label2"));
		   			passTest='N';
     			}
     			else{
			 		writeText("errorConsole2", "error", "");
			  		//document.getElementById("label2").style.color='black';
			  		unhighlightLabelErr(document.getElementById("label2"));
			  		document.getElementById("errordiv2").style.display='none';
			   		passTest='Y';
				}
			}
			if(field=='field_stname'){
		 		if((document.forms['propertySearchForm'].streetName.value =="") ){
		        	document.getElementById("errordiv3").style.display='block';
		        	writeText("errorConsole3", "error", "Please specify a 'Street Name'");
			      	//document.getElementById("label3").style.color='#ff0000'
			      	highlightLabelErr(document.getElementById("label3"));
		        	var passTest='N';
		    	}
		    	else if (isName(document.forms['propertySearchForm'].streetName.value)== -1){
		    		document.getElementById("errordiv3").style.display='block';
		        	writeText("errorConsole3", "error", 'Special Characters including !@#$%^&*(,{}|:"<> are not allowed in the Street name. Please try again.');
			      	//document.getElementById("label3").style.color='#ff0000'
			      	highlightLabelErr(document.getElementById("label3"));
		        	var passTest='N';
		    	}
		    	else if ((document.forms['propertySearchForm'].streetName.value.length < 2)){
		    		document.getElementById("errordiv3").style.display='block';
		        	writeText("errorConsole3", "error", 'Street Name must have at least 2 characters. Please try again.');
			      	//document.getElementById("label3").style.color='#ff0000'
			      	highlightLabelErr(document.getElementById("label3"));
		        	var passTest='N';
		    	}
		    	else{
			 		 writeText("errorConsole3", "error", "");
			     	//document.getElementById("label3").style.color='black';
			     	unhighlightLabelErr(document.getElementById("label3"));
			     	document.getElementById("errordiv3").style.display='none';
			     	var passTest='Y';
			 	}
			 }

	  }//search type adRange

		  if(passTest=='N'){return false;}
		  else{return true;}
	 }//true
//*******************************************************************************************************************************
	return true;
 }

function populateHiddenForm(document){
	// Note : searchType is populated from tab onClick
	document.forms['hiddenSearchForm'].lro.value = document.forms['propertySearchForm'].lro.value;
	document.forms['hiddenSearchForm'].postalCode.value = trim(document.forms['propertySearchForm'].postalCode.value);

	if(document.forms['hiddenSearchForm'].searchType.value=='SEARCH_BY_ADDRESS'){
		document.forms['hiddenSearchForm'].streetNumber.value = trim(document.forms['propertySearchForm'].streetNumber.value);
		document.forms['hiddenSearchForm'].streetName.value = trim(document.forms['propertySearchForm'].streetName.value);
		document.forms['hiddenSearchForm'].unitNo.value=trim(document.forms['propertySearchForm'].unitNo.value);
		document.forms['hiddenSearchForm'].searchType.value='SEARCH_BY_ADDRESS';
	}
	if(document.forms['hiddenSearchForm'].searchType.value=='SEARCH_BY_ADDRESS_RANGE'){
		document.forms['hiddenSearchForm'].streetNumberFrom.value = trim(document.forms['propertySearchForm'].streetNumberFrom.value);
		document.forms['hiddenSearchForm'].streetNumberTo.value = trim(document.forms['propertySearchForm'].streetNumberTo.value);
		document.forms['hiddenSearchForm'].streetName.value = trim(document.forms['propertySearchForm'].streetName.value);
		document.forms['hiddenSearchForm'].searchType.value='SEARCH_BY_ADDRESS_RANGE';
		}
	if(document.forms['hiddenSearchForm'].searchType.value=='SEARCH_BY_NAME'){
		document.forms['hiddenSearchForm'].firstName.value = trim(document.forms['propertySearchForm'].firstName.value);
		document.forms['hiddenSearchForm'].lastOrCompName.value=trim(document.forms['propertySearchForm'].lastOrCompName.value);
		document.forms['hiddenSearchForm'].searchType.value='SEARCH_BY_NAME';
	}
	if(document.forms['hiddenSearchForm'].searchType.value=='SEARCH_BY_PIN'){
		document.forms['hiddenSearchForm'].pin.value = trim(document.forms['propertySearchForm'].pin.value);
		document.forms['hiddenSearchForm'].searchType.value='SEARCH_BY_PIN';
	}
	if(document.forms['hiddenSearchForm'].searchType.value=='SEARCH_BY_ARN'){
		document.forms['hiddenSearchForm'].arn.value = trim(document.forms['propertySearchForm'].arn.value);
		document.forms['hiddenSearchForm'].searchType.value='SEARCH_BY_ARN';
		//for now use pin to search arn
		//document.forms['hiddenSearchForm'].pin.value = trim(document.forms['propertySearchForm'].arn.value);
		//document.forms['hiddenSearchForm'].searchType.value='SEARCH_BY_PIN';
	}
	if(document.forms['hiddenSearchForm'].searchType.value=='SEARCH_BY_INSTRUMENT'){
		document.forms['hiddenSearchForm'].instrument.value = trim(document.forms['propertySearchForm'].instrument.value);
		document.forms['hiddenSearchForm'].searchType.value='SEARCH_BY_INSTRUMENT';
	}
	if(document.forms['hiddenSearchForm'].searchType.value=='SEARCH_BY_EXACT_NAME'){
		document.forms['hiddenSearchForm'].firstName.value = trim(document.forms['propertySearchForm'].firstName.value);
		document.forms['hiddenSearchForm'].lastOrCompName.value=trim(document.forms['propertySearchForm'].lastOrCompName.value);
		document.forms['hiddenSearchForm'].searchType.value='SEARCH_BY_EXACT_NAME';
	}

	if(document.forms['hiddenSearchForm'].searchType.value=='SEARCH_BY_LOT'){
		document.forms['hiddenSearchForm'].township.value = trim(document.forms['propertySearchForm'].select_township.value);
		document.forms['hiddenSearchForm'].concession.value=trim(document.forms['propertySearchForm'].select_concession.value);
		document.forms['hiddenSearchForm'].lot.value=trim(document.forms['propertySearchForm'].select_lot.value) ;//(el.options[el.selectedIndex].text);
		var lotElement = document.getElementById("select_lot");
		if(lotElement && lotElement.disabled==false){
			if (lotElement.value !=0){
				document.forms['hiddenSearchForm'].lotId.value=lotElement.value; // set lot id for submit ready
			}
		}
		document.forms['hiddenSearchForm'].searchType.value='SEARCH_BY_LOT';
	}

}

function submitHiddenForm(document){
	//disableSearchButton();
	document.forms['hiddenSearchForm'].submit();
	document.body.focus();
	//setTimeout("enableSearchButton()",5000);
}

/*
 * Set visibility of Form fields
 */
function setSearchType(type){

	// clear errors
	clearErrors();
	clearTabsSytling();
	// setting the search typ for the hidden form.
	document.forms['hiddenSearchForm'].searchType.value=type;


	if(type=='SEARCH_BY_ADDRESS'){
		var label1 = document.getElementById("label1");
		label1.innerHTML = "street #";
		var label2 = document.getElementById("label2");
		label2.innerHTML = "street name";
		var label3 = document.getElementById("label3");
		label3.innerHTML = "suite #";
		hideAll();
		restoreDisplay("field_stno");
		restoreDisplay("field_stname");
		restoreDisplay("field_unitno");
		setActiveSearchTab('SEARCH_BY_ADDRESS');
	}
	if(type=='SEARCH_BY_ADDRESS_RANGE'){
		var label1 = document.getElementById("label1");
		//	label1.innerHTML = "street # <span class='tiny'>(from)</span>";
		label1.innerHTML = "street # (from)";

		var label2 = document.getElementById("label2");
		//	label2.innerHTML = "street # <span class='tiny'>(to)</span>";
		label2.innerHTML = "street # (to)";

		var label3 = document.getElementById("label3");
		label3.innerHTML = "street name";
		hideAll();
		restoreDisplay("field_stfrom");
		restoreDisplay("field_stto");
		restoreDisplay("field_stname");
		setActiveSearchTab('SEARCH_BY_ADDRESS_RANGE');

	}
	if(type=='SEARCH_BY_PIN'||type=='SEARCH_BY_BLOCK'){
		var label1 = document.getElementById("label1");
		label1.innerHTML = "PIN #";
		var label2 = document.getElementById("label2");
		label2.innerHTML = "";
		var label3 = document.getElementById("label3");
		label3.innerHTML = "";
		hideAll();
		restoreDisplay("field_pin");
		setActiveSearchTab('SEARCH_BY_PIN');
	}
	if(type=='SEARCH_BY_INSTRUMENT'){
		var label1 = document.getElementById("label1");
		label1.innerHTML = "Instrument/Plan #";
		var label2 = document.getElementById("label2");
		label2.innerHTML = "";
		var label3 = document.getElementById("label3");
		label3.innerHTML = "";
		hideAll();
		restoreDisplay("field_instrument");
		setActiveSearchTab('SEARCH_BY_INSTRUMENT');
	}
	if(type=='SEARCH_BY_NAME'){
		var label1 = document.getElementById("label1");
		label1.innerHTML = "First Name";
		var label2 = document.getElementById("label2");
		label2.innerHTML = "Last Name or Corp Name";
		var label3 = document.getElementById("label3");
		label3.innerHTML = "";
		hideAll();
		restoreDisplay("field_fname");
		restoreDisplay("field_lname");
		setActiveSearchTab('SEARCH_BY_NAME');
	}
	if(type=='SEARCH_BY_LOT'){
		var label1 = document.getElementById("label1");
		label1.innerHTML = "TOWNSHIP";
		var label2 = document.getElementById("label2");
		label2.innerHTML = "CONCESSION";
		var label3 = document.getElementById("label3");
		label3.innerHTML = "LOT";
		hideAll();
		restoreDisplay("field_select_township");
		restoreDisplay("field_select_concession");
		restoreDisplay("field_select_lot");
		setActiveSearchTab('SEARCH_BY_LOT');
	}
	if(type=='SEARCH_BY_ARN'){
		var label1 = document.getElementById("label1");
		label1.innerHTML = "ARN #";
		var label2 = document.getElementById("label2");
		label2.innerHTML = "";
		var label3 = document.getElementById("label3");
		label3.innerHTML = "";
		hideAll();
		restoreDisplay("field_arn");
		setActiveSearchTab('SEARCH_BY_ARN');
	}
}
function restoreDisplay(elem) {
	if (document.getElementById(elem)) document.getElementById(elem).style.display='';
}

function hideAll(){
	if (document.getElementById("field_stno")) document.getElementById("field_stno").style.display='none';
	if (document.getElementById("field_unitno")) document.getElementById("field_unitno").style.display='none';
	if (document.getElementById("field_stname")) document.getElementById("field_stname").style.display='none';
	if (document.getElementById("field_instrument")) document.getElementById("field_instrument").style.display='none';
	if (document.getElementById("field_pin")) document.getElementById("field_pin").style.display='none';
	if (document.getElementById("field_stfrom")) document.getElementById("field_stfrom").style.display='none';
	if (document.getElementById("field_stto")) document.getElementById("field_stto").style.display='none';
	if (document.getElementById("field_fname")) document.getElementById("field_fname").style.display='none';
	if (document.getElementById("field_lname")) document.getElementById("field_lname").style.display='none';
	if (document.getElementById("field_select_township")) document.getElementById("field_select_township").style.display='none';
	if (document.getElementById("field_select_concession")) document.getElementById("field_select_concession").style.display='none';
	if (document.getElementById("field_select_lot")) document.getElementById("field_select_lot").style.display='none';
	if (document.getElementById("field_arn")) document.getElementById("field_arn").style.display='none';
}


//*********

function clearform()
{
    document.forms['propertySearchForm'].lro.value ="" ;
	document.forms['propertySearchForm'].postalCode.value = "";
	document.forms['propertySearchForm'].streetNumber.value = "";
	document.forms['propertySearchForm'].streetName.value = "";
	document.forms['propertySearchForm'].pin.value ="" ;
	document.forms['propertySearchForm'].firstName.value = "";
	document.forms['propertySearchForm'].lastOrCompName.value="";
	document.forms['propertySearchForm'].unitNo.value="";
	document.forms['propertySearchForm'].streetNumberFrom.value="";
	document.forms['propertySearchForm'].streetNumberTo.value="";
  window.focus();
}

function clearHiddenForm(document){
	document.forms['hiddenSearchForm'].lro.value ="" ;
	document.forms['hiddenSearchForm'].postalCode.value = "";
	document.forms['hiddenSearchForm'].streetNumber.value = "";
	document.forms['hiddenSearchForm'].streetName.value = "";
	document.forms['hiddenSearchForm'].pin.value ="" ;
	document.forms['hiddenSearchForm'].firstName.value = "";
	document.forms['hiddenSearchForm'].lastOrCompName.value="";
	document.forms['hiddenSearchForm'].unitNo.value="";
	document.forms['hiddenSearchForm'].streetNumberFrom.value="";
	document.forms['hiddenSearchForm'].streetNumberTo.value="";
	//document.forms['hiddenSearchForm'].target="PropertySearchResults";
	//document.forms['hiddenSearchForm'].searchType.value ="" ;
}


 function isDigit(a)
{
	uni = a.charCodeAt(0);
	if((uni>47) && (uni<58))
		return 1;
	return -1;
}

function isNumber(n)
{
  l = n.length;
  for(i = 0 ; i < l; i++)
  {
    c = n.substr(i,1);
    a = isDigit(c);
    if((a == -1))
      return -1;
  }
  return 1;
}

function isRealNumber(n)
{
  l = n.length;
  isDecimalPt = 0;
  for(i = 0 ; i < l; i++)
  {
    c = n.substr(i,1);
    a = isDigit(c);
    if((a == -1) && (c == '.'))
{
	isDecimalPt = isDecimalPt + 1;
}
    if(isDecimalPt > 1)
    {
	return -1;
    }
    if((a == -1) && (c != '.'))
	return -1;
  }

  return 1;
}

function isSpecialChar(n)
{
    switch(n){
        case '!':
        case '@':
        case '#':
        case '$':
        case '%':
        case '^':
        case '&':
        case '*':
        case '(':
        case ',':
//        case '.':
        case '{':
        case '}':
        case '|':
        case ':':
        case '\"':
        case '<':
        case '>':
        case '?': return 1;
    }
    return -1;
}

function isBadCharForInstrument(n)
{
    switch(n){
        case '!':
        case '@':
        case '#':
        case '$':
        case '%':
        case '^':
        case '&':
        case '*':
        case '(':
        case ',':
        case '.':
        case '{':
        case '}':
        case '|':
        case ':':
        case '\"':
        case '\'':
        case '<':
        case ';':
        case '>':
        case '+':
        case '-':
        case '?': return 1;
    }
    return -1;
}

function isName(n)
{
  l = n.length;
  for(i = 0 ; i < l; i++)
  {
    c = n.substr(i,1);
    /*a = isDigit(c);
    if(a==1)
      return -1;*/
    a = isSpecialChar(c);
    if(a == 1)
        return -1;
  }
  return 1;
}

function isInstrument(n)
{
  l = n.length;
  for(i = 0 ; i < l; i++)
  {
    c = n.substr(i,1);
    /*a = isDigit(c);
    if(a==1)
      return -1;*/
    a = isBadCharForInstrument(c);
    if(a == 1)
        return -1;
  }
  return 1;
}
function trim(s)
{
    s1 = "";
    i = 0;
    c = s.substr(i,1);
    while((i < s.length) && (c == " "))
    {
            i = i + 1;
            c = s.substr(i,1);
    }
    s = s.substr(i,s.length-i);

    i = s.length;
    c = s.substr(i-1,1);

    while((i > 0) && ( c == " "))
    {
        i = i -1;
        c = s.substr(i,1);
    }
    s = s.substr(0,i+1);
    return s;
}
String.prototype.trimstr = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

function isPIN(n)
{
  l = n.length;
  for(i = 0 ; i < l; i++)
  {
    c = n.substr(i,1);
    a = isDigit(c);
    if(( a == -1 ) && ( c != ' '))
      return -1;
  }
  if ((l != 9) && (l != 5))
    return -2;
  return 1;
}

function setVal(field,val)
{
    x = eval("document.forms['propertySearchForm']." + field );
    x.value = toHtml(val);
}



function writeText(outputarea, type,errMsg) {
	var message = document.getElementById(outputarea);
	//message.innerHTML = "<tr><td>"+errMsg+"</td></tr>";
	message.innerHTML = errMsg;
	document.getElementById("errdd").style.visibility = 'visible';
	if (type=="error")
		message.style.color="#eb423d";
	else
		message.style.color="#666666";
}

function highlightLabelErr(labelobj) {
	labelobj.style.color='#eb423d';

}

function unhighlightLabelErr(labelobj) {
	labelobj.style.color='#666666';
}
function clearErrors() {
 document.getElementById("errordiv1").style.display='none';
 document.getElementById("errordiv2").style.display='none';
 document.getElementById("errordiv3").style.display='none';
 document.getElementById("errordiv4").style.display='none';
 document.getElementById("errordiv0").style.display='none';
 document.getElementById("label0").style.color='#666666';
 document.getElementById("label00").style.color='#666666';
 document.getElementById("label1").style.color='#666666';
 document.getElementById("label2").style.color='#666666';
 document.getElementById("label3").style.color='#666666';
}

function clearTabsSytling(){
	document.getElementById('SEARCH_BY_ADDRESS').className ="initialtab";
	document.getElementById('SEARCH_BY_ADDRESS').style.backgroundColor ="white";
	document.getElementById('SEARCH_BY_ADDRESS_RANGE').style.backgroundColor="white";
	document.getElementById('SEARCH_BY_NAME').style.backgroundColor="white";
	document.getElementById('SEARCH_BY_PIN').style.backgroundColor="white";
	document.getElementById('SEARCH_BY_INSTRUMENT').style.backgroundColor="white";
	document.getElementById('SEARCH_BY_LOT').style.backgroundColor="white";
	document.getElementById('SEARCH_BY_ADDRESS').style.color ="#000066";
	document.getElementById('SEARCH_BY_ADDRESS_RANGE').style.color="#000066";
	document.getElementById('SEARCH_BY_NAME').style.color="#000066";
	document.getElementById('SEARCH_BY_PIN').style.color="#000066";
	document.getElementById('SEARCH_BY_INSTRUMENT').style.color="#000066";
	document.getElementById('SEARCH_BY_LOT').style.color="#000066";
	document.getElementById('SEARCH_BY_ADDRESS').style.borderTop ="0";
	document.getElementById('SEARCH_BY_ADDRESS').style.borderLeft ="0";
	document.getElementById('SEARCH_BY_ADDRESS_RANGE').style.borderTop="0";
	document.getElementById('SEARCH_BY_NAME').style.borderTop="0";
	document.getElementById('SEARCH_BY_PIN').style.borderTop="0";
	document.getElementById('SEARCH_BY_INSTRUMENT').style.borderTop="0";
	document.getElementById('SEARCH_BY_LOT').style.borderTop="0";

	if(document.getElementById('SEARCH_BY_ARN')!=null){
		document.getElementById('SEARCH_BY_ARN').style.backgroundColor="white";

		document.getElementById('SEARCH_BY_ARN').style.color="#000066";

		document.getElementById('SEARCH_BY_ARN').style.borderTop="0";
		document.getElementById('SEARCH_BY_ARN').style.borderRight="0";
	}else{
		document.getElementById('SEARCH_BY_LOT').style.borderRight="0";
	}
}

function setActiveSearchTab(defaultSearch) {
	var activeTab = document.getElementById(defaultSearch);
	if(activeTab != null)
	{
		activeTab.style.backgroundColor="#61B8C7";
		activeTab.style.color="white";
		activeTab.style.borderTop="1px solid #000066";
		if (defaultSearch == 'SEARCH_BY_ADDRESS') activeTab.style.borderLeft="1px solid #000066";
		if(document.getElementById('SEARCH_BY_ARN')!=null){
			if (defaultSearch == 'SEARCH_BY_ARN') activeTab.style.borderRight="1px solid #000066";
		}else{
			if (defaultSearch == 'SEARCH_BY_LOT') activeTab.style.borderRight="1px solid #000066";
		}
		return defaultSearch;
	}
	else
		if(defaultSearch == 'SEARCH_BY_ARN')
		{
			setActiveSearchTab('SEARCH_BY_ADDRESS');
			return 'SEARCH_BY_ADDRESS';
		} // set SEARCH_BY_ADDRESS as the active tab

}

function updateLroForPin(lro){
	document.forms['propertySearchForm'].lro.value =lro;
	var sl = gwhmap.GetMapInfo().get("selectedlro");
	if(sl!=lro)gwhmap.DisplaySelectedLRO(lro);
}

function updateLroForArn(lro, userDefaulted){

	var sl = document.forms['propertySearchForm'].lro.value;
	//set lro when: 1. ARN has PIN and 2. the current selected one is not the one to be set (either default or pin associated)
	if(sl!=lro && !userDefaulted){
		document.forms['propertySearchForm'].lro.value =lro;
		gwhmap.DisplaySelectedLRO(lro);
	}
}

function updateVisibleForm(jsonCriteria,nullfiedUnitFlag){

	if(jsonCriteria && jsonCriteria !="" && jsonCriteria.searchCriteriaVO){

		var searchType= jsonCriteria.searchCriteriaVO.searchType;  			if(!searchType) searchType="";
  		var lro= jsonCriteria.searchCriteriaVO.lro;  						if(!lro) lro="";
    	var firstName=jsonCriteria.searchCriteriaVO.firstName;  			if(!firstName) firstName="";
  		var lastOrCompName=jsonCriteria.searchCriteriaVO.lastOrCompName;  	if(!lastOrCompName) lastOrCompName="";
    	var pin=jsonCriteria.searchCriteriaVO.pin;  						if(!pin) pin="";
   		var instrument=jsonCriteria.searchCriteriaVO.instrument;  			if(!instrument) instrument="";
   		var postalCode=jsonCriteria.searchCriteriaVO.postalCode;  			if(!postalCode) postalCode="";
  		var streetNumber=jsonCriteria.searchCriteriaVO.streetNumber;  		if(!streetNumber) streetNumber="";
  		var streetName=jsonCriteria.searchCriteriaVO.streetName;  			if(!streetName) streetName="";
  		var streetNumberFrom=jsonCriteria.searchCriteriaVO.streetNumberFrom;if(!streetNumberFrom) streetNumberFrom="";
  		var streetNumberTo=jsonCriteria.searchCriteriaVO.streetNumberTo;  	if(!streetNumberTo) streetNumberTo="";
  		var unitNo=jsonCriteria.searchCriteriaVO.unitNo;  					if(!unitNo) unitNo="";
  		var town=jsonCriteria.searchCriteriaVO.township;					if(!town) 	town="";
  		var conc=jsonCriteria.searchCriteriaVO.concession;					if(!conc) 	conc="";
  		var lot=jsonCriteria.searchCriteriaVO.lot;							if(!lot ) 	lot="";
  		var lotId=jsonCriteria.searchCriteriaVO.lotId;						if(!lotId ) lotId="";
  		var arn=jsonCriteria.searchCriteriaVO.arn;							if(!arn ) arn="";

		if(searchType=='SEARCH_BY_ADDRESS'){
				document.forms['propertySearchForm'].streetNumber.value =streetNumber;
				document.forms['propertySearchForm'].streetName.value = streetName;
				if(nullfiedUnitFlag==true){
					document.forms['propertySearchForm'].unitNo.value="";
				}
				else
					document.forms['propertySearchForm'].unitNo.value=unitNo;
				document.forms['hiddenSearchForm'].searchType.value='SEARCH_BY_ADDRESS';
		}

		if(searchType=='SEARCH_BY_ADDRESS_RANGE'){
				document.forms['propertySearchForm'].streetNumberFrom.value = streetNumberFrom;
				document.forms['propertySearchForm'].streetNumberTo.value =streetNumberTo;
				document.forms['propertySearchForm'].streetName.value =streetName;
				document.forms['hiddenSearchForm'].searchType.value='SEARCH_BY_ADDRESS_RANGE';
		}
		if(searchType=='SEARCH_BY_NAME'){
				document.forms['propertySearchForm'].firstName.value = firstName;
				document.forms['propertySearchForm'].lastOrCompName.value=lastOrCompName;
				document.forms['hiddenSearchForm'].searchType.value='SEARCH_BY_NAME';
		}
		if(searchType=='SEARCH_BY_PIN'){
				document.forms['propertySearchForm'].pin.value =pin;
				document.forms['hiddenSearchForm'].searchType.value='SEARCH_BY_PIN';
		}
		if(searchType=='SEARCH_BY_INSTRUMENT'){
				document.forms['propertySearchForm'].instrument.value = instrument;
				document.forms['hiddenSearchForm'].searchType.value='SEARCH_BY_INSTRUMENT';
		}
		if(searchType=='SEARCH_BY_EXACT_NAME'){
				document.forms['propertySearchForm'].firstName.value =firstName;
				document.forms['propertySearchForm'].lastOrCompName.value=lastOrCompName;
				document.forms['hiddenSearchForm'].searchType.value='SEARCH_BY_NAME';
				searchType='SEARCH_BY_NAME';
		}

		if(searchType=='SEARCH_BY_LOT'){
				document.forms['propertySearchForm'].lro.value =lro;
				filterTownship();
				document.forms['propertySearchForm'].select_township.value =town;
				filterConcession();
				document.forms['propertySearchForm'].select_concession.value=conc;
				filterLot();
				document.forms['propertySearchForm'].select_lot.value=lot;
				document.forms['hiddenSearchForm'].lotId.value=lotId;
				document.forms['hiddenSearchForm'].searchType.value='SEARCH_BY_LOT';
				searchType='SEARCH_BY_LOT';
				gwhmap.DisplaySelectedLOT(lotId,null,getLotDisplayInfo());

		}

		if(searchType=='SEARCH_BY_ARN'){
				document.forms['propertySearchForm'].arn.value =arn;
				document.forms['hiddenSearchForm'].searchType.value='SEARCH_BY_ARN';
		}

		setSearchType(searchType);
	}
}

function disableSearchButton() {
		document.propertySearchForm.searchButton.disabled=true;
		document.propertySearchForm.searchButton.className="formbtn_disabled";
		document.propertySearchForm.searchButton.title='Processing Results...';
}

function enableSearchButton() {
		document.propertySearchForm.searchButton.disabled=false;
		document.propertySearchForm.searchButton.className="formbtn";
		document.propertySearchForm.searchButton.title='Search Properties';
		searchCounter=0;

}

function toHtml (val)
{

    htmlString = val.split("&lt;").join("<");
    htmlString = htmlString.split("&gt;").join(">");
    htmlString = htmlString.split("&quot;").join("\"");
    htmlString = htmlString.split("&apos;").join("\'");
    htmlString = htmlString.split("&amp;").join("\&");

    htmlString = htmlString.split("&#92;&#34;").join("\"");

    htmlString = htmlString.split("&#60;").join("<");
    htmlString = htmlString.split("&#62;").join(">");
    htmlString = htmlString.split("&#34;").join("\"");
    htmlString = htmlString.split("&#034;").join("\"");
    htmlString = htmlString.split("&#39;").join("\'");



    //htmlString = htmlString.split("&#38;").join("%26%2338;");
    htmlString = htmlString.split("&#38;").join("\&");
    htmlString = htmlString.split("%26;").join("\&");
    //htmlString = htmlString.split("&#38;").join("&amp;");
    //htmlString = htmlString.split("%26%2338;").join("\&");

    htmlString = htmlString.split("&#32;").join(" ");
    htmlString = htmlString.split("&#47;").join("\/");
    htmlString = htmlString.split("&#44;").join(",");
    htmlString = htmlString.split("&#63;").join("\?");
    htmlString = htmlString.split("&#35;").join("\#");

    htmlString = htmlString.split("&#37;").join("\%");
    htmlString = htmlString.split("&#40;").join("\(");
    htmlString = htmlString.split("&#41;").join("\)");
    htmlString = htmlString.split("&#43;").join("\+");
    htmlString = htmlString.split("&#59;").join("\;");
    htmlString = htmlString.split("&#39;").join("\'");
    htmlString = htmlString.split("&#92;").join("\\");
    htmlString = htmlString.split("&#96;").join("`");
    htmlString = htmlString.split("&#126;").join("~");
    htmlString = htmlString.split("&#33;").join("!");
    htmlString = htmlString.split("&#64;").join("@");
    htmlString = htmlString.split("&#36;").join("$");
    htmlString = htmlString.split("&#94;").join("^");
    htmlString = htmlString.split("&#42;").join("*");
    htmlString = htmlString.split("&#95;").join("_");  // It is converted to ' in searchSPTemplate.jsp
    htmlString = htmlString.split("&#45;").join("-");
    htmlString = htmlString.split("&#61;").join("=");
    htmlString = htmlString.split("&#123;").join("{");
    htmlString = htmlString.split("&#125;").join("}");
    htmlString = htmlString.split("&#91;").join("[");
    htmlString = htmlString.split("&#93;").join("]");
    htmlString = htmlString.split("&#124;").join("|");
    htmlString = htmlString.split("&#58;").join(":");
    htmlString = htmlString.split("&#46;").join(".");

    htmlString = htmlString.split("&#092;&#034;").join("\"");

    htmlString = htmlString.split("&#060;").join("<");
    htmlString = htmlString.split("&#062;").join(">");
    htmlString = htmlString.split("&#034;").join("\"");
    htmlString = htmlString.split("&#039;").join("\'");



    htmlString = htmlString.split("&#038;").join("\&");
    htmlString = htmlString.split("%26;").join("\&");
    //htmlString = htmlString.split("&#038;").join("&amp;");
    //htmlString = htmlString.split("%26%2338;").join("\&");

    htmlString = htmlString.split("&#032;").join(" ");
    htmlString = htmlString.split("&#047;").join("\/");
    htmlString = htmlString.split("&#044;").join(",");
    htmlString = htmlString.split("&#063;").join("\?");
    htmlString = htmlString.split("&#035;").join("\#");

    htmlString = htmlString.split("&#037;").join("\%");
    htmlString = htmlString.split("&#040;").join("\(");
    htmlString = htmlString.split("&#041;").join("\)");
    htmlString = htmlString.split("&#043;").join("\+");
    htmlString = htmlString.split("&#059;").join("\;");
    htmlString = htmlString.split("&#039;").join("\'");
    htmlString = htmlString.split("&#092;").join("\\");
    htmlString = htmlString.split("&#096;").join("`");
    htmlString = htmlString.split("&#0126;").join("~");
    htmlString = htmlString.split("&#033;").join("!");
    htmlString = htmlString.split("&#064;").join("@");
    htmlString = htmlString.split("&#036;").join("$");
    htmlString = htmlString.split("&#094;").join("^");
    htmlString = htmlString.split("&#042;").join("*");
    htmlString = htmlString.split("&#095;").join("_");  // It is converted to ' in searchSPTemplate.jsp
    htmlString = htmlString.split("&#045;").join("-");
    htmlString = htmlString.split("&#061;").join("=");
    htmlString = htmlString.split("&#0123;").join("{");
    htmlString = htmlString.split("&#0125;").join("}");
    htmlString = htmlString.split("&#091;").join("[");
    htmlString = htmlString.split("&#093;").join("]");
    htmlString = htmlString.split("&#0124;").join("|");
    htmlString = htmlString.split("&#058;").join(":");
    htmlString = htmlString.split("&#046;").join(".");

    return htmlString;
}

function submitBackToSearchResultsForm(document) {
	document.forms['hiddenBackToSearchResultsForm'].submit();
	document.body.focus();
}

function showBackToSearchResultsLink(document) {
	document.getElementById('backtosearchresultsdiv').style.display = "block";
}

function hideBackToSearchResultsLink(document) {
	document.getElementById('backtosearchresultsdiv').style.display = "none";
}

/*
 * Township, Concession, Lot
 */
var CASCHING_LOTS_WS_URL = '/gwhweb/getLotInfo.do';
var TOWNSHIP_SEARCH_TYPE_STRING="?searchType=TOWNSHIP_BY_LRO";
var CONCESSION_SEARCH_TYPE_STRING="?searchType=CONCESSION_BY_TOWNSHIP";
var LOT_SEARCH_TYPE_STRING="?searchType=LOT_BY_CONCESSION";
var TWN_LEN=12;  // THE DESIRED LENGTH OF AN OPTION STRING IN SELECT LISTS.
var CON_LEN=10;
var LOT_LEN=8;
var lot_lNames=new Array();


	function initSelectLists(twn,con,lot){
		var SELECT_DISPLAY="-- SELECT --";
		var townshipElement = document.getElementById("select_township");
   		var concessionElement = document.getElementById("select_concession");
   		var lotElement = document.getElementById("select_lot");
		if(twn){
			while (townshipElement.options.length > 0) {
   			//townshipElement.options.remove(0);
   			townshipElement.options[0] = null;  //cross-browser
	  		}
	  		townshipElement.options.add(new Option(SELECT_DISPLAY,0));
	  		townshipElement.selectedIndex=0;
	  	}
	  	if(con){
	  		while (concessionElement.options.length > 0) {
   			//concessionElement.options.remove(0);
   			concessionElement.options[0] = null;	//cross-browser
	  		}
	  		concessionElement.options.add(new Option(SELECT_DISPLAY,0));
	  		concessionElement.selectedIndex=0;
	  	}
	  	if(lot){
	  		while (lotElement.options.length > 0) {
   			//lotElement.options.remove(0);
   			lotElement.options[0] = null;	//cross-browser
	  		}
	  		lotElement.options.add(new Option(SELECT_DISPLAY,0));
	  		lotElement.selectedIndex=0;
	  	}
	}


	function issueAjaxCall(url){
		var jsonResults="";
		var asXmlHttp = GWH.Ajax.getXmlHttpRequest();
			asXmlHttp.open("GET",url,false);
			asXmlHttp.send(null);
			if (asXmlHttp.readyState == 4) {
				if (asXmlHttp.status == 200||asXmlHttp.status == 0 ){
					try{
						jsonResults = eval('(' + asXmlHttp.responseText + ')');
					}
					catch(e){
				        window.status = 'issueAjax.e.src=' + e.source + '\ne.n=' + e.name + '\ne.m=' + e.message;
					}
				}
			}
			return jsonResults;
	}

	function filterTownship(lroChange){
	if(document.forms['hiddenSearchForm'].searchType.value =='SEARCH_BY_LOT' ){ 	// cause this function called on load also with default lro.
		var townshipElement = document.getElementById("select_township");
		var concessionElement = document.getElementById("select_concession");
   		var lotElement = document.getElementById("select_lot");
		var lroNum=document.getElementById("lro").value;
		if(!lroChange)lroChange=false;
		// Case of preserving search criteria in case lro didn't change.
		if (!lroChange && townshipElement.value!=0 &&lroNum == document.forms['hiddenSearchForm'].searchedLro.value ){
			return;
		}

		else{ // case of nullifying and filter for an lro.
			document.forms['hiddenSearchForm'].searchedLro.value=lroNum; // to check on stale lro
			var townshipJson="";
			initSelectLists(true,true,true);
			var servurl = CASCHING_LOTS_WS_URL + TOWNSHIP_SEARCH_TYPE_STRING+"&lro="+lroNum;
			townshipJson=issueAjaxCall(servurl);
   			if(townshipJson && townshipJson!=""){
   				if(townshipJson.LotInfoResVO.result.length==0){
   					townshipElement.disabled=true;
   					concessionElement.disabled=true;
   					lotElement.disabled=true;
   				}
   				else{
   					townshipElement.disabled=false;
   					concessionElement.disabled=false;
   					lotElement.disabled=false;
   					var len = townshipJson.LotInfoResVO.result.length;
   					var tName;
   					var tsName;
   					var tVal;
   					for (var i = 0; i < len; i++){
   						tName=townshipJson.LotInfoResVO.result[i]
   						tsName= townshipJson.LotInfoResVO.result[i].substring(0,TWN_LEN); // town short name
   						tVal=tName;  // full name needed for search.
             			townshipElement.options.add( new Option(tsName,tVal) );
					}
				}
			}
		}

	 }
	 else{ // search type is not by Lot
	 		return;
	 	}
	}

	function filterConcession(){
		var townshipElement = document.getElementById("select_township");
   		var concessionElement = document.getElementById("select_concession");
   		var lotElement = document.getElementById("select_lot");
		var lroNum=document.getElementById("lro").value;
		var concessionJson="";
		initSelectLists(false,true,true);
	  	if(townshipElement.value !=	0){
	  		var servurl = CASCHING_LOTS_WS_URL + CONCESSION_SEARCH_TYPE_STRING+"&lro="+lroNum+"&township="+escape(townshipElement.value);
	  		concessionJson=issueAjaxCall(servurl);
   			if(concessionJson && concessionJson!=""){
   				//Case Only Township available - result type = TOWNSHIPID.
   				if(concessionJson.LotIdInfoResVO){
   					if (concessionJson.LotIdInfoResVO.resultType=="TOWNSHIPID" ){
   						concessionElement.disabled=true;
   						lotElement.disabled=true;
   						// get the ID now which is for TownGeom.
   						var townId=concessionJson.LotIdInfoResVO.result[0].lotId;
   						document.forms['hiddenSearchForm'].lotId.value=townId;
   						gwhmap.DisplaySelectedLOT(townId,null,getLotDisplayInfo());
   					}
   				}
   				// Case returning Concessions Normally.
   				if(concessionJson.LotInfoResVO){
   					if (concessionJson.LotInfoResVO.resultType=="CONCESSION" && concessionJson.LotInfoResVO.result.length!=0){
   						concessionElement.disabled=false;
   						var len = concessionJson.LotInfoResVO.result.length;
   						var cName;
   						var csName;
   						var cVal;
   						var option
   						for (var i = 0; i < len; i++){
   							cName=concessionJson.LotInfoResVO.result[i]
   							csName=concessionJson.LotInfoResVO.result[i].substring(0,CON_LEN); // town short name
   							cVal=cName;
   							option=	new Option(csName,cVal); // full name for search
   							option.style.fontSize = 4;
             				concessionElement.options.add(option);
   							//tooltip1 = new YAHOO.widget.Tooltip("tooltip1", { context:"" + option.id + "", text:"I'm a tool tip...!" } );
						}
					}
				}
			}
   		}
	}

	function filterLot(){
		var townshipElement = document.getElementById("select_township");
   		var concessionElement = document.getElementById("select_concession");
   		var lotElement = document.getElementById("select_lot");
		var lroNum=document.getElementById("lro").value;
		var lotJson="";
		initSelectLists(false,false,true);
	  	if(concessionElement.value!=0 || townshipElement.value!=0){
	  		var servurl = CASCHING_LOTS_WS_URL + LOT_SEARCH_TYPE_STRING+"&lro="+lroNum+"&township="+escape(townshipElement.value)+"&concession="+escape(concessionElement.value);
	  		lotJson=issueAjaxCall(servurl);
   			if(lotJson && lotJson!=""){
   				if(lotJson.LotIdInfoResVO.result.length==0){
   					lotElement.disabled=true;
   				}
   				else{
   					lotElement.disabled=false;
   					var len = lotJson.LotIdInfoResVO.result.length;
   					var l;
   					var l_shrt;
   					var l_id;
   					var option;
   					for (var i = 0; i < len; i++){
   						l= lotJson.LotIdInfoResVO.result[i].lot; // complete lot name
   						l_shrt=lotJson.LotIdInfoResVO.result[i].lot.substring(0,LOT_LEN); // short lot name (16 chars)
   						l_id=lotJson.LotIdInfoResVO.result[i].lotId;
   						option=	new Option(l_shrt,l_id);//setting option value as the lotId for geom retrieval.
   						lot_lNames[i]=l;
             			lotElement.options.add(option);
             			//tooltip2 = new YAHOO.widget.Tooltip("tooltip2", { context:option.id , text:"I'm a tool tip...!" } );


					}
				}
			}
		}
	}


/*
 * This function assemble the lot info as a string that appears in the mouseover ballon.
 */
	function getLotDisplayInfo(){
	var title = "";
	var tEl = document.getElementById("select_township");

	setSearchType('SEARCH_BY_LOT');
	filterTownship();

   	var cEl = document.getElementById("select_concession"); //document.forms['hiddenSearchForm'].concession.value;
   	var lEl = document.getElementById("select_lot");
   	var cName="";var lName="";var tName="";
	if(cEl.selectedIndex!= -1 && cEl.disabled==false)cName=cEl.options[cEl.selectedIndex].value;
	if(lEl.selectedIndex!= -1 && lEl.disabled==false)lName=lot_lNames[lEl.selectedIndex-1];
	if(tEl.selectedIndex!= -1 && tEl.disabled==false)tName=tEl.options[tEl.selectedIndex].value;
	if(lName!= undefined && lName!="" &&cName!="" &	tName!=""){
		title =  "Lot: "+lName+"<br /><br />" +"Concession: " +cName+"<br /><br />"+"Township: " +tName;
	}
	else if (lName=="" &tName!=""){
		title = "Township: " +tName;
	}
	return title;
}


 /*************************************************
 *          PROPERTY SEARCH RESULTS FUNCTIONS
 **************************************************/
var __PROPERTY_SEARCH_RESULTS_FUNCTIONS__;
function submitSorting(orderBy) {
	parent.updateHash("/gwhweb/getmanipulateddata.do?orderBy="+orderBy+"&action=sort");
	var url="/gwhweb/getmanipulateddata.do";
	document.location.href=url+"?orderBy="+orderBy+"&action=sort";
}
function getSearchCriteriaCache() {
	if (searchCrJsonCache=='none') {
		return "";
	}
	return eval(searchCrJsonCache);
}
function getPageResultsCache(){
	if (searchRsltJsonCache=="" || searchRsltJsonCache=='none') {
		return null;
	}
	return eval(searchRsltJsonCache);
}
function getPropRsltArnJSONCache() {
	if (propRsltArnJsonCache=='null' || propRsltArnJsonCache=='none') {
		return null;
	}
	return eval(propRsltArnJsonCache);
}
function submitSearchExactAddress(streetNum,streetName,suit) {
	parent.submitSearchExactAddress(streetNum, streetName, suit);
}
function submitSearchExactName (ownerName,lro,mun) {
	var nameArray=ownerName.split(", ");
	var lastName=nameArray[0];
	var lastNameMod=lastName.split("/").join("'");
	var firstName=nameArray[1];
	if(!firstName)
		firstNameMod="";
	else
		var firstNameMod=firstName.split("/").join("'");
	parent.document.forms['propertySearchForm'].firstName.value=firstNameMod;
	parent.document.forms['propertySearchForm'].lastOrCompName.value=lastNameMod;
	parent.document.forms['propertySearchForm'].lro.value=lro;
	parent.document.forms['propertySearchForm'].postalCode.value=mun;
	parent.document.forms['hiddenSearchForm'].searchType.value=searchByExactName;
	parent.document.forms['hiddenSearchForm'].target=parent.document.getElementById('PropertySearchResultsID').name;
	parent.submitSearchForm (parent.document);
	//reset search type to search by name.
	parent.document.forms['hiddenSearchForm'].searchType.value=searchByName;
}
function isNullifiedUnitNo() {
	return isNullifiedUnitNum;
}


 /*************************************************
 *          PROPERTY SEARCH HELP FUNCTIONS
 **************************************************/
var __PROPERTY_SEARCH_HELP_FUNCTIONS__;

function hideSearchHelpDetails() {
	hideMoreDetails("searchByAddressMoreLink", "searchByAddressDetails");
	hideMoreDetails("searchByAddressRangeMoreLink", "searchByAddressRangeDetails");
	hideMoreDetails("searchByNameMoreLink", "searchByNameDetails");
	hideMoreDetails("searchByPINMoreLink", "searchByPINDetails");
	hideMoreDetails("searchByInstrumentMoreLink", "searchByInstrumentDetails");
	hideMoreDetails("mapViewControlMoreLink", "mapViewControlMoreDetails");
	hideMoreDetails("mapFeaturesMoreLink", "mapFeaturesMoreDetails");
	hideMoreDetails("mapSelectPropertyMoreLink", "mapSelectPropertyMoreDetails");
}

function showMoreDetails(moreLinkId, searchDetailId) {
	document.getElementById(moreLinkId).style.display = "none";
	document.getElementById(searchDetailId).style.display = "inline";
}

function hideMoreDetails(moreLinkId, searchDetailId) {
	document.getElementById(moreLinkId).style.display = "inline";
	document.getElementById(searchDetailId).style.display = "none";
}


 /*************************************************
 *               PROPERTY FUNCTIONS
 **************************************************/
var __PROPERTY_FUNCTIONS__;

function updateHash(newhash) {
	if(!newhash || !newhash.length || newhash.length==0) return;
 	if(newhash.indexOf("#")!=0) newhash = "#"+newhash;
	if(window.location.hash!=newhash) window.location.hash = newhash;
};


var selectProperty = (function() {
	var ver = 'v0.4';	// debug time variable
	var currElem;
	
	// if (console) console.log('In selectProperty - Constructing  selectProperty closure...');

	return function(e, elem, isOver) {
		var relTarg = e.relatedTarget || (isOver ? e.fromElement : e.toElement);
	
		// if (console) console.log('In selectProperty - processing: ', (isOver ? 'MouseOver' : 'MouseOut:'), 'relTarg: [' + (relTarg ? relTarg.className : 'no relTarg') + '], isOver=' + isOver + ', elem.id=' + elem.id);
		//alert ("Select Prop just called...");
		if (isOver) {
			if (!currElem || elem.id != currElem.id) {
				// if (console) console.log('In selectProperty - processing new PIN: currElem.id=' + (currElem ? currElem.id : '[no currElem]') + ', elem.id=' + elem.id);
				if (currElem) {
					hiliteProperty(currElem, true);	// de-highlight the previous
				}
				hiliteProperty(elem, true);
				currElem = elem;
			} else {
				// if (console) console.log('In selectProperty - still inside SAME div, id: ' + (elem ? elem.id : '[no element]') + ', isOver=' + isOver);
			}
		} else {
   			// alert('Mouseout of element: [' + elem.id + '], currElem.id=[' + (currElem ? currElem.id : 'currElem undefined') + ']');
		    if (!e) var e = window.event;
		    if (e) e.cancelBubble = true;
		    if (e.stopPropagation) e.stopPropagation();
    		if (currElem && elem && elem.id == 'searchresultcont') {
    			hiliteProperty(currElem, true);	// de-highlight the previous
    			currElem = null;
    		}
			// alert('Mouseout: relTarg.className=[' + (relTarg ? relTarg.className : 'undefined') + ']');
		}
	};
})();


function hiliteProperty(curel, onmap) {

	var pin = curel.id.substring(2);

	// if (console) console.log('In hiliteProperty - processing pin=' + pin + ', onmap=' + onmap + ', curel.className=[' + curel.className + ']');
	
	var links1 = document.getElementById("prodlinks1_"+pin);
	var links2 = document.getElementById("prodlinks2_"+pin);
	var hilite;
	if(curel.className=='sprdivmouseover'){
		curel.className='sprdivmouseout';
		
		if(onmap){
			if ( BrowserDetect.browser == 'Explorer' ) {
				if(links1)links1.style.display = "block";
				if(links2)links2.style.display = "block";
			} else {
				if(links1)links1.style.display = "table-row";
				if(links2)links2.style.display = "table-row";
			}
			hilite = false;
		}
	} else {
		curel.className='sprdivmouseover';
		//hilitedPin=pin;
		if(onmap){
			if ( BrowserDetect.browser == 'Explorer' ) {
				if(links1)links1.style.display = "block";
				if(links2)links2.style.display = "block";
			} else {
				if(links1)links1.style.display = "table-row";
				if(links2)links2.style.display = "table-row";
			}
		}
		hilite = true;
	}
	try {
		if (onmap) {
			// if (console) console.log('In hiliteProperty - calling parent.toggleMapHilightProperty', 'pin=' + pin + ', hilite=' + hilite);
			parent.toggleMapHilightProperty(pin, hilite, GWH.Util.Constants.SEARCH_RESULT);
		}
	} catch (e) { 
		// if (console) console.error('Exception calling toggleMapHilightProperty: ' + e.message);
	}
}



 /*************************************************
 *           PROPERTY DETAILS FUNCTIONS
 **************************************************/
var __PROPERTY_DETAILS_FUNCTIONS__;

function propDtlsOnLoadHandler(deepLinkSearchByARN, pageType, bannerAdAccess, municipality) {
    parent.setPropertyPINandLRO(subjectPin, subjectLro);

    if (deepLinkSearchByARN=='true'&& getPropRsltArnJSONCache() != null) {
		parent.DisplayArnSearchResultsOnMapForSearchByARN(getPropRsltArnJSONCache(), getPageResultsCache());
    } else {
		parent.DisplaySubjectPropertyMap(subjectPin, getPropDtlsJSONPropertyCache());
	}
	parent.document.forms['propertySearchForm'].lro.value=subjectLro;
	parent.directToHouseView(pinToHouseView);
	if (updateReportCtr) updateReportCounter();
	//parent.resizeIFrameDoc('propdtlsdivwrapper');
	onParentWindowResize();
	
	var	rightcolumnDiv = parent.document.getElementById('rightcolumn');
	//console.debug('rightcolumnDiv.offsetHeight = ' + rightcolumnDiv.offsetHeight);
	var propdtlsdivwrapperDiv = document.getElementById('propdtlsdivwrapper');
	//console.debug('propdtlsdivwrapperDiv.style.height = ' + propdtlsdivwrapperDiv.style.height);
	//if (propdtlsdivwrapperDiv)
	//{
	//	propdtlsdivwrapperDiv.style.height= rightcolumnDiv.style.height;
	//	propdtlsdivwrapperDiv.style.overflow='auto';
	//}
	parent.document.title = document.title;
	parent.updateTargetHashLoc(window.location, true);
	if(parent.gwhmap && parent.gwhmap.RepositionLayerControl){
		parent.gwhmap.RepositionLayerControl();
	}
	if (bannerAdAccess=='true') retrieveBannerAd(pageType, municipality);
}
function updateReportCounter() {
	parent.GWH.Ajax.getReportCount(3000, 1, 2000);
}
function getPropDtlsJSONPropertyCache() {
	if(propDtlsJsonCache=='none'){
		return null;
	}
	return eval(propDtlsJsonCache) ;
}
var conduitWnd;
function openConduitWindow(conduitUrl) {
	if (conduitWnd != null) {
		if(conduitWnd.closed == true) {
			conduitWnd = window.open(conduitUrl,"CONDUIT","height=660,resizable=yes, screenX=50, screenY= 50, width=850,scrollbars=yes, status=no,toolbar=no,menubar=no,location=no,titlebar=0");
		} else {
			setTimeout('conduitWnd.focus();',250);
		}
	} else {
		conduitWnd = window.open(conduitUrl,"CONDUIT","height=660,resizable=yes, screenX=50, screenY= 50, width=850,scrollbars=yes,status=no,toolbar=no,menubar=no,location=no,titlebar=0");
    	setTimeout('conduitWnd.focus();',250);
	}
}



 /*************************************************
 *           NEIGHBOURHOOD SALES FUNCTIONS
 **************************************************/
var __NEIGHBOURHOOD_SALES_FUNCTIONS__;

function initNSales(swfVersion, pageType, bannerAdAccess, municipality) {
	initNSalesFlashComponent(swfVersion);
	parent.updateTargetHashLoc(window.location, true);
	if (bannerAdAccess=='true') retrieveBannerAd(pageType, municipality);
	onParentWindowResize();
/*  [VT] This was removed in GSV/Ads project and reappeared after merging with Appraisers.
 *  It fixed again - see NeighbourhoodSales.jsp
 *  It can be removed after verifying and fixing adjustment-related bugs in the NS page.
	var iframeHeight = 500;
	if (swfVersion == "appraisers") {
		iframeHeight = 670;
	}
	if (window.console) console.log('[initNSales]: about to invoke resetIframeHeight() - iframeHeight=%s', iframeHeight);
	parent.resetIframeHeight('PropertySearchResultsID', iframeHeight, 'swfdiv');
	if (window.console) console.log('[initNSales]: back from resetIframeHeight(...)');
*/
}
function initNSalesFlashComponent(swfVersion) {
  if (hasAccessToNSalesProduct) {
	parent.DisplayInitialNhoodMap(nsInitVOPin, getNSalesJSONPropertyCache());
	// Globals
	// Major version of Flash required
	var requiredMajorVersion = 9;
	// Minor version of Flash required
	var requiredMinorVersion = 0;
	// Minor version of Flash required
	var requiredRevision = 28;

	// Version check for the Flash Player that has the ability to start Player Product Install (6.0r65)
	var hasProductInstall = DetectFlashVer(6, 0, 65);

	// Version check based upon the values defined in globals
	var hasRequestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);

	if (hasProductInstall && hasRequestedVersion) {
		// if we've detected an acceptable version
		// embed the Flash Content SWF when all tests are passed
		var nsSwf = "";
		if (isQTPSession) {
			if (swfVersion == 'standard') {
				nsSwf = "flex/nsales/NeighbourhoodSalesQTP";
			} else if (swfVersion == 'appraisers') {
				nsSwf = "flex/nsales/NeighbourhoodSalesAppraisersQTP";
			}
		} else {
			if (swfVersion == 'standard') {
				nsSwf = "flex/nsales/NeighbourhoodSales";
			} else if (swfVersion == 'appraisers') {
				nsSwf = "flex/nsales/NeighbourhoodSalesAppraisers";
			}
		}

		var nsParams = "lro=" + nsInitVOLro + "&pin=" + nsInitVOPin + "&area=" + nsInitVOArea + 
						"&defaultDateRange=" + nsInitVODefDateRange + "&defaultStartDate=" + nsInitVODefDateRangeFrom + "&defaultEndDate=" + nsInitVODefDateRangeTo + 
						"&defaultMinValue=" + nsInitVODefMinPriceVal + "&defaultMaxValue=" + nsInitVODefMaxPriceVal + "&defaultSearchRadius=" + nsInitVODefSearchRadius + 
						"&defaultSpatialSearchType=" + nsInitVODefSpatialSearchType +
						"&defaultPropertyType=" + nsInitVODefPropType + "&hasAccessToNeighbourhoodSalesResult=" + hasAccessToNSalesResult + 
						"&isCondo=" + isCondo + "&spatialDataAvailable=" + spatialDataAvailable + "&clientMode=" + swfVersion + 
						"&defaultTotalAreaFrom=" + nsInitVODefBuildTotalAreaFrom + "&defaultTotalAreaTo=" + nsInitVODefBuildTotalAreaTo + 
						"&defaultLotSizeToleranceFrom=" + nsInitVODefLotSizeToleranceFrom + "&defaultLotSizeToleranceTo=" + nsInitVODefLotSizeToleranceTo + 
						"&defaultYearBuiltFrom=" + nsInitVODefYearBuiltFrom + "&defaultYearBuiltTo=" + nsInitVODefYearBuiltTo + "&defaultPropertyTypeMpac=" + nsInitVODefPropTypeMpac +
						"&defaultPropertyCodeList=" + nsInitVODefPropCodeList + "&defaultMunicipalityList=" + nsInitVODefMunicipalityList +
						"&defaultSelectedPropertyCodeList=" + nsInitVODefSelectedPropCodeList + "&defaultSelectedMunicipalityList=" + nsInitVODefSelectedMunicipalityList +
						"&defaultAssessedMinValue=" + nsInitVODefMinAssessedVal + "&defaultAssessedMaxValue=" + nsInitVODefMaxAssessedVal + 
						"&maxCompsCountInReport=" + nsMaxCompsCountInReport + "&maxCompsCountInReportReachedErrorMessage=" + nsMaxCompsCountInReportReachedErrorMsg +
						"&licenseMaxLimit=" + nsLicenseMaxLimit + "&reportsPurchased=" + nsReportsPurchased + "&reportsViewed=" + nsReportsViewed;
						
		AC_FL_RunContent(
			"src", nsSwf,
			"FlashVars", nsParams,
			"width", "100%",
			"height", "100%",
			"align", "middle",
			"id", "nsSwfClient",
			"quality", "high",
			"bgcolor", "#ffffff",
			"name", "nsSwfClient",
			"wmode", "transparent",
			"allowScriptAccess","sameDomain",
			"type", "application/x-shockwave-flash",
			"pluginspage", "http://www.adobe.com/go/getflashplayer"
		);
	} else {	//cannot detect the plugin
		var alternateContent = FlashPlayerNotAvailable("Neighbourhood Sales", "Neighbourhood Sales tab", true);  // insert non-flash content
	}
	parent.setPropertyPIN(nsInitVOPin);
  }
  parent.document.title = document.title;
  parent.document.forms['propertySearchForm'].lro.value=nsInitVOLro;
}

/* Hide or show NS pin*/
function NeighbourhoodSale(pin,hideshowflag){
    parent.toggleNhoodPropertyPin(pin, hideshowflag);     //pin is PIN, hideshowflag is a boolean value (true or false )
}

function getNSalesJSONPropertyCache() {
	if(nSalesJsonCache=='none'){
		return null;
	}
	return eval(nSalesJsonCache);
}
function displayNeighbourhoodSalesOnMap(nsJSONData){
	if (nsJSONData && (nsJSONData != 'none' )) {
		parent.DisplayNeighbourhoodSalesOnMap(nsInitVOPin, eval('(' + nsJSONData + ')'));
	}
}
//when a NHood Sales search results record is highlighted (mouse over DataGrid row) or un-highlighted (mouse out DataGrid row)
function highlightPropertyPushPinOnMap(pin, hideShowFlag){
	//alert("in highlightPropertyPushPinOnMap()...pin = " + pin + ", hideShowFlag = " + hideShowFlag);
    //parent.toggleHilightNhoodProperty(pin, hideShowFlag);
    parent.toggleMapHilightProperty(pin, hideShowFlag, GWH.Util.Constants.NHOOD_RECORD);
}

//when the user un-checks (un-selects) a property from the NHood Sales table (or re-selects a previously un-selected property)
function togglePropertyPushPinOnMap(pin, hideShowFlag){
	//alert("in togglePropertyPushPinOnMap()...pin = " + pin + ", hideShowFlag = " + hideShowFlag);
    //parent.toggleNhoodPropertyPin(pin, hideShowFlag);
}

function setCurrentRadiusOnMap(pin, currentRadius){
	//alert("in setCurrentRadiusOnMap()...pin = " + pin + ", currentRadius = " + currentRadius);
	currentRadius = currentRadius.replace("_", "");
	currentRadius = currentRadius.replace("m", "");
	parent.DisplayNeighbourhoodBufferOnMap(pin, currentRadius);
}
function hideSearchRadiusOnMap() {
	parent.gwhmap.HideNeighbourhoodBufferOnMap();
}
function EnableSelectPolygon() {
	hideSearchRadiusOnMap();
	parent.gwhmap.EnableSelectPolygon();
}
function DisableSelectPolygon() {
	parent.gwhmap.DisableSelectPolygon();
}
function RetrievePolygonPoints() {
	var latlongPts = parent.gwhmap.RetrievePolygonPoints();
    var nsSwfClient = document.getElementById("nsSwfClient");

	//alert("PIN area=" + nsInitVOArea + ",polyArea=" + parent.gwhmap.polygonAreaM2);
	if ((nsInitVOArea >= 5000 && parent.gwhmap.polygonAreaM2 >= Math.PI * 5000 * 5000) ||
	    (nsInitVOArea < 5000 && parent.gwhmap.polygonAreaM2 >= Math.PI * 1000 * 1000) ) {
		
		// alert("Selected polygon is too large.\nPlease select a smaller polygon for search.");
		// nsSwfClient.setSearchPolygonPoints(null);
		// This approach is now aligned with other checks related to the polygon - see RetrievePolygonPoints in gwmap.js
		nsSwfClient.setSearchPolygonPoints("ERROR:The selected polygon is too large. Please mark a polygon covering a smaller area.");
	} 
	else {
		nsSwfClient.setSearchPolygonPoints(latlongPts);
	}
}
function LogWebActivityPolygonPoints(latlongPts) {
	//alert('log web activity');
}
function submitNSalesPolygon() {

	var url = "/gwhweb/neighbourhoodsalesresults.do?" +
				"rbDateRangeFixed=false&pin=" + nsInitVOPin + "&countOnly=false&search=Search&propertyType=ALL&requestToken=3410000000&saveAsDefault=false&minAssessedValue=200000&maxValue=800000&clientMode=appraisers&lotSizeTolerance=ALL&totalAreaFrom=0&minValue=0&yearBuiltTo=2011&rbDateRange=true&startDate=2004%2D03%2D01&endDate=2005%2D12%2D01&totalAreaTo=5000&propertyTypeMpac=ALL&rbMunicipality=false&rbSearchRadius=false&yearBuiltFrom=1950&block=07513&maxAssessedValue=800000&lro=80&rbSearchPolygon=true&searchPolygonPoints="
				+ parent.gwhmap.RetrievePolygonPoints();
	
    return url;
}
function updateReportCounter() {
	//alert("in updateReportCounter()...");
	parent.GWH.Ajax.getReportCount(3000, 1, 2000);
}
function isNSalesSearchDone(searchPIN) {
	//alert("in isNSalesSearchDone()...searchPIN = " + searchPIN);
	parent.nSalesSearchDone = searchPIN;
}
function synchronizeOnlineAndReportPINs(pin, excludedPINs, sortColumn, sortOrder) {
	//alert("in synchronizeOnlineAndReportPINs()...");
	var asXmlHttp = GWH.Ajax.getXmlHttpRequest();
	var serverURL = "/gwhweb/report/NSCustomSetting.jsp?pin=" + pin + "&pinList=" + excludedPINs + "&excluded=true" + "&sortColumn=" + sortColumn + "&sortOrder=" + sortOrder;
	asXmlHttp.open("GET", serverURL, false);
	asXmlHttp.send(null);

	if (asXmlHttp.readyState == 4) {
		if (asXmlHttp.status == 200||asXmlHttp.status == 0 ) {
			try {
				var responseText = asXmlHttp.responseText
				return responseText;
			} catch(e) {
				return "error " + e.source + '\e.name=' + e.name + '\e.message=' + e.message;
			}
		} else {
			return "error with status " + asXmlHttp.status;
		}
	} else {
		return "error with state " + asXmlHttp.readyState;
	}
}
function verifyValidSession() {
	//alert("in verifyValidSession()...");
	var asXmlHttp = GWH.Ajax.getXmlHttpRequest();
	var serverURL = "/gwhweb/SessionTimeoutChecker.jsp";
	asXmlHttp.open("GET", serverURL, false);
	asXmlHttp.send(null);

	if (asXmlHttp.readyState == 4) {
		if (asXmlHttp.status == 200||asXmlHttp.status == 0 ) {
			try {
				var responseText = asXmlHttp.responseText;
				var expi_prefix = expiPrefix;
				var expi_suffix = expiSuffix;
				var expi = expi;
				var curr = curr;
				var temp = responseText.substring(0, responseText.indexOf(expi_prefix));
				responseText = responseText.substring(temp.length + expi_prefix.length, responseText.indexOf(expi_suffix));
				if (responseText == expi) {
					var replaceurl = commErrUrl + noActSession + '&fullScreen=true';
					parent.location.replace(replaceurl);
					return expi;
				} else {
					return curr;
				}
			} catch(e) {
				return "error " + e.source + '\e.name=' + e.name + '\e.message=' + e.message;
			}
		} else {
			return "error with status " + asXmlHttp.status;
		}
	} else {
		return "error with state " + asXmlHttp.readyState;
	}
}


// show Dialog with wait indicator
function addPINsToCompsReport(subjectPin, compIds){
	var url = "arnCompsReport/initReportList.do";
	var params = 'subjectPropertyIdentifier.pin=' + encodeURIComponent(subjectPin) + '&ids=' + encodeURIComponent(compIds);
	getMainWindow(window).submitToCompsReportListDialog(url, params);
}

function addComparableToReport(pin, arn) {
	return addPINsToCompsReport('', "{source:[{pin:'"+pin+"',arn:'"+arn+"'}]}");
}

var compsReportListDialog = null;

function submitToCompsReportListDialog(url, params){

    if (compsReportListDialog){
        compsReportListDialog.hide();
        compsReportListDialog.destroy();
    }
    
    compsReportListDialog = new YAHOO.widget.Dialog("wait", {
            width: "380px",
            fixedcenter: true,
            close: true,
            draggable: true,
            zindex:1000,
            modal: true,
            visible: false }
    ); 
    
   compsReportListDialog.setHeader("SELECT COMPARABLES REPORT");
   compsReportListDialog.setBody("<div id='compsReportDialogContent' class='popupDialog' style='text-align:center'><img src='images/busy1.gif' style='vertical-align: middle;'/> Loading ...</div>");
   compsReportListDialog.render(document.body);
   compsReportListDialog.show(); 

    // make an AJAX call and replace wait indicator with retrieved HTML content
	YAHOO.util.Connect.asyncRequest('POST', url, new AjaxCallback(compsReportListDialog, 'compsReportDialogContent'), params);
}

function AjaxCallback(dialog, targetContentId) {
	this.targetContentId = targetContentId;
	this.success = function(o) {
		  updateReportCounter();
	      var container = document.getElementById(this.targetContentId);
	      container.innerHTML =  o.responseText;

	      dialog.center();
	      
	      //fix for the issue where popup shows login page when session expired.
	      //According to fix popup will not show login screen instead parent window will be redirected to login screen.
	      var loginForm = document.getElementById('form1');
	      if(loginForm){
	       var loginAction = loginForm.action;
			if(loginAction.indexOf('/login/auth.do') > 0){
			  dialog.hide();
		      window.location.reload();
			}
	      }

	      var nodes = container.getElementsByTagName("CODE");
	      if (nodes) {
	      	for(var i=0; i<nodes.length; i++) {
		      	if (nodes[i].title == 'JavaScript-base64') {
		      		var decodedScript = decode64(nodes[i].innerHTML);
		      		evalJS(decodedScript);
	      		}
	      	}
	      }
	}
	this.failure = function(o) {
	      var errorMsg="<div style='color:red'>AJAX call failed to retrieve data. Please reload the page and try again.</div>";
	      document.getElementById(this.targetContentId).innerHTML = errorMsg;
	}   
}
/**
 * evaluates javascriptText, properly adds/overrides functions defined in javascriptText
 */
function evalJS(javascriptText){
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.text =javascriptText
    document.getElementsByTagName('head')[0].appendChild(script);     
}
 

var newCompsReportDialog = null;

function showCreateNewReportDialog(params){
	if (newCompsReportDialog) {
		newCompsReportDialog.hide();
		newCompsReportDialog.destroy();
	} 
	newCompsReportDialog = new YAHOO.widget.Dialog("newCompsReportDialog",  
                                               { width: "580px", 
                                                 fixedcenter: true, 
                                                 close: true, 
                                                 draggable: true, 
                                                 zindex:1000,
                                                 modal: true,
                                                 visible: false
                                               } 
                                           );

    var header = "Create a New Comparables Report for Subject Property";

	newCompsReportDialog.setHeader(header);
	newCompsReportDialog.setBody("<div id='newCompsReportDialogContent' class='popupDialog' style='text-align:center'><img src='images/busy1.gif' style='vertical-align: middle;'/> Loading ...</div>");
	newCompsReportDialog.render(document.body);
	newCompsReportDialog.show();
	newCompsReportDialog.center();
	var url = 'newCompsReport.do';
	var method = params.indexOf('ok=') != -1 ? "POST" : "GET";
	if (method == 'GET') {
		url += '?' + params;
	}
	YAHOO.util.Connect.asyncRequest(method, url, new AjaxCallback(newCompsReportDialog, 'newCompsReportDialogContent'), params);
}

function compsNewReportAction(showCompsReport){
	form = document.forms['compsNewReportForm'];
	form.action = 'arnCompsReport/addToNewReport.do';

	var params = "report_name=" + encodeURIComponent(form.report_name.value) + "&client_name=" + encodeURIComponent(form.client_name.value) + "&job_number=" + encodeURIComponent(form.job_number.value) + "&comments=" + encodeURIComponent(form.comments.value);
	//alert(params);
	//params = encodeURIComponent(params);

    // make an AJAX call to create an empty report
	var callback = {
		success: function(o) {
			document.getElementById('errdiv').style.display = "none";
			document.getElementById('createrptprogressdiv').style.display = "none";
			var newReportId = trim(o.responseText);
			if (newCompsReportDialog) newCompsReportDialog.hide();
			if (compsReportListDialog) compsReportListDialog.hide();
			if (showCompsReport) {
				parent.submitToIFrame("PropertySearchResultsID", "compsReport/viewCustomReport.do", "report_id=" + newReportId + "&pin=" + form.subject_pin.value);		
			}
	   },
		failure: function(o) {
			document.getElementById('createrptprogressdiv').style.display = "none";
			document.getElementById('errdiv').style.display = "block";
			var errorMsg="<div style='color:red;width:100%;' align='center'>An error occurred while creating a new report.<br/>Please try again.</div>";
			document.getElementById('errdiv').innerHTML = errorMsg;
	   }
	}

	document.getElementById('errdiv').style.display = "none";
	document.getElementById('createrptprogressdiv').style.display = "block";
	var createNewRptTrans = YAHOO.util.Connect.asyncRequest('POST', form.action, callback, params);
}

 /*************************************************
 *           DEMOGRAPHICS FUNCTIONS
 **************************************************/
var __DEMOGRAPHICS_FUNCTIONS__;


/*
 *	Used by:
 *		demographics/Demographics.jsp
 *
 *	Usage:
 *	- Initialize demographics flash component
 */
function initDemographicsFlashComponent() {
	if (hasAccessToDemographics) {
		// Version check for the Flash Player that has the ability to start Player Product Install (6.0r65)
		var hasProductInstall = DetectFlashVer(6, 0, 65);
		// Version check based upon the values defined in globals
		var hasRequestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);

		if (hasProductInstall && hasRequestedVersion) {
			// if we've detected an acceptable version
			// embed the Flash Content SWF when all tests are passed

			var theLink = "";

			if (isQTPSession) {
			theLink = "flex/demographics/DemographicsMainQTP";
			}
			else {
			theLink = "flex/demographics/DemographicsMain";
			}

			var theParams = "postalCode=" + propertyPostalCode + "&pin=" + propertyPIN + "&serviceURL=" + serviceURL + "&servletURL=" + servletURL;

			AC_FL_RunContent(
			"src",
			theLink,
			"FlashVars", theParams,
			"width", "100%",
			"height", "100%",
			"align", "left",
			"id", "DemographicsMain",
			"quality", "high",
			"bgcolor", "#ffffff",
			"name", "DemographicsMain",
			"wmode", "transparent",
			"allowScriptAccess","allways",
			"type", "application/x-shockwave-flash",
			"pluginspage", "http://www.adobe.com/go/getflashplayer"
			);
		} else {	//cannot detect the plugin
			var alternateContent = FlashPlayerNotAvailable("Demographics", "Demographics tab", true);  // insert non-flash content
		}
		parent.setPropertyPIN(propertyPIN);
	}
	parent.document.title = document.title;
	parent.document.forms['propertySearchForm'].lro.value = propertyLRO;
}


/*
 *	Used by:
 *		demographics/Demographics.jsp
 *
 *	Usage:
 *	- Using AJAX to update the report counter
 *
 *	Note:
 *	- This function can actually removed, as nobody is using it
 */
function updateCounterWrapper(){
	parent.GWH.Ajax.getReportCountDefault();
}

 /*************************************************
 *             ASSESSMENT (ARN) FUNCTIONS
 **************************************************/
var __ASSESSMENT_FUNCTIONS__;

function hiliteARN(curel,onmap){
	var links1 = document.getElementById("prodlinks1_"+curel.id);
	var links2 = document.getElementById("prodlinks2_"+curel.id);
	var hilite;
	if(curel.className=='sprdivmouseover'){
		curel.className='sprdivmouseout';
		if(onmap){
			if(links1)links1.style.display = "block";
			if(links2)links2.style.display = "block";
			}
		hilite = false;
		}
	else {
		curel.className='sprdivmouseover';
		if(onmap){
			if(links1)links1.style.display = "block";
			if(links2)links2.style.display = "block";
			}
		hilite = true;
		}
	if(onmap) parent.toggleMapHilightARN(curel.id, hilite);
}
var arnJsonCache;
var pinJsonCache;
function getArnJSONCache() {
	if(arnJsonCache=='none'){
		return null;
	}
	return eval(arnJsonCache) ;
}
function getPinJSONCache() {
	if(pinJsonCache=='none'){
		return null;
	}
	return eval(pinJsonCache) ;
}
function preOnLoadHandler() {
	parent.document.title = document.title;
	parent.updateTargetHashLoc(window.location, true);
	parent.gwhmap.RepositionLayerControl();
}
function initArnMap(arnPin) {
	parent.setPropertyPIN(arnPin);
	parent.DisplayArnDetailsMap(getArnJSONCache(), getPinJSONCache());
}

 /*************************************************
 *                  MAP FUNCTIONS
 **************************************************/
var __MAP_FUNCTIONS__;

function controlSPFromMap(pin){
	var _infoTargetFrame = window.frames['PropertySearchResultsID'];
	var sprec = document.getElementById("ID" + pin)
	if(sprec && (sprec.id !=null)) hiliteProperty(sprec,false);
}

function HideMapView(){
	var gwm = document.getElementById('gwhmap');
	var ldv = document.getElementById('layersdiv');
	var lg = document.getElementById("maplegend");
	var thlg = document.getElementById("thematiclegend");
	
	lg.style.display = "none";
	gwm.style.display = "none";
	ldv.style.display = "none";
	if (thlg != null) thlg.style.display = "none";
	var gwm=null;var ldv=null;var lg=null;var thlg=null;
}

function DisplayMapView(){
	HideHouseView();
	HideStreetView();
	var gwm = document.getElementById('gwhmap');
	var ldv = document.getElementById('layersdiv');
	var lg = document.getElementById("maplegend");
	var thlg = document.getElementById("thematiclegend");
	gwm.style.display = "block";
	ldv.style.display = "none";
	lg.style.display = "block";
	if (thlg != null) thlg.style.display = "block";
	var gwm=null;var ldv=null;var lg=null;var thlg=null;
}

function DisplaySearchResultsOnMap(spjs,isaddrlist,selLRO){
	if(spjs){
		HideHouseViewControls();
		DisplayMapView();
		gwhmap.SetSearchLro(selLRO);
		var sl = gwhmap.GetMapInfo().get("selectedlro");
		//if ( selLRO != sl )
		var searchType=document.forms['hiddenSearchForm'].searchType.value;
		if(searchType !='SEARCH_BY_LOT') { // execlude the below condition so Map can stay on the lot display.
			if (spjs!=null && spjs.list!=null && spjs.list.length<2) gwhmap.DisplaySelectedLRO(selLRO);
		}
		gwhmap.DisplaySearchResultsOnMap(spjs,isaddrlist);
	}
}


function DisplaySubjectPropertyMap(pin,spjs, isDeepLinkSearchByARN){
	if(pin && spjs){
		ShowHouseViewControls('map');
		DisplayMapView();
		subjectproperty = pin;
        if(typeof setPropertyPIN == 'function')
            setPropertyPIN(pin);
        if(gwhmap && gwhmap.DisplaySubjectPropertyMap){
			gwhmap.DisplaySubjectPropertyMap(pin,spjs, isDeepLinkSearchByARN);
		}
	}
}
function DisplayPlanPinOnMap(pin,spjs){
	if(pin && spjs){
		gwhmap.DisplayPlanPinOnMap(pin,spjs);
		gwhmap.HideInfoBox();
		gwhmap.ShowPinInfoWindow(pin);
	}
}
function RemovePlanPinFromMap(pin){
	if(pin){
		gwhmap.RemovePlanPinFromMap(pin);
	}
}
function DisplayInitialNhoodMap(pin,spjs){
		if(pin && spjs){
		ShowHouseViewControls('mapv');
		gwhmap.DisplayInitialNhoodMap(pin,spjs);
		//Flex drives this : DisplayNeighbourhoodBufferOnMap(pin,UserMapCfg.DefaultNSBuffer);
	}
}

function DisplayInitialPlanMapByARN(arn,propRsltArnJSONCache){
	if(propRsltArnJSONCache != null){
		ShowHouseViewControls('mapv');
		//console.debug('getPropRsltArnJSONCache() = ' + getPropRsltArnJSONCache());
		gwhmap.DisplayInitialPlanMapByARN(arn,propRsltArnJSONCache);
	}
}

function DisplayInitialPlanMap(pin,spjs,isSearchByARN){
	if(pin && spjs){
		ShowHouseViewControls('mapv');
		gwhmap.DisplayInitialPlanMap(pin,spjs);
	}
}

function DisplayNeighbourhoodBufferOnMap(pin,r){
		if(pin && r){
		ShowHouseViewControls('mapv');
		DisplayMapView();
		gwhmap.DisplayNeighbourhoodBufferOnMap(pin,r);
	}
}

function DisplayNeighbourhoodSalesOnMap(pin,nsdata){
	if(pin && nsdata){
		ShowHouseViewControls('mapv');
		gwhmap.DisplayNeighbourhoodSalesOnMap(pin,nsdata);
	}
}

function DisplayDriveByOnMap(xl,yl){
	if(xl && yl){
		DisplayMapView();
		HideHouseViewControls();
		gwhmap.DisplayDriveByOnMap(xl,yl);
	}
}

function DisplayDriveByView(pin){
	if(pin){
		DisplayMapView();
		HideHouseViewControls();
		parent.submitToIFrame("PropertySearchResultsID", "streetscape/DriveByView.jsp", "pin=" + pin);
	}
}

/*
 * This is used when the ARN Details page is displayed.
 * arnlistjs: MpacPropertyAssessmentVO JSON List
 * pinlistjs: PropertyIdentificationInfoVO JSON List
 */
function DisplayArnDetailsMap(arnlistjs, pinlistjs) {
	// if (window.console) console.log('[(gwutil.js)DisplayArnDetailsMap] - received: arnlistjs=%o, pinlistjs=%o', arnlistjs, pinlistjs);
	
	if (arnlistjs!=null && arnlistjs.list!=null) {
		ShowHouseViewControls('map');
		DisplayMapView();
		gwhmap.DisplayArnDetailsMap(arnlistjs, pinlistjs);
	}
}

/*
 * This is used when the ARN Details page is displayed.
 * arnlistjs: MpacPropertyAssessmentVO JSON List
 * pinlistjs: PropertySearchResultVO JSON List
 */
function DisplayArnSearchResultsOnMap(arnlistjs, pinlistjs) {
	//console.debug('Inside DisplayArnSearchResultsOnMap with arnlistjs = ' + arnlistjs);
	if (arnlistjs!=null && arnlistjs.list!=null) {
		//console.debug('Inside if (arnlistjs!=null && arnlistjs.list!=null)');
		//ShowHouseViewControls('map');
		DisplayMapView();
		gwhmap.DisplayArnSearchResultsOnMap(arnlistjs, pinlistjs);
	}
}

/*
 * This is used when the ARN Details page is displayed.
 * arnlistjs: MpacPropertyAssessmentVO JSON List
 * pinlistjs: PropertySearchResultVO JSON List
 */
function DisplayArnSearchResultsOnMapForSearchByARN(arnlistjs, pinlistjs) {
	//console.debug('Inside DisplayArnSearchResultsOnMapForSearchByARN with arnlistjs = ' + arnlistjs);
	if (arnlistjs!=null && arnlistjs.list!=null) {
		//console.debug('Inside if (arnlistjs!=null && arnlistjs.list!=null)');
		ShowHouseViewControls('map');
		DisplayMapView();
		//var gwm = document.getElementById('gwhmap');
		//var ldv = document.getElementById('layersdiv');
		//var lg = document.getElementById("maplegend");
		//gwm.style.display = "block";
		//ldv.style.display = "none";
		//lg.style.display = "block";
		//var gwm=null;
		//var ldv=null;
		//var lg=null;
		gwhmap.DisplayArnSearchResultsOnMapForSearchByARN(arnlistjs, pinlistjs);
	}
}


// BEGIN: Added for Comparison reports
// Creates a URL for the house thumbnail image
// If the image can't be generated, the default house view image is provided
function generateHouseViewURL(compsSummaryVO) {

	if ( compsSummaryVO != undefined && compsSummaryVO != null && compsSummaryVO ) {
	
		var houseViewURL = "http://ssi001.ilookabout.com/?";

		// If the Image ID is provided, use it. Otherise, genereate the URL from the PIN.
		if ( compsSummaryVO.imageId != undefined && compsSummaryVO.imageId != null && compsSummaryVO.imageId ) {
			houseViewURL += "ID=" + compsSummaryVO.imageId;		
		} else if (compsSummaryVO.pin != undefined && compsSummaryVO.pin != null && compsSummaryVO.pin ) {
			houseViewURL += "PIN=" + compsSummaryVO.pin + "&partner=TERANET";
		} else if ( compsSummaryVO.numPins != undefined && compsSummaryVO.numPins != null && compsSummaryVO.numPins == 'M' ) {
			return "/gwhweb/images/multiple_home_photo_thumb.png"		
		} else {
			return "/gwhweb/images/no_home_photo_thumb.png"		
		}
		
		// Add remaining parameters
		houseViewURL += "&w=100&h=70&p=4&f=70";
		
		if (compsSummaryVO.viewDirection != undefined && compsSummaryVO.viewDirection != null) {
			if (compsSummaryVO.viewDirection == 1) {
				houseViewURL += "&y=40";
			} else if (compsSummaryVO.viewDirection == 3) {
				houseViewURL += "&y=-40";
			} else {
				houseViewURL += "&y=0";
			}
		
		}
	
		houseViewURL += "&sp=20";
		
		return houseViewURL;
	
	} else {
		return "/gwhweb/images/no_home_photo_thumb.png";	
	}
}

// Get PIN value from a tag's ID, null otherwise
function getPinFromTagId(prefix, tag) {

	if ( prefix == undefined || prefix == null || !prefix ) {
		return null;
	}
	
	if (tag.id !=  undefined && tag.id != null && tag.id ) {
		var prefixRegEx = new RegExp(prefix);
		var	elementId = tag.id;
		
		if (elementId.search(prefixRegEx) == -1) {
			prefixRegEx = null;
			return null;
		} else {
			return elementId.replace(prefixRegEx, "");
		}
	} else {
		return null;
	}
}

// This is used to display the map when clicking tthe view report
// mpaccompsreportjslist: ComparableReport (former MpacCompsReportVO) json 
function DisplayArnCompsReportDetailsOnMap(compsReportJson) {
	if (compsReportJson!=null) {
		ShowHouseViewControls('map');
		DisplayMapView();		
		gwhmap.DisplayArnCompsReportDetailsOnMap(compsReportJson);
	}
}

// This is used to display the map when clicking the comps report link
// arnjslist: MpacPropertyAssessmentVO json array
// piijslist: PropertyIdentificationInfoVO json array
function DisplayArnCompsReportSearchResultsOnMap(arnjslist, piijslist) {
	//alert("DisplayArnCompsReportSearchResultsOnMap arnjslist = " + arnjslist);
	if (arnjslist!=null) {
		ShowHouseViewControls('map');
		DisplayMapView();		
		gwhmap.DisplayArnCompsReportSearchResultsOnMap(arnjslist, piijslist);
	}
}



/* ============================*/
/* Add ARN Comparable Report   */
/* ============================*/

var removeCompsReportDialog = null;
function showRemoveCompsReportDialog(header, msg, reportId, subjectPin, subjectArn) {
    if (removeCompsReportDialog) {
    	removeCompsReportDialog.hide();
    	removeCompsReportDialog.destroy();
    }
	removeCompsReportDialog =   new YAHOO.widget.Dialog("wait",  
                                               { width: "550px", 
                                                 fixedcenter: true, 
                                                 close: true, 
                                                 draggable: true, 
                                                 zindex:1000,
                                                 modal: true,
                                                 visible: false
                                               } 
                                           );
	var dialogHtml = "<div id='confirmDialog'>";
	dialogHtml += "<div class='dpmargin'>";
	dialogHtml += "<p>";
	dialogHtml += "<div align='center' width='500px'>";
	dialogHtml += msg;
	dialogHtml += "<p>";
	dialogHtml += "<input class='formbtn' type='button' name='yes' value='Continue' onclick='removeCustomReport(\""+reportId+"\",\""+subjectPin+"\",\""+subjectArn+"\"); removeCompsReportDialog.hide();'>";
	dialogHtml += "&nbsp;&nbsp;";
	dialogHtml += "<input class='formbtn' type='button' name='cancel' value='Cancel' onclick='removeCompsReportDialog.hide();'>";
	dialogHtml += "</div>";
	dialogHtml += "</div>";
	dialogHtml += "</div>";
	removeCompsReportDialog.setHeader(header);
	
	removeCompsReportDialog.setBody(dialogHtml);
	removeCompsReportDialog.render(document.body);

	// Show the message dialog
	removeCompsReportDialog.show();
}

function removeComp(reportId, subjectArn, subjectPin, arnRemove, compId){
	parent.submitToIFrame('PropertySearchResultsID', '/gwhweb/compsReport/removeComparable.do', 'report_id='+reportId+'&pin='+subjectPin+'&arn='+subjectArn+'&arn_remove='+arnRemove+'&comp_id='+compId);
	return;
}

function removeCustomReport(reportId, subjectPin, subjectArn) {
	parent.submitToIFrame('PropertySearchResultsID', '/gwhweb/compsReport/removeCustomReport.do', 'report_id='+reportId+'&pin='+subjectPin+'&arn='+subjectArn);
	return true;
}

// END: Added for Comparison reports

function toggleMapHilightProperty(pin,mode,viewtype) {
	// if (window.console) console.log('[toggleMapHilightProperty] - processing pin=%s: mode=%s, viewtype=%s', pin, mode, viewtype);
	switch(viewtype){
			case GWH.Util.Constants.SEARCH_RESULT:
				window.status = "SEARCH_RESULT: " + viewtype +" " +pin;
				if (mode) {
					// if (console) console.log('In toggleMapHilightProperty - calling ShowPinInfoWindow(' + pin + ')', 'window.status=' + window.status);
					try {
						// alert('Calling ShowPinInfoWindow(' + pin + ')' + ': window.status=' + window.status);
						gwhmap.ShowPinInfoWindow(pin);
						// if (console) console.log('In toggleMapHilightProperty - returned from ShowPinInfoWindow(' + pin + ')');
						// alert('OK');
					} catch (e) {
						// if (console) console.log('In toggleMapHilightProperty - exception in ShowPinInfoWindow', 'exception=', e);
						// alert('Exception in ShowPinInfoWindow: ' + e.message + ', mode=' + mode);	
					}
				}
				else {
					gwhmap.HideInfoBox();
					//alert (" in Else, mode is:"+mode);
				}
				break;
			case GWH.Util.Constants.NHOOD_RECORD:
				if (mode) gwhmap.ShowNSPinInfoWindow(pin);
				else gwhmap.HideNSInfoBox();
				break;
			default:
				break;
		}
}

function toggleMapHilightARN(arn,mode){
	window.status = "SEARCH_RESULT: " +arn;
	if (mode) gwhmap.ShowArnInfoWindow(arn);
	else gwhmap.HideInfoBox();
}

/* Hide/Show NS Info Box*/
//pin is PIN, hiliteflag is a boolean value (true or false )
function toggleHilightNhoodProperty(pin,hiliteflag){
	if (hiliteflag)gwhmap.hiliteNHoodSale(pin);
	else gwhmap.HideInfoBox();
}


 /*************************************************
 *                 HOUSE VIEW FUNCTIONS
 **************************************************/
var __HOUSE_VIEW_FUNCTIONS__;

function ShowHouseViewControls(){
	var mapctrls = parent.document.getElementById('maptopctrl');
	mapctrls.style.display = "block";
	mapctrls = null;
}

function HideHouseViewControls(){
	var mapctrls = parent.document.getElementById('maptopctrl');
	mapctrls.style.display = "none";
	mapctrls = null;
}

function getSwfObject(objName){
		return document[objName];
}

	var houseviewer;

	var jsReady = false;
	var swfReady = false;

	// called by the onload event of the <body> tag
	function pageInit()
	{
	    // Record that JavaScript is ready to go.
	    jsReady = true;
	}

	function isReady()
	{
		return jsReady;
	}

		// called to notify the page that the SWF has set it's callbacks
	function setSWFIsReady() {
		swfReady = true;
	}

	function isSwfReady()
	{
		return swfReady;
	}

	function logHouseViewActivity(pin)
	{
	var asXmlHttp = GWH.Ajax.getXmlHttpRequest();
	var servurl = "/gwhweb/LogHouseViewActivity.jsp?pin=" + pin;
	asXmlHttp.open("GET",servurl,true);
	asXmlHttp.send(null);
	}



function DisplayHouseView(subjectPropertyPIN){

		var hv = document.getElementById("gwhouseview");

		hv.style.display = "block";

		var pin = subjectPropertyPIN;
		if(houseviewer==null) houseviewer = getSwfObject('houseview');
		if (houseviewer) {
			try{
				if(!isSwfReady()){
					setTimeout(function(){houseviewer.HouseView(pin); pin = null},1000);
				}
				else{
					houseviewer.HouseView(pin);
				}
			}
			catch(e){
	         	window.status = 'Disp.Hous.Vw..e.src=' + e.source + '\ne.n=' + e.name + '\ne.m=' + e.message;
				setTimeout(function(){houseviewer.HouseView(pin); pin = null},1000);
	         }
		}
		ShowHouseViewControls('dvhv');
		HideMapView();
		HideStreetView();
}

var	streetViewService;

function DisplayStreetView(subjectPropertyPIN){
	
	HideMapView();
	HideHouseView();
		
	GwhStreetView.renderStreetViewCurrProperty({id:'gwhstreetview', showControls: true});		
}

function DisplayStreetViewV2(svData) {
	// if (window.console) console.log('[(gwutil.js)DisplayStreetViewV2] - received svData=%o', svData);
	HideMapView();
	HideHouseView();
	gwhmap.HideInfoBox();
	var streetViewDiv = document.getElementById('gwhstreetview');
	streetViewDiv.style.display = "block";
	
	var logFunction = function(povData) {
				// if (window.console) console.log('[DisplayStreetViewV2] - received callback with params: svData=%s, povData=%o', svData, povData);
				var params = 'propertyPIN=' + encodeURIComponent(svData.pin ? svData.pin : svData)	// svData may come as a string or as an object
					+ '&status=' + encodeURIComponent(povData.status)
					+ '&viewAngle=' + encodeURIComponent(povData.povYaw)
					+ '&viewLat=' + encodeURIComponent(povData.povLat)
					+ '&viewLong=' + encodeURIComponent(povData.povLong);
				YAHOO.util.Connect.asyncRequest('POST', "/gwhweb/gsvLogging.do", new Object(), params);
	};
	
	/*
	 * If svData contains a PIN, heading, projection and centroid/heading coordinates, add additional properties and pass over 
	 * directly to renderStreetView (this is the flow from a comps report street view click);
	 * Otherwise, if it only contains PIN, as the case when clicking on the Street View link, call the other function, it will use previously saved parameters.
	 */
	if (svData.pin) {
		svData.id = 'gwhstreetview';
		svData.showControls = true;
		// TODO: [VT] - one day Cristian mentioned the message and how it is displayed need improvement - discuss.
		svData.noResultsHtml = "<p><span style='text-align:center;font-weight:bold;background-color:#808080;'>Sorry. No street view found for the specified property.</span></p>";
		svData.log = logFunction;
		// if (window.console) console.log('[(gwutil.js)DisplayStreetViewV2] - ready to render a property with svData=%o', svData);
		GwhStreetView2.renderStreetView(svData);
	} else {
		// if (window.console) console.log('[(gwutil.js)DisplayStreetViewV2] - ready to render the subject property');
		GwhStreetView2.renderStreetViewCurrProperty({id:'gwhstreetview', showControls:true, log:logFunction});
	}
}

var resizeStreetViewTimer;

function resizeStreetView() {
	if (resizeStreetViewTimer) {
		clearTimeout(resizeStreetViewTimer);
	}
	var div = document.getElementById('gwhstreetview');
	if (div && div.style.display != 'none') {
		resizeStreetViewTimer = setTimeout("doResizeStreetView()", 200);
	}
}
function doResizeStreetView() {
	GwhStreetView2.onWindowResize('gwhstreetview');
}
function zoomStreetView(e) {
	var div = document.getElementById('gwhstreetview');
	if (div && div.style.display != 'none') {
		e = e ? e : window.event;
		var normalized = e.detail ? e.detail * -1 : e.wheelDelta / 40;
		var zoomDelta = normalized < 0 ? -1: normalized > 0 ? 1 :0;
		GwhStreetView2.zoom(zoomDelta);
	}
}

var hirezviewer;

function onInitialized(source, args)//lat, lng, heading
{
    hirezviewer.setPhotoLinksEnabled(false);
}


var gwhhousedriveby = new function() {
	var Version = "1.0.0";
	var hdbvSwfFileName = _hdbvSwfName;
	this.getVersion = function(){return Version;};
	var Event = new function() {
		var List = new Array();
		function addListener(source, event, handler)
		{
			var eventlistener;
			for(var i=0; i<List.length; i++)
			{
				if(List[i].equals(source, event, handler))
				{
					eventlistener = List[i];
					break;
				}
			}
			if(!eventlistener)
			{
				eventlistener = new EventListener(source, event, handler);
				List.unshift(eventlistener);
			}
			return eventlistener;
		}
		function removeListener(eventlistener){
			for(var i=0; i<List.length; i++)
			{
				if(List[i] == eventlistener)
				{
					List.splice(i, 1);
					break;
				}
			}
		}
		function dispatchFromFlash(target, event, args){
			var v = getApp(target);
			var eventlistener;
			var i = 0;
			while(i < List.length)
			{
				eventlistener = List[i];
				if((eventlistener.source.getSwfObject() == v) && (eventlistener.event == event))
				{
					eventlistener.handler(eventlistener.source, args);
				}
				i++;
			}
		}

		function dispatch(target, event, args)
		{
			var eventlistener;
			var i = 0;
			while(i < List.length)
			{
				eventlistener = List[i];
				if((eventlistener.source == target) && (eventlistener.event == event))
				{
					eventlistener.handler(eventlistener.source, args);
				}
				i++;
			}
		}
//		return {addListener:addListener, removeListener:removeListener, viewChange:viewChange, locationChange:locationChange, inited:inited, dispatch:dispatch};
		return {addListener:addListener, removeListener:removeListener,  dispatch:dispatch};
	}

	function EventListener(source, event, handler)	{
		this.source = source;
		this.event = event;
		this.handler = handler;
	}

	EventListener.prototype.equals = function(source, event, handler){
		return ((this.source == source) && (this.event == event) && (this.handler == handler));}

	function HouseViewer(config){
		var that = this;
		var initialPov;
		var initialImageID;
		var container = document.getElementById(config.container);
		var viewerId = container.id + '_HouseView';
		var flashVars = 'pin=' + config.pin + '&highResEnabled=' + config.highResEnabled + '&mode=' + config.mode;//'Host=' + Host + '&PhotoLinksEnabled=' + PhotoLinksEnabled.toString() + '&EventPrefix=gwhilookabout.Event.';
		var s = '';
		s += "<object id='" + viewerId + "' classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' name='" + viewerId + "' codebase='http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab' height='100%' width='100%' type='application/x-shockwave-flash' align='left'>\n";
		s += "<param name='allowScriptAccess' value='sameDomain' />";
		s += "<param name='movie' value='" + hdbvSwfFileName + "'/><PARAM value='transparent' name='wmode'>\n";
		s += "<param name='flashVars' value='" + flashVars + "'/><PARAM value='#869ca7' name='bgcolor'/>\n";
		s += "<param name='quality' value='high'/>\n";
		s += "<embed name='" + viewerId + "' src='" + hdbvSwfFileName + "' pluginspage='http://www.adobe.com/go/getflashplayer' allowScriptAccess='always' height='100%' width='100%' flashVars='" + flashVars + "'/>\n"
		s += "</object>";

		container.innerHTML = s;
		var swfObject = getApp(viewerId);

		this.getContainer = function(){return container;};
		this.getSwfObject = function(){return swfObject;};
		this.getViewerId = function(){return viewerId;};
		this.showHouseView = function(pin,xlat,ylong){
			alert(pin + ' ' + xlat + ' ' + ylong);
			swfObject.DriveByToLocation(pin,xlat,ylong);
		}

	}

	HouseViewer.prototype.DisplayLocation = function(pin,xlat,ylong){
		var o = this.getSwfObject();
		alert('HouseViewer.prototype.DisplayLocation')
		o.DriveByToLocation (pin,xlat,ylong);

	}

	function getApp(appName){
			return document[appName];
	}

	return {Event:Event, HouseViewer:HouseViewer};

};

function HideHouseView(){
	var gwhv = document.getElementById('gwhouseview');
	gwhv.style.display = "none";
	var gwhv=null;
}

function HideStreetView(){
	var gsv = document.getElementById('gwhstreetview');
	if(typeof gsv === 'undefined' || gsv == null){
		return;
	} else {
		gsv.style.display = 'none';
	}
}

GWH.Util.ilaAuth = function(token)
{
    var ns = "GWH.Util.ilaAuth"; //should be same as the namespace above
    var url = "http://ss.ilookabout.com/getAuthorizationImage/";

    var statusList = {
                    "2px":        {code:200, msg:"Success"},
                    "3px":        {code:405, msg:"Token has expired"},
                    "4px":        {code:400, msg:"Token is missing or is not properly formatted"},
                    "5px":        {code:503, msg:"Service not available"},
                    "6px":        {code:403, msg:"Token is not valid"},
                    "7px":        {code:700, msg:"Browser did not accept the third party cookie"},
                    "imageError": {code:500, msg:"Invalid request or a server error"},
                    "timeout":    {code:502, msg:"Response did not complete within the allotted time"},
                    "unknown":    {code:600, msg:"Unknown response was returned by the server"}
                };

    var busy = false;
    var timedOut = false;
    var authTimer = null;
    var authImg = null;
    var verifyImg = null;
    var callbackfunction = null;

    function authTimeout()
    {
    //alert("authTimeout");
        timedOut = true;
        authComplete(new Status("timeout"));
    }
   	var msgdiv = document.getElementById('messageDiv');
    var authenticate = function(token, timeoutticks, callback)
    {
    //alert("authenticate - " + token);
        if(busy) return;
        busy = true;
        timedOut = false;
        callbackfunction = callback;
        authTimer = setTimeout(ns + ".__authTimeout()", timeoutticks);
        authImg = new Image();
        verifyImg = new Image();
        function imageError()
        {
            if(timedOut)return;
            authComplete(new Status("imageError"));
        }
        authImg.onerror = imageError;
        verifyImg.onError = imageError;

        var ut = unixTime();

        authImg.src = url + "?Token=" + token + "&t=" + ut;
        authImg.onload = function()
        {
            if(timedOut)return;
            if(authImg.width == 1)
            {
                //ok... need to verify that cookie was accepted
                verifyImg.src = url + "?Token=" + token + "&verify=true" + "&t=" + ut;
                verifyImg.onload = function()
                {
                    if(timedOut)return;
                    authComplete(new Status(verifyImg.width + "px"));
                }
            }
            else
            {
                authComplete(new Status(authImg.width + "px"));
            }
        }

    }

    function Status(id)
    {
        var o = statusList[id];
        if(o == null) o = statusList["unknown"];
        this.code = o.code;
        this.msg = o.msg;
		msgdiv.innerHTML  = msgdiv.innerHTML + ' ' +this.code+ ' ' +this.msg;
    }

    function authComplete(status)
    {
        clearTimeout(authTimer);
        authImg.onload = null;
        authImg.onerror = null;
        authImg = null;
        verifyImg.onload = null;
        verifyImg.onerror = null;
        verifyImg = null;
        busy = false;
        callbackfunction(status);
    }

    function unixTime()
    {
        var dt = new Date; // Generic JS date object
        var unixtime_ms = dt.getTime(); // Returns milliseconds since the epoch
        return parseInt(unixtime_ms / 1000);
    }


    return {authenticate:authenticate, __authTimeout:authTimeout};

}


//hirez
var _host = "http://ss.ilookabout.com";
var _uri = "/Panoviewer_hacker";
var _panoFlexPath = "../flex/streetscape/";
var _hdbvFlexPath = "/flex/streetscape/";
var _swfFileName = _panoFlexPath + "Panoviewer.swf";
var _hdbvSwfName = _hdbvFlexPath + "hdbv.swf";
var _photoLinksEnabled = false;


var gwhilookabout = new function() {
	var Version = "1.0.1";
	var Host = _host + _uri;
	var swfFileName = _swfFileName;
	var hdbvSwfFileName = _hdbvSwfName;
	var PhotoLinksEnabled = _photoLinksEnabled;
	this.getVersion = function(){return Version;};

	var Event = new function() {
		var List = new Array();
		function addListener(source, event, handler)
		{
			var eventlistener;
			for(var i=0; i<List.length; i++)
			{
				if(List[i].equals(source, event, handler))
				{
					eventlistener = List[i];
					break;
				}
			}
			if(!eventlistener)
			{
				eventlistener = new EventListener(source, event, handler);
				List.unshift(eventlistener);
			}
			return eventlistener;
		}
		function removeListener(eventlistener){
			for(var i=0; i<List.length; i++)
			{
				if(List[i] == eventlistener)
				{
					List.splice(i, 1);
					break;
				}
			}
		}
		function dispatchFromFlash(target, event, args){
			var v = getApp(target);
			var eventlistener;
			var i = 0;
			while(i < List.length)
			{
				eventlistener = List[i];
				if((eventlistener.source.getSwfObject() == v) && (eventlistener.event == event))
				{
					eventlistener.handler(eventlistener.source, args);
				}
				i++;
			}
		}
		function viewChange(target, yaw, pitch, vfov){dispatchFromFlash(target, "viewchange", {yaw:yaw, pitch:pitch, vfov:vfov});}
		function locationChange(target, lat, lng, heading){dispatchFromFlash(target, "initialized", {lat:lat, lng:lng, heading:heading}); }
		function inited(target){dispatchFromFlash(target, "inited", {}); }
		function dispatch(target, event, args)
		{
			var eventlistener;
			var i = 0;
			while(i < List.length)
			{
				eventlistener = List[i];
				if((eventlistener.source == target) && (eventlistener.event == event))
				{
					eventlistener.handler(eventlistener.source, args);
				}
				i++;
			}
		}
		return {addListener:addListener, removeListener:removeListener, viewChange:viewChange, locationChange:locationChange, inited:inited, dispatch:dispatch};
	}
	function EventListener(source, event, handler)	{
		this.source = source;
		this.event = event;
		this.handler = handler;
	}
	EventListener.prototype.equals = function(source, event, handler){
		return ((this.source == source) && (this.event == event) && (this.handler == handler));}

	function PanoViewer(container){
		var that = this;
		var initialPov;
		var initialImageID;
		var viewerId = container.id + '_PanoViewer';
		var flashVars = 'Host=' + Host + '&PhotoLinksEnabled=' + PhotoLinksEnabled.toString() + '&EventPrefix=gwhilookabout.Event.';
		var s = '';
		s += "<object id='" + viewerId + "' classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab' height='100%' width='100%'>\n";
		s += "<param name='allowScriptAccess' value='always' />";
		s += "<param name='movie' value='" + swfFileName + "'/>\n";
		s += "<param name='allowFullScreen' value='true' />\n";
		s += "<param name='flashVars' value='" + flashVars + "'/>\n";
		s += "<embed name='" + viewerId + "' src='" + swfFileName + "' pluginspage='http://www.adobe.com/go/getflashplayer' allowScriptAccess='always' allowFullScreen='true' height='100%' width='100%' flashVars='" + flashVars + "'/>\n"
		s += "</object>";
		container.innerHTML = s;
		var swfObject = getApp(viewerId);
		//event listener to catch the inited callback from the flash viewer
		var inited = function(source, args){
			//only gets called once
			Event.removeListener(ev);
			inited = null; //we know it has been called when inited is null
			if(initialImageID != null){
				//it is okay to call this now
				that.setImageIdAndPOV(initialImageID, initialPov);
			}
		}
		this.isInited = function(){return (inited==null);};
		this.getContainer = function(){return container;};
		this.getSwfObject = function(){return swfObject;};
		this.getViewerId = function(){return viewerId;};
		var ev = Event.addListener(this, "inited", inited);
		this.setImageIdAndPOV = function(ImageID, opt_pov){
			if(inited != null)
			{
				//hold off calling swfObject.Load()
				//cache the args and recall this function after the swf has been initialized
				initialImageID = ImageID;
				initialPov = opt_pov;
				return;
			}
			if(opt_pov == null)
			{
			//alert(ImageID);
				swfObject.Load(ImageID);
			}else
			{
			//alert(ImageID + ' ' + opt_pov.yaw + ' ' +  opt_pov.pitch + ' ' + opt_pov.vfov);
				swfObject.Load(ImageID, opt_pov.yaw, opt_pov.pitch, opt_pov.vfov);
			}
		}
	}
	PanoViewer.prototype.getLocation = function(){
		var lat = this.getSwfObject().getLatitude();
		var lng = this.getSwfObject().getLongitude();
		return new LatLng(lat, lng);
	}
	PanoViewer.prototype.getUtcDateTimeOfPhoto = function(){return this.getSwfObject().getUtcDateTime();}
	PanoViewer.prototype.getPOV = function(){
		var yaw = this.getSwfObject().getYaw();
		var pitch = this.getSwfObject().getPitch();
		var vfov = this.getSwfObject().getVFov();
		return new Pov(yaw, pitch, vfov);
	}
	PanoViewer.prototype.setPOV = function(pov){
		var o = this.getSwfObject();
		o.setYaw(pov.yaw);
		o.setPitch(pov.pitch);
		o.setVFov(pov.vfov);
	}
	PanoViewer.prototype.getTwist = function(){return this.getSwfObject().getTwist();}
	PanoViewer.prototype.setTwist = function(value){this.getSwfObject().setTwist(value);}
	PanoViewer.prototype.getTilt = function(){return this.getSwfObject().getTilt();}
	PanoViewer.prototype.setTilt = function(value){this.getSwfObject().setTilt(value);}
	PanoViewer.prototype.getPhotoLinksEnabled = function(){return this.getSwfObject().getPhotoLinksEnabled();}
	PanoViewer.prototype.setPhotoLinksEnabled = function(value){this.getSwfObject().setPhotoLinksEnabled(value);}
	PanoViewer.prototype.panTo = function(pov){this.getSwfObject().panToView(pov.yaw, pov.pitch, pov.vfov);}
	PanoViewer.prototype.getViewDirection = function(){return this.getSwfObject().getViewDirection();}
	PanoViewer.prototype.getWidth = function(){return this.getContainer().clientWidth;}
	PanoViewer.prototype.getHeight = function(){return this.getContainer().clientHeight;}
	PanoViewer.prototype.getGamma = function(){return this.getSwfObject().getGamma();}
	PanoViewer.prototype.getImageID = function(){return this.getSwfObject().getImageID();}
	function LatLng(lat, lng){
		this.lat = lat;
		this.lng = lng;
	}
	function Pov(yaw, pitch, vfov){
		this.yaw = yaw;
		this.pitch = pitch;
		this.vfov = vfov;
	}
	function getApp(appName){
		//if (navigator.appName.indexOf ("Microsoft") !=-1)
		//{
		//	return window[appName];
		//}
		//else
		//{
			return document[appName];
		//}
	}
	function Unload(){}
	return {Event:Event, PanoViewer:PanoViewer, LatLng:LatLng, Pov:Pov, Unload:Unload};
};

var regenerateToken= function(){
	var asXmlHttp = GWH.Ajax.getXmlHttpRequest();
	var servurl = "/gwhweb/RegenerateToken.jsp";
	asXmlHttp.open("GET",servurl,false);
	asXmlHttp.send(null);

    // If the request's status is "complete"
    if (asXmlHttp.readyState == 4) {
      // Check successful server response was received
      if (asXmlHttp.status == 200||asXmlHttp.status == 0 ){
			try{
				return asXmlHttp.responseText;
				}
			catch(e){
	         	window.status = 'regenerateToken =' + e.source + '\ne.n=' + e.name + '\ne.m=' + e.message;
	         	return null;
	         }
		}
      }
      else {
      	window.status = 'regenerateToken req faied';
		return null;
      }
}

/**
* Helper method to handle opening of the iLA popup
*/
function forwardToStreetScapeUtil(streetScapeWindow, pin, photoURL)
{
	url = "/gwhweb/streetScape.do?action=forwardToILA&pin=" + pin + "&photoURL=" + photoURL;
	streetScapeWindow = viewProductWithWSize(url, 690, 930, "Street Scape (and Pivot View) Report");
}


 /*************************************************
 *             HIGH RESOLUTION FUNCTIONS
 **************************************************/
var __HI_RESOLUTION_FUNCTIONS__;

var hirezviewer;
function onHiRezInitialized(source, args) {
	//lat, lng, heading
    hirezviewer.setPhotoLinksEnabled(false);
}
function initHiRez(imgid) {
	hirezviewer = new gwhilookabout.PanoViewer(document.getElementById("hirezcont"));
	hirezviewer.onInitialized = gwhilookabout.Event.addListener(hirezviewer, "initialized", onHiRezInitialized);
	hirezviewer.setImageIdAndPOV(imgid, {yaw:16, pitch:0, vfov:70});
}


 /*************************************************
 *           DRIVE BY VIEW FUNCTIONS
 **************************************************/
var __DRIVE_BY_VIEW_FUNCTIONS__;

var highReswindow;
var highResImage;
var streetScapeWindow;
/*this function provides the latitude and longitude of the current image in order to refresh the map*/
function getLatLong(lat, lon, dir) {
	parent.DisplayDriveByOnMap(lat,lon);
}

function forwardToStreetScape(pin, photoURL) {
	forwardToStreetScapeUtil(streetScapeWindow, pin, photoURL);
}

function crossStr() {
	var callResult = hdbv.CrossStreet();
	window.status = "crossStr";
}
function highRes(imageID) {
	//alert(imageID);
	url = "HighResolution.jsp?imageId="+imageID;
	if (highReswindow=='[object]') {
		if(highReswindow.closed == true) {
			// open up the High Res window with the imageID
			highReswindow = window.open(url,"HighRes","height=500,RESIZABLE=yes, screenX=200, screenY=200, width=500,scrollbars=no, status=no,toolbar=no,menubar=no,location=no,titlebar=0");
			highResImage = imageID;
		} else {
			setTimeout('highReswindow.focus();',0);
			// check if the image in the window needs to be refreshed
			if (highResImage != imageID) {
				//refresh the image in High Res window
				highReswindow = window.open(url,"HighRes","height=500,RESIZABLE=yes, screenX=200, screenY=200, width=500,scrollbars=no, status=no,toolbar=no,menubar=no,location=no,titlebar=0");
			}
		}
	} else {
		// highResWIndow undefined - create it and display imageID
		highReswindow = window.open(url,"HighRes","height=500,RESIZABLE=yes, screenX=200, screenY=200, width=500,scrollbars=no,status=no,toolbar=no,menubar=no,location=no,titlebar=0");
    	setTimeout('highReswindow.focus();',250);
		highResImage = imageID;
	}
}
function driveByToLocation() /*(pin,x,y)*/ {
	//window.status = "driveByToLocation";
	//var callResult = hdbv.DriveByToLocation('075130277',43.6560016492295,-79.510192363375);
}


 /*************************************************
 *             PLAN LIST BY PIN FUNCTIONS
 **************************************************/
var __PLAN_LIST_BY_PIN_FUNCTIONS__;

function showPinList(obj)
{	var headerID = obj + '_header';
	var dataID = obj + '_data';
	var el = document.getElementById(headerID);
	el.style.display='none';

	el = document.getElementById(dataID);
	el.style.display='';
}


/**
	** Commented out ... should be declared locally **
	var docImageWindow;
*/
function planListByPinOnLoadHandler(isSearchByARN, pageType, bannerAdAccess, municipality) {
	initChangePlansTab('PlansTabView');

	parent.document.forms['propertySearchForm'].lro.value=subjectLro;
	if (document.getElementById('bufferRange')) {
		initPlanListByPinMap(isSearchByARN); // getPropRsltArnJSONCache(), getPageResultsCache()
		bufferObj = document.getElementById('bufferRange');
		currentRadius = bufferObj.options[bufferObj.selectedIndex].value;
		if (currentRadius > 0) {
			changeGeographicBuffer(currentRadius);	//initialize map with current radius
		}
		if (updateReportCtr) updateReportCounter();
	}
	if (bannerAdAccess=='true') retrieveBannerAd(pageType, municipality);
	onParentWindowResize();
	return;
}
function initPlanListByPinMap(isSearchByARN) {
    parent.setPropertyPINandLRO(subjectPin, subjectLro);
    if (isSearchByARN == 'true')
    {
    	//console.debug('getPropRsltArnJSONCache()=' + getPropRsltArnJSONCache());
		parent.DisplayInitialPlanMapByARN(subjectARN, getPropRsltArnJSONCache());
    }
    else
    {
		parent.DisplayInitialPlanMap(subjectPin, getPlanListByPinJSONPropertyCache());
	}
}
function getPlanListByPinJSONPropertyCache() {
	if (plByPinJsonCache=='none') {
		return null;
	}
	return eval(plByPinJsonCache);
}
function updateReportCounter() {
	parent.GWH.Ajax.getReportCount(3000, 1, 2000);
}

/*
 *	Used by:
 *		Plan List by PIN
 *		SRPR Plan List by PIN
 */
function changeGeographicBuffer(radius) {
	parent.DisplayNeighbourhoodBufferOnMap(subjectPin, radius);
}
function searchPlans() {
	document.getElementById("planlistmsgdiv").innerHTML = busyText;
	document.getElementById("searchPlansBtn").disabled = true;
	document.getElementById("planlistdatadiv").innerHTML = "";	//clear results
	setTimeout("getPlansByPIN()", 500);
}
function getPlansByPIN() {
	var dt = new Date();
	var bufferRange = document.getElementById('bufferRange').value;
	var responseText = getPlansData("/gwhweb/viewPlanListByPin.do?pin=" + subjectPin2 + "&search=true&bufferRange=" + bufferRange + "&dt=" + dt);
}
function displayPreviousResults(subjectPin) {
	var dt = new Date();
	var responseText = getPlansData("/gwhweb/planlist/PlanListSearchResults.jsp?pin=" + subjectPin + "&dt=" + dt);
}
function getPlansData(url) {
	asXmlHttp = GWH.Ajax.getXmlHttpRequest();
	var serverURL = url;
	asXmlHttp.open("GET", serverURL, true);
	asXmlHttp.onreadystatechange = showPlans;
	asXmlHttp.send(null);
}
function showPlans() {
	var errUrl = "/gwhweb/errMessage.jsp";
	if (asXmlHttp.readyState == 4) {
		window.status = "showPlans async done";
		if (asXmlHttp.status == 200||asXmlHttp.status == 0 ) {
			try {
				var responseText = asXmlHttp.responseText;
				document.getElementById("planlistmsgdiv").innerHTML = selectDocText;
				document.getElementById("planlistdatadiv").innerHTML = responseText;
				parent.resizeIFrameDoc('planlistdatadivwrapper');
				document.getElementById("searchPlansBtn").disabled = false;
				getMainWindow(window).resizeContentFrame();
				//handling the case where the session has expired as the normal mechanism to do
				//so does not work when infilling a DIV
				if (responseText.indexOf('verifyTop') != -1)
				{	if (self != top)
					{	window.open(location.href, '_top');
						return;
					}
				}
				updateReportCounter();
			} catch(e) {
				window.status = 'showPlans.e.src=' + e.source + '\e.n=' + e.name + '\e.m=' + e.message;
				asXmlHttp = null;
				location.href = errUrl;
			}
		} else {
			window.status = "showPlans failed with status " + asXmlHttp.status;
			asXmlHttp = null;
			location.href = errUrl;
		}
	} else {
		window.status = "showPlans readyState " + asXmlHttp.readyState;
		//asXmlHttp = null;
		//location.href = errUrl;
	}
}
function renderPlan(url) {
	var planWnd = window.open(url, "planwnd",'toolbar=0,menubar=0,location=0,directories=0,resizable=1,status=0,scrollbars=1');
	if (window.focus) {planWnd.focus()}
}
function mapBubble(pin, alink) {
	if (lastMapItPinElem == null) {
		alink.style.color = '#B22222';
		alink.style.fontWeight = 700;
		lastMapItPinElem = alink;
	} else {
		lastMapItPinElem.style.color = '#3B62A5';
		lastMapItPinElem.style.fontWeight = 400;
		if (pin == lastMapItPin) {
			pin = lastMapItPin = null;
		}
	}

	if (pin != lastMapItPin) {
		lastMapItPinElem = alink;
		lastMapItPin = pin;
		alink.style.color = '#B22222';
		alink.style.fontWeight = 700;
		lastMapItPinElem = alink;

		var errUrl = "/gwhweb/errMessage.jsp";
		var url = "/gwhweb/planpinjson.do?pin=" + pin;
		var asXmlHttp = GWH.Ajax.getXmlHttpRequest();
		var serverURL = url;
		asXmlHttp.open("GET", serverURL, false);
		asXmlHttp.send(null);

		if (asXmlHttp.readyState == 4) {
			if (asXmlHttp.status == 200||asXmlHttp.status == 0 ) {
				try {
					spJsonArray = asXmlHttp.responseText;
					spJsonArray = spJsonArray.trimstr();
					if (spJsonArray == "none") {
						parent.showMessageDialog("Plan List By PIN", "No mapping data available.");
					} else {
						spJsonArray = eval('(' + spJsonArray + ')');
						//parent.DisplaySubjectPropertyMap(pin, spJsonArray);
						parent.DisplayPlanPinOnMap(pin, spJsonArray);
					}
				} catch(e) {
					window.status = 'mapBubble.e.src=' + e.source + '\e.n=' + e.name + '\e.m=' + e.message;
					asXmlHttp = null;
					location.href = errUrl;
				}
			} else {
				window.status = "mapBubble req failed with status " + asXmlHttp.status;
				asXmlHttp = null;
				location.href = errUrl;
			}
		} else {
			window.status = "mapBubble req failed with readyState " + asXmlHttp.readyState;
			asXmlHttp = null;
			location.href = errUrl;
		}
		asXmlHttp = null;
	}
}
function mapPlan(lro, planNum, hexPlanNum, showPlanNum, planNumDisplay, alink, planId,planType) {
	if (lastMapItElem == null) {
		alink.style.color = '#B22222';
		alink.style.fontWeight = 700;
		lastMapItElem = alink;
	} else {
		lastMapItElem.style.color = '#3B62A5';
		lastMapItElem.style.fontWeight = 400;
		if (planId == lastMapItPlan) {
			planId = lastMapItPlan = null;
		}
	}
	unmapPlan();
	if (planId != lastMapItPlan) {
		lastMapItElem = alink;
		lastMapItPlan = planId;
		alink.style.color = '#B22222';
		alink.style.fontWeight = 700;
		lastMapItElem = alink;
		encryptPlan = !showPlanNum;
		responseText = parent.gwhmap.DisplaySelectedPlan(lro, planNum, hexPlanNum, encryptPlan, planNumDisplay,planType,planId);

		if (responseText == 'none') {
			parent.showMessageDialog("Plan List By PIN", "No mapping data available.");
		} else if (responseText == 'error') {
			location.href = "/gwhweb/errMessage.jsp";
		}
	}
}
function unmapPlan() {
	parent.gwhmap.RemovePlanLayer();
}
function resetBufferRange(range,elementId) {
	bufferObj = document.getElementById(elementId);
	if(bufferObj){
		if (range == 0) bufferObj.selectedIndex = 0;
		if (range == 250) bufferObj.selectedIndex = 1;
		if (range == 500) bufferObj.selectedIndex = 2;
	}
	else
		return;
}
function initOpenDocument(token){
	if (viewType=="View") {
		openDocumentPlanList(token);
	} else if (viewType=="Purchase") {
		openTransactionalDocument(token);
	} else {
		return;
	}
}
function openDocumentPlanList(token) {
	var documentUrl="./documentImage.do?action=gettingDocumentRata&token="+token+"&product=planList";
	//docImageWindow = window.open ("","mywindow1","menubar=1,resizable=1,width=650,height=400");
	//docImageWindow.close();

	docImageWindow = window.open(documentUrl,"mywindow1","menubar=1,resizable=1,width=650,height=400");
	if(docImageWindow) {
		docImageWindow.focus();
	}
}
function openPurchasePlanSurveyDocument(token){
	var pdocumentUrl="./documentImage.do?action=gettingSurveyDocument&token="+token+"&product=someProduct";
	purchaseProduct(pdocumentUrl);
}

function openViewPlanSurveyDocument(token) {
	var pdocumentUrl="./documentImage.do?action=gettingSurveyDocument&token="+token+"&product=someProduct";
	docImageWindow = window.open("","mywindow1","menubar=1,resizable=1,width=650,height=400");
	docImageWindow.close();

	docImageWindow = window.open(pdocumentUrl,"mywindow1","menubar=1,resizable=1,width=650,height=400");
	if (docImageWindow.focus) {
		docImageWindow.focus();
	}
}
function openViewPlanLSRSurveyDocument(token) {
	openViewPlanSurveyDocument(token);
	downloadLSRSurveyNotes(token);
}
function downloadLSRSurveyNotes(token) {
	//determine whether survey notes exist
	var sNotesUrl="./documentImage.do?action=gettingLSRSurveyNotes&queryNotes=1&token="+token+"&product=someProduct";
	var asXmlHttp = GWH.Ajax.getXmlHttpRequest();
	asXmlHttp.open("GET", sNotesUrl, false);
	asXmlHttp.send(null);
	if (asXmlHttp.readyState == 4) {
		if (asXmlHttp.status == 200||asXmlHttp.status == 0 ) {
			try {
				var responseText = asXmlHttp.responseText;
				//alert(responseText);
				if (responseText == '1') {
					//survey notes exist; download it
					var sNotesUrl="./documentImage.do?action=gettingLSRSurveyNotes&queryNotes=0&token="+token+"&product=someProduct";
					sNotesWnd = window.open(sNotesUrl, "notes");
				}
			} catch(e) {
				return "error " + e.source + '\e.name=' + e.name + '\e.message=' + e.message;
			}
		} else {
			return "error with status " + asXmlHttp.status;
		}
	} else {
		return "error with state " + asXmlHttp.readyState;
	}
}
function openTransactionalDocument(token) {
	var documentUrl="./documentImage.do?action=purchaseDocumentPlist&token="+token+"&product=planList";
	purchaseProduct(documentUrl);
}


  /*************************************************
 *          SRPR PLAN LIST BY PIN FUNCTIONS
 **************************************************/
var __SRPR_PLAN_LIST_BY_PIN_FUNCTIONS__;

function srprOnLoadHandler(){
	initMap();
	bufferObj = document.getElementById('srprbuffRange');
	currentRadius = bufferObj.options[bufferObj.selectedIndex].value;
	if (currentRadius > 0) {
		changeGeographicBuffer(currentRadius);	//initialize map with current radius
	}
	if (updateReportCtr) updateReportCounter();
}

function searchSurveyPlans() {
	document.getElementById("srprplanlistmsgdiv").innerHTML = busyText;
	document.getElementById("srprsearchPlansBtn").disabled = true;
	document.getElementById("srprplanlistdatadiv").innerHTML = "";	//clear results
	setTimeout("getSRPRPlansByPIN()", 500);
}
function getSRPRPlansByPIN() {
	var dt = new Date();
	var srprbuffRange = document.getElementById('srprbuffRange').value;
	var responseText = getSRPRPlansData("/gwhweb/viewSRPRPlanListByPin.do?pin=" + subjectPin2 + "&search=true&buffRange=" + srprbuffRange + "&dt=" + dt);
}
function getSRPRPlansData(url) {
	asXmlHttp = GWH.Ajax.getXmlHttpRequest();
	var serverURL = url;
	asXmlHttp.open("GET", serverURL, true);
	asXmlHttp.onreadystatechange = showSurveyPlans;
	asXmlHttp.send(null);
}
function showSurveyPlans() {
	var errUrl = "/gwhweb/errMessage.jsp";
	if (asXmlHttp.readyState == 4) {
		window.status = "showSurveyPlans async done";
		if (asXmlHttp.status == 200||asXmlHttp.status == 0 ) {
			try {
				var responseText = asXmlHttp.responseText;
				document.getElementById("srprplanlistmsgdiv").innerHTML = sselectDocText;
				document.getElementById("srprplanlistdatadiv").innerHTML = responseText;
				parent.resizeIFrameDoc('srprplanlistdatadivwrapper');
				document.getElementById("srprsearchPlansBtn").disabled = false;
				getMainWindow(window).resizeContentFrame();
				//handling the case where the session has expired as the normal mechanism to do
				//so does not work when infilling a DIV
				if (responseText.indexOf('verifyTop') != -1)
				{	if (self != top)
					{	window.open(location.href, '_top');
						return;
					}
				}
				updateReportCounter();
			} catch(e) {
				window.status = 'showPlans.e.src=' + e.source + '\e.n=' + e.name + '\e.m=' + e.message;
				asXmlHttp = null;
				location.href = errUrl;
			}
		} else {
			window.status = "showPlans failed with status " + asXmlHttp.status;
			asXmlHttp = null;
			location.href = errUrl;
		}
	} else {
		window.status = "showPlans readyState " + asXmlHttp.readyState;
		//asXmlHttp = null;
		//location.href = errUrl;
	}
}
function renderSurveyPlan(url) {
	var planWnd = window.open(url, "planwnd",'toolbar=0,menubar=0,location=0,directories=0,resizable=1,status=0,scrollbars=1');
	if (window.focus) {planWnd.focus()}
}
function displaySurveyPreviousResults(subjectPin) {
	var dt = new Date();
	var responseText = getSRPRPlansData("/gwhweb/planlist/SRPRPlanListSearchResults.jsp?pin=" + subjectPin + "&dt=" + dt);
}


 /*******************************************************
 *  MPAC REPORT NON TRANSACTIONAL FULFILLMENT FUNCTIONS
 ********************************************************/
var __MPAC_REPORT_NON_TRANS_FULFILLMENT_FUNCTIONS__;
function closeNonTransWindow() {
	parent.close();
	return false;
}

function deliverProduct() {
  changeInactiveButtonBorder('continueButton');
  disableButton();
  var assessRptForm = document.getElementById("ViewAssessmentReportForm");
  if (trim(assessRptForm.emailAddress.value) != '' && validateCCEmailAddress(assessRptForm.emailAddress.value) > 0) {
	  document.getElementById("userButtonSectionId").style.display="none";
      assessRptForm.action.value = "deliverProduct";
   	  enableButton();
   	  return true;
  	  }
  	  else {
  	  enableButton();
  	  return false;
  	  //document.getElementById("errorMessageId").innerHTML = "<%=ErrorHandler.getErrorMessage(ErrorCodesEnum.INVALID_EMAIL_ADDRESS)%>";
  	  }
}

function disableButton() {
	document.getElementById("continueButton").disabled=true;
	document.getElementById("continueButton").src=assessRptFormContDisSrc;
	document.getElementById("continueButton").title="";
	//TODO: declare class buttond
	document.getElementById("continueButton").className="buttond";

	document.getElementById("cancelButton").disabled=true;
	document.getElementById("cancelButton").src=assessRptFormCancDisSrc;
	document.getElementById("cancelButton").title="";
	//TODO: declare class buttond
	document.getElementById("cancelButton").className="buttond";
}

function enableButton() {
	document.getElementById("continueButton").disabled=false;
	document.getElementById("continueButton").src=assessRptFormContEnaSrc;
	document.getElementById("continueButton").title="Continue";
	//TODO: declare class buttone
	document.getElementById("continueButton").className="buttone";

	document.getElementById("cancelButton").disabled=false;
	document.getElementById("cancelButton").src=assessRptFormCancEnaSrc;
	document.getElementById("cancelButton").title="Cancel";
	//TODO: declare class buttone
	document.getElementById("cancelButton").className="buttone";
}


 /*************************************************
 *             REPORT COUNTER FUNCTIONS
 **************************************************/
var __REPORT_COUNTER_FUNCTIONS__;

/*
 * Function to update the Report Counter Display
 * - Returns true if the counter cound be updated
 * - Returns false if the counter could not be updated (e.g. Property Veiw window not found)
 */
function refreshCounterDisplay(currentWindow) {
	if (currentWindow == null || currentWindow.closed ) {
		// Won't be able to find the main window
		return false;
	}

	// Check if the current window is the main window
	var mainWindow = getMainWindow(currentWindow);

	if ( mainWindow == null ) {
		return false;
	}

	mainWindow.GWH.Ajax.getReportCount(3000, 1, 2000);

	return true;
}

 /*************************************************
 *           ENHANCED REPORT FUNCTIONS
 **************************************************/
var __ENHANCED_REPORT_FUNCTIONS__;


function displayPrintDialog(reportType, pin, jsonExtra) {
	getMainWindow(window).showPrintDialog(reportType, pin, jsonExtra);
}

function displayReport(reportType, pin, excludedSections) {
	getMainWindow(window).runReport(reportType, pin, excludedSections, '750', '500');
}

function showEnhancedReportPrintDialog(reportType, pin)
{
	var ua = UserAccess;
	var rs = ReportSection;
	var isCondo = isCondoProperty(pin);

	reportSectionsMap = new HMap();	//reset each time the dialog is displayed

	if (printDialog.wait)
	{
		printDialog.wait.hide();
		printDialog.wait.destroy();
	}

	printDialog.wait =
               new YAHOO.widget.Dialog("wait",
                                               { width: "720px",
                                                 fixedcenter: true,
                                                 close: true,
                                                 draggable: true,
                                                 zindex:1000,
                                                 modal: true,
                                                 visible: false,
                                                 autofillheight: 'body'
                                               }
                                           );

 	var msgNSSerch = "Be advised you have not performed a neighbourhood sales search. You may proceed and obtain a printed report using the default criteria. <br/>Select &lt;Cancel&gt; to perform a search. Select &lt;Preview&gt; to continue.";

    var dialogHtml = "<div id='printDialog'>";

    dialogHtml += "<div id='noNSSearchWarning' class='nonssearchwarning'>";
    if (ua.ns == 'true' && parent.nSalesSearchDone != pin) {
    	dialogHtml += msgNSSerch;
    }
    dialogHtml += "</div>";

	if (ua.pdr == 'true') {
		dialogHtml += "<div class='dpmargin'>";
		dialogHtml += "<fieldset class='sectionfieldset'>";
		dialogHtml += "<legend class='section'><input type='checkbox' name='cbPropertyDetails' id='cbPropertyDetails' checked onclick='togglePropertyDetailsSection(this.checked);'/>  Property Details</legend>";

		if (ua.ci == 'true' && isCondo && isCondo != null && isCondo == "true") {
			dialogHtml += "<input class='subsection' type='checkbox' name='cbCondoInformation' id='cbCondoInformation' checked onclick='toggleReportSection(this.checked, \"" + rs.ci + "\");'/> Condo Information";
		}
		if (ua.pa == 'true') {
			dialogHtml += "<input class='subsection' type='checkbox' name='cbAssessmentInformation' id='cbAssessmentInformation' checked onclick='toggleReportSection(this.checked, \"" + rs.pa + "\");'/> Assessment Information";
		}
		dialogHtml += "<input class='subsection' type='checkbox' name='cbAerialView' id='cbAerialView' checked onclick='toggleReportSection(this.checked, \"" + rs.av + "\");'/> Aerial View of Property";
		if ( ua.gv == 'true' ) {
			dialogHtml += "<input class='subsection' type='checkbox' name='cbGoogleStreetView' id='cbGoogleStreetView' checked onclick='toggleReportSection(this.checked, \"" + rs.gv + "\");'/>Street View";
		
		} else if (ua.hv == 'true' ) {
			dialogHtml += "<input class='subsection' type='checkbox' name='cbHouseView' id='cbHouseView' checked onclick='toggleReportSection(this.checked, \"" + rs.hv + "\");'/> House View";
		}
		if (ua.sh == 'true') {
			dialogHtml += "<input class='subsection' type='checkbox' name='cbSalesHistoryFullDescription' id='cbSalesHistoryFullDescription' checked onclick='toggleReportSection(this.checked, \"" + rs.sh + "\");'/> Sales History and Full Description";
		}
		dialogHtml += "</fieldset>";
		dialogHtml += "</div>";
	}

	if (ua.ns == 'true') {
		dialogHtml += "<div class='dpmargin'>";
		dialogHtml += "<fieldset class='sectionfieldset'>";
		var nsLegendLabel = "Neighbourhood Sales";
		var nsIndexLabel = "Neighbourhood Sales Index";
		if (ua.cs == 'true') {
			nsLegendLabel = "Comparable Sales";
			nsIndexLabel = "Comparable Sales Index";
		}
		dialogHtml += "<legend class='section'><input type='checkbox' name='cbNeighbourhoodSales' id='cbNeighbourhoodSales' checked onclick='toggleNeighbourhoodSalesSection(this.checked, \"" + rs.nsall + "\");'/>" + nsLegendLabel + "</legend>";
		dialogHtml += "<input class='subsection' type='checkbox' name='cbNeighbourhoodIndex' id='cbNeighbourhoodIndex' checked onclick='toggleReportSection(this.checked, \"" + rs.nsi + "\");'/>" + nsIndexLabel + "<br/>";
		dialogHtml += "</fieldset>";
		dialogHtml += "</div>";
	}

	if (ua.demo == 'true') {
		dialogHtml += "<div class='dpmargin'>";
		dialogHtml += "<fieldset class='sectionfieldset'>";
		dialogHtml += "<legend class='section'><input type='checkbox' name='cbDemographics' id='cbDemographics' checked onclick='toggleDemographicsSection(this.checked, \"" + rs.demo + "\");'/> Demographics</legend>";
		dialogHtml += "<input class='subsection' type='checkbox' name='cbDominantMarketGroup' id='cbDominantMarketGroup' checked onclick='toggleReportSection(this.checked, \"" + rs.dmg + "\");'/> Dominant Market Group";
		dialogHtml += "<input class='subsection' type='checkbox' name='cbPopulation' id='cbPopulation' checked onclick='toggleReportSection(this.checked, \"" + rs.pop + "\");'/> Population";
		dialogHtml += "<input class='subsection' type='checkbox' name='cbHouseholds' id='cbHouseholds' checked onclick='toggleReportSection(this.checked, \"" + rs.hou + "\");'/> Households";
		dialogHtml += "<input class='subsection' type='checkbox' name='cbSocioEconomic' id='cbSocioEconomic' checked onclick='toggleReportSection(this.checked, \"" + rs.soc + "\");'/> Socio-Economic";
		dialogHtml += "<input class='subsection' type='checkbox' name='cbCultural' id='cbCultural' checked onclick='toggleReportSection(this.checked, \"" + rs.cul + "\");'/> Cultural";
		dialogHtml += "</fieldset>";
		dialogHtml += "</div>";
	}

	if (ua.banner =='true') {
		dialogHtml += "<div class='dpmargin'>";
		dialogHtml += "<fieldset class='sectionfieldset'>";
		dialogHtml += "<legend class='section'><input type='checkbox' name='cbOther' id='cbOther' onclick='toggleOtherSection(this.checked, \"" + rs.banner + "\");'/> Other</legend>";
		dialogHtml += "<input class='subsection' type='checkbox' disabled='true' name='cbClientIncentives' id='cbClientIncentives' onclick='toggleReportSection(this.checked, \"" + rs.banner + "\");'/> Client Incentives. <span id='clientIncentivesText' style='display:none;font-weight:bold'>Click here to complement your Enhanced Report with this offer. <a id='clientIncentivesLink' href='' target='_blank'>How does my client benefit?</a><br/></span>";
		dialogHtml += "<div id='reportConfigAddivid' style='width:100%;text-align:center'><a id='reportConfigAdhlid' href='' target='_blank'></a></div>";
		dialogHtml += "</fieldset>";
		dialogHtml += "</div>";
		toggleReportSection(false, rs.banner);
	}

	dialogHtml += "<p>";
	dialogHtml += "<div align='center'>";
	dialogHtml += "<input class='formbtn' type='button' name='print' value='Preview' alt='Preview' onclick='postPrintDialog(\"" + reportType + "\", \"" + pin + "\");'>";
	dialogHtml += "&nbsp;&nbsp;";
	dialogHtml += "<input class='formbtn' type='button' name='cancel' value='Cancel' onclick='printDialog.wait.hide();'>";
	dialogHtml += "</div>";
	dialogHtml += "</div>";

	printDialog.wait.setBody(dialogHtml);
	printDialog.wait.setHeader("ENHANCED REPORT - SECTIONS TO PRINT");
	printDialog.wait.render(document.body);

	if (ua.banner =='true') {
		var adResultCallback = function(result, jsonAd) {
			
			if (result == 'SUCCESS') {
				document.getElementById('clientIncentivesText').style.display = 'inline'
				var clientIncentivesLink = document.getElementById('clientIncentivesLink');
				if (clientIncentivesLink) {
					if (jsonAd['clickThroughURL']) {
						clientIncentivesLink.href = jsonAd['clickThroughURL'];
					} else {
						clientIncentivesLink.style.display = 'none';
					}
				}
			}
			else {
				var checkBox1 = document.getElementById('cbOther');
				var checkBox2 = document.getElementById('cbClientIncentives');
				checkBox1.checked = checkBox2.checked = false;
				checkBox1.disabled = checkBox2.disabled = true;
			}
			printDialog.wait.forceContainerRedraw(); 
			printDialog.wait.center(); 
		};
		
		var frame = document.getElementById('PropertySearchResultsID').contentWindow;
		var municipality = frame.piiMunicipality;
		if (! municipality) {
			var propCache = getPageResultsCache();
			if (propCache != null && propCache.list != null) {
				var len = propCache.list.length;
				for (var i=0; i<len; i++) {
					if (propCache.list[i].pin == pin) {
						municipality = propCache.list[i].municipality;
						break;
					}
				}
			}
		}
	
		retrieveBannerAd('ENHANCED_REPORT_CONFIG', municipality, null, adResultCallback);
	}	
	// Show the Print Dialog
	printDialog.wait.show();
}

function showPrintDialog(reportType, pin, jsonExtra)
{
	if (reportType == 'ENHANCED') {
		return showEnhancedReportPrintDialog(reportType, pin)
	}
	var ua = UserAccess;
	var rs = ReportSection;
	var isCondo = isCondoProperty(pin);

	reportSectionsMap = new HMap();	//reset each time the dialog is displayed

	if (printDialog.wait)
	{
		printDialog.wait.hide();
		printDialog.wait.destroy();
	}

	printDialog.wait =
               new YAHOO.widget.Dialog("wait",
                                               { width: "380px",
                                                 fixedcenter: true,
                                                 close: true,
                                                 draggable: true,
                                                 zindex:1000,
                                                 modal: true,
                                                 visible: false
                                               }
                                           );

 	var msgNSSerch = "Be advised you have not performed a neighbourhood sales search. You may proceed and obtain a printed report using the default criteria. <br /><br />Select &lt;Cancel&gt; to perform a search. <br />Select &lt;Preview&gt; to continue.";

	if (reportType == 'PROPERTY_DETAIL') {
		printDialog.wait.setHeader("PROPERTY DETAILS REPORT - SECTIONS TO PRINT");
	}
	else if (reportType == 'ARN_DETAIL') {
		printDialog.wait.setHeader("ASSESSMENT DETAILS REPORT - SECTIONS TO PRINT");
	}
	else if (reportType == 'NEIGHBOURHOOD_SALES') {
		var hdrText = "NEIGHBOURHOOD SALES REPORT - SECTIONS TO PRINT";
		if (ua.cs == 'true') {
			hdrText = "COMPARABLE SALES REPORT - SECTIONS TO PRINT";
		}
		printDialog.wait.setHeader(hdrText);
	}
	else if (reportType == 'DEMOGRAPHICS') {
		printDialog.wait.setHeader("DEMOGRAPHICS REPORT - SECTIONS TO PRINT");
	}
	else if (reportType == 'COMPARABLES') {
		printDialog.wait.setHeader("COMPARABLES REPORT - SECTIONS TO PRINT");
	}
	else {
		printDialog.wait.setHeader("ENHANCED REPORT - SECTIONS TO PRINT");
	}
	
    var dialogHtml = "<div id='printDialog'>";

    dialogHtml += "<div id='noNSSearchWarning' class='nonssearchwarning'>";
    dialogHtml += "</div>";

	if (reportType == 'PROPERTY_DETAIL' && ua.pdr == 'true') {
		dialogHtml += "<div class='dpmargin'>";
		dialogHtml += "<fieldset class='sectionfieldset'>";
		if (reportType == 'PROPERTY_DETAIL') {
			dialogHtml += "<legend class='section'>Property Details</legend>";
		}
		else {
			dialogHtml += "<legend class='section'><input type='checkbox' name='cbPropertyDetails' id='cbPropertyDetails' checked onclick='togglePropertyDetailsSection(this.checked);'/>  Property Details</legend>";
		}

		if (ua.ci == 'true' && isCondo && isCondo != null && isCondo == "true") {
			dialogHtml += "<input class='subsection' type='checkbox' name='cbCondoInformation' id='cbCondoInformation' checked onclick='toggleReportSection(this.checked, \"" + rs.ci + "\");'/> Condo Information<br/>";
		}
		if (ua.pa == 'true') {
			dialogHtml += "<input class='subsection' type='checkbox' name='cbAssessmentInformation' id='cbAssessmentInformation' checked onclick='toggleReportSection(this.checked, \"" + rs.pa + "\");'/> Assessment Information<br/>";
		}
		dialogHtml += "<input class='subsection' type='checkbox' name='cbAerialView' id='cbAerialView' checked onclick='toggleReportSection(this.checked, \"" + rs.av + "\");'/> Aerial View of Property<br/>";
		if ( ua.gv == 'true' ) {
			dialogHtml += "<input class='subsection' type='checkbox' name='cbGoogleStreetView' id='cbGoogleStreetView' checked onclick='toggleReportSection(this.checked, \"" + rs.gv + "\");'/> Street View<br/>";
		
		} else if (ua.hv == 'true' ) {
			dialogHtml += "<input class='subsection' type='checkbox' name='cbHouseView' id='cbHouseView' checked onclick='toggleReportSection(this.checked, \"" + rs.hv + "\");'/> House View<br/>";
		}
		if (ua.sh == 'true') {
			dialogHtml += "<input class='subsection' type='checkbox' name='cbSalesHistoryFullDescription' id='cbSalesHistoryFullDescription' checked onclick='toggleReportSection(this.checked, \"" + rs.sh + "\");'/> Sales History and Full Description<br/>";
		}
		dialogHtml += "</fieldset>";
		dialogHtml += "</div>";
	}
	else if (reportType == 'ARN_DETAIL' && ua.arnDetails == 'true') {
		dialogHtml += "<div class='dpmargin'>";
		dialogHtml += "<fieldset class='sectionfieldset'>";
		dialogHtml += "<legend class='section'>Assessment Details</legend>";

		if (! pin ) {
			dialogHtml += '<div style="color:red;text-align:center;">Land Registry Information is not available</div>';
		}
		if ( jsonExtra.arnCount  == 0) {
			dialogHtml += '<div style="color:red;text-align:center;">Assessment Information is not available</div>';
		}
		
		if (jsonExtra.arnCount < 2) {
			toggleArnSection(rs.arnCurrent, rs.arnAll);
		}
		else {
			dialogHtml += "<fieldset class='sectionfieldset'>";
			dialogHtml += " <input class='subsection' type='radio' name='radioArnDetails' style='margin-left: 12px;' checked='true' onclick='toggleArnSection(\"" + rs.arnCurrent + "\",\"" + rs.arnAll + "\")'/>Current Assessment Details<br/>";
			dialogHtml += " <input class='subsection' type='radio' name='radioArnDetails' style='margin-left: 12px;'				onclick='toggleArnSection(\"" + rs.arnAll + "\",\"" + rs.arnCurrent + "\")'/>All Assessment Details";
			dialogHtml += "</fieldset>"; 
			toggleReportSection(false, rs.arnAll); // exclude by default
		}
		dialogHtml += "<input class='subsection' type='checkbox' name='cbArnPinInfo' id='cbArnPinInfo' " + (!pin ? 'disabled':'checked')+" onclick='toggleReportSection(this.checked, \"" + rs.pii + "\");'/> Land Registry Information<br/>";
		dialogHtml += "<input class='subsection' type='checkbox' name='cbAerialView' id='cbAerialView' " + (!pin ? 'disabled':'checked')+" onclick='toggleReportSection(this.checked, \"" + rs.av + "\");'/> Aerial View of Property<br/>";
		if ( ua.gv == 'true' ) {
			dialogHtml += "<input class='subsection' type='checkbox' name='cbGoogleStreetView' id='cbGoogleStreetView' " + (!pin ? 'disabled':'checked')+" onclick='toggleReportSection(this.checked, \"" + rs.gv + "\");'/> Street View<br/>";
		
		} else if (ua.hv == 'true' ) {
			dialogHtml += "<input class='subsection' type='checkbox' name='cbHouseView' id='cbHouseView' " + (!pin ? 'disabled':'checked')+" onclick='toggleReportSection(this.checked, \"" + rs.hv + "\");'/> House View<br/>";
		}
		if ( ! pin) {
			toggleReportSection(false, rs.pii);
			toggleReportSection(false, rs.av);
			toggleReportSection(false, rs.gv);
			toggleReportSection(false, rs.hv);
		}
			dialogHtml += "<input class='subsection' type='checkbox' name='cbArnProp' id='cbArnProp' " + (jsonExtra.arnCount == 0 ? 'disabled':'checked')+" onclick='toggleReportSection(this.checked, \"" + rs.arnProp + "\");'/> Assessment Property Information<br/>";
			dialogHtml += "<input class='subsection' type='checkbox' name='cbArnSale' id='cbArnSale' " + (jsonExtra.arnCount == 0 ? 'disabled':'checked')+" onclick='toggleReportSection(this.checked, \"" + rs.arnSale + "\");'/> Valuation And Sale Information<br/>";
			dialogHtml += "<input class='subsection' type='checkbox' name='cbArnSite' id='cbArnSite' " + (jsonExtra.arnCount == 0 ? 'disabled':'checked')+" onclick='toggleReportSection(this.checked, \"" + rs.arnSite + "\");'/> Assessment Site Information<br/>";
			dialogHtml += "<input class='subsection' type='checkbox' name='cbArnResStruc' id='cbArnResStruc' " + (jsonExtra.arnCount == 0 ? 'disabled':'checked')+" onclick='toggleReportSection(this.checked, \"" + rs.arnResStruc + "\");'/> Residential Structure Information<br/>";
			if (ua.arnDetailsICI == 'true') {
				dialogHtml += "<input class='subsection' type='checkbox' name='cbArnIndStruc' id='cbArnIndStruc' " + (jsonExtra.arnCount == 0 ? 'disabled':'checked')+" onclick='toggleReportSection(this.checked, \"" + rs.arnIndStruc + "\");'/> Industrial Structure Information<br/>";
				dialogHtml += "<input class='subsection' type='checkbox' name='cbArnComm' id='cbArnComm' " + (jsonExtra.arnCount == 0 ? 'disabled':'checked')+" onclick='toggleReportSection(this.checked, \"" + rs.arnComm + "\");'/> Commercial Information<br/>";
			}
	
		dialogHtml += "</fieldset>";
		dialogHtml += "</div>";
	}
	else if (reportType == 'COMPARABLES' && ua.arnDetails == 'true') {
		dialogHtml += "<div class='dpmargin'>";
		dialogHtml += "<fieldset class='sectionfieldset'>";
		dialogHtml += "<legend class='section'>Subject Property Details</legend>";

		dialogHtml += "<input class='subsection' type='checkbox' name='cbArnPinInfo' id='cbArnPinInfo' checked onclick='toggleReportSection(this.checked, \"" + rs.pii + "\");'/> Land Registry Information<br/>";
		dialogHtml += "<input class='subsection' type='checkbox' name='cbAerialView' id='cbAerialView' checked onclick='toggleReportSection(this.checked, \"" + rs.av + "\");'/> Aerial View of Property<br/>";
		if ( ua.gv == 'true' ) {
			dialogHtml += "<input class='subsection' type='checkbox' name='cbGoogleStreetView' id='cbGoogleStreetView' checked onclick='toggleReportSection(this.checked, \"" + rs.gv + "\");'/> Street View<br/>";
		} else if (ua.hv == 'true' ) {
			dialogHtml += "<input class='subsection' type='checkbox' name='cbHouseView' id='cbHouseView' checked onclick='toggleReportSection(this.checked, \"" + rs.hv + "\");'/> House View<br/>";
		}
		dialogHtml += "</fieldset>";

		dialogHtml += "<fieldset class='sectionfieldset'>";
		dialogHtml += "<legend class='section'>Comparables</legend>";

		dialogHtml += "<input class='subsection' type='checkbox' name='cbArnProp' id='cbArnProp' checked onclick='toggleReportSection(this.checked, \"" + rs.arnProp + "\");'/> Assessment Property Information<br/>";
		dialogHtml += "<input class='subsection' type='checkbox' name='cbArnSale' id='cbArnSale' checked onclick='toggleReportSection(this.checked, \"" + rs.arnSale + "\");'/> Valuation And Sale Information<br/>";
		dialogHtml += "<input class='subsection' type='checkbox' name='cbArnSite' id='cbArnSite' checked onclick='toggleReportSection(this.checked, \"" + rs.arnSite + "\");'/> Assessment Site Information<br/>";
		//dialogHtml += "<input class='subsection' type='checkbox' name='cbArnResStruc' id='cbArnResStruc' checked onclick='toggleReportSection(this.checked, \"" + rs.arnResStruc + "\");'/> Residential Structure Information<br/>";
		if (ua.arnDetailsICI == 'true') {
			dialogHtml += "<input class='subsection' type='checkbox' name='cbArnIndStruc' id='cbArnIndStruc' checked onclick='toggleReportSection(this.checked, \"" + rs.arnIndStruc + "\");'/> Industrial Structure Information<br/>";
			dialogHtml += "<input class='subsection' type='checkbox' name='cbArnComm' id='cbArnComm' checked onclick='toggleReportSection(this.checked, \"" + rs.arnComm + "\");'/> Commercial Information<br/>";
		}
	
		dialogHtml += "</fieldset>";
		dialogHtml += "</div>";
	}

	if (reportType == 'NEIGHBOURHOOD_SALES' && ua.ns == 'true') {
		dialogHtml += "<div class='dpmargin'>";
		dialogHtml += "<fieldset class='sectionfieldset'>";
		var nsLegendLabel = "Neighbourhood Sales";
		var nsIndexLabel = "Neighbourhood Sales Index";
		if (ua.cs == 'true') {
			nsLegendLabel = "Comparable Sales";
			nsIndexLabel = "Comparable Sales Index";
		}
		dialogHtml += "<legend class='section'>" + nsLegendLabel + "</legend>";
		dialogHtml += "<input class='subsection' type='checkbox' name='cbNeighbourhoodIndex' id='cbNeighbourhoodIndex' checked onclick='toggleReportSection(this.checked, \"" + rs.nsi + "\");'/>" + nsIndexLabel + "<br/>";
		dialogHtml += "</fieldset>";
		dialogHtml += "</div>";
	}

	if (reportType == 'DEMOGRAPHICS' && ua.demo == 'true') {
		dialogHtml += "<div class='dpmargin'>";
		dialogHtml += "<fieldset class='sectionfieldset'>";
		dialogHtml += "<legend class='section'>Demographics</legend>";
		dialogHtml += "<input class='subsection' type='checkbox' name='cbDominantMarketGroup' id='cbDominantMarketGroup' checked onclick='toggleReportSection(this.checked, \"" + rs.dmg + "\");'/> Dominant Market Group<br/>";
		dialogHtml += "<input class='subsection' type='checkbox' name='cbPopulation' id='cbPopulation' checked onclick='toggleReportSection(this.checked, \"" + rs.pop + "\");'/> Population<br/>";
		dialogHtml += "<input class='subsection' type='checkbox' name='cbHouseholds' id='cbHouseholds' checked onclick='toggleReportSection(this.checked, \"" + rs.hou + "\");'/> Households<br/>";
		dialogHtml += "<input class='subsection' type='checkbox' name='cbSocioEconomic' id='cbSocioEconomic' checked onclick='toggleReportSection(this.checked, \"" + rs.soc + "\");'/> Socio-Economic<br/>";
		dialogHtml += "<input class='subsection' type='checkbox' name='cbCultural' id='cbCultural' checked onclick='toggleReportSection(this.checked, \"" + rs.cul + "\");'/> Cultural<br/>";
		dialogHtml += "</fieldset>";
		dialogHtml += "</div>";
	}

	if(reportType =='OTHER' && ua.banner =='true'){
		dialogHtml += "<div class='dpmargin'>";
		dialogHtml += "<fieldset class='sectionfieldset'>";
		dialogHtml += "<legend class='section'>Other</legend>";
		dialogHtml += "<input class='subsection' type='checkbox' name='cbClientIncentives' id='cbClientIncentives' checked onclick='toggleReportSection(this.checked, \"" + rs.banner + "\");'/> Client Incentives<br/>";
		dialogHtml += "</fieldset>";
		dialogHtml += "</div>";
	}

	dialogHtml += "<p>";
	dialogHtml += "<div align='center'>";
	dialogHtml += "<input class='formbtn' type='button' name='print' value='Preview' alt='Preview' onclick='postPrintDialog(\"" + reportType + "\", \"" + pin + "\");'>";
	dialogHtml += "&nbsp;&nbsp;";
	dialogHtml += "<input class='formbtn' type='button' name='cancel' value='Cancel' onclick='printDialog.wait.hide();'>";
	dialogHtml += "</div>";
	dialogHtml += "</div>";


	printDialog.wait.setBody(dialogHtml);
	printDialog.wait.render(document.body);

	// Show the Print Dialog
	printDialog.wait.show();
}

function isCondoProperty(pin) {
	var isCondoUrl="./viewpropertydetails.do?pin=" + pin + "&getCondo=true&arn=&ts=" + new Date().getTime();
	var isCondo = "";
	var asXmlHttp = GWH.Ajax.getXmlHttpRequest();
	asXmlHttp.open("GET", isCondoUrl, false);
	asXmlHttp.send(null);
	if (asXmlHttp.readyState == 4) {
		if (asXmlHttp.status == 200||asXmlHttp.status == 0 ) {
			try {
				isCondo = asXmlHttp.responseText;
			} catch(e) {
				//alert("error " + e.source + ' e.name=' + e.name + ' e.message=' + e.message);
			}
		} else {
			//alert("error with status " + asXmlHttp.status);
		}
	} else {
		//alert("error with state " + asXmlHttp.readyState);
	}
	return isCondo;
}

function hideNoSearchNSWarning() {
	parent.document.getElementById('noNSSearchWarning').style.display = 'none';

}

function postPrintDialog(reportType, pin)
{
	if (printDialog.wait) {
		printDialog.wait.hide();

		excludedSections = '';	//comma delimited list of report sections to exclude
		excludedSectionsArray = new Array();
		var sectionKeys = reportSectionsMap.getkeys();
		for (var k = 0 ; k < sectionKeys.length ; k++)
		{
			if (reportSectionsMap.get(sectionKeys[k]) == false)	//this corresponds to the unchecked report section checkbox
			{
				excludedSectionsArray[excludedSectionsArray.length] = sectionKeys[k];
			}
		}
		for (var s = 0 ; s < excludedSectionsArray.length ; s++)
		{
			excludedSections += excludedSectionsArray[s];
			if ((s+1) < excludedSectionsArray.length) excludedSections += ",";
		}

		var ua = UserAccess;
		var rs = ReportSection;

		if (ua.pdr != 'true') {
			if (excludedSections != '') {
				excludedSections += ",";
			}
			excludedSections += rs.ci;
			excludedSections += ",";
			excludedSections += rs.pa;
			excludedSections += ",";
			excludedSections += rs.gv;
			excludedSections += ",";
			excludedSections += rs.hv;
			excludedSections += ",";
			excludedSections += rs.av;
			excludedSections += ",";
			excludedSections += rs.sh;
		}

		if (ua.sh != 'true') {
			if (excludedSections != '') {
				excludedSections += ",";
			}
			excludedSections += rs.sh;
		}

		if (ua.pa != 'true') {
			if (excludedSections != '') {
				excludedSections += ",";
			}
			excludedSections += rs.pa;
		}

		if (ua.ci != 'true') {
			if (excludedSections != '') {
				excludedSections += ",";
			}
			excludedSections += rs.ci;
		}

		if (ua.gv != 'true') {
			if (excludedSections != '') {
				excludedSections += ",";
			}
			excludedSections += rs.gv;
		}

		if (ua.hv != 'true') {
			if (excludedSections != '') {
				excludedSections += ",";
			}
			excludedSections += rs.hv;
		}

		if (ua.ns != 'true') {
			if (excludedSections != '') {
				excludedSections += ",";
			}
			excludedSections += rs.nsall;
			excludedSections += ",";
			excludedSections += rs.nsi;
		}

		if (ua.demo != 'true') {
			if (excludedSections != '') {
				excludedSections += ",";
			}
			excludedSections += rs.demo;
			excludedSections += ",";
			excludedSections += rs.dmg;
			excludedSections += ",";
			excludedSections += rs.pop;
			excludedSections += ",";
			excludedSections += rs.hou;
			excludedSections += ",";
			excludedSections += rs.soc;
			excludedSections += ",";
			excludedSections += rs.cul;
		}

		displayReport(reportType, pin, excludedSections);
	}
}

function toggleReportSection(include, section)
{
	reportSectionsMap.put(section, include);
}

function togglePropertyDetailsSection(cbChecked)
{
	var ua = UserAccess;
	var rs = ReportSection;

	var cbSalesHistoryFullDescription = document.getElementById("cbSalesHistoryFullDescription");
	var cbHouseView = document.getElementById("cbHouseView");
	var cbGoogleStreetView = document.getElementById("cbGoogleStreetView");
	var cbCondoInformation = document.getElementById("cbCondoInformation");
	var cbAssessmentInformation = document.getElementById("cbAssessmentInformation");
	var cbAerialView = document.getElementById("cbAerialView");

	if (cbChecked)
	{
		if (ua.sh == 'true') {
			cbSalesHistoryFullDescription.disabled = false;
		}
		if (ua.gv == 'true') {
			cbGoogleStreetView.disabled = false;
		}
		else if (ua.hv == 'true') {
			cbHouseView.disabled = false;
		}
		if (ua.ci == 'true' && cbCondoInformation != undefined ) {
			cbCondoInformation.disabled = false;
		}
		if (ua.pa == 'true') {
			cbAssessmentInformation.disabled = false;
		}
		cbAerialView.disabled = false;
		if (ua.sh == 'true' && !cbSalesHistoryFullDescription.checked) {
			cbSalesHistoryFullDescription.checked = true;
			toggleReportSection(true, rs.sh);
		}
		if (ua.gv == 'true' && !cbGoogleStreetView.checked) {
			cbGoogleStreetView.checked = true; 
			toggleReportSection(true, rs.gv);
		} else if (ua.hv == 'true' && !cbHouseView.checked) {
			cbHouseView.checked = true;
			toggleReportSection(true, rs.hv);
		}
		if (!cbAerialView.checked) {
			cbAerialView.checked = true;
			toggleReportSection(true, rs.av);
		}
		if (ua.pa == 'true' && !cbAssessmentInformation.checked) {
			cbAssessmentInformation.checked = true;
			toggleReportSection(true, rs.pa);
		}
		if (ua.ci == 'true' && cbCondoInformation != undefined && !cbCondoInformation.checked) {
			cbCondoInformation.checked = true;
			toggleReportSection(true, rs.ci);
		}
	} else
	{
		if (ua.sh == 'true') {
			if (cbSalesHistoryFullDescription.checked) {
				cbSalesHistoryFullDescription.checked = false;
				toggleReportSection(false, rs.sh);
			}
			cbSalesHistoryFullDescription.disabled = true;
		}
		if (ua.gv == 'true') {
		 	if (cbGoogleStreetView.checked) { 
		 		cbGoogleStreetView.checked = false;
				toggleReportSection(false, rs.gv);
			}
			cbGoogleStreetView.disabled = true;
		} else if (ua.hv == 'true') {
			if (cbHouseView.checked) {
				cbHouseView.checked = false;
				toggleReportSection(false, rs.hv);
			}
			cbHouseView.disabled = true;
		}
		if (ua.pa == 'true') {
			if (cbAssessmentInformation.checked) {
				cbAssessmentInformation.checked = false;
				toggleReportSection(false, rs.pa);
			}
			cbAssessmentInformation.disabled = true;
		}
		if (ua.ci == 'true' && cbCondoInformation != undefined ) {	
			if (cbCondoInformation.checked) {
				cbCondoInformation.checked = false;
				toggleReportSection(false, rs.ci);
			}
			cbCondoInformation.disabled = true;
		}
		if (cbAerialView.checked) {
			cbAerialView.checked = false;
			toggleReportSection(false, rs.av);
		}
		cbAerialView.disabled = true;
	}
}

function toggleNeighbourhoodSalesSection(cbChecked, reportSection)
{
	var cbNeighbourhoodIndex = document.getElementById("cbNeighbourhoodIndex");
	var rs = ReportSection;

	toggleReportSection(cbChecked, reportSection);

	if (cbChecked)
	{
		cbNeighbourhoodIndex.disabled = false;
		if (!cbNeighbourhoodIndex.checked) {
			cbNeighbourhoodIndex.checked = true;
			toggleReportSection(true, rs.nsi);
		}
	} else
	{
		if (cbNeighbourhoodIndex.checked) {
			cbNeighbourhoodIndex.checked = false;
			toggleReportSection(false, rs.nsi);
		}
		cbNeighbourhoodIndex.disabled = true;
	}
}

function toggleArnSection(sectionToInclude, sectionToExclude) {
	toggleReportSection(true, sectionToInclude);
	toggleReportSection(false, sectionToExclude);
}
function toggleDemographicsSection(cbChecked, reportSection)
{

	var rs = ReportSection;
	var cbDominantMarketGroup = document.getElementById("cbDominantMarketGroup");
	var cbPopulation = document.getElementById("cbPopulation");
	var cbHouseholds = document.getElementById("cbHouseholds");
	var cbSocioEconomic = document.getElementById("cbSocioEconomic");
	var cbCultural = document.getElementById("cbCultural");

	toggleReportSection(cbChecked, reportSection);

	if (cbChecked)
	{
		cbDominantMarketGroup.disabled = false;
		cbPopulation.disabled = false;
		cbHouseholds.disabled = false;
		cbSocioEconomic.disabled = false;
		cbCultural.disabled = false;
		if (!cbDominantMarketGroup.checked) {
			cbDominantMarketGroup.checked = true;
			toggleReportSection(true, rs.dmg);
		}
		if (!cbPopulation.checked) {
			cbPopulation.checked = true;
			toggleReportSection(true, rs.pop);
		}
		if (!cbHouseholds.checked) {
			cbHouseholds.checked = true;
			toggleReportSection(true, rs.hou);
		}
		if (!cbSocioEconomic.checked) {
			cbSocioEconomic.checked = true;
			toggleReportSection(true, rs.soc);
		}
		if (!cbCultural.checked) {
			cbCultural.checked = true;
			toggleReportSection(true, rs.cul);
		}
	} else
	{
		if (cbDominantMarketGroup.checked) {
			cbDominantMarketGroup.checked = false;
			toggleReportSection(false, rs.dmg);
		}
		cbDominantMarketGroup.disabled = true;

		if (cbPopulation.checked) {
			cbPopulation.checked = false;
			toggleReportSection(false, rs.pop);
		}
		cbPopulation.disabled = true;

		if (cbHouseholds.checked) {
			cbHouseholds.checked = false;
			toggleReportSection(false, rs.hou);
		}
		cbHouseholds.disabled = true;

		if (cbSocioEconomic.checked) {
			cbSocioEconomic.checked = false;
			toggleReportSection(false, rs.soc);
		}
		cbSocioEconomic.disabled = true;

		if (cbCultural.checked) {
			cbCultural.checked = false;
			toggleReportSection(false, rs.cul);
		}
		cbCultural.disabled = true;
	}
}

function toggleOtherSection(cbChecked, reportSection)
{

	var rs = ReportSection;
	var cbClientIncentives = document.getElementById("cbClientIncentives");


	toggleReportSection(cbChecked, reportSection);
	cbClientIncentives.disabled = !cbChecked;

	if (cbChecked)
	{
		if (!cbClientIncentives.checked) {
			cbClientIncentives.checked = true;
			toggleReportSection(true, rs.banner);
		}
	}
	else
	{
		if (cbClientIncentives.checked) {
			cbClientIncentives.checked = false;
			toggleReportSection(false, rs.banner);
		}
	}
}

function initReport(pageType, bannerAdAccess, municipality) {
	initializeMaps();
	refreshCounterDisplay(window);
	showPrintButton();
	generatePageBreaks();
	disableSelection(document.body) //disable text selection on entire body of page
	//adjustReportWithBannerAd();
	if (bannerAdAccess=='true') {
		retrieveBannerAd(pageType, municipality);
	}
}
function showPrintButton() {
	document.getElementById("printBtnHeader").className='formbtn';
	document.getElementById("printBtnFooter").className='formbtn';
}
function disableSelection(target) {
	if (typeof target.onselectstart!="undefined") {
		//IE
		target.onselectstart=function(){
			return false
		}
	} else if (typeof target.style.MozUserSelect!="undefined") {
		//Firefox
		target.style.MozUserSelect="none"
	} else {
		//All other browsers(ie: Opera)
		target.onmousedown=function(){return false}
	}
	target.style.cursor = "default"
}
function getPropertyRptMapJsonData() {
	if (propertyRptMapJsonData == 'none') {
		return null;
	}
	return eval(propertyRptMapJsonData);
}
function getNsPropertyJsonData() {
	if (nsPropertyJsonData == 'none') {
		return null;
	}
	return eval(nsPropertyJsonData);
}
function getNsJsonData() {
	if (nsJsonData == 'none') {
		return null;
	}
	return eval(nsJsonData);
}

 /*************************************************
 *               PARCEL REGISTER FUNCTIONS
 **************************************************/
var __PARCEL_REGISTER_FUNCTIONS__;


function parcelregister(url, pin)
{
	var mainWindow = getMainWindow(window);
	mainWindow.runParcelRegister(url, pin);
}


function regeneratePR(chk, pin, pinstatus, transactional){
	//window.document.getElementById("productConfig").disabled = true;
	document.getElementById("productConfig").disabled = true;
	var includeDeletedInstruments;
	if(chk.checked){
	// include deleted instruments
		includeDeletedInstruments="true";
	}
	else{
	// do not include deleted instruments
		includeDeletedInstruments="false";
	}
	if(transactional == false){
		prDisableButton();
	} else {
		pdsDisableButton();
	}
	asXmlHttp = GWH.Ajax.getXmlHttpRequest();
	var servUrl = "/gwhweb/parcelRegister.do?pin="+pin+"&transactional="+transactional+"&includeDeletedInstruments="+
		includeDeletedInstruments + "&pinStatus=" + pinstatus +
		"&firstRequest=false";
	asXmlHttp.open("GET", servUrl, true);
	if(transactional == true)
		asXmlHttp.onreadystatechange = handleServerResponsePRTrans;
	else
		asXmlHttp.onreadystatechange = handleServerResponsePRNonTrans;
	asXmlHttp.send(null);
}

function handleServerResponsePRTrans(){
	if (asXmlHttp.readyState == 4) {
		if(asXmlHttp.status == 200) {
			var errMessage =  asXmlHttp.responseXML.getElementsByTagName("errorMessage")[0].childNodes[0].nodeValue;
			errMessage = errMessage.substr(1,errMessage.length-2);
			if (errMessage != 'null') {
				errorUrl = "errMessage.jsp?ErrorMsgToDisplay=" + errMessage;
				location.replace(errorUrl);
				return;
			}
			else {
				var message =  asXmlHttp.responseXML.getElementsByTagName("price")[0].childNodes[0].nodeValue;
				var Extra_Pages_Statutory =  asXmlHttp.responseXML.getElementsByTagName("Extra_Pages_Statutory")[0].childNodes[0].nodeValue;
				var Extra_Pages_None_Statutory =  asXmlHttp.responseXML.getElementsByTagName("Extra_Pages_None_Statutory")[0].childNodes[0].nodeValue;
				var Page_1_Statutory =  asXmlHttp.responseXML.getElementsByTagName("Page_1_Statutory")[0].childNodes[0].nodeValue;
				var Page_1_None_Statutory =  asXmlHttp.responseXML.getElementsByTagName("Page_1_None_Statutory")[0].childNodes[0].nodeValue;

				document.getElementById("itemprice").innerHTML= '$'+ message.substr(1,message.length-2);

 				var HTMLStr="";
				HTMLStr+="$"+Page_1_Statutory.substr(1,Page_1_Statutory.length-2)+" <acronym name=\"STATUTORY\">Statutory</acronym> Fee Page 1<br>";
				HTMLStr+="$"+Page_1_None_Statutory.substr(1,Page_1_None_Statutory.length-2)+" <acronym name=\"ELRSA\">ELRSA</acronym> Fee Page 1<br>";
				HTMLStr+="$"+Extra_Pages_Statutory.substr(1,Extra_Pages_Statutory.length-2)+" <acronym name=\"STATUTORY\">Statutory</acronym> Fee Extra Pages<br>";
				HTMLStr+="$"+Extra_Pages_None_Statutory.substr(1,Extra_Pages_None_Statutory.length-2)+" <acronym name=\"ELRSA\">ELRSA</acronym> Fee Extra Pages<br>";
				HTMLStr+="<br>";
				HTMLStr+="Plus applicable taxes.";

				document.getElementById("productDetail").innerHTML=HTMLStr;

				var message =  asXmlHttp.responseXML.getElementsByTagName("numpages")[0].childNodes[0].nodeValue;
				document.getElementById("attributevalue0_0").value = message.substr(1,message.length-2);
			}
		}
		else {
			alert("Error during AJAX call. Please try again");
		}
		window.document.getElementById("productConfig").disabled = false;

		pdsEnableButton();
	}
}

function handleServerResponsePRNonTrans(){
	  if (asXmlHttp.readyState == 4) {
	     if(asXmlHttp.status == 200) {
	     	try {
		     	var errMessage =  asXmlHttp.responseXML.getElementsByTagName("errorMessage")[0].childNodes[0].nodeValue;
				errMessage = errMessage.substr(1,errMessage.length-2);
				if (errMessage != 'null') {
					errorUrl = "errMessage.jsp?ErrorMsgToDisplay=" + errMessage;
					location.replace(errorUrl);
					return;
				}
			}
			catch (e) {
				// don't need to do anything
				// when this error occur that's means the regenerate is succesful
				// This errMessage object will only available when regenerate has error
			}

		     var message =  "<a href=\"JavaScript:downloadParcelRegister(emailAddress.value);\">Download Parcel Register</a>";
			 prEnableButton(false);
	     }
	     else {
	        alert("Error during AJAX call. Please try again");
	     }
	     window.document.getElementById("productConfig").disabled = false;
   		}
}

function validateEmailAddress(e)
{
    if(e.length ==0)
    {
        alert("Please Specify the Email Address");
        return -1;
    }
    i = e.indexOf("@", 0);
    if((i == -1) || (i == 0))
    {
        alert("Incorrect Email Address");
        return -1;
    }
    j = e.indexOf("@", i+1);
    if(j != -1)
    {
        alert("Incorrect Email Address");
        return -1;
    }
    j = e.indexOf(".",i+1);
    m = j-i;
    if(m == 1)
    {
        alert("Incorrect Email Address");
        return -1;
    }
    j = e.lastIndexOf(".");
    if(j == -1)
    {
        alert("Incorrect Email Address");
        return -1;
    }
    domain = e.substr(j+1,e.length-j-1);
    i = domain.length;
    if(i < 2)
    {
        alert("Incorrect Domain Name");
        return -1;
    }
    for (j = 0; j < i; j++)
    {
        l = domain.substr(j,1);
        if((l >= "a" && l <= "z") || (l >= "A" && l <= "Z" ))
            {
                // is letter
            }
        else
        {
            alert("Incorrect Domain Name");
            return -1;
        }
    }
    return 1;
}


/*
 *	Used by:
 *		parcelregister/PRNonTransDetailScreen.jsp
 *
 *	Usage:
 *	- Send the parcel register through email
 */
function downloadParcelRegister(email){
	changeInactiveButtonBorder('continueButton');
	prDisableButton();
	var i = validateEmailAddress(email);
	if(i < 0) {
		prEnableButton(false);
		return;
	}

 	document.getElementById("userButtonSectionId").style.display="none";
	var servUrl= contextPath + "/parcelregister/DeliverParcelRegisterDocumentServlet?emailAddress="+email;
	window.open(servUrl,"ProductDetailScreen","height=500, RESIZABLE=yes, width=690, scrollbars=no, status=no, toolbar=no, menubar=no, location=no, titlebar=0");
	prEnableButton(true);
}


/*
 *	Used by:
 *		parcelregister/PRNonTransDetailScreen.jsp
 *
 *	Usage:
 *	- Disable the buttons on the parcel register screen
 */
function prDisableButton() {
	document.getElementById("continueButton").disabled=true;
	document.getElementById("continueButton").src=contextPath + "/images/continue_d.png";
	document.getElementById("continueButton").title="";
	document.getElementById("continueButton").className="buttond";


	document.getElementById("cancelButton").disabled=true;
	document.getElementById("cancelButton").src=contextPath + "/images/03_cancel_01d.png";
	document.getElementById("cancelButton").title="";
	document.getElementById("cancelButton").className="buttond";

	document.getElementById("productConfig").disabled = true;
	document.getElementById("emailAddress").disabled = true;
}


/*
 *	Used by:
 *		parcelregister/PRNonTransDetailScreen.jsp
 *
 *	Usage:
 *	- Enable the buttons on the parcel register screen
 */
function prEnableButton(leaveEmailChkBoxDisabled) {
	document.getElementById("continueButton").disabled=false;
	document.getElementById("continueButton").src=contextPath + "/images/continue.png";
	document.getElementById("continueButton").title='Continue';
	document.getElementById("continueButton").className="button";

	document.getElementById("cancelButton").disabled=false;
	document.getElementById("cancelButton").src=contextPath + "/images/03_cancel_01.png";
	document.getElementById("cancelButton").title='Cancel';
	document.getElementById("cancelButton").className="button";

	if (!leaveEmailChkBoxDisabled) {
		document.getElementById("productConfig").disabled = false;
		document.getElementById("emailAddress").disabled = false;
	}
}


 /*************************************************
 *               MESSAGE CENTER FUNCTIONS
 **************************************************/
var __MESSAGE_CENTER_FUNCTIONS__;

function messageCounter(){
	atXmlHttp = GWH.Ajax.getXmlHttpRequest();
	var serverURL = "/gwhweb/messageCenterCounter.do?display="+"count";
	atXmlHttp.open("GET", serverURL, true);
	atXmlHttp.onreadystatechange = handleMessageServerResponse;
	atXmlHttp.send(null);
}

function handleMessageServerResponse(){
	  if (atXmlHttp.readyState == 4) {
	     if(atXmlHttp.status == 200) {
	     	 try {
		    	 var message =  atXmlHttp.responseXML.getElementsByTagName("messagecount")[0].childNodes[0].nodeValue;
		    	 if(document.getElementById("messagecounter")==null){
			    	if (parent.document.getElementById("messagecounter") != null)
			    	{
		    	 		parent.document.getElementById("messagecounter").innerHTML="<span style='text-decoration: blink;color:#FFA500'>("+parseInt(message)+")</span>&nbsp;&nbsp;<span style='border-right:solid 1px white'>&nbsp;</span>";
		    	 	}
		    	 }else{
		         document.getElementById("messagecounter").innerHTML="<span style='text-decoration: blink;color:#FFA500'> ("+parseInt(message)+")</span>&nbsp;&nbsp;<span style='border-right:solid 1px white'>&nbsp;</span>";
		         }
	         } catch(exception) { }
	     }
	     else {
	        //alert("Error during AJAX call. Please try again");
	    }
   	}
}

 function deleteMessage(msgId){
	divmsgId="div"+msgId;
	document.getElementById(divmsgId).style.visibility="hidden";
	msgId = msgId+document.getElementById("hi"+msgId).value+";";
	messageUpdate(msgId,"I");
	setTimeout("reloadMessagePage()",2000);
}

function messageUpdate(msgId,newStatus){
	atuXmlHttp = GWH.Ajax.getXmlHttpRequest();
	var serverURL = "/gwhweb/messageCenter.do?display=update&messageArray="+msgId+"&newStatus="+newStatus;
	atuXmlHttp.open("GET", serverURL, true);
	if(newStatus=='I'){
	atuXmlHttp.onreadystatechange = handleMessagedeleteResponse;
	}else{
	atuXmlHttp.onreadystatechange = handleMessageReadResponse;
	}
	atuXmlHttp.send(null);
}

function handleMessagedeleteResponse(){
	  if (atuXmlHttp.readyState == 4) {
	     if(atuXmlHttp.status == 200) {
	        setTimeout("reloadMessagePage()",2000);
	    }
   	}
}

function handleMessageReadResponse(){
	  if (atuXmlHttp.readyState == 4) {
	     if(atuXmlHttp.status != 200) {
	       // alert("Error during AJAX call. Please try again");
	    }
   	}
}
function reloadMessagePage(){
	if(document.all){
		parent.location.href = "/gwhweb/myGeoWarehouse.do?display=messages";
	}else{
		parent.location.href = "/gwhweb/myGeoWarehouse.do?display=messages";
	}
}
function showMessageView(val){
	//if(val!="block"){
	if (document.getElementById('messageWin').style.display=="") {
			document.getElementById('messageWin').style.display="block";
//			document.getElementById('messageWin1').style.display="block";
	} else {
		document.getElementById('messageWin').style.display = "";
	//	document.getElementById('messageWin1').style.display="";
		if (parent.document.getElementById('messagedetails')) {
			parent.document.getElementById('messagedetails').style.display = "";
		}
	}
}

/*----------- Message Ads related functions ----------------
 * logAdMsg 
 * logAdMsgClickThrou 
 * reportMessageAd 
 * reportMessageAdToServer 
 * reportMessageAdToGoogleAnalytics
 ----------------------------------------------------------*/

function isImgLoaded(img) {
    if (!img.complete) {
        return false;
    }
    if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
        return false;
    }
    return true;
}
function setOnClickHandler(nodes, fn) {
	for (var i=0; i < nodes.length; i++) { 
		nodes[i].onclick = fn;
	}
}
function logAdMsg(id,beid,companyName,msgName,advertiser,trigger){

	var divid = id;
	if(trigger=='New'){
		divid = "body"+id;
	}
	else if(trigger=='Read'){
		divid = "span"+id;
	}
	else{
		return;
	}
	
	var imgCounter = 0;
	var imgs = document.getElementById(divid).getElementsByTagName('IMG');
	for (var i=0; i < imgs.length; i++){ // all <IMG>'s in the div
		if (isImgLoaded(imgs[i])) {
		    imgCounter++;
		}
	}
	if (imgs.length == imgCounter) {
		reportMessageAd(msgName, advertiser, companyName, beid, 'MSG_AD_SUCCESS');
	}
	else {
 		reportMessageAd(msgName, advertiser, companyName, beid, 'MSG_AD_FAIL');
	}
}
	
/* [VT] TODO: 2011-09-02 Remove this commented out block but do it in the Appraisers project 
   so not to create complications when rebasing the Appraisers to this production stream
   
	var aCount=0;
	var aImgcnt=0;
	var sImg=0;
	var fImg=0;
	var toLogSuccess=false;
	var ua = window.navigator.userAgent
	var msie = ua.indexOf ( "MSIE " );
	var ff = ua.indexOf ( "Firefox" )
	var ch= ua.indexOf("Chrome");
	// alert ("All Info for Logging:\n msgId="+id +"\n userId="+beid+"\n company="+companyName+"\n msgName="+msgName+"_"+advertiser);
	var nodesA=document.getElementById(divid).getElementsByTagName('A');
	for (a=0;a<nodesA.length;a++){ // all A's in the div
 		var theAnchor= (nodesA[a]);
 		var aHref=theAnchor.href;
 		if(aHref.indexOf("gwhweb") == -1){ // doesn't contain gwhweb as this is an app tag and not client
 			aCount++; // client anchor found.
 			//alert ("client Anchor in process is: "+aHref);
 			var imgs=theAnchor.getElementsByTagName('img');
 			if(imgs.length==0){
 				//alert("No images found for this Client Anchor:"+aHref); // need to handle the click on text here??
 			}
 			for (i=0;i<imgs.length;i++){// loop for all images in the anchor.
 				//alert ("Number of images for this anchor is:"+imgs.length);
 				var theImg= (imgs[i]);
 				var imgSrc=theImg.src;
 				if(imgSrc.indexOf("gwhweb") == -1){ // temp to allow broken images
 					aImgcnt++;
 					//alert("Clickable client Image source found: "+imgSrc) ;
 					var cturl=theAnchor.href // stored in a different var
 					//detect successfull retrieval and rendering of the client msg
 					//alert("ua is "+ua+"\n ff is"+ff+"\n ch is"+ch+"\n msie is"+msie+"\n image width is :"+theImg.offsetWidth+"\n is complete:"+theImg.complete);
 					if((ff>-1||ch>-1||msie==-1) && theImg.width >0){ // fireFox/Chrome/anybrowser check load based on width - img is completly loaded
 						//alert(" FF/CH-Clickable img is loaded Successfuly. \n"+"msgId="+id+"\n"+"imageSrc="+imgSrc +"\nCTURL="+cturl );
 						toLogSuccess=true;
 						sImg++;
 						// theImg.onclick=function(){logAdMsgClickThrou(id,imgSrc,cturl)}
						theImg.onclick=function() {
 							reportMessageAd(msgName, advertiser, companyName, beid, 'MSG_AD_URL_SELECTED');
 						}
 					}
 					else if (msie>-1&&theImg.complete){//  IE, check load based on complete - img is completly loaded
 						//alert("IE- Clickable img is loaded Successfuly. \n"+"msgId="+id+"\n"+"imageSrc="+imgSrc +"\nCTURL="+cturl );
 						toLogSuccess=true;
 						sImg++;
 						// theImg.onclick=function(){logAdMsgClickThrou(id,imgSrc,cturl)}
 						theImg.onclick=function() {
 							reportMessageAd(msgName, advertiser, companyName, beid, 'MSG_AD_URL_SELECTED');
 						}
 					}
 					else{ // image is not loaded
 						//alert("Browser -OOPS this image is missing. "+imgSrc+" Will cause the ad to Log MSG_AD_FAIL! \n\n"+"is Complete: "+theImg.complete+"\n Img size is: "+theImg.width);
 						fImg++;
 						toLogSuccess=false;
 					}
 				}
 				else{
 					//alert ("this image src found but seems not client image"+imgSrc);
 				}
 			}// end for images in one anchor .
 		}// end if not gwhweb anchor
 		else{
 			//alert ("found this anchor but rejected it: "+aHref);
 		}
 	}//end of anchor for loop
 	//alert("Total client Anchors found="+aCount +" \n Total clickable imgs found="+aImgcnt+"\n Total success imgs found="+sImg+"\n Total failed imgs found="+fImg );
 	//case the client has an image without Anchor
 	if(aCount==0){ // no clients anchor found - start search for images.
 		var nodesImgs=document.getElementById(divid).getElementsByTagName('img');
 		for (g=0;g<nodesImgs.length;g++){// loop for all images in the anchor, usually one.
 				var anImg= (nodesImgs[g]);
 				var anImgSrc=anImg.src;
 				if(anImgSrc.indexOf("gwhweb") == -1){
 					//alert("Non-clickable client Image i.e. without anchor, found: "+anImgSrc) ;
 					//detect successfull retrieval and rendering of the client msg
 					//alert("image width is :"+anImg.width+"\n is complete:"+anImg.complete)
 					if(anImg.complete && anImg.width>0){
 						//alert(" Non-clickable Img is Fine!, issue Ajax call and log impression to DB..\n"+"msgId="+id+"\n"+"imageSrc="+anImgSrc);
 						//alert(" Non Clickable img is loaded Successfuly. \n"+"msgId="+id+"\n"+"imageSrc="+imgSrc +"\nCTURL="+cturl );
 						toLogSuccess=true;
 						sImg++;
 					}
 					else{ // image was not loaded
 						//alert("OOPS Image is not complete, nothing to be logged!");
 						//alert("OOPS this image is missing. "+imgSrc+" Will cause the ad to Log MSG_AD_FAIL! \n\n"+"is Complete: "+theImg.complete+"\n Img size is: "+theImg.width);
 						fImg++;
 						toLogSuccess=false;
 					}
 				}
 			}// end for -Non clickable.
 	}// end search for dead images in case of no anchors found
 	// Logging to DB...........
 	if(toLogSuccess){
 		// alert ("Ad is a success- Log MSG_AD_SUCCESS");
 		// companyName is a composite key in companyName_companyBEID formate; the beid is the user ID.
 		reportMessageAd(msgName, advertiser, companyName, beid, 'MSG_AD_SUCCESS');
 	}
 	else{
 		// alert ("Ad Failed- Log MSG_AD_FAIL");
 		reportMessageAd(msgName, advertiser, companyName, beid, 'MSG_AD_FAIL');
 	}
 	// set this flag so it does it only once
 	if(trigger=='New'){
 		thisMsgId=id;
 	}
}
// TODO: do we still need this function? (VT)
function logAdMsgClickThrou(id,imgSrc,cturl){
	alert("Client Image clicked successfuly - LOG MSG_AD_URL_SELECTED. \n\n msgId="+id+"\n"+"imageSrc="+imgSrc+"\n"+"clickthrouURL is:"+cturl);
}
*/

function reportMessageAd(campaignName, advertiserName, companyKey, userId, adActionType) {
	// alert('In reportMessageAd: campaignName=[' + campaignName + '], advertiserName=[' + advertiserName + '], companyKey=[' + companyKey + '], userId=' + userId + '], adActionType=[' + adActionType + ']');
	// companyKey required format: companyName_beid - it is already passed in this format
	// var companyKey = companyName + '_' + beid;
	
	reportMessageAdToServer(campaignName, advertiserName, companyKey, adActionType);
	reportMessageAdToGoogleAnalytics(campaignName + '_' + advertiserName, companyKey, userId, adActionType);
}

function reportMessageAdToServer(adCampaignName, advertiserName, companyKey, adActionType) {
	var params = 'messageAdName=' + encodeURIComponent(adCampaignName)
		+ '&advertiserName=' + encodeURIComponent(advertiserName)
		+ '&userCompanyKey=' + encodeURIComponent(companyKey)
		+ '&renderStatus=' + encodeURIComponent(adActionType)
		+ '&pageType=MESSAGE_CENTER';
		
	YAHOO.util.Connect.asyncRequest('POST', "/gwhweb/msgAdLogging.do", new Object(), params);
}

function reportMessageAdToGoogleAnalytics(campaignName_advertiserName, companyKey, userId, adActionType) {
	//MessageCenter AD id
	_gaq.push(['_setCustomVar', 1,  'AD_CAMPAIGN_NAME', campaignName_advertiserName, 3]); 
	//companyName_beid
	_gaq.push(['_setCustomVar', 2,  'NAME_ID', companyKey, 3]); 

	_gaq.push(['_setCustomVar', 5,  'USER_ID', userId, 3]); 
	//MSG_AD_SUCCESS, MSG_AD_FAIL, MSG_AD_URL_SELECTED
	_gaq.push(['_setCustomVar', 3,  'EVENT_TYPE', adActionType, 3]);
 	_gaq.push(['_setCustomVar', 4,  'REPORT_TYPE', 'MESSAGE_CENTER', 3]);
	_gaq.push(['_trackPageview', '/gwhweb/myGeoWarehouse.do?display=messages']);
}
/*------------------ end of Message Ads section -----------------------*/


function showmsgdetail(msgid){
		parent.document.getElementById('messageWin').style.display="block";
 		parent.document.getElementById('messagedetails').style.display="block";
}

function renderReply(msgid,subject) {
	if (gwhFeedBackDialog) {
	  gwhFeedBackDialog.hide();
	  gwhFeedBackDialog.destroy();
	}

    // Obtain From Email Address
    var asXmlHttpRequest = GWH.Ajax.getXmlHttpRequest();
    var url = "/gwhweb/collectFeedback.do?action=load";

    asXmlHttpRequest.open("GET", url, false);  // third parameter indicate if request is asynchronous (non-blocking)
    asXmlHttpRequest.send(null);

    if (asXmlHttpRequest.status == HTTP_REQUEST_SUCCESS) {
	    var feedBackResponse = eval('('+ asXmlHttpRequest.responseText + ')');

		if (feedBackResponse.feedbackVO.errorFound != 'true') {  // Request successful
			gwhFeedBackDialog = new YAHOO.widget.Dialog("feedBackDialogId",
														{ width : "450px",
														  fixedcenter : true,
														  draggable: true,
														  visible : false,
														  constraintoviewport : true,
														  modal: false,
														  close: true,
														  underlay: "none"
														});

		    // Render the Dialog
			var dialogHtml  = "<div id='feedbackDialogId'>";
			    dialogHtml += "  <form method='POST' action='/gwhweb/collectFeedBack.do'>";
			    dialogHtml += "    <input type='hidden' name='action' value='load'>";
			    dialogHtml += "    <table>";
			    dialogHtml += "      <tr>";
		  	    dialogHtml += "        <td id='feedbackLabelId'>From:</td>";
		  	    dialogHtml += "        <td>" + feedBackResponse.feedbackVO.fromUser + "</td>";
			    dialogHtml += "      </tr>";
			    dialogHtml += "      <tr>";
		  	    dialogHtml += "        <td id='feedbackLabelId'>To:</td>";
		  	    //dialogHtml += "        <td>" + feedBackResponse.feedbackVO.toEmailAddress + "</td>";
		  	    dialogHtml += "        <td> GeoWarehouse Online -  Customer Support </td>";
			    dialogHtml += "      </tr>";
			    dialogHtml += "      <tr>";
		  	    dialogHtml += "        <td id='feedbackLabelId'>Subject:</td>";
		  	    dialogHtml += "        <td> <input type='text' style='width: 300px' name='subject' value='"+subject+"' disabled>";
		  	    dialogHtml += "        <input type='hidden' name='msgid' value='"+msgid+"'></td>";
			    dialogHtml += "      </tr>";
			    dialogHtml += "      <tr>";
		  	    dialogHtml += "        <td colspan=2>";
			    dialogHtml += "          <textarea name='message' rows=6 cols='75' style='width:420px; height:100px;' onkeydown='javascript:limitMessageLength(this,MAX_FEEDBACK_MESSAGE_LENGTH);' onkeyup='javascript:limitMessageLength(this,MAX_FEEDBACK_MESSAGE_LENGTH);'></textarea>";
		  	    dialogHtml += "        </td>";
			    dialogHtml += "      </tr>";
			    dialogHtml += "      <tr>";
		  	    dialogHtml += "        <td colspan=2>";
			    dialogHtml += "          <span id='charactersRemaining'>300</span> - characters remaining";
		  	    dialogHtml += "        </td>";
			    dialogHtml += "      </tr>";
			    dialogHtml += "      <tr>";
		  	    dialogHtml += "        <td align='center' colspan=2>";
		  	    dialogHtml += "          <button id='sendButton' name='sendButton' class='feedbackFormButton' onclick='javascript:sendReply(this.form);return false;'>SEND REPLY</button>&nbsp;&nbsp;";
		  	    dialogHtml += "          <button name='cancelButton' class='feedbackFormButton' onclick='javascript:cancelFeedback();return false;'>CANCEL</button>";
		  	    dialogHtml += "        </td>";
			    dialogHtml += "      </tr>";
			    dialogHtml += "    </table>";
			    dialogHtml += "  </form>";
		   	    dialogHtml += "</div>";

			gwhFeedBackDialog.setHeader("REPLY FORM");
		  	gwhFeedBackDialog.setBody(dialogHtml);	;
			gwhFeedBackDialog.render(document.body);
	        gwhFeedBackDialog.show();
        }
        else {  // session has expired or error encountered
	      var message = FEEDBACK_MESSAGE_FORM.replace('[FEEDBACK_MESSAGE]', feedBackResponse.feedbackVO.responseMessage);
    	  showContextSensitiveHelp(message, HEADER_LABEL_FEEDBACK_ERROR);
        }
    }
    else {  // Failed to obtain response from server
      var message = FEEDBACK_MESSAGE_FORM.replace('[FEEDBACK_MESSAGE]', FEEDBACK_ERROR);
      alert();
      showContextSensitiveHelp(message, HEADER_LABEL_FEEDBACK_ERROR);
    }
}

function sendReply(currentForm,msgid) {
    //currentForm.sendButton.disabled = true;  // disallow user to send duplicate feedback
	if (validFeedback(currentForm)) {

	    // Send feed back
	    var arXmlHttpRequest = GWH.Ajax.getXmlHttpRequest();
	    var url = "/gwhweb/collectFeedback.do";
	    var params = "action=REPLY_FEEDBACK&" +
	    			 "messageId="+currentForm.msgid.value+ "&" +
	                 "subject=" + currentForm.subject.value + "&" +
	                 "message=" + encodeURIComponent(currentForm.message.value);

	    arXmlHttpRequest.open("POST", url, false);  // third parameter indicate if request is asynchronous (non-blocking)
	    arXmlHttpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		arXmlHttpRequest.setRequestHeader("Content-length", params.length);
		arXmlHttpRequest.setRequestHeader("Connection", "close");
	    arXmlHttpRequest.send(params);

	    if (arXmlHttpRequest.status == HTTP_REQUEST_SUCCESS                     &&
	        arXmlHttpRequest.responseText != null                                 ) {
	        if (arXmlHttpRequest.responseText.indexOf("Input Validation Error") >= 0   ) {   // Web input validation error
		      currentForm.sendButton.disabled = false;
		      showFeedbackErrorMessage(INPUT_VALIDATION_ERROR);
	        }
	        else {
			    var feedBackResponse = eval('('+ arXmlHttpRequest.responseText + ')');
		        if (feedBackResponse.feedbackVO.errorFound == 'true') {   // display error message in message area
			      currentForm.sendButton.disabled = false;
 			      showFeedbackErrorMessage(feedBackResponse.feedbackVO.responseMessage);
	    	    }
		        else { // display confirmation message
					gwhFeedBackDialog.hide();
			        var message = FEEDBACK_MESSAGE_FORM.replace('[FEEDBACK_MESSAGE]', feedBackResponse.feedbackVO.responseMessage);
			        showContextSensitiveHelp(message, HEADER_LABEL_FEEDBACK_CONFIRMATION);
			    }
		    }
		}
		else {
		  currentForm.sendButton.disabled = false;
          showFeedbackErrorMessage(FEEDBACK_ERROR);
		}

	}

}

function wincloseevent(){
		if(window.location.href.indexOf("/Property")==-1){
			window.location.reload(true);
			}else{
				reloadMessagePage();
			}
}


 /*************************************************
 *      INSTRUMENT AND PLAN IMAGE FUNCTIONS
 **************************************************/
var __INSTRUMENT_IMAGE_FUNCTIONS__;

/*
 *	Used by:
 *		docimage/documentImageResultDataEncrypt.jsp
 *
 *	Usage:
 *	-
 */
 function openMainDocumentRata(token,isCertified,numberOfPages, isPlan)
{
	var documentUrl="./documentImage.do?action=gettingDocumentRata&token="+token+"&product=rata";
	return openDocumentRata(documentUrl,isCertified,numberOfPages, isPlan);
}

/*
 *	Used by:
 *		docimage/documentImageResultDataEncrypt.jsp
 *
 *	Usage:
 *	-
 */
function openAttachmentRata(token,attachmentNumber,isCertified,numberOfPages)
{
	var documentUrl="./documentImage.do?action=gettingDocumentRata&token="+token+"&product=rata&attachmentNumber="+attachmentNumber;
	return openDocumentRata(documentUrl,isCertified,numberOfPages, false);
}

/*
 *	Used by:
 *		docimage/documentImageResultDataEncrypt.jsp
 *
 *	Usage:
 *	-
 */
function openDocumentRata(documentUrl,isCertified,numberOfPages,isPlan){
	//alert("isCertified=" + isCertified);
	if(numberOfPages == '0'){
		alert(noImageFoundMsg);
		return true;
	}
	var acceptNonCertifiedResp;

	if((isCertified != "true") && (isPlan == false))
	{
		acceptNonCertifiedResp=confirm(nonCertifiedMsg);
	}
	else
	{
		acceptNonCertifiedResp=true;
	}

	if(acceptNonCertifiedResp){
	   //docImageWindow = window.open (documentUrl,	"mywindow1","menubar=1,resizable=1,width=650,height=400");
		docImageWindow = window.open ("","mywindow1","menubar=1,resizable=1,width=650,height=400");
		docImageWindow.close();

		docImageWindow = window.open (documentUrl,"mywindow1","menubar=1,resizable=1,width=650,height=400");
		if(docImageWindow.focus)
		{
			docImageWindow.focus();
		}

	}

}

/*
 *	Used by:
 *		docimage/documentImageResultData.jsp
 *
 *	Usage:
 *	-
 */
function openMainDocument(instrumentNumber,lroNumber,isCertified,numberOfPages, isPlan,viewType)
{

	var documentUrl="./documentImage.do?action=gettingDocument&docNumber="+instrumentNumber+"&lro="+lroNumber;
	return openDocument(documentUrl,isCertified,numberOfPages,instrumentNumber, isPlan, viewType);
}

/*
 *	Used by:
 *		docimage/documentImageResultData.jsp
 *
 *	Usage:
 *	-
 */
function openAttachment(instrumentNumber,lroNumber,attachmentNumber,isCertified,numberOfPages, viewType)
{
	var documentUrl="./documentImage.do?action=gettingDocument&docNumber="+instrumentNumber+"&lro="+lroNumber+"&attachmentNumber="+attachmentNumber;
	return openDocument(documentUrl,isCertified,numberOfPages,instrumentNumber+attachmentNumber, false, viewType);
}

/*
 *	Used by:
 *		docimage/documentImageResultData.jsp
 *
 *	Usage:
 *	-
 */
function openDocument(documentUrl,isCertified,numberOfPages,documentName,isPlan,viewType)
{
	if(numberOfPages == '0')
	{
		alert(noImageFoundMsg);
		return true;
	}
	var acceptNonCertifiedResp;
	if((isCertified != "true") && (isPlan == false))
	{
		acceptNonCertifiedResp=confirm(nonCertifiedMsg);
	}	else
	{
		acceptNonCertifiedResp=true;
	}
	if(acceptNonCertifiedResp)
	{
		if (viewType == 'View') {
			var newwnd = window.open(documentUrl,documentName,"menubar=1,resizable=1,width=650,height=400");
			if(newwnd.focus)
			{
				newwnd.focus();
			}
		}
		else {
			location.replace(documentUrl);
		}
	}
	return true;
}

 /*************************************************
 *              FEEDBACK FUNCTIONS
 **************************************************/
var __FEEDBACK_FUNCTIONS__;

/*
 * Cilent Feedback
 */

var gwhFeedBackDialog = null;
var FEEDBACK_ERROR = "Unable to accept your Feedback at this time.  Please try again later.";
var FEEDBACK_MESSAGE_LENGTH_ERROR = "Unable to accept your Feedback.  Maximum message length allowed is 300 characters.";
var EMPTY_FEEDBACK_ERROR = "Please provide the details of your feedback in the message section before sending.";
var INPUT_VALIDATION_ERROR = "We were unable to process your request due to incorrect data entered.  Please verify entries and resubmit your request.";
var HTTP_REQUEST_SUCCESS = 200;
var MAX_FEEDBACK_MESSAGE_LENGTH = 300;
var FEEDBACK_MESSAGE_FORM="<HTML><HEAD><LINK href='/gwhweb/styles/gwpropertyview.css' type=text/css rel=stylesheet></HEAD><BODY><div id='feedbackMessage'><table><tr id='feedbackMessage'><td>[FEEDBACK_MESSAGE]</td></tr></table></div><br /><div align='center'><BUTTON class='feedbackFormButton' onclick='gwhContextHelpDialog.hide();wincloseevent();'>CLOSE</BUTTON></div></BODY></HTML>";
var FEEDBACK_MESSAGE_AREA_FORM="<HTML><HEAD><LINK href='/gwhweb/styles/gwpropertyview.css' type=text/css rel=stylesheet></HEAD><BODY><div id=feedbackAreaMessage><br /><table><tr><td id='feedbackAreaMessage'>[FEEDBACK_MESSAGE]</td></tr></table></div><br /><div align='center'></div></BODY></HTML>";
var gwhFeedBackDialog;
var HEADER_LABEL_FEEDBACK_CONFIRMATION = "FEEDBACK CONFIRMATION";
var HEADER_LABEL_FEEDBACK_ERROR = "FEEDBACK ERROR";

var gwhSurveyPlanListDialog = null;
var gwhSurveyPlanList=null;
var MAX_SURVER_PLAN_LIST=16;
var lsrPlanImage = null;
var lsrRegisteredPlan = null;
var lsrLro = null;
var lsrAddress = null;
var lsrAddressRange = null;
var lsrLotCon = null;
var contextPath = null;
var isCustomPinListFromDeepLink = false;

function collectFeedback() {
	var mainWindow = getMainWindow(window);

	// Feedback can appear in My Geowarehouse and Property View page.  Property View's iframe could make
	// the dialog display center at the iframe.  Hence, needs to render dialog in main window.
	if (mainWindow != null)
  	  mainWindow.renderFeedbackDialog();
  	else
      renderFeedbackDialog();
}

function renderFeedbackDialog() {

	if (gwhFeedBackDialog) {
	  gwhFeedBackDialog.hide();
	  gwhFeedBackDialog.destroy();
	}

    // Obtain From Email Address
    var asXmlHttpRequest = GWH.Ajax.getXmlHttpRequest();
    var url = "/gwhweb/collectFeedback.do?action=load";

    asXmlHttpRequest.open("GET", url, false);  // third parameter indicate if request is asynchronous (non-blocking)
    asXmlHttpRequest.send(null);

    if (asXmlHttpRequest.status == HTTP_REQUEST_SUCCESS) {
    
	    var feedBackResponse = null;
    	try {
	    	feedBackResponse = eval('('+ asXmlHttpRequest.responseText + ')');
	    } catch (e){ }	

		if (feedBackResponse && feedBackResponse.feedbackVO.errorFound != 'true') {  // Request successful
			gwhFeedBackDialog = new YAHOO.widget.Dialog("feedBackDialogId",
														{ width : "450px",
														  fixedcenter : true,
														  draggable: true,
														  visible : false,
														  constraintoviewport : true,
														  modal: false,
														  close: true,
														  underlay: "none"
														});

		    // Render the Dialog
			var dialogHtml  = "<div id='feedbackDialogId'>";
			    dialogHtml += "  <form method='POST' action='/gwhweb/collectFeedBack.do'>";
			    dialogHtml += "    <input type='hidden' name='action' value='load'>";
			    dialogHtml += "    <table>";
			    dialogHtml += "      <tr>";
		  	    dialogHtml += "        <td id='feedbackLabelId'>From:</td>";
		  	    dialogHtml += "        <td>" + feedBackResponse.feedbackVO.fromUser + "</td>";
			    dialogHtml += "      </tr>";
			    dialogHtml += "      <tr>";
		  	    dialogHtml += "        <td id='feedbackLabelId'>To:</td>";
		  	    dialogHtml += "        <td> GeoWarehouse Online -  Customer Support </td>";
			    dialogHtml += "      </tr>";
			    dialogHtml += "      <tr>";
		  	    dialogHtml += "        <td id='feedbackLabelId'>Subject:</td>";
		  	    dialogHtml += "        <td>"+feedBackResponse.feedbackVO.subjectList;
		  	    dialogHtml += "        </td>";
			    dialogHtml += "      </tr>";
			    dialogHtml += "      <tr>";
		  	    dialogHtml += "        <td colspan=2>";
			    dialogHtml += "          <textarea name='message' rows=6 cols='75' style='width:420px; height:100px;' onkeydown='javascript:limitMessageLength(this,MAX_FEEDBACK_MESSAGE_LENGTH);' onkeyup='javascript:limitMessageLength(this,MAX_FEEDBACK_MESSAGE_LENGTH);'></textarea>";
		  	    dialogHtml += "        </td>";
			    dialogHtml += "      </tr>";
			    dialogHtml += "      <tr>";
		  	    dialogHtml += "        <td colspan=2>";
			    dialogHtml += "          <span id='charactersRemaining'>300</span> - characters remaining";
		  	    dialogHtml += "        </td>";
			    dialogHtml += "      </tr>";
			    dialogHtml += "      <tr>";
		  	    dialogHtml += "        <td align='center' colspan=2>";
		  	    dialogHtml += "          <button name='sendButton' class='feedbackFormButton' onclick='javascript:sendFeedback(this.form);return false;'>SEND FEEDBACK</button>&nbsp;&nbsp;";
		  	    dialogHtml += "          <button name='cancelButton' class='feedbackFormButton' onclick='javascript:cancelFeedback();return false;'>CANCEL</button>";
		  	    dialogHtml += "        </td>";
			    dialogHtml += "      </tr>";
			    dialogHtml += "    </table>";
			    dialogHtml += "  </form>";
		   	    dialogHtml += "</div>";

			gwhFeedBackDialog.setHeader("FEEDBACK FORM");
		  	gwhFeedBackDialog.setBody(dialogHtml);	;
			gwhFeedBackDialog.render(document.body);
	        gwhFeedBackDialog.show();
        }
        else {  // session has expired or error encountered
	      var message = FEEDBACK_MESSAGE_FORM.replace('[FEEDBACK_MESSAGE]', feedBackResponse ? feedBackResponse.feedbackVO.responseMessage : FEEDBACK_ERROR);
    	  showContextSensitiveHelp(message, HEADER_LABEL_FEEDBACK_ERROR);
        }
    }
    else {  // Failed to obtain response from server
      var message = FEEDBACK_MESSAGE_FORM.replace('[FEEDBACK_MESSAGE]', FEEDBACK_ERROR);
      showContextSensitiveHelp(message, HEADER_LABEL_FEEDBACK_ERROR);
    }

}


function sendFeedback(currentForm) {
    currentForm.sendButton.disabled = true;  // disallow user to send duplicate feedback
	if (validFeedback(currentForm)) {

	    // Send feed back
	    var asXmlHttpRequest = GWH.Ajax.getXmlHttpRequest();
	    var url = "/gwhweb/collectFeedback.do";
	    var params = "action=SEND_FEEDBACK&" +
	                 "subject=" + currentForm.subject.value + "&" +
	                 "message=" + encodeURIComponent(currentForm.message.value);

	    asXmlHttpRequest.open("POST", url, false);  // third parameter indicate if request is asynchronous (non-blocking)
	    asXmlHttpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		asXmlHttpRequest.setRequestHeader("Content-length", params.length);
		asXmlHttpRequest.setRequestHeader("Connection", "close");
	    asXmlHttpRequest.send(params);

	    if (asXmlHttpRequest.status == HTTP_REQUEST_SUCCESS                     &&
	        asXmlHttpRequest.responseText != null                                 ) {
	        if (asXmlHttpRequest.responseText.indexOf("Input Validation Error") >= 0   ) {   // Web input validation error
		      currentForm.sendButton.disabled = false;
		      showFeedbackErrorMessage(INPUT_VALIDATION_ERROR);
	        }
	        else {
			    var feedBackResponse = eval('('+ asXmlHttpRequest.responseText + ')');
		        if (feedBackResponse.feedbackVO.errorFound == 'true') {   // display error message in message area
			      currentForm.sendButton.disabled = false;
 			      showFeedbackErrorMessage(feedBackResponse.feedbackVO.responseMessage);
	    	    }
		        else { // display confirmation message
					gwhFeedBackDialog.hide();
			        var message = FEEDBACK_MESSAGE_FORM.replace('[FEEDBACK_MESSAGE]', feedBackResponse.feedbackVO.responseMessage);
			        showContextSensitiveHelp(message, HEADER_LABEL_FEEDBACK_CONFIRMATION);
			    }
		    }
		}
		else {
		  currentForm.sendButton.disabled = false;
          showFeedbackErrorMessage(FEEDBACK_ERROR);
		}

	}

}

function cancelFeedback() {
	gwhFeedBackDialog.hide();
}

function validMessageLength(message) {
  if (message.length > MAX_FEEDBACK_MESSAGE_LENGTH)
    return false;
  else
    return true;
}

function validFeedback(currentForm) {
  if (currentForm.message.value.length <= 0) {
    currentForm.sendButton.disabled = false;
    showFeedbackErrorMessage(EMPTY_FEEDBACK_ERROR);
    return false;
  }
  else if (!validMessageLength(currentForm.message.value)) {
    currentForm.sendButton.disabled = false;
    showFeedbackErrorMessage(FEEDBACK_MESSAGE_LENGTH_ERROR);
    return false;
  }

  return true;
}

function showFeedbackErrorMessage(errorMessage) {
    if (gwhFeedBackDialog != null) {
	  var message = FEEDBACK_MESSAGE_AREA_FORM.replace("[FEEDBACK_MESSAGE]", errorMessage);
	  var messageAreaElement = document.createElement('div');
	  messageAreaElement.innerHTML = message;

	  // clean up previous error message if any
	  var feedbackBody = gwhFeedBackDialog.body.innerHTML;
	  if (feedbackBody.indexOf("feedbackAreaMessage", 0) > 0) {
        feedbackBody = feedbackBody.replace(feedbackBody.substr(feedbackBody.indexOf("feedbackAreaMessage") - 8), "");
	  }
	  gwhFeedBackDialog.setBody(feedbackBody);

	  gwhFeedBackDialog.appendToBody(messageAreaElement);
    }
}

function limitMessageLength(field, maxLength){
  var len = field.value.length;
  if (len > maxLength) {
    field.value = field.value.substring(0, maxLength);
    len = maxLength;
  }
  document.getElementById('charactersRemaining').innerHTML = maxLength - len;
}


 /*************************************************
 *                   RATA FUNCTONS
 **************************************************/
var __RATA_FUNCTIONS__;

function documentViewEncrypt(token){

	var newWindowStyle = "height=500, width=750, RESIZABLE=yes, scrollbars=no, " +
					 	 "status=no, toolbar=no, menubar=no, location=no, titlebar=0";

	url = "documentImage.do?action=displayDocumentDetailsRata&token=" + token ;
	if(docViewEncryptWindow=='[object]'){
		if(docViewEncryptWindow.closed == true)
		{
			// open up the Document Details window with the imageID
			docViewEncryptWindow=
				window.open(url, "docImageEncr", newWindowStyle);
			tokenStr=token;
		}
		else{
			setTimeout('docViewEncryptWindow.focus();',0);
			// check if the image in the window needs to be refreshed
			if(tokenStr!= token)
			{
				//refresh the image in Document Details window
				docViewEncryptWindow=
					window.open(url, "docImageEncr", newWindowStyle);
			}
		}
	}
	else {
		// docViewEncryptWindow undefined - create it and display imageID
		docViewEncryptWindow= window.open(url, "docImageEncr", newWindowStyle);
	    	setTimeout('docViewEncryptWindow.focus();',250);
		tokenStr= token;
	}
}

/** Looks Like This Funcion is no longer used
var docViewWindow;
var instrumentNum;
var lroNum;

function documentView_old(instrument, lro){

	topPos = calculatePopupTopPosition((document.all)?getMainWindow(window).screenTop:window.screenY, getMainWindow(window).document.body.clientHeight, 690);
	leftPos = calculatePopupLeftPosition((document.all)?getMainWindow(window).screenLeft:window.screenX, getMainWindow(window).document.body.clientWidth, 690);

	var newWindowStyle = "height=690, width=690, RESIZABLE=no, scrollbars=no, " +
					 	 "status=no, toolbar=no, menubar=no, location=no, titlebar=no, " +
					 	 "top=" + topPos + ", " +
					 	 "left=" + leftPos;

	url = "documentImage.do?action=displayDocumentDetails&docNumber=" + instrument + "&lro=" + lro;
	if(docViewWindow=='[object]'){
		if(docViewWindow.closed == true)
		{
			// open up the Document Details window with the imageID
			docViewWindow =
				window.open(url,"docImage", newWindowStyle);
			instrumentNum = instrument;
			lroNum = lro;
		}
		else{
			setTimeout('docViewWindow.focus();',0);
			// check if the image in the window needs to be refreshed
			if(instrumentNum != instrument)
			{
				//refresh the image in Document Details window
				docViewWindow =
					window.open(url, "docImage", newWindowStyle);
			}
		}
	}
	else {
		// docViewWindow undefined - create it and display imageID
		docViewWindow =
			window.open(url, "docImage", newWindowStyle);
    	setTimeout('docViewWindow.focus();',250);
		instrumentNum = instrument;
		lroNum = lro;
	}
}
**/

function documentView(instrument, lro){
	url = "documentImage.do?action=displayDocumentDetails&docNumber=" + instrument + "&lro=" + lro;
	viewProduct(url);
}

/*
 *	Used by:
 *		rata/reactrTemplate.jsp
 *
 *	Usage:
 *	-
 */
function filterreactimgsrc (action) {
	var imgbutton = document.getElementById('filterreact');
	if (showfilter) {
		imgbutton.src=filterreact_cancel.src

	} else {

		if (action == 'ovr') imgbutton.src=filterreact_ovr.src;
		else  imgbutton.src=filterreact_out.src;
	}
}

/*
 *	Used by:
 *		rata/reactrTemplate.jsp
 *
 *	Usage:
 *	-
 */
function toggleFilterForm(filtersetid,linkid,txton,txtoff,buttonid) {

	var linkobj = document.getElementById(linkid);
	var imgbutton = document.getElementById(buttonid);
	var filterstyle = showfilter?'none':'';
	var oFrameDocAll =window.rataReportFrame.document;
	var oFrame	=	document.getElementById("rataReportFrame");
	if(oFrameDocAll.getElementById("filter1")){
		oFrameDocAll.getElementById("filter1").style.display=filterstyle;
		imgbutton.title = showfilter?decodeURIComponent(txton):decodeURIComponent(txtoff);
		showfilter = showfilter?false:true;
		if (showfilter == false){
			showReport();
		} else {
	    	if (oFrameDocAll.getElementById("filterForm") != null){
	     		oFrameDocAll.getElementById("filterForm").scrollIntoView(true);
	     	}
		}
	}

	var element = document.getElementById("reportPeriod");
	element.focus();
}

/*
 *	Used by:
 *		rata/reactrTemplate.jsp
 *
 *	Usage:
 *	-
 */

function resetCounter() {
	runcounter=0;
}

/*
 *	Used by:
 *		rata/reactrTemplate.jsp
 *
 *	Usage:
 *	-
 */
function setCounter(arg1) {
	runcounter=arg1*1.0;
}

/*
 *	Used by:
 *		rata/reactrTemplate.jsp
 *
 *	Usage:
 *	-
 */
function getCounter() {
	return runcounter;
}

/*
 *	Used by:
 *		rata/reactrTemplate.jsp
 *
 *	Usage:
 *	-
 */
function handlerKey(evt) {

	var tmp;
	if (!evt) {
		evt = window.event;
		tmp = evt.keyCode ? evt.keyCode : evt.charCode;
	} else {
		tmp = evt.which;
	}
	if(tmp==13)	{
		//submitform();
	}
}

/*
 *	Used by:
 *		rata/reactrTemplate.jsp
 *
 *	Usage:
 *	-
 */
function filterModels() {

    var element = document.getElementById("rataModel");
    var reportsElement= document.getElementById("reportPeriod");
    var c= document.form1.ratreporttype.value;

    while (element.options.length > 0) {
    	//element.options.remove(0);
		element.options[0] = null;  //cross-browser
	}
    while (reportsElement.options.length > 1) {
    	//reportsElement.options.remove(1);
    	reportsElement.options[1] = null;  //cross-browser
	}

    var tag = c + "^^";
    var modelName;
    var uniqStr="";
    element.options.add(new Option("   --- SELECT MODEL NAME ---"));
    if (tag.indexOf("^^") > 0) {
	    for (var i = 0; i < strArray.length; i++) {

	        if (strArray[i].indexOf(tag) >= 0) {
	           strArray[i] = strArray[i].replace(/^\s+/,'');
	           strArray[i] = strArray[i].replace(/\s+$/,'');
	           modelName = strArray[i].substring(tag.length,strArray[i].indexOf("::"));

	           if (uniqStr.indexOf(modelName +"-*^") < 0) {

		              element.options.add(new Option(modelName));
		              uniqStr = uniqStr +  modelName +"-*^";
	           }
	        }
		}
	}
}

/*
 *	Used by:
 *		rata/reactrTemplate.jsp
 *
 *	Usage:
 *	-
 */
function filterPeriods(caller) {

    var element = document.getElementById("reportPeriod");
   	var callerIndex = caller.selectedIndex;
    var c= caller.options[callerIndex].text;

    while (element.options.length > 0) {
    	//element.options.remove(0);
    	element.options[0] = null;  //cross-browser
	  }

    var tag = c + "::";
    var reportPeriod;
    var uniqStr="";
    element.options.add(new Option("--- SELECT REPORT PERIOD ---"));

    for (var i = 0; i < strArray.length; i++) {

        if (strArray[i].indexOf(tag) >= 0) {

           var tagIndex=strArray[i].indexOf(tag);
           reportPeriod = strArray[i].substring(tagIndex+tag.length,strArray[i].indexOf("**"));
           processId = strArray[i].substring(strArray[i].indexOf("**")+2,strArray[i].indexOf("~~"));

           if (uniqStr.indexOf(reportPeriod +"-*^") < 0) {
              element.options.add(new Option(reportPeriod, processId));
              uniqStr = uniqStr +  reportPeriod +"-*^";
           }
        }
	}
}


/*
 *	Used by:
 *		rata/reactrTemplate.jsp
 *
 *	Usage:
 *	-
 */
function submitForm(theAction) {

	//var oFrameDocAll =document.frames("rataReportFrame").document.all;
	var oFrameDocAll =window.rataReportFrame.document;
	if (oFrameDocAll.getElementById("filterForm") != null){

		if (theAction == 'download') {
			 setTimeout('runcounter=0;',3000);
			 var d = oFrameDocAll.getElementById("filterForm").countOfSelected.value;
			 if (d == 0){
		     	alert("Download Error: No records have been selected for download");
				return;
			 }
		}

		if (runcounter == 0) {
			oFrameDocAll.getElementById("filterForm").action.value=theAction;
		    oFrameDocAll.getElementById("filterForm").submit();
	        runcounter = runcounter +1;

	        if (theAction != "download"){
	           document.getElementById("loadingdiv").style.visibility='visible';
	        }

	     } else {
			setTimeout('runcounter=0;',5000);
			alert("We are processing your previous request. Please wait for the view to be updated.");
		}
	}
}


/*
 *	Used by:
 *		rata/reactrTemplate.jsp
 *
 *	Usage:
 *	-
 */
function showReport() {

    var reportingPeriod = document.getElementById("reportPeriod");
    var repType = document.getElementById("ratreporttype");
    var modelName = document.getElementById("rataModel");

    var selectedRepTypeIndex=repType.selectedIndex;
    var selectedModelNameIndex= modelName.selectedIndex;
   	var reportingPeriodIndex = reportingPeriod.selectedIndex;

    var selectedReportingPeriod= reportingPeriod.options[reportingPeriodIndex].value;

    var selectedRepType= repType.options[selectedRepTypeIndex].value;

    var selectedModelName= modelName.options[selectedModelNameIndex].text;

    if (selectedRepTypeIndex == '0' ||
        selectedModelNameIndex == '0' ||
        reportingPeriodIndex == '0'){
       alert("Please select a report type, model name, and a reporting period prior to pressing display");
       return;
    }

    document.getElementById('reactrSubmitForm').processId.value=selectedReportingPeriod;
    document.getElementById('reactrSubmitForm').reportTypeName.value=selectedRepType;
    document.getElementById('reactrSubmitForm').modelName.value=selectedModelName;
    document.getElementById('reactrSubmitForm').target="rataReportFrame";
	document.getElementById('reactrSubmitForm').action.value="display";

	if (runcounter == 0){
        document.getElementById('reactrSubmitForm').submit();
        runcounter = runcounter +1;
        document.getElementById("loadingdiv").style.visibility='visible';

	}else{

	   	alert("We are processing your previous request. Please wait for the view to be updated.");
	}
	setTimeout('runcounter=0;',5000);
}

/*
 *	Used by:
 *		rata/reactrTemplate.jsp
 *
 *	Usage:
 *	-
 */
function nextPage() {

	var filterForm = document.getElementById("filterForm");
    filterForm.action.value="nextPage";
    filterForm.submit();
}

/*
 *	Used by:
 *		rata/reactrTemplate.jsp
 *
 *	Usage:
 *	-
 */
function download() {
	var filterForm = document.getElementById("filterForm");
    filterForm.action.value="download";
    filterForm.submit();
}

/*
 *	Used by:
 *		rata/reactrTemplate.jsp
 *
 *	Usage:
 *	-
 */
function previousPage() {
	var filterForm = document.getElementById("filterForm");
    filterForm.action.value="previousPage";
    filterForm.submit();
}

/*
 *	Used by:
 *		rata/reactrTemplate.jsp
 *
 *	Usage:
 *	-
 */
function reSize() {
	try {
		var oBody=document.body;
		var oFrame=document.getElementById("rataReportFrame");
//		var oFrameDocAll=document.frames("rataReportFrame").document.all;
		var oFrameDocAll=window.rataReportFrame.document;
		var separtor=document.getElementById("piiSepartor");
		separtor.style.display='none';
		var oFrameFooter=document.getElementById("rataFooter");
		var maxftrheigth=oBody.scrollHeight + (oBody.offsetHeight - oBody.clientHeight);
		if (oFrameFooter) {
			var ftrheigth=oFrameFooter.style.Height;
			window.defaultStatus=oFrameFooter.style.posHeight;
			oFrame.style.posHeight = 60;
		}
		oFrame=document.getElementById("rataDetails");
		oFrame.style.display='none';
		var closeratdetailsimg = document.getElementById("closeratdetailsimg");
		closeratdetailsimg.style.display='none';
		window.defaultStatus = closeratdetailsimg.src;
	} catch(e) {
		//An error is raised if the IFrame domain != its container's domain
		window.status =	'Error: ' + e.number + '; ' + e.description;
	}
}


/*
 *	Used by:
 *		rata/filterEntries.jsp
 *		rata/file3filterEntries.jsp
 *
 *	Usage:
 *	-
 */
String.prototype.startsWith = function(str){
	return (this.match("^"+str)==str)
}
String.prototype.endsWith = function(str, suffix){
	return str.match(suffix+"$")==suffix;
}
function checkInstrumentTypes(boolValue){
	var this_checkbox="";
	var filterForm=document.getElementById("filterForm");
	var c=document.getElementsByTagName("body")[0].getElementsByTagName("*");
	var outstr="";
	var idVals="";
	for (var x=0;x<c.length;x++) {
		if (c[x].tagName.toLowerCase()=="input" && c[x].type.toLowerCase()=="checkbox" && c[x].id.startsWith("dwl")) {
			c[x].checked=boolValue;
			idVals=idVals+c[x].name+',';
		}
	}
	idVals=idVals.substring(0,idVals.length-1);
	filterForm.recordsList.value=idVals;
}

/*
 *	Used by:
 *		rata/filterEntries.jsp
 *		rata/file3filterEntries.jsp
 *
 *	Usage:
 *	-
 */
function selectall(isSelected)
{

    if (isSelected == '1'){
        checkInstrumentTypes('true');
    }
    if (isSelected == '0'){
        checkInstrumentTypes('');
    }

}

/*
 *	Used by:
 *		rata/filterEntries.jsp
 *		rata/file3filterEntries.jsp
 *
 *	Usage:
 *	-
 */
function showPii(pin){
	try{
		var frameDetails=parent.document.getElementById("rataDetails");
		var separtor=parent.document.getElementById("piiSepartor");
		frameDetails.src="blank.htm";
		var piiForm=document.getElementById("piiForm");
	    piiForm.piiPin.value=pin;
		piiForm.target="rataDetails";
		piiForm.submit();
		frameDetails.style.display='';
		separtor.style.display='';
		var closeratdetailsimg=parent.document.getElementById("closeratdetailsimg");
		closeratdetailsimg.style.display='';
		//parent.document.getElementById("rataReportFrame").style.posHeight = 350;
		parent.document.getElementById("rataReportFrame").style.height = 350 + "px";
		resizeRATASearchResultsDiv();
	}catch(e){
		window.status =	'Error submitting for details: ' + e.number + '; ' + e.description;
	}
}

function resizeRATASearchResultsDiv() {
	var rptDataDiv=document.getElementById("reportData");
	var rataRptFrameHeight=parent.document.getElementById("rataReportFrame").clientHeight;
	//var rptDataDivHeight = (document.body.clientHeight-document.getElementById('filter1').clientHeight-document.getElementById('reportHeader').clientHeight);
	//as as result of W3C changes to RATA pages, use the report frame height for correct area computation
	var rptDataDivHeight=(rataRptFrameHeight-document.getElementById('filter1').clientHeight-document.getElementById('reportHeader').clientHeight);
	rptDataDiv.style.height=rptDataDivHeight*0.98 + 'px';
}
/*
 *	Used by:
 *		rata/filterEntries.jsp
 *		rata/file3filterEntries.jsp
 *
 *	Usage:
 *	-
 */
function rtd(pin){
	try{

	var frameDetails	=	parent.document.getElementById("rataDetails");
	window.status =	'pin: ' +pin + ';frameDetails: ' + frameDetails;
	frameDetails.src = pin + '_React_details.htm';
	frameDetails.style.display='';
	var closeratdetailsimg = parent.document.getElementById("closeratdetailsimg");
	closeratdetailsimg.style.display='';
	parent.document.getElementById("rataReport").style.posHeight = 40;
	return;
	}
	catch(e)
	{
		//window.status =	'Error: ' + e.number + '; ' + e.description;
	}
}

/*
 *	Used by:
 *		rata/filterEntries.jsp
 *		rata/file3filterEntries.jsp
 *
 *	Usage:
 *	-
 */
function syncReactrTemplate(){
	var filterForm = document.getElementById("filterForm");
	filterForm.countOfSelected.value = selListSize*1.0;
	if (parent.showfilter==true){
		parent.showfilter=false;
	  parent.toggleFilterForm('filter1','applyFilterLink',
	  encodeURIComponent('Show&nbsp;Filter&nbsp;&rsaquo;&rsaquo;'),
	  encodeURIComponent('Remove&nbsp;Filter&nbsp;&rsaquo;&rsaquo;'),'filterreact');
  }
}

/*
 *	Used by:
 *		rata/filterEntries.jsp
 *
 *	Usage:
 *	-
 */
function submitFilterForm(action){

	var filterForm = document.getElementById("filterForm");
	filterForm.action.value=action;
	if (action == 'applyFilter'){
		//Validate Pin
		if (filterForm.pin.value.length > 0){
			pinRegex = /^\d{9}$/;
      if( !filterForm.pin.value.match( pinRegex ) ) {
      	alert("Filter Error: The PIN must be a 9 digit number. PIN Entered:"+ filterForm.pin.value);
      	return;
		  }
		}else if (filterForm.registrationDateAsString.value.length > 0){
			registrationDateRegex = /^\d{2}-\d{2}-\d{4}$/;
      if( !filterForm.registrationDateAsString.value.match( registrationDateRegex ) ) {
      	alert("Filter Error: The registration date must be entered as MM-DD-YYYY. registration date Entered:"+ filterForm.registrationDateAsString.value);
      	return;
		  }
			var month = filterForm.registrationDateAsString.value.substring(0,2);
			var day = filterForm.registrationDateAsString.value.substring(3,5);
			if (month > 12 || month < 1){
      	alert("Filter Error: Incorrect month Entry. The registration date must be entered as MM-DD-YYYY. registration date Entered:"+ filterForm.registrationDateAsString.value);
      	return;
			}else if (day > 31 || day < 1){
      	alert("Filter Error: Incorrect Day Entry. The registration date must be entered as MM-DD-YYYY. registration date Entered:"+ filterForm.registrationDateAsString.value);
      	return;
			}
		}
	}
	  var counter = parent.getCounter();
	  if (counter == 0){
	      filterForm.submit();
        parent.setCounter(counter*1.0 +1);
	      parent.document.getElementById('loadingdiv').style.visibility='visible';
		 }else{
		 	  setTimeout('parent.setCounter(0);',5000);
		   	alert("We are processing your previous request. Please wait for the view to be updated.");
		 }

}

/*
 *	Used by:
 *		rata/filterEntries.jsp
 *		rata/file3filterEntries.jsp
 *
 *	Usage:
 *	-
 */
function resetSelectedCount(caller)
{
	var x = 1.0;
	if (!caller.checked)
	{
		x = -1.0;
	}
	var filterForm = document.getElementById("filterForm");
	filterForm.countOfSelected.value = x + filterForm.countOfSelected.value*1.0 ;
}

/*
 *	Used by:
 *		rata/filterEntries.jsp
 *
 *	Usage:
 *	-
 */
function onLoadFilterEntries()
{
	var filterForm = initFilterEntriesPage();
	populateFilterForm(filterForm);
}

function initFilterEntriesPage() {
	resizeRATASearchResultsDiv();
	var filterForm = document.getElementById("filterForm");
	parent.reSize();
	if (1== reportCurrentPage){
		parent.document.getElementById('previousPageDiv').style.visibility='hidden';
	}else{
		parent.document.getElementById('previousPageDiv').style.visibility='visible';
	}
	if (reportNumberOfPages == reportCurrentPage){
		parent.document.getElementById('nextPageDiv').style.visibility='hidden';
	}else{
		parent.document.getElementById('nextPageDiv').style.visibility='visible';
	}
	parent.document.getElementById('paginationDiv').innerHTML = "page&nbsp;" + reportCurrentPage + "&nbsp;of&nbsp;" + reportNumberOfPages;
	var divStyle = parent.document.getElementById('paginationDiv').style;
	parent.document.getElementById('paginationDiv').style.visibility='visible';
	divStyle.display='inline';
	parent.document.getElementById('loadingdiv').style.visibility='hidden';
	parent.resetCounter();
	return filterForm;
}

function populateFilterForm(filterForm) {
	filterForm.pin.value = pin;
	filterForm.partyFrom.value = partyFrom;
	filterForm.partyTo.value = partyTo;
	filterForm.registrationDateAsString.value = registrationDateAsString;
}

/*
 *	Used by:
 *		rata/file3FilterEntries.jsp
 *
 *	Usage:
 *	-
 */
function submitFile3FilterForm(action){

	var filterForm = document.getElementById("filterForm");
	filterForm.action.value=action;
	if (action == 'applyFilter'){
		//Validate Pin
		if (filterForm.pin.value.length > 0){
			pinRegex = /^\d{9}$/;
      if( !filterForm.pin.value.match( pinRegex ) ) {
      	alert("Filter Error: The PIN must be a 9 digit number. PIN Entered:"+ filterForm.pin.value);
      	return;
		  }
		}else if (filterForm.transferRegistrationDateAsString.value.length > 0){
			registrationDateRegex = /^\d{2}-\d{2}-\d{4}$/;
      if( !filterForm.transferRegistrationDateAsString.value.match( registrationDateRegex ) ) {
      	alert("Filter Error: The transfer registration date must be entered as MM-DD-YYYY. transfer registration date Entered:"+ filterForm.registrationDateAsString.value);
      	return;
		  }
			var month = filterForm.transferRegistrationDateAsString.value.substring(0,2);
			var day = filterForm.transferRegistrationDateAsString.value.substring(3,5);
			if (month > 12 || month < 1){
      	alert("Filter Error: Incorrect month Entry. The transfer registration date must be entered as MM-DD-YYYY. transfer registration date Entered:"+ filterForm.transferRegistrationDateAsString.value);
      	return;
			}else if (day > 31 || day < 1){
      	alert("Filter Error: Incorrect Day Entry. The transfer registration date must be entered as MM-DD-YYYY. transfer registration date Entered:"+ filterForm.transferRegistrationDateAsString.value);
      	return;
			}
		}else if 	(filterForm.chargeRegistrationDateAsString.value.length > 0){
			registrationDateRegex = /^\d{2}-\d{2}-\d{4}$/;
      if( !filterForm.chargeRegistrationDateAsString.value.match( registrationDateRegex ) ) {
      	alert("Filter Error: The charge registration date must be entered as MM-DD-YYYY. charge registration date Entered:"+ filterForm.chargeRegistrationDateAsString.value);
      	return;
		  }
			var month = filterForm.chargeRegistrationDateAsString.value.substring(0,2);
			var day = filterForm.chargeRegistrationDateAsString.value.substring(3,5);
			if (month > 12 || month < 1){
      	alert("Filter Error: Incorrect month Entry. The charge registration date must be entered as MM-DD-YYYY. charge registration date Entered:"+ filterForm.chargeRegistrationDateAsString.value);
      	return;
			}else if (day > 31 || day < 1){
      	alert("Filter Error: Incorrect Day Entry. The charge registration date must be entered as MM-DD-YYYY. charge registration date Entered:"+ filterForm.chargeRegistrationDateAsString.value);
      	return;
			}
		}
	}
	  var counter = parent.getCounter();
	  if (counter == 0){
	      filterForm.submit();
        parent.setCounter(counter*1.0 +1);
	      parent.document.getElementById('loadingdiv').style.visibility='visible';
		 }else{
		 	  setTimeout('parent.setCounter(0);',5000);
		   	alert("We are processing your previous request. Please wait for the view to be updated.");
		 }
}

/*
 *	Used by:
 *		rata/file3filterEntries.jsp
 *
 *	Usage:
 *	-
 */
function onLoadFile3FilterEntries()
{
	var filterForm = initFilterEntriesPage();	//re-use
	populateFile3FilterForm(filterForm);
}

function populateFile3FilterForm(filterForm) {
	filterForm.pin.value = pin;
	filterForm.partyFrom.value = partyFrom;
	filterForm.partyTo.value = partyTo;
	filterForm.transferRegistrationDateAsString.value = transferRegistrationDateAsString;
	filterForm.chargeRegistrationDateAsString.value= chargeRegistrationDateAsString;
}

/*
 *	Used by:
 *		rata/rataPii.jsp
 *
 *	Usage:
 *	-
 */

function submitViewInstrumentImage()
{

	var instrumentNumber=document.forms['form1'].strINSTR.value

	if(instrumentNumber == '')
	{
		alert(noInstrumentNumberMsg);
	}else
	{
		if(instrumentNumberRules.test(instrumentNumber))
		{
			alert(invalidInstrumentNumberMsg);
		}else
		{
			document.forms['view'].lroNumber.value=document.forms['form1'].lro.value;
			document.forms['view'].instrumentNumber.value=document.forms['form1'].strINSTR.value;
			document.forms['view'].submit();
		}
	}
}

/*
 *	Used by:
 *		rata/rataPii.jsp
 *
 *	Usage:
 *	-
 */
function openDocumentImage(token, action){

	var documentUrl="./showDocImages.do?token="+token+"&action="+ action;
	showDocImageWindow = window.open (documentUrl,	"showDocImageWindow","height=400,width=650,status=no,toolbar=no,menubar=no,location=no,scrollbars");
  showDocImageWindow.focus();
}


 /*************************************************
 *             ESTORE FUNCTIONS
 **************************************************/
var __ESTORE_FUNCTIONS__;

// eStore fulfillment
function downloadProduct(cartId, itemId) {
	var downloadUrl = '/gwhweb/ProductDownload?cartId='+cartId+"&itemId="+itemId+"&token="+new Date().getTime();
	location.href=downloadUrl;
}
function downloadLSRProduct(cartId, itemId) {
	//download survey image
	downloadProduct(cartId, itemId);

	// determine whether survey notes exist
	var sNotesUrl = '/gwhweb/ProductDownload?queryNotes=1&cartId='+cartId+"&itemId="+itemId+"&token="+new Date().getTime();
	var asXmlHttp = GWH.Ajax.getXmlHttpRequest();
	asXmlHttp.open("GET", sNotesUrl, false);
	asXmlHttp.send(null);
	if (asXmlHttp.readyState == 4) {
		if (asXmlHttp.status == 200||asXmlHttp.status == 0 ) {
			try {
				var responseText = asXmlHttp.responseText;
				//alert(responseText);
				if (responseText == '1') {
					//survey notes exist; download it
					var sNotesUrl = '/gwhweb/ProductDownload?queryNotes=0&cartId='+cartId+"&itemId="+itemId+"&token="+new Date().getTime();
					sNotesWnd = window.open(sNotesUrl, "notes");
				}
			} catch(e) {
				return "error " + e.source + '\e.name=' + e.name + '\e.message=' + e.message;
			}
		} else {
			return "error with status " + asXmlHttp.status;
		}
	} else {
		return "error with state " + asXmlHttp.readyState;
	}
}

// Modal Product Detail Screen: Start

var purchaseWindow;

/*
	This is to open a popup window for the purchase product:
	This is called by:
		- Parcel Register (from Geowarehouse Store)
		- MPAC Report (from Geowarehouse Store)
		- Plan List by PIN
		- SRPR
		- StreetScape
*/
function purchaseProductWithWSize(url, height, width, defaultTitle) {
	var winArgs = "height=" + height + ", " +
				  "width=" + width + ", " +
				  "resizable=no, " +
				  "scrollbars=no, " +
				  "status=no, " +
				  "toolbar=no, " +
				  "menubar=no, " +
				  "location=no, " +
				  "titlebar=no" ;
	var productDetailFrameUrl = "/gwhweb/estore/ProductDetailFrame.jsp?" +
			"defaultTitle=" + escape(defaultTitle) +
			"&nextUrl=" + escape(url);
	purchaseWindow = window.open(productDetailFrameUrl, "PurchaseWindow", winArgs);
	if (purchaseWindow != null) {
		purchaseWindow.focus();
	}
	return purchaseWindow;
}

function purchaseProduct(url) {
	return purchaseProductWithWSize(url, 690, 670, "");
}

/*
	This is to open a popup window for the plan/instrument product:
	This is called by:
		- Plan/Instrument Image
		- StreetScape
*/
function viewProductWithWSize(url, height, width, defaultTitle) {
	var winArgs = "height=" + height + ", " +
				  "width=" + width + ", " +
				  "resizable=no, " +
				  "scrollbars=no, " +
				  "status=no, " +
				  "toolbar=no, " +
				  "menubar=no, " +
				  "location=no, " +
				  "titlebar=no" ;
	var productDetailFrameUrl = "/gwhweb/estore/ViewProductFrame.jsp?" +
			"defaultTitle=" + escape(defaultTitle) +
			"&nextUrl=" + escape(url);
	purchaseWindow = window.open(productDetailFrameUrl, "ViewWindow", winArgs);
	if (purchaseWindow != null) {
		purchaseWindow.focus();
	}
	return purchaseWindow;
}

function viewProduct(url) {
	return viewProductWithWSize(url, 690, 670, "");
}

/*
	Show cart view
*/
function showCartView() {
	var url = "/gwhweb/viewCart.do";
	purchaseWindow = purchaseProduct(url);
}


/*
	This is to close the frozen div background and close the
	Product Detail Screen popup when the Product Detail Screen
	needs to unload
*/
function closePurchaseWindow()
{
	if (purchaseWindow == null) {
		window.HideModalDiv();
	}
//	else {
//		if (purchaseWindow.closed == false) {
//		alert(2);
//			purchaseWindow.close();
//		}
		//if(divLoaded && window.opener != null && !window.opener.closed)
		//{ alert(3);
			//window.opener.HideModalDiv();
		//}
//	}
}


function refreshMainPage()
{
	if (purchaseWindow != null) {
		if (purchaseWindow.closed == false) {
			purchaseWindow.close();
		}
	}
}

var purchaseParentWindow;

/*
	This is to load the divBackground
*/

var cirBoxDisabled;
var srprcirBoxDisabled;
var divLoaded = false;
function LoadModalDiv()
{
	var bcgDiv = getBackgroundDiv();

	if (divLoaded == false && bcgDiv != null)
	{
		if (purchaseParentWindow != null) {
			if (purchaseParentWindow.name == "StoreCatalogue") {
				if (purchaseParentWindow.document.fromMPACForm != undefined) {
					var fromMPAC = purchaseParentWindow.document.fromMPACForm.fromMPAC.value;
					if (fromMPAC == "true") {
						purchaseParentWindow.location.hash = "#MPAC_REPORT";
					}
				}
			}
		}
		bcgDiv.style.display="block";

		if (document.body.clientHeight > document.body.scrollHeight)
		{
			bcgDiv.style.height = purchaseParentWindow.document.body.clientHeight + "px";
		}
		else
		{
			bcgDiv.style.height = purchaseParentWindow.document.body.scrollHeight + "px" ;
		}

		bcgDiv.style.width = "100%";
		divLoaded = true;

		disableElementForDivBackground();
	}
}

function disableElementForDivBackground() {

	changeElementStatusForDivBackground(true);

	var searchPlansBtn = window.opener.document.getElementById("searchPlansBtn");
	if (searchPlansBtn != null) {
		searchPlansBtn.disabled = true;
	}

	var srprsearchPlansBtn = window.opener.document.getElementById("srprsearchPlansBtn");
	if (srprsearchPlansBtn != null) {
		srprsearchPlansBtn.disabled = true;
	}

	// This element is special, as you have to look at its previous state first
	var cirBox = window.opener.document.getElementById("bufferRange");
	if (cirBox != null) {
		cirBoxDisabled = cirBox.disabled;
		cirBox.disabled = true;
	}

	// This element is special, as you have to look at its previous state first
	var srprcirBox = window.opener.document.getElementById("srprbuffRange");
	if (srprcirBox != null) {
		srprcirBoxDisabled = srprcirBox.disabled;
		srprcirBox.disabled = true;
	}

}

/*
	This is to unload the divBackground
*/
function HideModalDiv()
{
	if (purchaseParentWindow != null && purchaseParentWindow.document != null) {
		try {
			window.opener.parent.estoreCounter();
		}
		catch (e) {
			// don't need to do anything
			// will only come to this point when user refresh the main page
			// and user open the popup from Search Results
		}

		var bcgDiv = purchaseParentWindow.document.getElementById("divBackground");
		if (bcgDiv != null) {
			if (purchaseParentWindow.name == "StoreCatalogue") {
				if (purchaseParentWindow.document.fromMPACForm != undefined) {
					var fromMPAC = purchaseParentWindow.document.fromMPACForm.fromMPAC.value;
					if (fromMPAC == "true") {
						purchaseParentWindow.location.hash = "#MPAC_REPORT";
					}
				}
			}
			bcgDiv.style.display="none";
			purchaseParentWindow.unsetEventListener(disableMainPageKey);
			divLoaded = false;
		}

		enableElementForDivBackground(false);
	}
}

function enableElementForDivBackground() {
	changeElementStatusForDivBackground(false);

	try {
		var searchPlansBtn = window.opener.document.getElementById("searchPlansBtn");
		if (searchPlansBtn != null) {
			searchPlansBtn.disabled = false;
		}

		var srprsearchPlansBtn = window.opener.document.getElementById("srprsearchPlansBtn");
		if (srprsearchPlansBtn != null) {
			srprsearchPlansBtn.disabled = false;
		}

		// This element is special, as you have to restore its previous state
		var cirBox = window.opener.document.getElementById("bufferRange");
		if (cirBox != null) {
			cirBox.disabled = cirBoxDisabled;
		}

		// This element is special, as you have to restore its previous state
		var srprcirBox = window.opener.document.getElementById("srprbuffRange");
		if (srprcirBox != null) {
			srprcirBox.disabled = srprcirBoxDisabled;
		}
	}
	catch (e) {
		// don't need to do anything
		// will only come to this point when user refresh the main page
		// and user open the popup from Search Results
	}
}

/**
 * This function will enable/disable the element behind the divBackground
 */
function changeElementStatusForDivBackground(disable) {

	var lrobox = purchaseParentWindow.document.getElementById("lro");
	if (lrobox != null) {
		lrobox.disabled = disable;
	}

	var srhButton = purchaseParentWindow.document.getElementById("searchButton");
	if (srhButton != null) {
		srhButton.disabled = disable;
	}

}

/*
	Get the background div and return it
*/
function getBackgroundDiv() {

	purchaseParentWindow = getMainWindow(window);

	if (purchaseParentWindow == null) {
		purchaseParentWindow = window.opener;
		// Open by Store Catalogue
		purchaseParentWindow.name = "StoreCatalogue";
	}
	else {
		// Open by PropertyView.jsp
		purchaseParentWindow.name = "PropertyView";
	}

	bcgDiv = purchaseParentWindow.document.getElementById("divBackground");

	return bcgDiv;
}

// Modal Product Detail Screen: End

/*
	To change the window title for the eStore process
*/
function changeTitle(title) {
    try {
		var mainWindow = window.parent;
		mainWindow.document.title = "GeoWarehouse" + String.fromCharCode(174)+ " Online - " + title;
	} catch (exception) {
	}
}

/*
	To change the window title for the eStore process
*/
function changeSizeBackToDefault(prodId) {
	var mainWindow = window.parent;
	if (prodId == '701' || prodId == '702') {
		// The height needs to be 30 pixels more than original
		// Otherwise the window will smaller than the regular one.
		// resizeTo(width, height)
		mainWindow.resizeTo(680,730);
		productFrame = mainWindow.document.getElementById("ProductDetailFrameID");
		if (productFrame != null) {
			productFrame.scrolling = "no";
		}
	}
}





/*valid
	This function will hide the div for plan/instrument image
	if viewType is "View"
*/
function determineDivBackground(viewType) {
	if (viewType == 'Purchase') {
		window.parent.LoadModalDiv();
	}
}


function estoreCounter(){

	asXmlHttp = GWH.Ajax.getXmlHttpRequest();
	var serverURL = "/gwhweb/cartviews/counterXML.jsp";
	asXmlHttp.open("GET", serverURL, true);
	asXmlHttp.onreadystatechange = handleServerResponse;
	asXmlHttp.send(null);


}

function handleServerResponse(){
	  if (asXmlHttp.readyState == 4) {
	     if(asXmlHttp.status == 200) {
		    var message =  asXmlHttp.responseXML.getElementsByTagName("count")[0].childNodes[0].nodeValue;
		    if (document.getElementById("itemcounter") != null)
		    {
				document.getElementById("itemcounter").innerHTML="("+parseInt(message)+")";
			}
	     }
	     else {
	        alert("Error during AJAX call. Please try again");
	     }
   		}

}

function addToCounter(){
	var c = document.getElementById("itemcounter").innerHTML;
	var d = c.replace("(", "");
	var e = d.replace(")", "");
	var cInt = parseInt(e) +1;
	document.getElementById("itemcounter").innerHTML= "(" +cInt +")";
}
/** Adjusts div height and height of it's IFrame to fit on a screen without vertical scrolling */
function adjustScrollHeightInIFrame(scrollDivId, iframeId) {
	try {
		var parentDoc = getMainWindow(window).document;
		var iframe = parentDoc.getElementById(iframeId)
		var footer = parentDoc.getElementById('gwhfooter')
		var clientHeight = parentDoc.documentElement.clientHeight
		var footerHeight = footer.offsetHeight + 20;

		var frameHeight = clientHeight- findPosY(iframe) - footerHeight;
		var scrollDiv = document.getElementById(scrollDivId);
		scrollDiv.style.height = frameHeight - findPosY(scrollDiv) + "px";
		iframe.style.height = frameHeight + "px";
	} catch(exception) {	
	}
}
/** returns Y position of the obj element within document */
function findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    } else if (obj.y) {
        curtop += obj.y;
    }    
    return curtop;
}
/**
 * This function will be called when the main window is resized
 */
var resizeTimer = 0;
function onResizeWindow() {
	if (resizeTimer) {
		clearTimeout(resizeTimer);
	}

	resizeTimer = setTimeout(resizeDivBackground, 500);
}

function resizeDivBackground() {
	var bcgDiv = null;
	if (purchaseParentWindow != null && purchaseParentWindow.document != null) {
		bcgDiv = purchaseParentWindow.document.getElementById("divBackground");
	}
	else {
		bcgDiv = window.document.getElementById("divBackground");
	}

	if (bcgDiv != null) {
		bcgDiv.style.height = "100%";
		bcgDiv.style.width = "100%";
	}
	resizeStoreCatalog();
}

function resizeStoreCatalog() {
	var storeCatDiv = window.document.getElementById("storeCatDiv");
	if (storeCatDiv != null) {
		var catOccupiedDivHeight = 0;
		var buffer = 80;
		var catDiv1 = window.document.getElementById("catalogue_returndiv");
		var catDiv2 = window.document.getElementById("catalgoue_logo_icon_div");
		var catDiv3 = window.document.getElementById("piisummarydiv");

		if (catDiv1 != null) catOccupiedDivHeight = catOccupiedDivHeight + catDiv1.offsetHeight;
		if (catDiv2 != null) catOccupiedDivHeight = catOccupiedDivHeight + catDiv2.offsetHeight;
		if (catDiv3 != null) catOccupiedDivHeight = catOccupiedDivHeight + catDiv3.offsetHeight;

		var bodyHeight = getBodyHeight();
		if (bodyHeight > (catOccupiedDivHeight + buffer)) {
			var newCatHeight = bodyHeight - catOccupiedDivHeight;
			storeCatDiv.style.height = newCatHeight - buffer + "px";
		}
	}
}

function refreshToMPACAnchor() {
	var parentWindow = window.parent.opener;
	if (parentWindow != null) {
		if (parentWindow.document.fromMPACForm != undefined) {
			var fromMPAC = parentWindow.document.fromMPACForm.fromMPAC.value;
			if (fromMPAC == "true") {
				parentWindow.location.hash = "#MPAC_REPORT";
			}
		}
	}
}



function changeActiveButtonBorder(buttonName) {
	document.getElementById(buttonName).style.borderColor = "#009DFF";
}

function changeInactiveButtonBorder(buttonName) {
	document.getElementById(buttonName).style.borderLeftColor = "#919495";
	document.getElementById(buttonName).style.borderRightColor = "#919495";
	document.getElementById(buttonName).style.borderTopColor = "#B7BABC";
	document.getElementById(buttonName).style.borderBottomColor = "#5E6162";
}

/*
 *	Used by:
 *		estore/ProductDetailScreen.jsp
 *
 *	Usage:
 *	- Submit the form from Product Detail Screen
 */
function onSubmitPDSForm()
{
	if( "Y" == existsInCart )  {
		alert (estoreMessageProductAlreadyExists);
		return false;

	} else{
		if(document.pressed == 'directcheckout'){
			window.parent.increaseCounter();
			document.getElementById("cart1").action = sslPrefix + contextPath + "/addAndPayCart.do";
		} else {
	 		if(document.pressed == 'addtocart') {
	 	  		document.getElementById("cart1").action = contextPath + "/addToCart.do";
	  		}
	  	}
	  	changeInactiveButtonBorder('addToCartButton');
	  	changeInactiveButtonBorder('directCheckoutButton');
		pdsDisableButton(document.pressed);
		return true;
	}
}


/*
 *	Used by:
 *		estore/ProductDetailScreen.jsp
 *
 *	Usage:
 *	- Disabled all the button when the AddToCart or DirectToCheckout button is pressed
 */
function pdsDisableButton(dpressed) {
	if (dpressed == 'directcheckout') {

		buttonMsg = 'Direct checkout in progress';
	}
	else if (dpressed == 'addtocart') {
		buttonMsg = 'Adding to cart in progress';
	}
	else {
		buttonMsg = 'Recalculating price in progress';
	}

	if (document.getElementById("addToCartButton").disabled == false) {
		addToCartButtonOrgState = false;
		document.getElementById("addToCartButton").disabled=true;
		document.getElementById("addToCartButton").src=contextPath + "/images/02_addcart_01d.png";
		document.getElementById("addToCartButton").title=buttonMsg;
		document.getElementById("addToCartButton").className="buttond";
	}
	else {
		addToCartButtonOrgState = true;
	}

	document.getElementById("cancelButton").disabled=true;
	document.getElementById("cancelButton").src=contextPath + "/images/03_cancel_01d.png";
	document.getElementById("cancelButton").title=buttonMsg;
	document.getElementById("cancelButton").className="buttond";

	document.getElementById("directCheckoutButton").disabled=true;
	document.getElementById("directCheckoutButton").src=contextPath + "/images/01_dir_checkout_01d.png";
	document.getElementById("directCheckoutButton").title=buttonMsg;
	document.getElementById("directCheckoutButton").className="buttond";
}


/*
 *	Used by:
 *		estore/ProductDetailScreen.jsp (function actually not used in the jsp)
 *
 *	Usage:
 *	- Disabled all the button when the AddToCart or DirectToCheckout button is pressed
 *
 *	Note:
 *	- This function can actually removed, as nobody is using it
 */
function pdsEnableButton() {
	if (addToCartButtonOrgState == false) {
		document.getElementById("addToCartButton").disabled=false;
		document.getElementById("addToCartButton").src=contextPath + "/images/02_addcart_01.png";
		document.getElementById("addToCartButton").title='Add product to cart';
		document.getElementById("addToCartButton").className="button";
	}

	document.getElementById("cancelButton").disabled=false;
	document.getElementById("cancelButton").src=contextPath + "/images/03_cancel_01.png";
	document.getElementById("cancelButton").title='Cancel purchase';
	document.getElementById("cancelButton").className="button";

	document.getElementById("directCheckoutButton").disabled=false;
	document.getElementById("directCheckoutButton").src=contextPath + "/images/01_dir_checkout_01.png";
	document.getElementById("directCheckoutButton").title='Direct to checkout';
	document.getElementById("directCheckoutButton").className="button";
}


/*
 *	Used by:
 *		cartviews/paymentoptions.jsp
 *
 *	Usage:
 *	- Submit the Payment option form
 */
function onSubmitPOPTForm()
{
	changeInactiveButtonBorder('_eventId_payorder');
	poptDisableButton(document.pressed);
	if(document.pressed == 'payorder') {
		setEmailInSession();
		document.getElementById("paymentoptions").action = sslPrefix + flowExecutionUrl + "&_eventId=payorder";
		var vcc = poptConfirmSubmit();
		if (vcc == false) {
			poptEnableButton();
		}
		return vcc;
	} else {
		if (document.pressed == 'gotoshoppingcart') {
			document.getElementById("paymentoptions").action = nonSslPrefix + flowExecutionUrl+ "&_eventId=gotoshoppingcart";
			return true;
		}
	}
}


/*
 *	Used by:
 *		cartviews/paymentoptions.jsp
 *
 *	Usage:
 *	- Set the email into the session
 */
function setEmailInSession() 	{
	if ( document.getElementById("emailAddress").value == null || document.getElementById("emailAddress").value.length == 0 ) {
		return;
	}

	var asXmlHttp = GWH.Ajax.getXmlHttpRequest();
	var serverURL = contextPath + "/sessionAttribute.do?name=ESTORE_RECEIPT_EMAIL&value="+document.getElementById("emailAddress").value;
	asXmlHttp.open("GET", serverURL, false);
	asXmlHttp.send(null);

	if (asXmlHttp.status == 200||asXmlHttp.status == 0 ) {
		try {
			var responseText = asXmlHttp.responseText;
			if (responseText == "success") {
				window.status = 'setEmailAttribute success';
			} else {
				window.status = 'setEmailAttribute failure';
			}
			asXmlHttp = null;

		} catch(e) {
			window.status = 'setEmailAttribute.e.src=' + e.source + '\ne.n=' + e.name + '\ne.m=' + e.message;
			asXmlHttp = null;
		}

	} else {
		window.status = "setEmailAttribute failed with status " + asXmlHttp.status;
		asXmlHttp = null;
	}

}


/*
 *	Used by:
 *		cartviews/paymentoptions.jsp (function actually not used in the jsp)
 *
 *	Usage:
 *	- Update the quantity for a particular line item
 *
 *	Note:
 *	- This function can actually removed, as nobody is using it
 *  - We only need this function ff we allow user to change the quantity of a particular item they purchase
 */
function updateLineItemQty(priceResultKey, qty, prodIndex){

	window.location = flowExecutionUrl + "&_eventId=updateLineItemQty&lineKey="+priceResultKey+"&quantity="+qty+"&sessionToken=" + sessionId;
}


/*
 *	Used by:
 *		cartviews/paymentoptions.jsp (function actually not used in the jsp)
 *
 *	Usage:
 *	- Potential call when cancel button is pressed
 *
 *	Note:
 *	- This function can actually removed, as nobody is using it
 */
function cancelButton(){
	window.location = flowExecutionUrl + "&_eventId_cancelCheckout";
}


/*
 *	Used by:
 *		cartviews/paymentoptions.jsp
 *
 *	Usage:
 *	- Proxy to call the credit card validation function in the payment option page
 */
function poptConfirmSubmit()
{
    document.getElementById("paymentoptions").target = "";
    return validateCC();
}


/*
 *	Used by:
 *		cartviews/paymentoptions.jsp
 *
 *	Usage:
 *	- Disabled all the button when the FinalizeOrder or ShoppingCart button is pressed
 */
function poptDisableButton(dpressed) {
	if (dpressed == 'payorder') {
		buttonMsg = 'Finalize order in progress';
	}
	else {
		buttonMsg = 'Go to shopping cart in progress';
	}

	document.getElementById("_eventId_gotoshoppingcart").disabled=true;
	document.getElementById("_eventId_gotoshoppingcart").src=contextPath + "/images/shopping_cartd.png";
	document.getElementById("_eventId_gotoshoppingcart").title=buttonMsg;
	document.getElementById("_eventId_gotoshoppingcart").className="buttond";

	document.getElementById("_eventId_continueshopping").disabled=true;
	document.getElementById("_eventId_continueshopping").src=contextPath + "/images/05_cont_shop_01d.png";
	document.getElementById("_eventId_continueshopping").title=buttonMsg;
	document.getElementById("_eventId_continueshopping").className="buttond";

	document.getElementById("_eventId_payorder").disabled=true;
	document.getElementById("_eventId_payorder").src=contextPath + "/images/07_finalize_01d.png";
	document.getElementById("_eventId_payorder").title=buttonMsg;
	document.getElementById("_eventId_payorder").className="buttond";
}


/*
 *	Used by:
 *		cartviews/paymentoptions.jsp
 *
 *	Usage:
 *	- Enabled all the button when the FinalizeOrder or ShoppingCart button is pressed
 */
function poptEnableButton() {
	document.getElementById("_eventId_gotoshoppingcart").disabled=false;
	document.getElementById("_eventId_gotoshoppingcart").src=contextPath + "/images/shopping_cart.png";
	document.getElementById("_eventId_gotoshoppingcart").title='View shopping cart';
	document.getElementById("_eventId_gotoshoppingcart").className="button";

	document.getElementById("_eventId_continueshopping").disabled=false;
	document.getElementById("_eventId_continueshopping").src=contextPath + "/images/05_cont_shop_01.png";
	document.getElementById("_eventId_continueshopping").title='Close window and continue shopping';
	document.getElementById("_eventId_continueshopping").className="button";

	document.getElementById("_eventId_payorder").disabled=false;
	document.getElementById("_eventId_payorder").src=contextPath + "/images/07_finalize_01.png";
	document.getElementById("_eventId_payorder").title='Finalize order';
	document.getElementById("_eventId_payorder").className="button";
}


/*
 *	Used by:
 *		cartviews/viewcart.jsp
 *
 *	Usage:
 *	- Submit the view cart form
 */
function onSubmitViewCartForm() {
	document.getElementById("form1").action = sslPrefix + flowExecutionUrl;
	return true;
}


/*
 *	Used by:
 *		cartviews/orderreceipt.jsp
 *
 *	Usage:
 *	- Go to the fulfillment page
 */
function showFulfillment() {
	var dt = new Date().getTime();
	var fulfillmentUrl = nonSslPrefix + contextPath + "/fulfillment.do?token="+dt+"&sessionToken="+sessionId;
	location.href = fulfillmentUrl;
}

/*
 *	Used by:
 *		estore/ViewProductFrame.jsp
 *
 *	Usage:
 *	- Increments the eStore counter
 */
function increaseCounter() {
	if (window.opener && !window.opener.closed) {
	  	window.opener.parent.addToCounter();
	}
}

/*
 *	Used by:
 *		cartviews/orderreceipt.jsp
 *
 *	Usage:
 *	- Go to the fulfillment page
 */
function sendProductAttachments() {
	asXmlHttp = GWH.Ajax.getXmlHttpRequest();

	var serverURL = contextPath + "/fulfillmentEmail.do?token="+currentDate+"&emailTo=" + estoreReceiptEmail;

	asXmlHttp.open("GET", serverURL, true);
	asXmlHttp.onreadystatechange = sendFulfillmentEmail;
	asXmlHttp.send(null);
}

/*
 *	Used by:
 *		cartviews/orderreceipt.jsp
 *
 *	Usage:
 *	- Go to the fulfillment page
 */
function sendFulfillmentEmail() {
	var errUrl = contextPath + "/errMessage.jsp";
	if (asXmlHttp.readyState == 4) {
		if (asXmlHttp.status == 200||asXmlHttp.status == 0 ) {
			try {
				var responseText = asXmlHttp.responseText;
				if (responseText == "success") {
					//do next step
				} else {
					//deal with this error
				}
			} catch(e) {
				window.status = ' sendFulfillmentEmail.e.src=' + e.source + '\e.n=' + e.name + '\e.m=' + e.message;
				asXmlHttp = null;
				location.href = errUrl;
			}
		} else {
			window.status = "sendFulfillmentEmail failed with status " + asXmlHttp.status;
			asXmlHttp = null;
			location.href = errUrl;
		}
	} else {
		window.status = "sendFulfillmentEmail readyState " + asXmlHttp.readyState;
		//asXmlHttp = null;
		//location.href = errUrl;
	}
}


/*
 *	Used by:
 *		estore/Fulfillment.jsp
 *
 *	Usage:
 *	- After the Fulfillment page loads
 */
function onFulfillmentLoadHandler() {
	/*** Looks like it's not needed
	var wndHeight;
	if (window.innerWidth) {
		wndHeight = window.innerHeight;
	} else if (document.all) {
		wndHeight = document.body.clientHeight;
	}
	document.getElementById('fulfilldivwrapper').style.height = (wndHeight - 30) + "px";
	***/
}


/*
 *	Used by:
 *		estore/ViewProductFrame.jsp
 *
 *	Usage:
 *	- Retrieves the initial value of the eStore counter
 */
function setFrameCounter() {

	if (window.opener && !window.opener.closed) {
		window.opener.parent.estoreCounter();
	}
}


 /*************************************************
 *              HELP FUNCTIONS
 **************************************************/
var __HELP_FUNCTIONS__;

/*
 * Context-Sensitive Help
 */
var gwhContextHelpDialog = null;
var propertyAssessmentHelpInfo="<HTML><HEAD><LINK href='/gwhweb/styles/gwpropertyview.css' type='text/css' rel='stylesheet'></HEAD><BODY><div class='moreText'>Assessment Information may not be available for the property for the following reasons:<ol start='1'><li>The property may not have an Assessment Roll Number.  Some properties such as roads and reserves, are not assigned Roll numbers by the Municipal Property Assessment Corporation.</li><br /><br /><li>The title and assessment information have been correlated using a geospatial comparison. In some instances, the ownership map data and the assessment map data were not similar enough to allow for automated correlation with a high degree of confidence.</li></ol><p><b>Another way to find the assessment information and purchase assessment reports</b> for a property is to right click on the property on the map (you may wish to turn on the 'Assessment Parcels' layer by clicking 'Layers' in the map controls) and then select 'Assessment Information'. </div><br /><div align='center'><BUTTON class='feedbackFormButton' onclick='gwhContextHelpDialog.hide();wincloseevent();'>CLOSE</BUTTON></div></BODY></HTML>";
var propertyAssessmentHelpHeader="ASSESSMENT INFORMATION NOT AVAILABLE";
var salesHistoryHelpInfo="<HTML><HEAD><LINK href='/gwhweb/styles/gwpropertyview.css' type='text/css' rel='stylesheet'></HEAD><BODY><div class='moreText'>The Sales History Information Section displays Transfer Type documents registered against the PIN you have searched.  <b>If no information is available</b> it means that none of the following document types have been registered against the property you are viewing:<br /><br /><ul id='searchHelpList'><li>T = Transfer</li><li>TPSA = Transfer Under Power of Sale (Grant)</li><li>TRAPL = Transfer by Personal Representative (Land)</li><li>TLP = Transfer by Partnership</li><li>TPR = Transfer by Personal Representative</li><li>TTRBK =  Transfer by Trustee in Bankruptcy</li></ul></div><br /><div align='center'><BUTTON class='contextSensitiveHelpButton' onclick='gwhContextHelpDialog.hide();'>CLOSE</BUTTON></div></BODY></HTML>";
var salesHistoryHelpHeader="SALES HISTORY INFORMATION NOT AVAILABLE";
var neighbourhoodSalesHelpHeader="MAPPING NOT AVAILABLE";
var neighbourhoodSalesHelpInfo="<HTML><HEAD><LINK href='/gwhweb/styles/gwpropertyview.css' type='text/css' rel='stylesheet'></HEAD><BODY><div class='moreText'>The property you are requesting a Neighbourhood Sales Report for is a Condominium.  <B>Lot Size, Search Radius and Property Type are not selectable for Condominiums.</B>  GeoWarehouse will simply search the entire Condominium Block for Sales corresponding to the Date and Price Range you have specified.</div><br /><div align='center'><BUTTON class='contextSensitiveHelpButton' onclick='gwhContextHelpDialog.hide();'>CLOSE</BUTTON></div></BODY></HTML>";

function showContextSensitiveHelp(helpInfo, helpHeader) {
	var mainWindow = getMainWindow(window);
	if (mainWindow != null){
	  mainWindow.renderContextSensitiveHelpDialog(helpInfo, helpHeader);
	}
	else {
	  renderContextSensitiveHelpDialog(helpInfo, helpHeader);
	  }
}

function renderContextSensitiveHelpDialog(helpInfo, helpHeader) {
	if (gwhContextHelpDialog!=null && gwhContextHelpDialog) {
	  gwhContextHelpDialog.hide();
	  gwhContextHelpDialog.destroy();
	}

	// Render the Dialog
	gwhContextHelpDialog = new YAHOO.widget.Dialog("contextHelpDialogId",
												{ width : "440px",
												  fixedcenter : true,
												  draggable: true,
												  visible : false,
												  constraintoviewport : true,
												  modal: false,
												  close: true,
												  underlay: "none",
												  zIndex: 1000
												});

	var dialogHtml  = "<div id='contextHelpDialogId'>";
	    dialogHtml += helpInfo;
	    dialogHtml += "</div>";

		gwhContextHelpDialog.setHeader(helpHeader);
	  	gwhContextHelpDialog.setBody(dialogHtml);
		gwhContextHelpDialog.render(document.body);
        gwhContextHelpDialog.show();
}

function getContextSensitiveHelpTag(tagName) {
  if (tagName == "neighbourhoodSalesHelpHeader")
    return neighbourhoodSalesHelpHeader;
  else if (tagName == "neighbourhoodSalesHelpInfo")
    return neighbourhoodSalesHelpInfo;
  else
    return null;
}


 /*************************************************
 *   MY GEOWAREHOUSE AND USER PROFILE FUNCTIONS
 **************************************************/
var __MY_GEOWAREHOUSE_USER_PROFILE_FUNCTIONS__;

var formModified = false;
function setFormModified() {
	formModified = true;
}
function setFormNotModified() {
	formModified = false;
}
function isFormModified() {
	return formModified;
}
function changeParentUrl(toUrl){
	document.location = toUrl;
}
function previewProfile(userId) {
	previewwindow=window.open("userProfileInitialEditController.do?action=previewUserProfile&businessEntityId="+userId, "preview","menubar=0,location=0,directories=0,status=0,scrollbars=0,width=500,height=400");
	previewwindow.moveTo(50,50);
}

function enablePreview() {
	var previewButton = document.getElementById('preview');
	previewButton.disabled=false;
	previewButton.className='formbtn';
}

function disablePreview() {
	var previewButton = document.getElementById('preview');
	previewButton.disabled=true;
	previewButton.className='formbtn_disabled';
}

function confirmReset() {

	var answer = confirm("Are you sure?");

	if (answer) {
		resetErrorFields();
		resetRequiredFields();
		clearMessages();
		setFormNotModified();
		return true;
	} else {
		return false;
	}
}

function previewProfileFromEdit(userId, sessionId){
	previewwindow=window.open("userProfileEdit.do?action=previewUserProfile&sessionToken="+sessionId+"&businessEntityId="+userId, "preview","menubar=0,location=0,directories=0,status=0,scrollbars=0,width=400,height=250");
	previewwindow.moveTo(50,50);
}

function clearMessages() {
	var infoMessages = document.getElementById('infoMessages');
	infoMessages.innerHTML="";

	var userProfileMessages = document.getElementById('userProfileMessages');
	userProfileMessages.innerHTML="";

	var userProfileImageMessages = document.getElementById('userProfileImageMessages');
	userProfileImageMessages.innerHTML="";
	// Also clear all other fields
}

function confirmExit() {

	var myGeoChanged = false;
	// Check if the User Profile is in the middle of editing.
	if ( (document.getElementById('userprofile') != null) && (document.getElementById('userprofile') != "undefined") ) {
		myGeoChanged = document.getElementById('userprofile').contentWindow.isFormModified();
	}
	// Check if the Password Change is in the middle of editing.
	if ( (myGeoChanged == false) && (document.getElementById('passwordchange') != null) && (document.getElementById('passwordchange') != "undefined") ) {
		myGeoChanged = document.getElementById('passwordchange').contentWindow.isFormModified();
	}
	// Only prompt the user if one of user profile or password change is in the middle of the editing process
	if ( myGeoChanged == true ) {
		var answer = confirm("Your changes have not been saved!  Do you still wish to exit My GeoWarehouse?");
		return answer;
	} else {
		return true;
	}
}

function updateMyGwhReturnUrl(toUri) {
	var relpath = "";
	if(toUri == "" || toUri == "#")
		toUri = "/gwhweb/PropertyView.jsp";
	else
		relpath = "/gwhweb/PropertyView.jsp";

	document.getElementById("myGWH_return").href = relpath + toUri;
}

var transRcptMap = new HMap();
function openTransReceipt(transId, transRcptUrl) {
	var existingWindow = transRcptMap.get(transId);
	if (transRcptMap.get(transId) != "" && !existingWindow.closed) {
		existingWindow.close();
	}
	var transWnd=window.open(transRcptUrl,"RECEIPT","height=720,width=660,resizable=no,scrollbars=no,status=no,toolbar=no,menubar=no,location=no,titlebar=no");
	transRcptMap.put(transId, transWnd);
}

function showStartCal() {
	selectDateRange();
	cal1.show();
}

function showEndCal() {
	selectDateRange();
	cal2.show();
}

function selectFixedRange() {
	var searchSelectRadio = document.getElementById("fixedRangeRadio");
	searchSelectRadio.checked=true;
}

function selectDateRange() {
	var searchSelectRadio = document.getElementById("dateRangeRadio");
	searchSelectRadio.checked=true;
}

function handleStartSelect(type,args,obj) {
	var dates = args[0];
	var date = dates[0];
	var year = date[0], month = date[1], day = date[2];

	// Prepend "0" to month and day if necessary
	month = dateValueTwoChars(month);
	day = dateValueTwoChars(day);

	var txtDate1 = document.getElementById("startDate");
	txtDate1.value = month + "/" + day + "/" +  year;
	obj.hide();
}

function handleEndSelect(type,args,obj) {
	var dates = args[0];
	var date = dates[0];
	var year = date[0], month = date[1], day = date[2];

	// Prepend "0" to month and day if necessary
	month = dateValueTwoChars(month);
	day = dateValueTwoChars(day);

	var txtDate2 = document.getElementById("endDate");
	txtDate2.value = month + "/" + day + "/" +  year;
	obj.hide();
}

// Convert a date value to two characters. Prepend a "0" if needed
function dateValueTwoChars(dateValue) {
	if ( dateValue < 10 ) {
		return "0" + dateValue;
	} else if ( dateValue >= 10 ) {
		return dateValue + "";
	}
}

function updateStartCal() {
	var txtDate1 = document.getElementById("startDate");

	if ((txtDate1.value != null) && (txtDate1.value.length > 0)) {
		if ( validateDate(txtDate1) == true ) {
			cal1.select(txtDate1.value);
			var selectedDates = cal1.getSelectedDates();
			if (selectedDates.length > 0) {
				var firstDate = selectedDates[0];
				cal1.cfg.setProperty("pagedate", (firstDate.getMonth()+1) + "/" + firstDate.getFullYear());
				cal1.render();
			}
		}
	}
}

function updateEndCal() {
	var txtDate2 = document.getElementById("endDate");

	if ((txtDate2.value != null) && (txtDate2.value.length > 0)) {
		if ( validateDate(txtDate2) == true ) {
			cal2.select(txtDate2.value);
			var selectedDates = cal2.getSelectedDates();
			if (selectedDates.length > 0) {
				var firstDate = selectedDates[0];
				cal2.cfg.setProperty("pagedate", (firstDate.getMonth()+1) + "/" + firstDate.getFullYear());
				cal2.render();
			}

		}
	}
}

function validateDate(dateField) {

	var regExPattern= /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;

    if ((dateField.value.match(regExPattern)) && (dateField.value!='')) {
        return true;
    } else {
	    return false;
    }
}

function clearMessagesForTransactionSearch() {
	var errorMessageDiv = document.getElementById('errorMessageDiv');
	errorMessageDiv.innerHTML="";
}

function addErrorMessage(message) {
	var errorMessageDiv = document.getElementById('errorMessageDiv');
	errorMessageDiv.innerHTML = errorMessageDiv.innerHTML + message + '<br/>';
}

function validateForm() {
	var noError = true;
	var fixedRangeRadio = document.getElementById("fixedRangeRadio");
	var dateRangeRadio = document.getElementById("dateRangeRadio");

	if ( fixedRangeRadio.checked == true ) {
		// No validation checks
	} else if ( dateRangeRadio.checked == true ) {
		var txtDate1 = document.getElementById("startDate");
		var txtDate2 = document.getElementById("endDate");

		if ( (txtDate1.value == null) || (txtDate1.value.length == 0) ) {
			addErrorMessage('The \"from\" date of the date range is empty');
			noError = false;
		} else {
			if ( validateDate(txtDate1) == false ) {
				addErrorMessage('The \"from\" date of the date range is not a valid date');
				noError = false;
			}
		}

		if ( (txtDate2.value == null) || (txtDate2.value.length == 0) ) {
			addErrorMessage('The \"to\" date of the date range is empty');
			noError = false;
		} else {
			if ( validateDate(txtDate2) == false ) {
				addErrorMessage('The \"to\" date of the date range is not a valid date');
				noError = false;
			}
		}

		if ( noError == false ) {
			// Don't continue validation if one of the dates is invalid
			return noError;
		}

		var date1split = txtDate1.value.split("/");
		var date1 = new Date(date1split[2], date1split[0]-1, date1split[1]);

		var date2split = txtDate2.value.split("/");
		var date2 = new Date(date2split[2], date2split[0]-1, date2split[1]);

		if ( date2 < date1 ) {
			addErrorMessage('Invalid date range.  The \"from\" date occurs after the \"to\" date.  Please re-select the date range and resubmit the request.');
			noError = false;
		}

		var todayDate = new Date();
		if ( date2 > todayDate ) {
			addErrorMessage('Invalid \"to\" date specified.  The date occurs in the future.  Please re-select the date range and resubmit the request.');
			noError = false;
		}

	} else {
		addErrorMessage('Please select the radio button for either the date drop-down or date range');
		noError = false;
	}

	return noError;
}

function initTransactionHistorySearch() {

	var transDivW = document.getElementById("myGWH_trans_divwrapper");
	var transDiv = document.getElementById("contentdiv");

	if (transDivW && transDiv) {
		var transDivWHeight = transDivW.offsetHeight;
		var transDivHeight = transDiv.offsetHeight;
		if (transDivHeight >= transDivWHeight) {
			transDivW.className = 'myGWH_trans_divwrapper_scroll';
		} else {
			transDivW.className = 'myGWH_trans_divwrapper';
		}
	}
}

function initCalendar() {
	// Calendar 1
	cal1 = new YAHOO.widget.Calendar("cal1","startCalendar", {LOCALE_WEEKDAYS:"1char", HIDE_BLANK_WEEKS:true});

	// Update calendar field when date selected in calendar
	cal1.selectEvent.subscribe(handleStartSelect, cal1, true);
	cal1.render();

	// Show calendar when button is clicked
	YAHOO.util.Event.addListener("showStart", "click", showStartCal);

	// Update calendar field when date selected in calendar
	YAHOO.util.Event.addListener("startDate", "change", updateStartCal);

	// Initialize start calendar to last input date
	updateStartCal();

	// Calendar 2
	cal2 = new YAHOO.widget.Calendar("cal2","endCalendar", {LOCALE_WEEKDAYS:"1char", HIDE_BLANK_WEEKS:true});

	// Update calendar field when date selected in calendar
	cal2.selectEvent.subscribe(handleEndSelect, cal2, true);
	cal2.render();

	// Update calendar field when date selected in calendar
	YAHOO.util.Event.addListener("showEnd", "click", showEndCal);

	// Update calendar field when date selected in calendar
	YAHOO.util.Event.addListener("endDate", "change", updateEndCal);

	// Initialize end calendar to last input date
	updateEndCal();
}

function validateAll(isLppAdmin) {
	var oldPwd = document.passwordChangeVO.oldPassword.value;
	var newPwd = document.passwordChangeVO.newPassword.value;
	var confirmPwd = document.passwordChangeVO.confirmPassword.value;

	document.passwordChangeVO.submitButton.className="formbtn_disabled";

	// Verify that newPassword is a valid password
	// This has to go first, since if newPassword is invalid
	// there is no point to continue the validation
	if (!isNewPasswordValid(isLppAdmin)) {
		document.passwordChangeVO.submitButton.disabled = true;
		document.passwordChangeVO.invalidPassword.src = '/gwhweb/images/cross.jpg';
		return false;
	}
	else {
		document.passwordChangeVO.invalidPassword.src = '/gwhweb/images/checkmark.jpg';
	}

	// Verify that oldPassword is not empty
	if (isEmpty(oldPwd)) {
		document.passwordChangeVO.submitButton.disabled = true;
		return false;
	}

	// Verify that confirmPassword is not empty
	if (isEmpty(confirmPwd)) {
		document.passwordChangeVO.submitButton.disabled = true;
		return false;
	}

	// Verify that oldPassword != newPassword
	if (oldPwd == newPwd) {
		document.passwordChangeVO.submitButton.disabled = true;
		return false;
	}

	// Verify that newPassword == confirmPassword
	if (newPwd != confirmPwd) {
		document.passwordChangeVO.submitButton.disabled = true;
		return false;
	}

	document.passwordChangeVO.submitButton.disabled = false;
	document.passwordChangeVO.submitButton.className="formbtn";
	return true;
}

// Check if s is empty
function isEmpty(s) {
	if(s == null || s.length == 0) {
		return true;
	}
 	return false;
}

// Check to see if s has only alphaNumeric, dash - or underscore _
function hasOtherThanAlphaNumericDashUnderscore(s) {
	var pattern = new RegExp('[^0-9a-zA-Z_-]');
	return pattern.test(s);
}

// Check to see if s has at least 1 numeric character
function atLeast1Numeric(s) {
	var pattern = new RegExp('[0-9]+');
	return pattern.test(s);
}

// Check to see if s has at least 1 upper case character
function atLeast1UpperCase(s) {
	var pattern = new RegExp('[A-Z]+');
	return pattern.test(s);
}

// Check to see if s has at least 1 lower case character
function atLeast1LowerCase(s) {
	var pattern = new RegExp('[a-z]+');
	return pattern.test(s);
}

// Check to see if s has at least minLength
function validMinLength(s, minLength) {
	if (s.length < minLength) {
		return false;
	}
	return true;
}

// Check to see if s has no more than maxLength
function validMaxLength(s, maxLength) {
	if (s.length > maxLength) {
		return false;
	}
	return true;
}

// Validate if password is valid
function isNewPasswordValid(isLppAdmin) {
	if (isLppAdmin) {
		if (!isNewAdminPasswordValid()) {
			return false;
		}
	} else {
		if (!isNewUserPasswordValid()) {
			return false;
		}
	}

	return true;
}

// Validate an admin password
function isNewAdminPasswordValid() {
	var newPwd = document.passwordChangeVO.newPassword.value;

	if (isEmpty(newPwd)) {
		document.passwordChangeVO.invalidPassword.title = '<%=UserProfileConstants.MSG_NEW_PASSWORD_IS_REQUIRED%>';
		return false;
	}

	if (!validMinLength(newPwd, 8)) {
		document.passwordChangeVO.invalidPassword.title = '<%=UserProfileConstants.MSG_NEW_PASSWORD_ATLEAST_8_CHAR%>';
		return false;
	}

	if (!atLeast1LowerCase(newPwd)) {
		document.passwordChangeVO.invalidPassword.title = '<%=UserProfileConstants.MSG_NEW_PASSWORD_ATLEAST_1_LOWER_CHAR%>';
		return false;
	}

	if (!atLeast1UpperCase(newPwd)) {
		document.passwordChangeVO.invalidPassword.title = '<%=UserProfileConstants.MSG_NEW_PASSWORD_ATLEAST_1_UPPER_CHAR%>';
		return false;
	}

	if (!atLeast1Numeric(newPwd)) {
		document.passwordChangeVO.invalidPassword.title = '<%=UserProfileConstants.MSG_NEW_PASSWORD_ATLEAST_1_NUMERIC%>';
		return false;
	}

	document.passwordChangeVO.invalidPassword.title = '';
	return true;
}

// Validate an user password
function isNewUserPasswordValid() {
	var newPwd = document.passwordChangeVO.newPassword.value;

	if (isEmpty(newPwd)) {
		document.passwordChangeVO.invalidPassword.title = '<%=UserProfileConstants.MSG_NEW_PASSWORD_IS_REQUIRED%>';
		return false;
	}
	if (!validMinLength(newPwd, 6)) {
		document.passwordChangeVO.invalidPassword.title = '<%=UserProfileConstants.MSG_NEW_PASSWORD_ATLEAST_6_CHAR%>';
		return false;
	}

	if (!validMaxLength(newPwd, 20)) {
		document.passwordChangeVO.invalidPassword.title = '<%=UserProfileConstants.MSG_NEW_PASSWORD_ATMOST_20_CHAR%>';
		return false;
	}

	if (hasOtherThanAlphaNumericDashUnderscore(newPwd)) {
		document.passwordChangeVO.invalidPassword.title = '<%=UserProfileConstants.MSG_NEW_PASSWORD_CONTAIN_NO_SPECIAL_CHAR%>';
		return false;
	}

	document.passwordChangeVO.invalidPassword.title = '';
	return true;
}

function printReceipt() {
	e = eval("window");
	if(navigator.platform == 'Win32') {
		e.print();
	} else {
		alert('To print this page, click OK, then press Command-P.');
	}
}


 /*************************************************
 *                  UNKNOWN USAGE
 **************************************************/
var __OTHER_FUNCTIONS__;

function syncView(){
	var _infoTargetFrame = document.getElementById("PropertySearchResultsID");
	var reqhash = window.location.hash.substring(1);
  	if(reqhash){
	   //var valpairs = reqhash.split("&");
		_infoTargetFrame.src = 	   reqhash;
	   }
}

function callMainPage(targeturl){
	var reqhash = window.location.hash.substring(1);
	var newlocation = targeturl +"?#"+ reqhash;
	window.location = newlocation;
}

/*
function isEmpty(mytext) {
	var re = /^\s{1,}$/g; //match any white space including space, tab, form-feed, etc.
	if ((mytext.value.length==0) || (mytext.value==null) || ((mytext.value.search(re)) > -1)) {
	return true;
	}
	else {
	return false;
	}
}
*/

/* Returns the effective style sheet property value */
function getElementStyle(elemID, IEStyleProp, CSSStyleProp) {
    var elem = document.getElementById(elemID);
    if (elem.currentStyle) { //if IE5+
        return elem.currentStyle[IEStyleProp];
    } else if (window.getComputedStyle) { //if NS6+
        var compStyle = window.getComputedStyle(elem, "");
        return compStyle.getPropertyValue(CSSStyleProp);
    }
    return "";
}

function validEmail(email){
	var emailReg = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
	return emailReg.test(email);
}


 /*************************************************
 *                 LSR FUNCTIONS
 **************************************************/
var __LSR_FUNCTIONS__;

//
// Survey low res sample
//


var gwhLowResImageDialog = null;
var RIGHT_SIDE_PANEL_BORDER_PX = 55;
var VERTICAL_SCROLL_BAR_SPACE_PX = 50;
var CLOSE_BUTTON_SPACE_PX = 50;
var LINKS_SPACE_PX = 20;
var HORIZONTAL_SCROLL_BAR_SPACE_PX = 80;
var MENU_SPACE_PX = 10;

var MAX_WINDOW_WIDTH = 650;
var MAX_WINDOW_HEIGHT = 550;

function hideshowSurveySample() {
	el1=document.getElementById("divSurveyImageExist");
	el2=document.getElementById("divSurveyImageDontExist");
	el1.style.display="none";
	el2.style.display="block";
}

function showSurveySampleImage() {
	elImage = document.getElementById("divSurveyLowResSmall");
	elSample = document.getElementById("divSurveySample");
	elImage.style.display="none";
	elSample.style.display="block";
}

function renderLowResImageDialog(imageUrl, zoomUrls) {
	if (gwhLowResImageDialog) {
	  gwhLowResImageDialog.hide();
	  gwhLowResImageDialog.destroy();
	}

	// Retrieve image to get width of the panel to show properly the header of the panel.
	var newImg = new Image();
	newImg.src = imageUrl;
	var imgWidth = newImg.width;
	var imgHeight = newImg.height;

	// in case the image is not in cache (and we can't retrieve the width and height) we use the maximum available space
	imgHeight=(imgHeight==0)?MAX_WINDOW_HEIGHT:imgHeight;
	imgWidth=(imgWidth==0)?MAX_WINDOW_WIDTH:imgWidth;

	var panelWidth = Math.min(MAX_WINDOW_WIDTH, (RIGHT_SIDE_PANEL_BORDER_PX + imgWidth + VERTICAL_SCROLL_BAR_SPACE_PX));
	var panelHeight = Math.min(MAX_WINDOW_HEIGHT, (imgHeight + HORIZONTAL_SCROLL_BAR_SPACE_PX + CLOSE_BUTTON_SPACE_PX + MENU_SPACE_PX + LINKS_SPACE_PX));
	var divWidth = panelWidth-VERTICAL_SCROLL_BAR_SPACE_PX;
	var divHeight = panelHeight-HORIZONTAL_SCROLL_BAR_SPACE_PX-CLOSE_BUTTON_SPACE_PX-10;

	gwhLowResImageDialog = new YAHOO.widget.Dialog("lowResImageDialogId",
														{ width : panelWidth + "px",
														  height : panelHeight + "px",
														  fixedcenter : true,
														  draggable: true,
														  visible : false,
														  constraintoviewport : true,
														  modal: true,
														  close: true,
														  underlay: "shadow"
														});

    // Render the Dialog
    var dialogHtml = "<a class=\"preview-link preview-link-active\" name=\"preview-link\" href=\""+imageUrl+"\""+
    					"onclick=\"linkClicked('"+imageUrl+"');return false;\">FULL PREVIEW</a>";
	for (var i=0; i<zoomUrls.length; i++) {
		dialogHtml += "<a class=\"preview-link\" name=\"preview-link\" href=\""+zoomUrls[i]+"\""+
						"onclick=\"linkClicked('"+zoomUrls[i]+"');return false;\">ZOOM "+(i+1)+"</a>";
	}
	    dialogHtml += "<br /><br />";
		dialogHtml += "<div id='lowResImageDialogId' class='fulfilldivwrapper' style='overflow:auto; width:"+divWidth+"px; height:"+divHeight+"px;'>";
	  	dialogHtml += "  <form method='POST'>";
	    dialogHtml += "    <table>";
	    dialogHtml += "      <tr>";
  	    dialogHtml += "        <td>";
  	    dialogHtml += "          <img id='preview' alt='Low Resolution Preview' src='" + imageUrl + "'>";
  	    dialogHtml += "        </td>";
	    dialogHtml += "      </tr>";
	    dialogHtml += "    </table>";
	    dialogHtml += "  </form>";
   	    dialogHtml += "</div>";

    	dialogHtml += "<table align='center' style='width:100%'>";
    	dialogHtml += "      <tr>";
  	    dialogHtml += "        <td align='center'>";
  	    dialogHtml += "          <button name='cancelButton' class='feedbackFormButton' onclick='hideLowResImageDialog();'>CLOSE</button>";
  	    dialogHtml += "        </td>";
	    dialogHtml += "      </tr>";
    	dialogHtml += "</table>";

	gwhLowResImageDialog.setHeader("Property Survey Image Low Resolution Preview");
  	gwhLowResImageDialog.setBody(dialogHtml);
	gwhLowResImageDialog.render(document.body);
    gwhLowResImageDialog.show();
}

function linkClicked(url) {
	prevLinks=document.getElementsByName("preview-link");
	for(var i=0; i<prevLinks.length; i++) {
		if(prevLinks[i].getAttribute("href")==url) {
			prevLinks[i].className="preview-link preview-link-active";
   		} else {
   			prevLinks[i].className="preview-link";
   		}
    }
	document.getElementById("preview").setAttribute("src", url);
}

function hideLowResImageDialog() {
	gwhLowResImageDialog.hide();
}


/* ========================= */
/* Survey Request Plan email */
/* ========================= */

var SURVEY_REQUEST_ERROR = "Unable to accept your request at this time.  Please try again later.";
var SURVEY_REQUEST_MESSAGE_LENGTH_ERROR = "Unable to accept your request.  Maximum message length allowed is 300 characters.";
var EMPTY_SURVEY_REQUEST_ERROR = "Please provide the details of your survey request in the comments section before sending.";
var INPUT_VALIDATION_ERROR = "We were unable to process your request due to incorrect data entered.  Please verify entries and resubmit your request.";
var HTTP_REQUEST_SUCCESS = 200;
var MAX_SURVEY_REQUEST_MESSAGE_LENGTH = 300;
var SURVEY_REQUEST_MESSAGE_FORM="<HTML><HEAD><LINK href='/gwhweb/styles/gwpropertyview.css' type=text/css rel=stylesheet></HEAD><BODY><div id='surveyRequestMessage'><table><tr id='surveyRequestMessage'><td>[SURVEY_REQUEST_MESSAGE]</td></tr></table></div><br /><div align='center'><BUTTON class='contextSensitiveHelpButton' onclick='gwhContextHelpDialog.hide();'>CLOSE</BUTTON></div></BODY></HTML>";
var SURVEY_REQUEST_MESSAGE_AREA_FORM="<HTML><HEAD><LINK href='/gwhweb/styles/gwpropertyview.css' type=text/css rel=stylesheet></HEAD><BODY><div id=surveyRequestAreaMessage><br /><table><tr><td id='surveyRequestAreaMessage'>[SURVEY_REQUEST_MESSAGE]</td></tr></table></div><br /><div align='center'></div></BODY></HTML>";
var HEADER_LABEL_SURVEY_REQUEST_CONFIRMATION = "SURVEY REQUEST CONFIRMATION";
var HEADER_LABEL_SURVEY_REQUEST_ERROR = "SURVEY REQUEST ERROR";

var gwhSurveyRequestDialog = null;

function requestSurvey(token) {

	var mainWindow = getMainWindow(window);
	if (mainWindow != null) {
  	    mainWindow.renderSurveyRequestDialog(token);
  	    // mainWindow.renderFeedbackDialog();
  	} else {
  	   	renderSurveyRequestDialog(token);
  	}

}

function renderSurveyRequestDialog(token) {

	if (gwhSurveyRequestDialog) {
	  gwhSurveyRequestDialog.hide();
	  gwhSurveyRequestDialog.destroy();
	}

    // Obtain Request Plan data
    var asXmlHttpRequest = GWH.Ajax.getXmlHttpRequest();
    var url = "/gwhweb/sendSurveyRequestPlan.do?action=load&token="+token;

    asXmlHttpRequest.open("POST", url, false);  // third parameter indicate if request is asynchronous (non-blocking)
    asXmlHttpRequest.send(null);
    if (asXmlHttpRequest.status == HTTP_REQUEST_SUCCESS) {
	    var surveyRequestResponse = eval('('+ asXmlHttpRequest.responseText + ')');
		if (surveyRequestResponse.surveyRequestPlanVO.errorFound != 'true') {  // Request successful
			gwhSurveyRequestDialog = new YAHOO.widget.Dialog("surveyRequestDialogId",
														{ width : "450px",
														  fixedcenter : true,
														  draggable: true,
														  visible : false,
														  constraintoviewport : true,
														  modal: false,
														  close: true,
														  underlay: "none"
														});

		    // Render the Dialog
			var dialogHtml  = "<div id='surveyRequestDialogId'>";
			    dialogHtml += "  <form method='POST' action='/gwhweb/sendSurveyRequestPlan.do'>";
			    dialogHtml += "    <input type='hidden' name='action' value='load'>";
			    dialogHtml += "    <table>";

			    dialogHtml += "      <tr>";
		  	    dialogHtml += "        <td id='surveyRequestLabelId'>From:</td>";
		  	    dialogHtml += "        <td>" + surveyRequestResponse.surveyRequestPlanVO.fromEmailAddress + "</td>";
			    dialogHtml += "      </tr>";
			    dialogHtml += "      <tr>";
		  	    dialogHtml += "        <td id='surveyRequestLabelId'>To:</td>";
		  	    dialogHtml += "        <td><input type='text' value='" + surveyRequestResponse.surveyRequestPlanVO.toEmailAddress + "' size=60 name='toEmailAddress'></td>";
			    dialogHtml += "      </tr>";
			    dialogHtml += "      <tr>";
		  	    dialogHtml += "        <td valign='top' id='surveyRequestLabelId'>Subject:</td>";
		  	    dialogHtml += "        <td>" + surveyRequestResponse.surveyRequestPlanVO.subject + "</td>";
			    dialogHtml += "      </tr>";
			    dialogHtml += "      <tr>";
		  	    dialogHtml += "        <td valign='top' id='surveyRequestLabelId'>Body:</td>";
		  	    dialogHtml += "        <td colspan=2>";
			    dialogHtml += "          <textarea name='body' readonly='readonly' rows=10 cols='60' stylebackground-color='' style='border: 1px solid rgb(127, 157, 185)' >";
			    dialogHtml +=            surveyRequestResponse.surveyRequestPlanVO.body;
			    dialogHtml += "          </textarea>";
		  	    dialogHtml += "        </td>";
			    dialogHtml += "      </tr>";
			    dialogHtml += "      <tr>";
		  	    dialogHtml += "        <td valign='top' id='surveyRequestLabelId'>Comments:</td>";
		  	    dialogHtml += "        <td colspan=2>";
			    dialogHtml += "          <textarea name='comments' rows=3 cols='60' stylebackground-color='' style='border: 1px solid rgb(127, 157, 185)' ";
			    dialogHtml += "          onkeydown='javascript:limitMessageLength(this,MAX_SURVEY_REQUEST_MESSAGE_LENGTH);' ";
			    dialogHtml += "          onkeyup='javascript:limitMessageLength(this,MAX_SURVEY_REQUEST_MESSAGE_LENGTH);'></textarea>";
		  	    dialogHtml += "        </td>";
			    dialogHtml += "      </tr>";
			    dialogHtml += "      <tr>";
		  	    dialogHtml += "        <td colspan=2>";
			    dialogHtml += "          <span id='charactersRemaining'>300</span> - characters remaining";
		  	    dialogHtml += "        </td>";
			    dialogHtml += "      </tr>";
			    dialogHtml += "      <tr>";
		  	    dialogHtml += "        <td align='center' colspan=2>";
		  	    dialogHtml += "          <button name='sendButton' class='surveyrequestFormButton' onclick='javascript:sendSurveyRequest(this.form);'>SEND REQUEST</button>&nbsp;&nbsp;";
		  	    dialogHtml += "          <button name='cancelButton' class='surveyrequestFormButton' onclick='javascript:cancelSurveyRequest();'>CANCEL</button>";
		  	    dialogHtml += "        </td>";
			    dialogHtml += "      </tr>";

			    dialogHtml += "    </table>";
			    dialogHtml += "  </form>";
		   	    dialogHtml += "</div>";

			gwhSurveyRequestDialog.setHeader("SRI SURVEY REQUEST FORM");
		  	gwhSurveyRequestDialog.setBody(dialogHtml);	;
			gwhSurveyRequestDialog.render(document.body);
	        gwhSurveyRequestDialog.show();
        }
        else {  // session has expired or error encountered
	      var message = SURVEY_REQUEST_MESSAGE_FORM.replace('[SURVEY_REQUEST_MESSAGE]', surveyRequestResponse.surveyRequestPlanVO.responseMessage);
    	  showContextSensitiveHelp(message, HEADER_LABEL_SURVEY_REQUEST_ERROR);
        }
    }
    else {  // Failed to obtain response from server
      var message = SURVEY_REQUEST_MESSAGE_FORM.replace('[SURVEY_REQUEST_MESSAGE]', SURVEY_REQUEST_ERROR);
      showContextSensitiveHelp(message, HEADER_LABEL_SURVEY_REQUEST_ERROR);
    }

}


function sendSurveyRequest(currentForm) {
    currentForm.sendButton.disabled = true;  // disallow user to send duplicate email
	if (validSurveyRequest(currentForm)) {
	    // Send email
	    var asXmlHttpRequest = GWH.Ajax.getXmlHttpRequest();
	    var url = "/gwhweb/sendSurveyRequestPlan.do";
	    var params = "action=SEND_SURVEY_REQUEST" +
	    			 "&toEmailAddress=" + encodeURIComponent(currentForm.toEmailAddress.value) +
	                 "&comments=" + encodeURIComponent(currentForm.comments.value);

	    asXmlHttpRequest.open("POST", url, false);  // third parameter indicate if request is asynchronous (non-blocking)
	    asXmlHttpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		asXmlHttpRequest.setRequestHeader("Content-length", params.length);
		asXmlHttpRequest.setRequestHeader("Connection", "close");
	    asXmlHttpRequest.send(params);

	    if (asXmlHttpRequest.status == HTTP_REQUEST_SUCCESS  &&
	        asXmlHttpRequest.responseText != null ) {
	        if (asXmlHttpRequest.responseText.indexOf("Input Validation Error") >= 0   ) {   // Web input validation error
		      currentForm.sendButton.disabled = false;
		      showSurveyRequestErrorMessage(INPUT_VALIDATION_ERROR);
	        }
	        else {
			    var surveyRequestResponse = eval('('+ asXmlHttpRequest.responseText + ')');
		        if (surveyRequestResponse.surveyRequestPlanVO.errorFound == 'true') {   // display error message in message area
			      currentForm.sendButton.disabled = false;
 			      showSurveyRequestErrorMessage(surveyRequestResponse.surveyRequestPlanVO.responseMessage);
	    	    }
		        else { // display confirmation message
					gwhSurveyRequestDialog.hide();
			        var message = SURVEY_REQUEST_MESSAGE_FORM.replace('[SURVEY_REQUEST_MESSAGE]', surveyRequestResponse.surveyRequestPlanVO.responseMessage);
			        showContextSensitiveHelp(message, HEADER_LABEL_SURVEY_REQUEST_CONFIRMATION);
			    }
		    }
		}
		else {
		  currentForm.sendButton.disabled = false;
          showSurveyRequestErrorMessage(SURVEY_REQUEST_ERROR);
		}

	}
}

function cancelSurveyRequest() {
	gwhSurveyRequestDialog.hide();
}

function validCommentsLength(message) {
  if (message.length > MAX_SURVEY_REQUEST_MESSAGE_LENGTH)
    return false;
  else
    return true;
}

function validSurveyRequest(currentForm) {

  if (!validMessageLength(currentForm.comments.value)) {
    currentForm.sendButton.disabled = false;
    showSurveyRequestErrorMessage(SURVEY_REQUEST_MESSAGE_LENGTH_ERROR);
    return false;
  }

  return true;
}

function showSurveyRequestErrorMessage(errorMessage) {

    if (gwhSurveyRequestDialog != null) {
	  var message = SURVEY_REQUEST_MESSAGE_AREA_FORM.replace("[SURVEY_REQUEST_MESSAGE]", errorMessage);
	  var messageAreaElement = document.createElement('div');
	  messageAreaElement.innerHTML = message;

	  // clean up previous error message if any
	  var surveyRequestBody = gwhSurveyRequestDialog.body.innerHTML;
	  if (surveyRequestBody.indexOf("surveyRequestAreaMessage", 0) > 0) {
        surveyRequestBody = surveyRequestBody.replace(surveyRequestBody.substr(surveyRequestBody.indexOf("surveyRequestAreaMessage") - 13), "");
	  }
	  gwhSurveyRequestDialog.setBody(surveyRequestBody);

	  gwhSurveyRequestDialog.appendToBody(messageAreaElement);
    }
}

/* ========================= */
/* Comparison report by ARN  */
/* ========================= */

// This is used to display the map when clicking the comps report link
// arnjslist: MpacPropertyAssessmentVO json array
// piijslist: PropertyIdentificationInfoVO json array
function DisplayArnCompsReportSearchResultsOnMap(arnjslist, piijslist) {
	//alert("DisplayArnCompsReportSearchResultsOnMap arnjslist = " + arnjslist);
	if (arnjslist!=null) {
		ShowHouseViewControls('map');
		DisplayMapView();		
		gwhmap.DisplayArnCompsReportSearchResultsOnMap(arnjslist, piijslist);
	}
}

function showSurveyPlanListInit(lsrPlanImageIn,lsrRegisteredPlanIn,lsrLroIn,lsrAddressIn,lsrAddressRangeIn,lsrLotConIn,contextPathIn,isCustomPinListFromDeepLinkIn, gwhSurveyPlanListIn) {

   if(isCustomPinListFromDeepLinkIn=='false') {
		isCustomPinListFromDeepLink = false;
     	return;
    } else {
		isCustomPinListFromDeepLink = true;
    }


    lsrPlanImage = lsrPlanImageIn;
    lsrRegisteredPlan = lsrRegisteredPlanIn;
    lsrLro = lsrLroIn;
	lsrAddress = lsrAddressIn.split("/").join("'");
	lsrAddressRange = lsrAddressRangeIn.split("/").join("'");
	lsrLotCon = lsrLotConIn;
    contextPath=contextPathIn;

	// Initialize to empty list if an empty PIN list was passed in
	gwhSurveyPlanList = new Array(0);

	if ( gwhSurveyPlanListIn != null && gwhSurveyPlanListIn.trim().length > 0 ) {

		var tmpSurveyPlanList = gwhSurveyPlanListIn.split(',');

	    for( i = 0; i < tmpSurveyPlanList.length; i++ ) {
			gwhmap.DisplayPinListPin(tmpSurveyPlanList[i]);
	    }

	    tmpSurveyPlanList = null;

	} else {
		// Only call to show list if there were no PINs in
		// gwhSurveyPlanListIn as the call to DisplayPinListPin() will already
		// call showSurveyPlanList();
		showSurveyPlanList();
	}

	addPlanListToMapMenubar();
}


function addPlanListToMapMenubar() {
	document.getElementById(document.getElementById("layerlnk").parentElement.id).parentElement.style.width = "460px";

	var navActionSeparator = document.createElement("div");
	navActionSeparator.className ="MSVE_navAction_separator";
	navActionSeparator.id ="MSVE_navAction_separator3";

	var topBar = document.getElementById("MSVE_navAction_topBar");
	topBar.insertBefore(navActionSeparator,null);

	var PINListMenu = document.createElement("div");
	PINListMenu.id = "PINListlnk";
	PINListMenu.title = "Open PIN List Window";
	PINListMenu.innerHTML="PIN List";
	PINListMenu.style.fontWeight="bold";
	var tempObject = document.getElementById("MSVE_navAction_RoadMapStyle");
	PINListMenu.className = tempObject.className;
	PINListMenu.onclick= showSurveyPlanList;
	var topBar = document.getElementById("MSVE_navAction_topBar");
	topBar.insertBefore(PINListMenu ,null);

	topBar = navActionSeparator = PINListMenu = null;

}


function addSurveyPlanList(pin) {

   if(isCustomPinListFromDeepLink==false)
    return;

   if(gwhSurveyPlanList.length>MAX_SURVER_PLAN_LIST-1){
       alert('You have selected the maximum number of PINs ('+MAX_SURVER_PLAN_LIST+') for this plan.');
    return false;
	}

   if(removeSurveyPlanList(pin,false)==true)
    return false;

    gwhSurveyPlanList[gwhSurveyPlanList.length]=pin;

   updateSurveyPlanPINListSession();
   return true;
}

function removeSurveyPlanList(pin, updateSession) {

   if(isCustomPinListFromDeepLink==false)
    return;

    for(var i=0; i<gwhSurveyPlanList.length;i++ )
     {
        if(gwhSurveyPlanList[i]==pin){
            gwhSurveyPlanList.splice(i,1);
           	updateSurveyPlanPINListSession();
            return true;
        }
     }
   if(updateSession==true)
    updateSurveyPlanPINListSession();
   return false;
}

function clearSurveyPlanList() {

   if(isCustomPinListFromDeepLink==false)
    return;

    gwhSurveyPlanList.length = 0;
	updateSurveyPlanPINListSession();
}

function showSurveyPlanList() {

	if(isCustomPinListFromDeepLink==false) return;

    action = contextPath+ "/exportPinList.do" + "?lro="+lsrLro+"&registeredPlan="+lsrRegisteredPlan+"&surveyPlanImageID="+lsrPlanImage+"&pinsList=";

    for(var i = 0; i < gwhSurveyPlanList.length; i++) {
    	if (i > 0) {
    		action += ",";
    	}
		action += gwhSurveyPlanList[i];
   	}

    // Render the Dialog
	if(gwhSurveyPlanListDialog==null) gwhSurveyPlanListDialog = new YAHOO.widget.Dialog("pinList",
										{ width : "300px",
										  height : "340px",
										  x: 700,
										  y: 300,
										  draggable: true,
										  constraintoviewport : true,
										  zindex: 1000,
										  modal: false,
										  underlay: "none"
										});

	gwhSurveyPlanListDialog.setHeader("PIN LIST");
  	gwhSurveyPlanListDialog.setBody(createHtmlForSurveyPlanList());
	gwhSurveyPlanListDialog.render(document.body);
    gwhSurveyPlanListDialog.show();

    // Make the dialog resizable
    var resize = new YAHOO.util.Resize('pinList', {
      handles: ['br'],
      autoRatio: false,
      minWidth: 300,
      minHeight: 340,
      status: false
	});

	resize.on('resize', function(args) {
   		var panelHeight = args.height;
	    this.cfg.setProperty("height", panelHeight + "px");
	    document.getElementById('surveyPlanPinList').style.height=panelHeight - 230 + "px";
	}, gwhSurveyPlanListDialog, true);

	resize.on("startResize", function(args) {
	    if (this.cfg.getProperty("constraintoviewport")) {
            var D = YAHOO.util.Dom;
            var clientRegion = D.getClientRegion();
            var elRegion = D.getRegion(this.element);
            resize.set("maxWidth", clientRegion.right - elRegion.left - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
            resize.set("maxHeight", clientRegion.bottom - elRegion.top - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
        } else {
            resize.set("maxWidth", null);
            resize.set("maxHeight", null);
    	}
    }, gwhSurveyPlanListDialog, true);
}

function createHtmlForSurveyPlanList() {
var dialogHtml  = "<div id='surveyPlanPINListDialogId'>";
    dialogHtml += "  <form id='surveyPlanPINListForm' method='POST' action='"+action+"'>";
    dialogHtml += "    <table border=0>";
    dialogHtml += "      <tr>";
 	dialogHtml += "        <td  width='300' id='surveyPlanPINListLabelId'>Survey Plan Information:</td>";
    dialogHtml += "      </tr>";
    dialogHtml += "      <tr>";
 	dialogHtml += "        <td  >";
    dialogHtml += "           Company Survey ID: " + lsrPlanImage;
    dialogHtml += "           <br />";
    dialogHtml += "           LRO: " + lsrLro;
    dialogHtml += "           <br />";
    dialogHtml += "           Registered Plan: " + lsrRegisteredPlan;
    dialogHtml += "           <br />";
    dialogHtml += "           Lot &amp; Con: " + lsrLotCon;
    dialogHtml += "           <br />";
    dialogHtml += "           Address: " + lsrAddress;
    dialogHtml += "           <br />";
    dialogHtml += "           Address Range: " + lsrAddressRange;
    dialogHtml += "           <br />&nbsp;";
    dialogHtml += "        </td>";
    dialogHtml += "      </tr>";
    dialogHtml += "      <tr>";
 	dialogHtml += "        <td id='surveyPlanPINListLabelId'>Selected PINs:";
 	dialogHtml += "      </td>";
    dialogHtml += "      </tr>";
    dialogHtml += "      <tr>";
 	dialogHtml += "        <td>";
 	dialogHtml += " <div id='surveyPlanPinList' style='height:"+Math.max(document.getElementById('pinList').clientHeight-230,110)+"px;'>";
 	dialogHtml += "        <table  border=0>";
    for(var i=0; i<gwhSurveyPlanList.length;i++ ){
  		dialogHtml += "        <tr>";
  	    dialogHtml += "        <td>";
	  	if(gwhSurveyPlanList[i]==undefined)
	  		dialogHtml +="&nbsp;";
	  	else
 		    dialogHtml +=gwhSurveyPlanList[i];
  	    dialogHtml += "        </td>";
  	    dialogHtml += "        </tr>";
	}
 	dialogHtml += "        </table>";
 	dialogHtml += " </div>";
 	dialogHtml += "        </td>";
    dialogHtml += "      </tr>";
    dialogHtml += "      <tr align='center'>";
 	dialogHtml += "        <td id='surveyPlanPINListLabelId'>";
 	dialogHtml += "        <br/>";
 	dialogHtml += "        <button name='export' class='surveyPlanPINListFormButton' ";

	if( gwhSurveyPlanList.length==0) dialogHtml += " disabled='true' ";
    	dialogHtml += "onclick='javascript:this.form.submit();return true;'";
 	    dialogHtml += ">EXPORT</button>";
 	    dialogHtml += "&nbsp;&nbsp;&nbsp;"
 	    dialogHtml += "        <button name='clear' class='surveyPlanPINListFormButton' ";

	if( gwhSurveyPlanList.length==0) dialogHtml += " disabled='true' ";
 	    dialogHtml += "onclick='javascript:clearSurveyPlanPINListAndMap();return false;'";
 	    dialogHtml += ">CLEAR LIST</button>";
 	    dialogHtml += "      </td>";
	    dialogHtml += "      </tr>";
    	dialogHtml += "    </table>";
	    dialogHtml += "  </form>";
  	    dialogHtml += "</div>";

	return dialogHtml;
}

function clearSurveyPlanPINListAndMap() {
	document.getElementById('surveyPlanPINListForm').action="#";
	clearSurveyPlanList();
	gwhmap.DeletePinListLayer();
	showSurveyPlanList();
}

function updateSurveyPlanPINListSession() {

	var asXmlHttp = GWH.Ajax.getXmlHttpRequest();
	var serverURL = contextPath + "/sessionAttribute.do?name=SURVEY_PIN_LIST&value=";

    for(i=0; i < gwhSurveyPlanList.length-1;i++ ) {
      serverURL+=gwhSurveyPlanList[i]+",";
    }
    if(gwhSurveyPlanList.length>0)
      serverURL+=gwhSurveyPlanList[i];

	asXmlHttp.open("GET", serverURL, false);
	asXmlHttp.send(null);

	if (asXmlHttp.status == 200||asXmlHttp.status == 0 ) {
		try {
			var responseText = asXmlHttp.responseText;
			if (responseText == "success") {
				window.status = 'save survey plan list success';
			} else {
				window.status = 'save survey plan list failure';
			}
			asXmlHttp = null;

		} catch(e) {
			window.status = 'Error saving survey plan list: e.src=' + e.source + '\ne.n=' + e.name + '\ne.m=' + e.message;
			asXmlHttp = null;
		}

	} else {
		window.status = "setEmailAttribute failed with status " + asXmlHttp.status;
		asXmlHttp = null;
	}

}

var ACRONYMS = new Array();
ACRONYMS['ELRSA'] = '"ELRSA Fees" are those fees that are made under the authority of Section 2(3)(b) of the Electronic Land Registration Services Act.';
ACRONYMS['STATUTORY'] = '"Statutory Fees" are those fees payable under the various Land Registration Statutes';

/**
 * Find all <acronym name="acronymId"> tags in the document and builds YUI Tooltips for them if
 * acronym "name" attr is present in ACRONYMS map
 */
function acronyms() {

	var acronyms = document.getElementsByTagName("acronym");
	if (acronyms) {
		var size = acronyms.length;
		for (var i=0; i < size; i++) {
			try {
				var text = ACRONYMS[ acronyms[i].getAttribute("name") ];
				if (text) {
				   new YAHOO.widget.Tooltip("acronym" + i, { context:acronyms[i], text:text });
				}
			}catch(exception) {
				//alert(exception);
			}
		}
	}
}

function addEvent(elem, type, callback) {
	if (typeof(elem) == "string") {
    	elem = document.getElementById(elem);
    }
    if (elem == null || elem == undefined) return;
    if ( elem.addEventListener ) {
    	if(type == 'mousewheel') {
			elem.addEventListener('DOMMouseScroll', callback, false); 
      	}
        elem.addEventListener( type, callback, false );
    } else if ( elem.attachEvent ) {
        elem.attachEvent( "on" + type, callback );
    }
}

function adjustScrollHeightInPropertyView(scrollDivId) {
	var minHeight = 0;
	var elems = [getMainWindow(window).document.getElementById('rightColumnContent'), getMainWindow(window).document.getElementById('leftbanneraddivid')];
	var minHeight = 0;
	for (var i =0; i < elems.length; i++) {
		if (elems[i]) {
			minHeight = Math.max(minHeight, (BrowserDetect.browser == 'Explorer') ? elems[i].scrollHeight : elems[i].clientHeight);
		}
	}
	adjustScrollHeightInIFrame(scrollDivId, 'PropertySearchResultsID', minHeight);
}
/** Adjusts div height and height of it's IFrame to fit on a screen without vertical scrolling */
function adjustScrollHeightInIFrame(scrollDivId, iframeId, minHeight, maxHeight) {
	try {
		var parentDoc = getMainWindow(window).document;
		var iframe = parentDoc.getElementById(iframeId)
		var footer = parentDoc.getElementById('gwhfooter')
		var clientHeight = parentDoc.documentElement.clientHeight
		var footerHeight = footer.offsetHeight + 20;

		if (! minHeight){
			minHeight = 0;
		}
		if (! maxHeight) {
			maxHeight = 99999;
		}
		var frameHeight = Math.min(maxHeight, Math.max(minHeight, clientHeight- findPosY(iframe) - footerHeight));
		var scrollDiv = document.getElementById(scrollDivId);
		if (scrollDiv) {
			scrollDiv.style.height = frameHeight - findPosY(scrollDiv) + "px";
		}
		iframe.style.height = frameHeight + "px";
	} catch(exception) {	
	}
}
/** returns Y position of the obj element within document */
function findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    } else if (obj.y) {
        curtop += obj.y;
    }    
    return curtop;
}

var _______CONTINUE_FROM_HERE________;

