//========================================================
//  Functions and variables called every page, 
//  to be defined later in page
//========================================================
function PageLoader(){ void(null); }
function GUnload(){ void(null); }
var PageCache = null;


/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Enable Background Image Caching for image backgrounds in CSS
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
try
{
    document.execCommand("BackgroundImageCache",false,true);
}
catch(err){};

//var ImageCache = new Object();
    //ImageCache.IsLoading = new Image();
    //ImageCache.IsLoading.src = "Images/IsLoading.gif";
    //ImageCache.ZeroResults = new Image();
    //ImageCache.ZeroResults.src = "Images/ZeroResults.gif";
    
    
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Reload page if anchor tag exists with Query on results
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
if (window.location.href.indexOf('#') > -1)
{
    var SEOPath = window.location.href.substring(window.location.href.indexOf('#')+1);
    if (SEOPath.indexOf("/") > -1 && SEOPath.length > 3)
    {
        window.location.href = "http://" + window.location.hostname + SEOPath;
    }
}


//========================================================
//   standard TRIM() function using Regular Expressions
//========================================================
function trim(str) 
{
    if (str==null) { return ""; }
    if (GetType(str) == "object") { return ""; }
	return str.replace(/^\s*|\s*$/g,"");
}


//========================================================
//   shorthand for document.getElementById with null check
//========================================================
function gE(objId)
{
    if (document.getElementById(objId))
    {
        return document.getElementById(objId);
    }
    return null;
}
//========================================================
//   Format Currency
//   by passing numeric value it will return in $000,000.00
//========================================================
function formatCurrency(num) 
{
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
    num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
    cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+','+
    num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + '$' +  num );//+ '.' + cents
}
//========================================================
//   CalculateMortgage
//   Passes Mortgagae value to MortgageCalculator page
//========================================================
function MortgageCalThickBox(Address,CityState,IdWeb,Price,SponseredURL,AdvertiserLogo)
{
    var url = WebRoot + "Controls/AjaxCalls/MortgageCalculater.aspx?height=500&width=450&Address=" + escape(Address) + "&IdWeb=" + escape(IdWeb) + "&Price=" + escape(Price) + "&SponseredURL=" + SponseredURL + "&AdvertiserLogo=" + AdvertiserLogo + "&CityState=" + escape(CityState);    
   tb_show('Calculate Mortgage', url, false);
}	

//========================================================
//  Mortgage Calculator
//   takes values loan term,interest rate,down payment and returns 
// estimated monthly payment
//========================================================
function MortgageCalculate(theForm)
{  
   var price = parseInt(theForm.Price.value);     
   var downPayment=theForm.DownPayment.value;  
   if (!IsNumeric(downPayment)|| theForm.DownPayment.value == "")
    {
        alert("Please enter numeric value in Down payment");
        theForm.DownPayment.focus();
        return (false);   
            
    }  
    var loanTerm=theForm.LoanTerm.value;
    if (!IsNumeric(loanTerm)||theForm.LoanTerm.value == "" )
     {
        alert("Please enter numeric value in Loan Term");
        theForm.LoanTerm.focus();
        return (false);
     }
    loanTerm= parseFloat(theForm.LoanTerm.value)*12;
   
    var Rate=theForm.IntersetRate.value;    
    if( !IsNumeric(Rate) || theForm.IntersetRate.value == "" )
     {
        alert("Please enter numeric value in Interset Rate");
        theForm.IntersetRate.focus();
        return (false);
     }
    Rate=(parseInt(theForm.IntersetRate.value)/100)/12;   
   
    var Principal= (price) - ((price*downPayment)/100)
   
    var totalMonthlypayment=0;
    
    totalMonthlypayment= (Rate + (Rate / (Math.pow(1 + Rate, loanTerm) - 1))) * Principal;  
    
    theForm.MonthlyPayment.value= formatCurrency(Math.round(totalMonthlypayment));
   
    
}

function ResetValue(theForm)
{
    var price = parseInt(theForm.Price.value); 
    theForm.DownPayment.value="20";
    theForm.LoanTerm.value="30";
    theForm.IntersetRate.value="6";    
    var Rate=(parseInt(theForm.IntersetRate.value)/100)/12;
    var Principal= (price) - ((price*parseInt(theForm.DownPayment.value))/100)
    var totalMonthlypayment=0;    
    totalMonthlypayment= (Rate + (Rate / (Math.pow(1 + Rate, (parseInt(theForm.LoanTerm.value)*12)) - 1))) * Principal; 
    theForm.MonthlyPayment.value= formatCurrency(totalMonthlypayment);  
}
//========================================================
//   gEDisplay
//========================================================
function gEDisplay(objId, display)
{
    gE(objId).style.display = display;
}
		
		
//========================================================
//   ResizedPhoto
//========================================================
function ResizedPhoto(OriginalImageURL, IdListing, Width, Height, Quality)
{
	var OriginalImageDomain = OriginalImageURL.toLowerCase().replace("http://", "");
	OriginalImageDomain = OriginalImageDomain.substring(0, OriginalImageDomain.indexOf("/"));

    var NewImageFilename = String.format("{0}_{1}_{2}x{3}.jpg", OriginalImageDomain, IdListing, Width, Height);
	//var NewImageFilename = OriginalImageURL.substring(OriginalImageURL.lastIndexOf("/") + 1);
	//NewImageFilename = NewImageFilename.substring(0, NewImageFilename.lastIndexOf("."));
	//NewImageFilename = String.format("{0}_{1}_{2}x{3}.jpg", OriginalImageDomain, NewImageFilename, Width, Height);
	
	var NewImageDirectory = String.format("{0}/{1}/{2}", ClientName, PortalName, WebsiteName);
	return ResizedPhotoPath(OriginalImageURL, Width, Height, NewImageFilename, NewImageDirectory, Quality);
}
		
		
//========================================================
//   ResizedPhotoPath
//========================================================
function ResizedPhotoPath(OriginalImageURL, Width, Height, NewImageFilename, NewImageDirectory, Quality)
{
	var BaseURL = "http://autoimages.gabriels.net/";
	return String.format("{0}?q={1}&w={2}&mw={2}&h={3}&mh={3}&f={4}&s={5}&i={6}",
        BaseURL,
        Quality,
        Width,
        Height,
        escape(NewImageDirectory),
        escape(NewImageFilename),
        escape(OriginalImageURL));
}


//========================================================
//   Report Through Ajax Asyncronusly
//========================================================
function DoReport(Data)
{
    if (Data != "")
    {
        var URL = WebRoot + "Controls/AjaxCalls/DoReport.aspx?Data=" + Data;
        $AJAX.GetAsync(URL);
    }
}

//========================================================
//   Report Through Ajax Asyncronusly
//========================================================
function DisplayAdvertiserInfo(url) {
        window.open(url);
}


//========================================================
//   Set Cookie State Through Ajax Asyncronusly
//========================================================
function SetCookieState(CookieName, Key, Value)
{
    var Query = String.format("CookieName={0}&Key={1}&Value={2}", CookieName, Key, Value); 
//    alert(Query);
    var URL = WebRoot + "Controls/AjaxCalls/SetCookieState.aspx?" + Query;
    $AJAX.GetAsync(URL);
}


//========================================================
//  Capture MouseMove event X, Y, stores it in the MousePosition object
//  Mouse position is globally available in the  object
//========================================================

// Global variables
var MousePosition = new Object();
    MousePosition.X = 0;
    MousePosition.Y = 0;

    //========================================================
    //  captureMousePosition
    //========================================================
    function captureMousePosition(e) 
    {
        if (document.layers) 
        {
            MousePosition.X = e.pageX + 25;
            MousePosition.Y = e.pageY - 25;
        } 
        else if (document.all) 
        {
            MousePosition.X = window.event.x + document.body.scrollLeft + 25;
            MousePosition.Y = window.event.y + document.body.scrollTop - 25;
        } 
        else if (document.getElementById) 
        {
            MousePosition.X = e.pageX + 25;
            MousePosition.Y = e.pageY - 25;
        }
    }

    //========================================================
    //  CaptureMouseXY
    //========================================================
    function CaptureMouseXY() 
    {
	    // Set Netscape up to run the "captureMousePosition" function whenever
	    // the mouse is moved. For Internet Explorer and Netscape 6, you can capture
	    // the movement a little easier.
	    if (document.layers) { // Netscape -6
	        document.captureEvents(Event.MOUSEMOVE);
	        document.onmousemove = captureMousePosition;
	    } else if (document.all) { // Internet Explorer
	        document.onmousemove = captureMousePosition;
	    } else if (document.getElementById) { // Mozilla
	        document.onmousemove = captureMousePosition;
	    }
    }


//========================================================
//  RecurseOffset(object)
//  returns true cross-browser offsetLeft and offsetTop of an object.
//  offsetWidth and offsetHeight are included for 
//  ease of use.
//--------------------------------------------------------
//  ex. var Left = RecurseOffset(obj).offsetLeft;
//========================================================
function RecurseOffset(obj)
{
    if (GetType(obj)=="string")
    {
        if (gE(obj)==null)
        {
            alert("RecurseOffset requires a valid DOM object");
        }
        else
        {
            obj = gE(obj);
        }
    }
   var ROO = new RecurseOffsetObject(obj);
   var Offsets = new Object();
       Offsets.offsetLeft   = ROO.GetOffsetLeft();
       Offsets.offsetTop    = ROO.GetOffsetTop();
       Offsets.offsetWidth  = ROO.GetOffsetWidth();
       Offsets.offsetHeight = ROO.GetOffsetHeight();
   
   return Offsets;
}


//========================================================
//  RecurseOffsetObject(object) used in RecurseOffset(object)
//  This can be called directly
//========================================================
function RecurseOffsetObject(obj)
{
	this.ParentObj = null;
	this.CurrentObj = obj;
    this.offsetLeft = obj.offsetLeft;
    this.offsetTop = obj.offsetTop;
    this.offsetWidth = obj.offsetWidth;
    this.offsetHeight = obj.offsetHeight;
    
	RecurseOffsetObject.prototype.Init = function()
	{
	    if (this.CurrentObj.offsetParent != null)
	    {
	        do
		    {
                this.ParentObj = this.CurrentObj.offsetParent;
                this.offsetLeft += this.ParentObj.offsetLeft;
                this.offsetTop += this.ParentObj.offsetTop;
                this.CurrentObj = this.ParentObj;
		    }
		    while (this.CurrentObj.offsetParent != null);
	    }
	};
	RecurseOffsetObject.prototype.GetOffsetLeft = function(){ return this.offsetLeft; };
	RecurseOffsetObject.prototype.GetOffsetTop = function(){ return this.offsetTop; };
	RecurseOffsetObject.prototype.GetOffsetWidth = function(){ return this.offsetWidth; };
	RecurseOffsetObject.prototype.GetOffsetHeight = function(){ return this.offsetHeight; };
	this.Init();
}


//========================================================
//   String.format gives you C# style string formatting
//========================================================
String.format = function()
{
	if (arguments.length==0) 
	{ 
		throw("String.format requires arguments"); 
	}
	var str = " " + arguments[0];
	for(var i=1;i<arguments.length;i++)
    {
		var re = new RegExp('([^\\{]{1})(\\{' + (i-1) + '\\}(?!\\}))','gm');
        str = str.replace(re,'\$1' + arguments[i]);
    }
	str = str.replace(new RegExp('\\{\\{','gm'),"{");
	str = str.replace(new RegExp('\\}\\}','gm'),"}");
    return str.substring(1);
};


//===============================================
//	System Types are caught with GetType()
//	Or, any custom type built with a constructor
//===============================================
function GetType(Element)
{
	if (Element==null)
	{
		return "null";
	}
	if (Element.constructor == null)
	{
		return "object";
	}
	else
	{
		var Catches = Element.constructor.toString().toLowerCase().match(/([a-z0-9]+)(\(\))/i);
		if (Catches != null)
		{
			return Catches[1];
		}
		else
		{
			return "unknown";
		}
	}
}


//=========================================================
//  GetWindowBunds (Bounds)
//  function to calculate the visible width of the window
//  and the actual width of the BODY element
//=========================================================
function GetWindowBunds()
{
	this.PageWidth  = 0;
    this.PageHeight = 0;
    this.VisibleTop = 0;
    this.VisibleLeft = 0;
    this.VisibleWidth  = 0;
    this.VisibleHeight = 0;
	this.isDefined = true;
	
	GetWindowBunds.prototype.Init = function()
	{
        if( window.innerHeight && window.scrollMaxY ) // Firefox 
	    {
		    this.PageWidth = window.innerWidth + window.scrollMaxX;
		    this.PageHeight = window.innerHeight + window.scrollMaxY;
	    }
	    else if( document.body.scrollHeight > document.body.offsetHeight ) // all but Explorer Mac
	    {
		    this.PageWidth = document.body.scrollWidth;
		    this.PageHeight = document.body.scrollHeight;
	    }
	    else // works in Explorer 6 Strict, Mozilla (not FF) and Safari
	    { 
		    this.PageWidth = document.body.offsetWidth + document.body.offsetLeft; 
		    this.PageHeight = document.body.offsetHeight + document.body.offsetTop; 
	    }
        
        //==========================
        //  Get Width / Height
        //==========================
        // alert(window.innerWidth);
        if( typeof( window.innerWidth ) == 'number' ) 
        {
            //alert("other");
            this.VisibleWidth = window.innerWidth;
            this.VisibleHeight = window.innerHeight;
        }
        else if (document.documentElement && document.documentElement.clientWidth)
        {
            //alert("document.documentElement");
            this.VisibleWidth    = document.documentElement.clientWidth;
            this.VisibleHeight   = document.documentElement.clientHeight;
        } 
        else if (document.body && document.body.clientWidth)
        {
            //alert("document.body");
		    this.VisibleWidth    = document.body.clientWidth;
            this.VisibleHeight   = document.body.clientHeight;
        } 
        
        //==========================
        //  Get Scroll Top / Scroll Left
        //==========================
        if (!isNaN(window.pageYOffset))
        {
            //alert("window.pageYOffset");
            this.VisibleTop      = window.pageYOffset;
            this.VisibleLeft     = window.pageXOffset;
        }
        else if (document.body && ( document.body.scrollTop || document.body.scrollLeft)) 
        {
            //alert("document.body.scrollTop");
            this.VisibleTop      = document.body.scrollTop;
            this.VisibleLeft     = document.body.scrollLeft;
        }
        else if (document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop) )
        {
            //alert("document.documentElement.scrollTop");
            this.VisibleTop      = document.documentElement.scrollTop;
            this.VisibleLeft     = document.documentElement.scrollLeft;
        }  
        else
        {
            this.isDefined = false;
            //alert("Unknown Scrolling");
        }
    	
	    if (navigator.userAgent.indexOf('Safari') > -1)
	    {
		    this.VisibleHeight = window.innerHeight;
	    }
	    
	        /*
	        // uncomment block for testing
            alert(navigator.userAgent);
           
            window.alert(String.format('\
            this.PageWidth: {0}\n\
            this.PageHeight: {1}\n\
            this.VisibleTop: {2}\n\
            this.VisibleLeft: {3}\n\
            this.VisibleWidth: {4}\n\
            this.VisibleHeight: {5}',
            this.PageWidth,
            this.PageHeight,
            this.VisibleTop,
            this.VisibleLeft,
            this.VisibleWidth,
            this.VisibleHeight));
	        */
	};
	
	this.Init();
}


//========================================================
//   FormatNumber
//========================================================
function FormatNumber(NumberString)
{
	NumberString += '';
	Parts = NumberString.split('.');
	Number1 = Parts[0];
	Number2 = Parts.length > 1 ? '.' + Parts[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(Number1)) 
	{
		Number1 = Number1.replace(rgx, '$1' + ',' + '$2');
	}
	return Number1 + Number2;
}


//========================================================
//   ImportJS
//========================================================
function ImportJS(strFile, strTemplateName)
{
    document.write('<scri' + 'pt language="javascript" type="text/javascript" src="http://www.househunting.ca/scripts/include.aspx?file=/themes/' + strTemplateName + '/' + strFile + '.inc"></scr' + 'ipt>');
}

//========================================================
//   EmailAgent
//========================================================
function EmailAgentDir(IdAgentForeignKey, Agent, EmailLeadType)
{
    if (EmailLeadType == '2')
    {
        tb_show('Email Agent', WebRoot + "Controls/AjaxCalls/EmailAgent.aspx?height=500&width=450&modal=true&IdAgentForeignKey=" + IdAgentForeignKey +"&Agent=" +escape(Agent)+"&EmailLeadType=" +EmailLeadType, false);
    }       
    else
    {
        tb_show('Email Agent', WebRoot + "Controls/AjaxCalls/EmailAgent.aspx?height=320&width=450&modal=true&IdAgentForeignKey=" + IdAgentForeignKey +"&Agent=" +escape(Agent)+"&EmailLeadType=" +EmailLeadType, false);
    }
}

//========================================================
//   EmailAgent
//========================================================
function EmailAgent(IdListing, Agent, EmailLeadType, SEOSection, Refer) {    
    if (EmailLeadType == '2') {
        tb_show('Email Agent', WebRoot + "Controls/AjaxCalls/EmailAgent.aspx?height=500&width=450&modal=true&IdListing=" + IdListing + "&Agent=" + escape(Agent) + "&EmailLeadType=" + EmailLeadType + "&Refer=" + Refer + "&SeoSection=" + SEOSection, false);
    }
    else {
        tb_show('Email Agent', WebRoot + "Controls/AjaxCalls/EmailAgent.aspx?height=320&width=450&modal=true&IdListing=" + IdListing + "&Agent=" + escape(Agent) + "&EmailLeadType=" + EmailLeadType + "&Refer=" + Refer + "&SeoSection=" + SEOSection, false);
    }
}


//========================================================
//   EmailFriend
//========================================================
function EmailFriend(IdListing, SEOSection) {
    tb_show('Listing you are sharing:', WebRoot + "Controls/AjaxCalls/EmailFriend.aspx?height=345&width=450&IdListing=" + IdListing + "&PageFlag=L&&SEOSection=" + SEOSection, false);
}

function SendToCell(AgentPhone, IdListing, SEOSection)
{    
    tb_show('Listing you are sharing:', WebRoot + "Controls/AjaxCalls/SendToCell.aspx?height=345&width=410&AgentPhone=" + AgentPhone + "&IdListing=" + IdListing + "&PageFlag=L&SEOSection=" + SEOSection, false);
}

//========================================================
//   SendEmail
//   Passes email form values to send_email_lead page
//========================================================
function SendEmail(emailstring) {    
    tb_show('Success', WebRoot + "send_email_lead.aspx?" + emailstring + "&height=50&width=250", false);
}

//========================================================
//   Validate Send to Cell
//   Validates the Send to Cell
//========================================================
function ValidateSendtoCell(theForm)
{

if (theForm.myAreaCode.value == "")
  {
    alert("Please enter your 3 digit area code.");
    theForm.myAreaCode.focus();
    return (false);
  }

  if (theForm.myAreaCode.value.length > 3)
  {
    alert("Please enter at most 3 characters in the \"Area Code\" field.");
    theForm.myAreaCode.focus();
    return (false);
  }

  if (theForm.myAreaCode.value.length < 3)
  {
    alert("Please enter at least 3 characters in the \"Area Code\" field.");
    theForm.myAreaCode.focus();
    return (false);
  }

  var checkOK = "0123456789";
  var checkStr = theForm.myAreaCode.value;
  var allValid = true;
  for (i = 0;  i < checkStr.length;  i++)
  {
    ch = checkStr.charAt(i);
    for (j = 0;  j < checkOK.length;  j++)
      if (ch == checkOK.charAt(j))
        break;
    if (j == checkOK.length)
    {
      allValid = false;
      break;
    }
  }
  if (!allValid)
  {
    alert("Please enter only digits in the \"Area Code\" field.");
    theForm.myAreaCode.focus();
    return (false);
  }


if (theForm.myFirst3Digits.value == "")
  {
    alert("Please enter the first 3 digits of your mobile phone.");
    theForm.myFirst3Digits.focus();
    return (false);
  }

  if (theForm.myFirst3Digits.value.length > 3)
  {
    alert("Please enter at most 3 characters as the first 3 digits of your mobile phone.");
    theForm.myFirst3Digits.focus();
    return (false);
  }

  if (theForm.myFirst3Digits.value.length < 3)
  {
    alert("Please enter at least 3 characters as the last 3 digits of your mobile phone.");
    theForm.myFirst3Digits.focus();
    return (false);
  }
  
  
    var checkOK = "0123456789";
  var checkStr = theForm.myFirst3Digits.value;
  var allValid = true;
  for (i = 0;  i < checkStr.length;  i++)
  {
    ch = checkStr.charAt(i);
    for (j = 0;  j < checkOK.length;  j++)
      if (ch == checkOK.charAt(j))
        break;
    if (j == checkOK.length)
    {
      allValid = false;
      break;
    }
  }
  if (!allValid)
  {
    alert("Please enter only numeric characters as the first three numbers of your mobile phone.");
    theForm.myFirst3Digits.focus();
    return (false);
  }

if (theForm.myLast4Digits.value == "")
  {
    alert("Please enter the last 4 digits of your mobile phone.");
    theForm.myLast4Digits.focus();
    return (false);
  }

  if (theForm.myLast4Digits.value.length > 4)
  {
    alert("Please enter at most 4 characters as the last 4 digits of your mobile phone.");
    theForm.myLast4Digits.focus();
    return (false);
  }

  if (theForm.myLast4Digits.value.length < 4)
  {
    alert("Please enter at least 4 characters as the last 4 digits of your mobile phone.");
    theForm.myLast4Digits.focus();
    return (false);
  }
  
  
    var checkOK = "0123456789";
  var checkStr = theForm.myLast4Digits.value;
  var allValid = true;
  for (i = 0;  i < checkStr.length;  i++)
  {
    ch = checkStr.charAt(i);
    for (j = 0;  j < checkOK.length;  j++)
      if (ch == checkOK.charAt(j))
        break;
    if (j == checkOK.length)
    {
      allValid = false;
      break;
    }
  }
  if (!allValid)
  {
    alert("Please enter only numeric characters as the last four numbers of your mobile phone.");
    theForm.myLast4Digits.focus();
    return (false);
  }


  if (theForm.provider.value == "x")
  {
    alert("Please choose a provider for your mobile phone.");
    theForm.myLast4Digits.focus();
    return (false);
  }
  
    var myCEmail = theForm.myAreaCode.value + theForm.myFirst3Digits.value + theForm.myLast4Digits.value + "@" + theForm.provider.value;

    //alert(myCEmail);  
    
    SendEmail("PageFlag=" + theForm.PageFlag.value + "&IdListing=" + theForm.IdListing.value + "&EmailAddress=" + theForm.EmailAddress.value + "&EmailFriendAddress=" + myCEmail + "&Message=&Name=" + theForm.flName.value + "&NameFriend=" + theForm.NameFriend.value + "&emailto=cell");
    return(true);

}

//========================================================
//   ValidateEmailFriend
//   Validates the Email a Friend Form
//========================================================
function ValidateEmailFriend(theForm)
{
    if (theForm.flName.value == "")
    {
        alert("Please enter your name.");
        theForm.flName.focus();
        return (false);
    }
    
    if (theForm.EmailAddress.value == "")
    {
        alert("Please enter your email address.");
        theForm.EmailAddress.focus();
        return (false);
    }
    var addFlag = validEmailField(theForm.EmailAddress,"Please Enter valid E-mail address in the form: yourname@yourdomain.com");
    if(!addFlag)
    {
        return (false);
    }

    if (theForm.NameFriend.value == "")
    {
        alert("Please enter your Friend's name.");
        theForm.NameFriend.focus();
        return (false);
    }
            
    if (theForm.EmailFriendAddress.value == "")
    {
        alert("Please enter your Friend's email address.");
        theForm.EmailFriendAddress.focus();
        return (false);
    }
    var addrss = theForm.EmailFriendAddress.value;
    theForm.EmailFriendAddress.value = addrss.replace(";",",");
    var faddFlag = validEmailFieldMultiple(theForm.EmailFriendAddress,",","Please Enter valid E-mail addresses in the form: yourname@yourdomain.com");
    if(!faddFlag)
    {
        return (false);
    }
            
    if (theForm.Message.value != "" )
    {
        var checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzƒŠŒŽšœžŸÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ0123456789-@%:')(#_*&+!.$/ ,- ; <=^>\"\t\r\n\f~";
  	    var checkStr = escape(theForm.Message.value);
  	    var allValid = true;
  	    var k = checkStr.length;
  	    var p = 0;
  	    for (i = 0;  i < k;  i++)
  	    {   
    	    ch = checkStr.charAt(p);
    	    for (j = 0;  j < checkOK.length;  j++)
            {
                if (ch == checkOK.charAt(j))
      	        {  	
                    p = p + 1;
                    break;
                }
                if (j == checkOK.length)
                {
                    checkStr = checkStr.substring(0,p) + checkStr.substring(p+1);
                }
            }
  	    }
  	    theForm.Message.value = checkStr;
  	    if (!allValid)
  	    {
    	    alert("Please enter only letter, digit, whitespace and \"@%*$/:)(#_&-+!.;,<=^> \" characters in the \"Message\" field.");
    	    document.theForm.Message.focus();
    	    return (false);
  	    }
    }
    
    theForm.flName.value = escape(theForm.flName.value);
    theForm.NameFriend.value = escape(theForm.NameFriend.value);

    SendEmail("PageFlag=" + theForm.PageFlag.value + "&IdListing=" + theForm.IdListing.value + "&EmailAddress=" + theForm.EmailAddress.value + "&EmailFriendAddress=" + theForm.EmailFriendAddress.value + "&Message=" + theForm.Message.value + "&Name=" + theForm.flName.value + "&NameFriend=" + theForm.NameFriend.value + "&emailto=friend&seosection=" + theForm.SEOSection.value);
    return(true);
}

//========================================================
//   ValidateEmailAgent
//   Validates the Email Agent Lead Form
//========================================================
function ValidateEmailAgent(theForm) {
    var EmailLeadType = theForm.EmailLeadType.value;
    var GUID = theForm.guid.value;

    if (theForm.FirstName.value == "") {
        alert("Please enter your first name.");
        theForm.FirstName.focus();
        return (false);
    }

    if (theForm.LastName.value == "") {
        alert("Please enter your last name.");
        theForm.LastName.focus();
        return (false);
    }


    if (theForm.EmailAddress.value == "") {
        alert("Please enter your email address.");
        theForm.EmailAddress.focus();
        return (false);
    }

    var addFlag = validEmailField(theForm.EmailAddress, "Please enter valid email address in the format: yourname@yourdomain.com", 1);

    if (!addFlag)
        return (false);

    //    if (EmailLeadType != "2")
    //    {
    //        addFlag = validateUSPhone(theForm.Phone,"Please enter valid phone number",2);
    //        if(!addFlag)
    //        return (false);
    //    }

    if (theForm.Message.value != "") {
        var checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzƒ0123456789-@%:')(#_*&+!.$/ ,- ; <=^>\"\t\r\n\f~";
        var checkStr = escape(theForm.Message.value);
        var allValid = true;
        var k = checkStr.length;
        var p = 0;
        for (i = 0; i < k; i++) {
            ch = checkStr.charAt(p);
            for (j = 0; j < checkOK.length; j++) {
                if (ch == checkOK.charAt(j)) {
                    p = p + 1;
                    break;
                }
                if (j == checkOK.length) {
                    checkStr = checkStr.substring(0, p) + checkStr.substring(p + 1);
                }
            }
        }
        theForm.Message.value = checkStr;
        if (!allValid) {
            alert("Please enter only letter, digit, whitespace and \"@%*$/:)(#_&-+!.;,<=^> \" characters in the \"Message\" field.");
            document.theForm.Message.focus();
            return (false);
        }
    }
    theForm.FirstName.value = escape(theForm.FirstName.value);
    theForm.LastName.value = escape(theForm.LastName.value);
    if (EmailLeadType == "2") {
        DoReport("EmailAgentForm-Submit-" + theForm.IdListing.value + "-" + GUID);
        SendEmail("IdListing=" + theForm.IdListing.value + "&IdAgentForeignKey=" + theForm.IdAgentForeignKey.value + "&EmailAddress=" + theForm.EmailAddress.value + "&Phone=" + theForm.Phone.value + "&Extension=" + theForm.Extension.value + "&Message=" + theForm.Message.value + "&Move=" + theForm.Move.value + "&FirstName=" + theForm.FirstName.value + "&LastName=" + theForm.LastName.value + "&State=" + theForm.State.value + "&City=" + theForm.City.value + "&Street=" + theForm.Street.value + "&Zip=" + theForm.Zip.value + "&emailto=agent&guid=" + GUID + "&refer=" + theForm.refer.value);
    }
    else {
        DoReport("EmailAgentForm-Submit-" + theForm.IdListing.value + "-" + GUID);
        SendEmail("IdListing=" + theForm.IdListing.value + "&IdAgentForeignKey=" + theForm.IdAgentForeignKey.value + "&EmailAddress=" + theForm.EmailAddress.value + "&Phone=" + "&Message=" + theForm.Message.value + "&FirstName=" + theForm.FirstName.value + "&LastName=" + theForm.LastName.value + "&emailto=agent&guid=" + GUID + "&refer=" + theForm.refer.value + "&seosection=" + theForm.SEOSection.value);
    }
    return (true);
}



//========================================================
//   ValidateSmallEmailAgent
//   Validates the Email Agent Lead Form with basic fields.
//========================================================
function ValidateSmallEmailAgent(theForm)
{
    var EmailLeadType = theForm.EmailLeadType.value;
    var GUID = theForm.guid.value;
    
    if (theForm.FirstName.value == "")
    {
        alert("Please enter your first name.");
        theForm.FirstName.focus();
        return (false);
    }
    if (theForm.LastName.value == "")
    {
        alert("Please enter your last name.");
        theForm.LastName.focus();
        return (false);
    }
    if (theForm.EmailAddress.value == "")
    {
        alert("Please enter your email address.");
        theForm.EmailAddress.focus();
        return (false);
    }

    var addFlag = validEmailField(theForm.EmailAddress,"Please enter valid email address in the format: yourname@yourdomain.com",undefined);
      theForm.FirstName.value = escape(theForm.FirstName.value);
      theForm.LastName.value = escape(theForm.LastName.value);
    
    if(!addFlag)
        return (false);
        
     if (EmailLeadType == "2")
      {
         DoReport("EmailAgentForm-Submit-" + theForm.IdListing.value + "-" + GUID);
         SendEmail("IdListing=" + theForm.IdListing.value + "&IdAgentForeignKey=" + theForm.IdAgentForeignKey.value + "&EmailAddress=" + theForm.EmailAddress.value + "&FirstName=" + theForm.FirstName.value + "&LastName=" + theForm.LastName.value + "&emailto=agent&AgentEmail=" + theForm.AgentEmail.value + "&guid=" + GUID + "&IdAgent=" + theForm.IdAgent.value + "&refer=" + theForm.refer.value);
      }
      else
      {
         DoReport("EmailAgentForm-Submit-" + theForm.IdListing.value + "-" + GUID);
         SendEmail("IdListing=" + theForm.IdListing.value + "&IdAgentForeignKey=" + theForm.IdAgentForeignKey.value + "&EmailAddress=" + theForm.EmailAddress.value + "&FirstName=" + theForm.FirstName.value + "&LastName=" + theForm.LastName.value + "&emailto=agent&AgentEmail=" + theForm.AgentEmail.value + "&guid=" + GUID + "&IdAgent=" + theForm.IdAgent.value + "&refer=" + theForm.refer.value);
      }           
   return (true);
}

//========================================================
//   RestoreSelects
//   Restores selects on page hidden by menu
//========================================================
function RestoreSelects()
{
    if (!document.all) { return; } // no need in other than IE
    var SelectCollection = document.getElementsByTagName("select");
        for (var s=0;s<SelectCollection.length;s++)
        {   
            SelectCollection[s].style.visibility="visible";
        }
}


//========================================================
//   SweepSelects(TargetObject)
//   Hides selects in collision with TargetObject
//========================================================
function SweepSelects(TargetObject)
{
    if (!document.all) { return; } // no need in other than IE
    
    var TRO = new RecurseOffset(TargetObject);
    var MatchLeft = TRO.offsetLeft;
    var MatchTop = TRO.offsetTop;
    var MatchRight = MatchLeft + TRO.offsetWidth;
    var MatchBottom = MatchTop + TRO.offsetHeight;
    
    //alert(MatchLeft +":"+  MatchTop +":"+  MatchRight +":"+  MatchBottom  );
    
    var SelectCollection = document.getElementsByTagName("select");
    
    for (var s=0;s<SelectCollection.length;s++)
    {
        var SelectObject = SelectCollection[s];
        
        var SRO = new RecurseOffset(SelectObject);

	    var SelectLeft = SRO.offsetLeft;
        var SelectTop = SRO.offsetTop;
        var SelectRight = SelectLeft + SRO.offsetWidth;
        var SelectBottom = SelectTop + SRO.offsetHeight;
        
        //====================== detect collision
       
        if (
            (SelectRight > MatchLeft) &&
            (SelectBottom > MatchTop) &&
            (SelectLeft < MatchRight) &&
            (SelectTop < MatchBottom)
            )
            {
                SelectObject.style.visibility = "hidden";
                //return;
            }
            
        //======================= if position of select is not detectible, hide to be sure
        if ((SelectLeft == 0) && (SelectTop == 0))
        {
            SelectObject.style.visibility = "hidden";
            //return;
        }
    }
}


//================================================================
//  UrlGen
//  Mimics functionality of Endeca "UrlGen"
//================================================================
function UrlGen(strQueryString)
{
    this.Parameters = new Array();
    
    UrlGen.prototype.Init = function(strQueryString)
    {with(this){
        Parameters = new Array();
        var QueryString = strQueryString.replace(/&amp;/gi,'&');
            QueryString = QueryString.replace('%7c','|');
            QueryString = unescape(QueryString);
        
        var _tempParams = QueryString.split('&');
        for (var i=0; i < _tempParams.length; i++)
        {
            var _Param = _tempParams[i].split('=');
            Parameters.push(_Param);
        }
    }};
    
    UrlGen.prototype.RemoveParam = function(strKey)
    {with(this){
        var _tempParams = new Array();
        for (var i=0; i<Parameters.length; i++)
        {
            if (Parameters[i][0].toLowerCase() != strKey.toLowerCase())
            {
                _tempParams.push(Parameters[i]);
            }
        }
        Parameters = _tempParams;
    }};
    
    UrlGen.prototype.RemoveParams = function(arrParams)
    {with(this){
        for (var p=0; p<arrParams.length; p++)
        {
            RemoveParam(arrParams[p]);
        }
    }};
    
    UrlGen.prototype.AddParam = function(strKey, strValue)
    {with(this){
        Parameters.push(new Array(strKey, strValue));
    }};
    
    UrlGen.prototype.GetParam = function(strKey)
    {with(this){
        for (var i=0; i<Parameters.length; i++)
        {
           if (Parameters[i][0].toLowerCase() == strKey.toLowerCase())
           {
                return Parameters[i][1];
           }
        }
        return "";
    }};

    UrlGen.prototype.ToString = function()
    {with(this){
        var _tempParams = new Array();
        for (var i=0; i<Parameters.length; i++)
        {
            if (trim(Parameters[i][0]) != "")
            {
                _tempParams.push(Parameters[i].join('='));
            }
        }
        return _tempParams.join('&');
    }};
    
    this.Init(strQueryString);
}


//================================================================
//  setAdTagsParameters function
//================================================================
function setAdTagsParameters()
{
    // set up global vars with pageHeader information
    document.globalPageSite = "DOOR";
    document.globalPageSctnName = adtag_globalPageSctnName;
    document.globalPageSctnId = adtag_globalPageSctnId;
    document.globalPageType = adtag_globalPageType;
    document.globalCategoryDspName = adtag_globalCategoryDspName;
    document.globalSctnDspName = adtag_globalSctnDspName;
    document.globalPageTitle = adtag_globalPageTitle;
    document.globalPageAbstract = adtag_globalPageAbstract;
    document.globalPageKeywords = adtag_globalPageKeywords;
    document.globalPageSponsorship = adtag_globalPageSponsorship;
    document.globalSctnLineage = adtag_globalSctnLineage;
    
    mdManager.addParameter("Url",			    adtag_url);
    mdManager.addParameter("Type",			    adtag_globalPageType);
    mdManager.addParameter("Role",			    "");
    mdManager.addParameter("Title",			    adtag_globalPageTitle);
    mdManager.addParameter("Sponsorship",		adtag_globalPageSponsorship);
    mdManager.addParameter("Abstract",		    adtag_globalPageAbstract);
    mdManager.addParameter("Keywords",		    adtag_globalPageKeywords);
    mdManager.addParameter("Classification",	adtag_globalSctnLineage);
    mdManager.addParameter("Site",			    "DOOR"); 
    mdManager.addParameter("SctnName",		    adtag_globalPageSctnName);
    mdManager.addParameter("SctnDspName",		adtag_globalSctnDspName);
    mdManager.addParameter("CategoryDspName", 	adtag_globalCategoryDspName);
    mdManager.addParameter("SctnId", 		    adtag_globalPageSctnId);
    mdManager.addParameter("DetailId", 		    "");
    mdManager.addParameter("PageNumber", 		"1");
    mdManager.addParameter("UniqueId", 		    adtag_globalUniqueId);
    mdManager.addParameter("Show_Abbr",		    "");
    mdManager.addParameter("SearchKeywords",    "<% // FROM INITIAL SEARCH BOX %>");
    mdManager.addParameter("SearchFilters",     "<% // FROM REFINEMENTS %>");
}


//================================================================
//  SetDefault(CurrentValue, DefaultValue)
//  Used for functions with multiple parameters, defines a value
//  if a value is not defined in the syntax of a method
//================================================================
function SetDefault(CurrentValue, DefaultValue)
{
    if (CurrentValue == undefined)
    {
        return DefaultValue;
    }
    return CurrentValue;
}




// validate for the price format $100,000.
//function ValidateAndReturnPrice(price)
//{
//    var priceTemp = price.value.replace('$','').replace(/,/g,'');
//    if(trim(priceTemp).length > 0)
//    {
//        if(IsNumeric(priceTemp))
//        {
//            return priceTemp;
//        }
//        else
//        {
//            AlertFocus(price,"Please enter Numeric Values",undefined)
//            return -1;
//        }
//    }
//    return 0;
//    
//}


// validate for the Interest Rate eg. 6.7%.
//function ValidateAndReturnInterestRate(rate, min_num, max_num)
//{
//    var rateTemp = rate.value.replace('%','');
//    if(trim(rateTemp).length > 0)
//    {
//        if(IsNumeric(rateTemp))
//        {            
//            if(rateTemp >= min_num && rateTemp <= max_num)
//            {
//                return (rateTemp/100);
//            }
//            else
//            {
//                AlertFocus(rate,"Please enter Numeric Values between "+min_num+"% and "+max_num+"%.",undefined);
//                return -1;
//            }
//        }
//        else
//        {
//            AlertFocus(rate,"Please enter Numeric Values",undefined)
//            return -1;
//        }
//    }
//    return 0;
//    
//}


// validate months.
//function ValidateAndReturnTimeSpan(months_years, min_num, max_num)
//{
//    if(trim(months_years.value).length > 0)
//    {
//        if(IsNumeric(months_years.value))
//        {
//            if(months_years.value.indexOf('.') > -1)
//            {
//                AlertFocus(months_years,"Please enter Numeric Values",undefined);
//                return -1;
//            }
//            if(months_years.value >= min_num && months_years.value <= max_num)
//            {
//                return months_years.value;
//            }
//            else
//            {
//                AlertFocus(months_years,"Please enter Numeric Values between "+min_num+" and "+max_num,undefined);
//                return -1;
//            }
//        }
//        else
//        {
//            AlertFocus(months_years,"Please enter Numeric Values",undefined);
//            return -1;
//        }
//    }
//    return "";    
//}




//function EmailFormDelegate(AjaxResponse)
//{
//   var EF = gE("emailforms");
//   EF.style.display = "none";
//   var EFM = gE("emailformsmask");
//   EFM.style.display = "none";
//   
//   gE("emailforms").innerHTML = AjaxResponse;
//   gE("emailforms").style.width = "450px";
//   EmailFormMask();
//   EmailForms();
//}

//function FormDelegate(AjaxResponse)
//{
//    gE("emailforms").innerHTML = AjaxResponse;
//    gE("emailforms").style.width = "450px";
//    EmailFormMask();
//    EmailForms();
//}

//function PhotoFormDelegate(AjaxResponse)
//{
//    gE("emailforms").innerHTML = AjaxResponse;
//    gE("emailforms").style.width = "603px";
//    EmailFormMask();
//    EmailForms();
//}

//function EmailForms()
//{
//    var EF = gE("emailforms");
//    
//    if (EF.style.display == "block")
//    {
//        EF.innerHTML = "";
//        EF.style.display = "none";
//        //document.getElementById("map_border").style.display='block';
//        EF.style.left = "-1000px";
//        EF.style.top = "-1000px";
//    }
//    else
//    {
//        EF.style.display = "block";
//       // document.getElementById("map_border").style.display='none';
//        var WindowBounds = new GetWindowBunds();
//                /*
//                window.alert("VisibleWidth=" + WindowBounds.VisibleWidth + ":" + 
//                            "\nVisibleHeight=" + WindowBounds.VisibleHeight + ":" + 
//                            "\nVisibleTop=" + WindowBounds.VisibleTop + ":" + 
//                            "\nVisibleLeft=" + WindowBounds.VisibleLeft + ":" + 
//                            "\nPageWidth=" + WindowBounds.PageWidth + ":" + 
//                            "\nPageHeight=" + WindowBounds.PageHeight);
//                */
//                
//        EF.style.left = parseInt((WindowBounds.VisibleWidth / 2) - (RecurseOffset(EF).offsetWidth / 2),10) + "px";
//        EF.style.top = WindowBounds.VisibleTop + parseInt(((WindowBounds.VisibleHeight - RecurseOffset(EF).offsetHeight) / 2),10) + "px";        
//    }
//}

//function EmailFormMask()
//{
//    var EFM = gE("emailformsmask");
//    
//    if (EFM.style.display == "block")
//    {
//        RestoreSelects();
//        EFM.style.display = "none";
//        EFM.style.left = "-1000px";
//        EFM.style.top = "-1000px";
//    }
//    else
//    {
//        WindowBounds = new GetWindowBunds();
//        EFM.style.left = "1px";
//        EFM.style.top = "1px";
//        EFM.style.width = WindowBounds.PageWidth + "px";
//        EFM.style.height = WindowBounds.PageHeight + "px";
//        EFM.style.display = "block";
//        SweepSelects(EFM);
//    }
//}


//function SendEmail(emailstring)
//{
//  $AJAX.GetForDelegate(EmailFormDelegate, WebRoot + "send_email_lead.aspx?" + emailstring);
//}


//function EmailFriend(IdListing, IdWeb,Address,AddressCityState)
//{
//   $AJAX.GetForDelegate(FormDelegate, WebRoot + "Controls/AjaxCalls/EmailFriend.aspx?IdListing=" + IdListing + "&IdWeb=" + IdWeb +"&Address=" +Address + "&AddressCityState=" +AddressCityState);
//}


//function EmailAgent(IdListing, Agent)
//{
//  $AJAX.GetForDelegate(FormDelegate, WebRoot + "Controls/AjaxCalls/EmailAgent.aspx?IdListing=" + IdListing +"&Agent=" +Agent);         
//}

// Randomly showing up the featured ads.

//    function generateFeaturedAd()
//    {
//        var flagID = Math.floor(Math.random()*2+1);
//        if(flagID == 1)
//        {
//            document.write("<div id=\"FeaListing\"> <Include:Fea_Listing ID=\"Fea_Listing1\" runat=\"server\" /> </div>");
//            document.write("<div id=\"FeaRealtor\"> <Include:Fea_Realtor ID=\"Fea_Realtor1\" runat=\"server\" /> </div>");
//        }
//        else
//        {
//            document.write("<div id=\"FeaRealtor\"> <Include:Fea_Realtor ID=\"Fea_Realtor1\" runat=\"server\" /> </div>"); 
//            document.write("<div id=\"FeaListing\"> <Include:Fea_Listing ID=\"Fea_Listing1\" runat=\"server\" /> </div>");       
//        }        
//    }

//========================================================
//   changes the search state of the top tabs
//========================================================

//function SearchState(state)
//{
//    var L = gE("sListings");
//    var C = gE("sCommunity");
//    switch(state)
//    {
//        case "sListings":
//            L.className = "active";
//            C.className = "";
//            break;
//        case "sCommunity":
//            L.className = "";
//            C.className = "active";
//            break;
//    }
//    
//}

//========================================================
//   gets a string describing the current search type
//========================================================
//function GetSearchType()
//{
//    return "sale";
//    
//    /*
//    var tab = gE("search_tabs");
//    
//    if (tab.className == "show_sale")
//    {
//        return "sale";
//    }
//    else
//    {
//        if (tab.className == "show_rent")
//        {
//            return "rent";
//        }
//        else
//        {
//            return "pp";
//        }
//    }
//    */
//}

//====================================================================
//   Tab control to switch between sales, rentals and private search.
//====================================================================
//function changeSearchType(state)
//    {
//        var S = gE("sales");
//        var S_data = gE("search_sales");
//        var R = gE("rentals");
//        var R_data = gE("search_Rentals");
//        var P = gE("private");
//        var P_data = gE("search_Private");
//        
//        switch(state)
//        {
//            case "sales":
//                S_data.style.display = 'block';
//                S.className = "active";
//                R_data.style.display = 'none';
//                R.className = "";
//                P_data.style.display = 'none';
//                P.className = "";
//                break;
//            case "rentals":
//                S_data.style.display = 'none';
//                S.className = "";
//                R_data.style.display = 'block';
//                R.className = "active";
//                P_data.style.display = 'none';
//                P.className = "";
//                break;
//            case "private":
//                S_data.style.display = 'none';
//                S.className = "";
//                R_data.style.display = 'none';
//                R.className = "";
//                P_data.style.display = 'block';
//                P.className = "active";
//                break;
//        }
//    }
    

//var saleID = "829246";


//========================================================
//   displays message if no regions are returned from Ajax
//========================================================
//function ZeroResults()
//{
//        var ilWidth = 230; // image width
//        var ilHeight = 70;  // image height
//        var load = document.createElement("div");
//            load.id="ZeroResults";
//            load.className="IsLoading"; // use same positioning
//	        load.style.left = parseInt((gE("map").offsetWidth - ilWidth) / 2,10) + "px";
//            load.style.top = parseInt((gE("map").offsetHeight - ilHeight) / 2,10) + "px";
//            loadImg = document.createElement("img");
//            loadImg.border=0;
//            loadImg.align="left";
//            loadImg.src = ImageCache.ZeroResults.src;
//            load.appendChild(loadImg);
//            gE("map").appendChild(load);
//            
//       window.setTimeout(function()
//       {
//            if (gE("ZeroResults"))
//            {
//                gE("map").removeChild(gE("ZeroResults"));
//            }
//       },1500);  
//            
//}

//========================================================
//   displays Loading messages on the map.
//========================================================
//function ShowLoading(boolOpenClose)
//{
//    if (boolOpenClose)
//    {
//        var ilWidth = 230; // image width
//        var ilHeight = 70;  // image height
//        var load = document.createElement("div");
//            load.id="IsLoading";
//            load.className="IsLoading";
//	        load.style.left = parseInt((gE("map").offsetWidth - ilWidth) / 2,10) + "px";
//            load.style.top = parseInt((gE("map").offsetHeight - ilHeight) / 2,10) + "px";
//            loadImg = document.createElement("img");
//            loadImg.border=0;
//            loadImg.align="left";
//            loadImg.src = ImageCache.IsLoading.src;
//            load.appendChild(loadImg);
//            gE("map").appendChild(load);
//    }
//    else
//    {
//        if (gE("IsLoading"))
//        {
//            gE("map").removeChild(gE("IsLoading"));
//        }
//    }
//}


//==========================================
//  Captures Enter Key for all pages
//  Performs search if enter key is pressed
//==========================================
//var isnav = window.Event ? true : false;
//if (isnav) 
//{
//   window.captureEvents(Event.KEYDOWN);
//   window.onkeydown = NetscapeEventHandler_KeyDown;
//} 
//else 
//{
//   document.onkeydown = MicrosoftEventHandler_KeyDown;
//}
//function NetscapeEventHandler_KeyDown(e) 
//{
//  	if (e.which == 13) 
//  	{ 
//  	    DoSearch("salesform");
//	} 
//	return true;
//}
//function MicrosoftEventHandler_KeyDown() 
//{
//  	if (event.keyCode == 13) 
//  	{ 
//  	    DoSearch("salesform");
//	} 
//    return true;
//}

//========================================================
//   Functions should reflect the same as in Common.HTML.cs
//========================================================
//function PhotoDiv(OriginalImageURL, LinkHREF, IdListing, Width, Height, CssClass, Quality)
//{
//	var OriginalImageDomain = OriginalImageURL.toLowerCase().replace("http://", "");
//	OriginalImageDomain = OriginalImageDomain.substring(0, OriginalImageDomain.lastIndexOf("/"));

//	var NewImageFilename = OriginalImageURL.substring(OriginalImageURL.lastIndexOf("/") + 1);
//	NewImageFilename = NewImageFilename.substring(0, NewImageFilename.lastIndexOf("."));
//	NewImageFilename = String.Format("{0}_{1}_{2}x{3}.jpg", OriginalImageDomain, NewImageFilename, Width, Height);

//    var NewImageDirectory = String.format("{0}/{1}/{2}", ClientName, PortalName, WebsiteName);
//	var ImgPath = ResizedPhotoPath(OriginalImageURL, Width, Height, NewImageFilename, NewImageDirectory, Quality);

//	return String.format("<div class=\"{0}\" style=\"background-image:url({1});\"><a href=\"{2}\"><img src=\"{3}images/spacer.gif\" width=\"{4}\" height=\"{5}\" alt=\"{6}\" border=\"0\"/></a></div>",
//	CssClass,
//	ImgPath,
//	LinkHREF,
//	WebRoot,
//	Width,
//	Height,
//	"Property Image for Listing " + IdListing);

//}

function changeme(id, action, item) {
       if (action=="hide") {
            document.getElementById("phoneOn").style.display = "block";
            document.getElementById("phoneOff").style.display = "none";
       } 
}
function togglephone(id, action, item) {
       if (action=="hide") {
            document.getElementById("toolsPhoneOn").style.display = "inline";
            document.getElementById("toolsPhoneOff").style.display = "none";
       } 
}
function toggle(obj, id) {
	var el = document.getElementById(obj);
	if ( el.style.display != 'none' ) {
		el.style.display = 'none';
	}
	else {
		el.style.display = '';
	}
}

//=====================================================================
//   Foreclosure listing function for results page OCR Specific
//=====================================================================
function foreclosurePop() {
		window.open('../../ForeClosure/fctext.html','myFC','height=250,width=400,toolbar=no,status=no,directories=no,menubar=no,resizable=no,scrollbars=no,left=0,top=0');
		//alert("Hello");
	}
//=====================================================================
//   Equal Housing Opp function for results page OCR Specific
//=====================================================================
function ehopopup() {

    // Edited by Eric Chan on 5.21.2009; open pop up in the center of the screen.
    var width = 500;
    var height = 450;
    var left = parseInt((screen.availWidth / 2) - (width / 2));
    var top = parseInt((screen.availHeight / 2) - (height / 2));

	window.open('/Foreclosure/ehotext.html','myEHO','height=' + height + ',width=' + width +',toolbar=no,location=no,statusbar=no,status=no,directories=no,menubar=no,resizable=no,scrollbars=no,left=' + left + ',top=' + top);
	//alert("Hello");
}

//=====================================================================
//  Showphone function for results page OCR Specific
//=====================================================================
function showPhone(num,obj)
{   
    var str = num;
//	if(!document.getElementById("imgTemp"))	addElement("imgTemp");

//	document.getElementById("imgTemp").src="<%'%>../components/Listing.CallForDetails.AJAXtracking.asp?cid="+cid+"&anticache="+Math.floor(Math.random()*5000)+"&ListingId="+ListingId+"&UserEmail="+UserEmail+"&ReportSection="+ReportSection+"&CampaignId="+CampaignId+"&AgentId="+AgentId;
    //alert(obj);
    if (document.getElementById(obj)) {
        //document.getElementById(obj).style.fontSize = "11px";        
        document.getElementById(obj).innerHTML = "Office: " + str;
    }
}


