//========================================================
//  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;
}


function gEDisplay(objId, display)
{
    gE(objId).style.display = display;
}

//========================================================
//   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 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);
}


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);
    }
}

//========================================================
//   Set Cookie State Through Ajax Asyncronusly
//========================================================
function SetCookieState(CookieName, Key, Value)
{
    var Query = String.format("CookieName={0}&Key={1}&Value={2}", CookieName, Key, Value); 
    var URL = WebRoot + "Controls/AjaxCalls/SetCookieState.aspx?" + Query;
    $AJAX.GetAsync(URL);
}	

//==========================================================
//  Removes cookie
//==========================================================
function RemoveCookie(CookieName)
{
    var Query = String.format("CookieName={0}", CookieName); 
    var URL = WebRoot + "Controls/AjaxCalls/RemoveCookie.aspx?" + Query;
    $AJAX.GetAsync(URL);
}	

//==================================================================
// Reads Cookie
//==================================================================
function ReadCookie(CookieName)
{
	var nameEQ = CookieName + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}	


function CookieRedirect(strName, strKey, strValue, strRedirect)
{
    //alert(String.format("Name:{0}\nKey:{1}\nValue:{2}\nRedirect:{3}", strName, strKey, escape(strValue), strRedirect));
    
    SetCookieState(strName, strKey, escape(strValue));
    window.setTimeout(function(){window.location.href = strRedirect;},250);
}


// 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";
    var newHomesID = "975576";
    var openHousesID = "1118487";

//========================================================
//   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;
//}

//========================================================
//  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;

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;
    }
}

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.addEventListener(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
        {
            if (!(navigator.userAgent.indexOf('MSIE 6.') > -1))
	        {
                //alert("Unknown Scrolling");
                this.isDefined = false;
            }
        }
        
    	
	    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();
}

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;
}

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>');
}


function EmailAgent(IdListing, Agent)
{
  $AJAX.GetForDelegate(FormDelegate, WebRoot + "Controls/AjaxCalls/EmailAgent.aspx?IdListing=" + IdListing +"&Agent=" +Agent);         
}

function EmailAgentThickBox(IdListing, Agent, EmailLeadType)
{
  if (EmailLeadType == '2')
    tb_showhtml('Email Agent', WebRoot + "Controls/AjaxCalls/EmailAgent.aspx?height=320&width=445&IdListing=" + IdListing +"&Agent=" +Agent+"&EmailLeadType=" +EmailLeadType, false);         
  else  
     tb_showhtml('Email Agent', WebRoot + "Controls/AjaxCalls/EmailAgent.aspx?height=320&width=445&IdListing=" + IdListing +"&Agent=" +Agent+"&EmailLeadType=" +EmailLeadType, false);  
}

function EmailFriend(IdListing, IdWeb,Address,AddressCityState)
{
   $AJAX.GetForDelegate(FormDelegate, WebRoot + "Controls/AjaxCalls/EmailFriend.aspx?IdListing=" + IdListing + "&IdWeb=" + IdWeb +"&Address=" +Address + "&AddressCityState=" +AddressCityState);
}

function EmailFriendThickBox(IdListing)
{
   tb_showhtml('Listing you are sharing:', WebRoot + "Controls/AjaxCalls/EmailFriend.aspx?height=453&width=470&IdListing=" + IdListing + "&PageFlag=L", false);
}

function SendSMS(IdListing)
{
   tb_showhtml('Listing you are sharing:', WebRoot + "Controls/AjaxCalls/EmailToMobile.aspx?height=300&width=355&IdListing=" + IdListing + "&PageFlag=L", false);
}
function SendEmail(emailstring)
{
  $AJAX.GetForDelegate(EmailFormDelegate, WebRoot + "SendEmail.aspx?" + emailstring);
}

function SendEmailThickbox(emailstring)
{
  tb_showhtml('', WebRoot + "SendEmail.aspx?" + emailstring + "&height=100&width=450", false);
  if(emailstring.indexOf("emailto=friend") > -1)
  {
      window.setTimeout("tb_remove();", 4000);
  }
}

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 ValidateEmailMobile(theForm)
{

if (theForm.myAreaCode.value == "")
  {
   gE("num_valid").style.display = "block";
   gE("num_valid").innerHTML = "Please enter your 3 digit area code.";
   gE("num_h3").style.color = "#A41d21";
    theForm.myAreaCode.focus();
    return (false);
  }
  else{
   gE("num_valid").style.display = "none";
       gE("num_h3").style.color = "#575744";
  }
  
    if (theForm.myAreaCode.value.length < 3)
  {
     gE("num_valid").style.display = "block";
   gE("num_valid").innerHTML = "Please enter at least 3 numbers in the area code field.";
   gE("num_h3").style.color = "#A41d21";
    theForm.myAreaCode.focus();
    return (false);
  }
   else{
   gE("num_valid").style.display = "none";
       gE("num_h3").style.color = "#575744";
  } 

        
  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)
  {
     gE("num_valid").style.display = "block";
   gE("num_valid").innerHTML = "Please enter only numbers in the area code field.";
   gE("num_h3").style.color = "#A41d21";
    theForm.myAreaCode.focus();
    return (false);
  }
  else{
   gE("num_valid").style.display = "none";
       gE("num_h3").style.color = "#575744";
  }


if (theForm.myFirst3Digits.value == "")
  {
    gE("num_valid").style.display = "block";
   gE("num_valid").innerHTML = "Please enter the first 3 digits of your mobile phone.";
   gE("num_h3").style.color = "#A41d21";
    theForm.myFirst3Digits.focus();
    return (false);
  }
  else{
   gE("num_valid").style.display = "none";
       gE("num_h3").style.color = "#575744";
  }

  if (theForm.myFirst3Digits.value.length < 3)
  {
     gE("num_valid").style.display = "block";
   gE("num_valid").innerHTML = "Please enter at least 3 numbers as the first 3 digits of your mobile phone.";
   gE("num_h3").style.color = "#A41d21";
    theForm.myFirst3Digits.focus();
    return (false);
  }
    else{
   gE("num_valid").style.display = "none";
       gE("num_h3").style.color = "#575744";
  }
  
  
    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)
  {
     gE("num_valid").style.display = "block";
   gE("num_valid").innerHTML = "Please enter only numbers as the first three numbers of your mobile phone.";
   gE("num_h3").style.color = "#A41d21";
    theForm.myFirst3Digits.focus();
    return (false);
  }
  else{
   gE("num_valid").style.display = "none";
       gE("num_h3").style.color = "#575744";
  }

if (theForm.myLast4Digits.value == "")
  {
     gE("num_valid").style.display = "block";
   gE("num_valid").innerHTML = "Please enter the last 4 digits of your mobile phone.";
   gE("num_h3").style.color = "#A41d21";
    theForm.myLast4Digits.focus();
    return (false);
  }
  else{
   gE("num_valid").style.display = "none";
       gE("num_h3").style.color = "#575744";
  }
  
  if (theForm.myLast4Digits.value.length < 4)
  {
     gE("num_valid").style.display = "block";
   gE("num_valid").innerHTML = "Please enter at least 4 numbers as the last 4 digits of your mobile phone.";
   gE("num_h3").style.color = "#A41d21";
    theForm.myLast4Digits.focus();
    return (false);
  }
    else{
   gE("num_valid").style.display = "none";
       gE("num_h3").style.color = "#575744";
  }
  
    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)
  {
     gE("num_valid").style.display = "block";
   gE("num_valid").innerHTML = "Please enter only numeric characters as the last four numbers of your mobile phone.";
     gE("num_h3").style.color = "#A41d21";
    theForm.myLast4Digits.focus();
    return (false);
  }
  else{
   gE("num_valid").style.display = "none";
    gE("num_h3").style.color = "#575744";
  }

  if (theForm.provider.value == "x")
  {
     gE("provider_valid").style.display = "block";
   gE("provider_valid").innerHTML = "Please choose a provider for your mobile phone.";
    gE("provider_h3").style.color = "#A41d21";
    theForm.myLast4Digits.focus();
    return (false);
  }
    else{
   gE("provider_valid").style.display = "none";
       gE("provider_h3").style.color = "#575744";
  }
    	if (theForm.accept_terms.checked == false)
	{
		 gE("terms_valid").style.display = "block";
  gE("terms_valid").innerHTML = "Please accept the Terms and Conditions";
   gE("accept_terms_label").style.color = "#A41d21";
		theForm.accept_terms.focus();
		return (false);
	}
      else{
   gE("terms_valid").style.display = "none";
    gE("accept_terms_label").style.color = "#575744";
  }
    var myAreaCode = theForm.myAreaCode.value;
    var myFirst3Digits = theForm.myFirst3Digits.value;
    var myLast4Digits = theForm.myLast4Digits.value;
    var toEmailAddress = theForm.myAreaCode.value + theForm.myFirst3Digits.value + theForm.myLast4Digits.value + "@" + theForm.provider.value;
    SendEmailThickbox("PageFlag=" + theForm.PageFlag.value + "&IdListing=" + theForm.IdListing.value + "&EmailFriendAddress=" + toEmailAddress +"&myAreaCode=" + myAreaCode + "&myFirst3Digits=" + myFirst3Digits + "&myLast4Digits=" + myLast4Digits + "&emailto=mobile");
    return(true);
}



function ValidateEmailFriend(theForm)
{
    if (theForm.flName.value == "")
    {
        //alert("Please enter your name.");
        var errorElem = document.getElementById( 'flNameError' );
        errorElem.style.display = 'block';
        theForm.flName.focus();
        return (false);
    }
    else
    {    
        var errorElem = document.getElementById( 'flNameError' );
        errorElem.style.display = 'none';
    }
    
    var errorElem = document.getElementById( 'EmailAddressError' );
    if (theForm.EmailAddress.value == "")
    {
        //alert("Please enter your email address.");
        errorElem.style.display = 'block';
        theForm.EmailAddress.focus();
        return (false);
    }
    else
    {
        errorElem.style.display = 'none';
    }
    var addFlag = validateEmail(theForm.EmailAddress, errorElem, "Please enter a valid e-mail address.");
    if(!addFlag)
    {
        return (false);
    }

    if (theForm.NameFriend.value == "")
    {
        //alert("Please enter your Friend's name.");
        var errorElem = document.getElementById( 'NameFriendError' );
        errorElem.style.display = 'block';
        theForm.NameFriend.focus();
        return (false);
    }
    else
    {
        var errorElem = document.getElementById( 'NameFriendError' );
        errorElem.style.display = 'none';
    }
            
    if (theForm.EmailFriendAddress.value == "")
    {
       // alert("Please enter your Friend's email address.");
        var errorElem = document.getElementById( 'EmailFriendAddressError' );
        errorElem.style.display = 'block';
        theForm.EmailFriendAddress.focus();
        return (false);
    }
    else
    {
        var errorElem = document.getElementById( 'EmailFriendAddressError' );
        errorElem.style.display = 'none';
    }
    var addrss = theForm.EmailFriendAddress.value;
    theForm.EmailFriendAddress.value = addrss.replace(";",",");
     var addFlag = validateEmail(theForm.EmailFriendAddress, errorElem, "Please enter a valid e-mail address.");
    if(!addFlag)
    {
        return (false);
    }
//    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 = 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);
  	    }
    }
    SendEmailThickbox("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");
    return(true);
}






function ValidateEmailAgent(theForm)
{
    var EmailLeadType = theForm.EmailLeadType.value;
    if (theForm.YourName.value == "")
    {
        gE("name_valid").style.display = "block";
        gE("name_valid").innerHTML = "Please enter your name.";
        //alert("Please enter your first name.");
        theForm.YourName.focus();
        return (false);
    }
    else {
    gE("name_valid").style.display = "none";
    }
    if (theForm.EmailAddress.value == "")
    {
       // alert("Please enter your email address.");
       gE("email_valid").style.display = "block";
       gE("email_valid").innerHTML = "Please enter your email address.";
        theForm.EmailAddress.focus();
        return (false);
    }

    var addFlag = validateEmail(theForm.EmailAddress, errorElem, "Please enter a valid e-mail address.");
    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 = 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)
  	    {
    	    gE("name_valid").innerHTML ="Please enter only letter, digit, whitespace and \"@%*$/:)(#_&-+!.;,<=^> \" characters in the \"Message\" field.";
    	    document.theForm.Message.focus();
    	    return (false);
  	    }
      }
      if (EmailLeadType == "2")
      {
         SendEmailThickbox("IdListing=" + theForm.IdListing.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");
      }
      else
      {
//         SendEmailThickbox("IdListing=" + theForm.IdListing.value  + "&EmailAddress=" + theForm.EmailAddress.value + "&Phone=" + theForm.Phone.value + "&Extension=" + theForm.Extension.value + "&Message=" + theForm.Message.value + "&YourName=" + theForm.YourName.value + "&emailto=agent");
SendEmailThickbox("IdListing=" + theForm.IdListing.value  + "&EmailAddress=" + theForm.EmailAddress.value +  "&Message=" + theForm.Message.value + "&YourName=" + theForm.YourName.value + "&emailto=agent");
//alert("sending thickbox");
      }           
   return (true);
}

// 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 "";    
}

	//========================================================
	//   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);
}



//================================================================
//  Displays full list of news articles
//================================================================
function DisplayMoreArticles()
			{
			    document.getElementById("show_more_articles").style.display = "none";
			    document.getElementById("more_articles").style.display = "block";
			}
//================================================================
//  Closes full list of news articles
//================================================================
function DisplayFewerArticles()
			{
			    document.getElementById("show_more_articles").style.display = "block"; 
			    document.getElementById("more_articles").style.display = "none";
			}

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 %>");
}


//================================================================
//  Writes unspamable email address 
//================================================================
function emailit(whoto,domainto,title,subject,displayname)
{
	if (domainto == null || domainto == '') {domainto = 'frontdoor.com';}
	var writeit = whoto + '@' + domainto;
	if (displayname == null || displayname == '') {displayname = writeit;}
	
	if (subject == null || subject == '') {
		document.write("<a href='mailto:"+writeit+"' title='"+title+"'>"+displayname+"</a>");
	}
	else {
		document.write("<a href='mailto:"+writeit+"?subject="+subject+"' title='"+title+"'>"+displayname+"</a>");
	}
}


//================================================================
//  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;
}

//===================================================
//Opens virtual tour window
//===================================================
function openVT(vtUrl){
    window.open("/virtualTour.aspx?vtUrl=" + escape(vtUrl),"virtualTourWindow", "status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=1,channelmode=yes|1,scrollbars=0,height=555,width=600");
}

//===================================================
//Open link to an external web page
//===================================================
function goExternal(extUrl) {
    extUrl = unescape(extUrl);
    window.open(extUrl, "FrontDoorExternal");
}
            
//===================================================
//Open and close tab dropdowns
//===================================================

function openBuyDropdown(){
gE("buy-dropdown").style.display ="block";
gE("close-buy-dropdown").style.display ="block";
gE("sell-dropdown").style.display ="none";
gE("close-sell-dropdown").style.display ="none";
gE("guides-dropdown").style.display ="none";
gE("close-guides-dropdown").style.display ="none";
gE("city-dropdown").style.display ="none";
gE("close-city-dropdown").style.display ="none";
gE("nav_buy_url").className ="buyActive";
gE("nav_sell_url").className ="";
gE("nav_guides_url").className ="";
gE("nav_city_url").className ="";
//gE("searchbardiv").style.zIndex ="999995";
//gE("my_fd_options_rt").style.zIndex ="999995";
}

function closeBuyDropdown(){
gE("buy-dropdown").style.display ="none";
gE("close-buy-dropdown").style.display ="none";
gE("nav_buy_url").className ="";
//gE("searchbardiv").style.zIndex ="999999";
//gE("my_fd_options_rt").style.zIndex ="999999";
}

function openSellDropdown(){
gE("sell-dropdown").style.display ="block";
gE("close-sell-dropdown").style.display ="block";
gE("buy-dropdown").style.display ="none";
gE("close-buy-dropdown").style.display ="none";
gE("guides-dropdown").style.display ="none";
gE("close-guides-dropdown").style.display ="none";
gE("city-dropdown").style.display ="none";
gE("close-city-dropdown").style.display ="none";
gE("nav_buy_url").className ="";
gE("nav_sell_url").className ="sellActive";
gE("nav_guides_url").className ="";
gE("nav_city_url").className ="";

//gE("searchbardiv").style.zIndex ="999995";
//gE("my_fd_options_rt").style.zIndex ="999995";
}

function closeSellDropdown(){
gE("sell-dropdown").style.display ="none";
gE("close-sell-dropdown").style.display ="none";
gE("nav_sell_url").className ="";
//gE("searchbardiv").style.zIndex ="999999";
//gE("my_fd_options_rt").style.zIndex ="999999";
}

function openGuidesDropdown(){
gE("guides-dropdown").style.display ="block";
gE("close-guides-dropdown").style.display ="block";
gE("buy-dropdown").style.display ="none";
gE("close-buy-dropdown").style.display ="none";
gE("sell-dropdown").style.display ="none";
gE("close-sell-dropdown").style.display ="none";
gE("city-dropdown").style.display ="none";
gE("close-city-dropdown").style.display ="none";
gE("nav_buy_url").className ="";
gE("nav_sell_url").className ="";
gE("nav_guides_url").className ="guidesActive";
gE("nav_city_url").className ="";
//gE("searchbardiv").style.zIndex ="999995";
//gE("my_fd_options_rt").style.zIndex ="999995";
}

function closeGuidesDropdown(){
gE("guides-dropdown").style.display ="none";
gE("close-guides-dropdown").style.display ="none";
gE("nav_guides_url").className ="";
//gE("searchbardiv").style.zIndex ="999999";
//gE("my_fd_options_rt").style.zIndex ="999999";
}

function openCityDropdown(){
gE("city-dropdown").style.display ="block";
gE("close-city-dropdown").style.display ="block";

gE("buy-dropdown").style.display ="none";
gE("close-buy-dropdown").style.display ="none";
gE("sell-dropdown").style.display ="none";
gE("close-sell-dropdown").style.display ="none";
gE("guides-dropdown").style.display ="none";
gE("close-guides-dropdown").style.display ="none";

gE("my_fd_options_rt").style.display ="none";
gE("loggedin").className ="";

gE("nav_buy_url").className ="";
gE("nav_sell_url").className ="";
gE("nav_guides_url").className ="";
gE("nav_city_url").className ="cityActive";

//gE("searchbardiv").style.zIndex ="999995";
//gE("my_fd_options_rt").style.zIndex ="999995";
} 
function closeCityDropdown(){
gE("city-dropdown").style.display ="none";
gE("close-city-dropdown").style.display ="none";
gE("nav_city_url").className ="";
//gE("searchbardiv").style.zIndex ="999999";
//gE("my_fd_options_rt").style.zIndex ="999999";
} 

function CapFirstLetterPhrase(Phrase)
{
    Phrase = trim(Phrase);
	Phrase = Phrase.replace('/ +/', ' ');
	var Parts = Phrase.split(' ');
	if (Parts.length == 1)
	{
		return CapFirstLetter(Phrase);
	}
	var P = new Array();
	for ( var i = 0; i < Parts.length; i++)
	{
		P.push(CapFirstLetter(Parts[i]));
	}
	return P.join(" ");
}

function CapFirstLetter(Phrase)
{
	Phrase = trim(Phrase).toLowerCase();
	if (Phrase.length < 2)
	{
		return Phrase.toUpperCase();
	}
	return Phrase.substr(0, 1).toUpperCase()+ Phrase.substr(1);
}

function isZip(s) {

    reZip = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);

    if (!reZip.test(s)) {
        return false;
    }

    return true;
}


//===================================================
//Toggle Map and List View on the results page
//===================================================

// This function will toggle the data needed on the results page.
// Written by Joey Avino
// Email: javino@gabriels.net

function toogle_map_view(is_map) {

        var id_listing = 'listing_';
        var id_map = $('#map_view');
        var id_list = $('#list_view');
        var id_map_header = $('#map_header');
        var id_sort_selection = $('#listings_sort_selection');
        var id_pag_results = $('#results_header #status h2');
        var id_pagination1 = $('#pagingtop');
        var id_pagination2 = $('#pagingbottom');
        var listArr = new Array();
        //Give total_listings dynamic count.
        var total_listings = 0;
        listArr = getElemsByClass('div', 'results');
        for(var i=0; i<listArr.length; i++){
            if(listArr[i].id.indexOf('listing_') > -1){
                total_listings++
            }
        }
        
        var id_btm_ad_unit = $('#BIGBOX2_wrapper');
        var currentmapstate = 'notfound';
        if (MapState != null) { if(MapState.Current!=null && MapState.Current!='undefined') {currentmapstate = MapState.Current; }     }          
        if (is_map || currentmapstate != 'map_hidden') {

            // Hide the results divs.
           for (var i = 0; i <= total_listings; i++)
           {
            if (gE(id_listing+i) != null) gE(id_listing+i).style.display = 'none';                 
           }

            // Show the map header.
            id_map_header.css('display', 'block');
            
            // Hide pagination stuff.
           // id_pag_results.css('visibility', 'hidden');
            id_pagination1.css('display', 'none');
            id_pagination2.css('display', 'none');

            // Remove sorting optoins.
           // id_sort_selection.css('display', 'none');

            // Toggle class on/off for map.
            id_map.removeClass('map_off');
            id_map.addClass('map_on');

            // Toggle class on/off for list.
            id_list.addClass('list_off');
            id_list.removeClass('list_on');
            
            // Hides the ad at bottom of page.
            id_btm_ad_unit.css('display', 'none');
            
        }

        else {

            // Show the results divs.
            for (var i = 0; i <= total_listings; i++)
            if (gE(id_listing+i) != null){
                 gE(id_listing+i).style.display = 'block';}

            // Show the map header.
            id_map_header.css('display', 'none');

            // Show pagination stuff.
            id_pag_results.css('visibility', 'visible');
            id_pagination1.css('display', 'block');
            id_pagination2.css('display', 'block');

            // Re-add sorting optoins.
            id_sort_selection.css('display', 'block');

            // Toggle class on/off for map.
            id_map.removeClass('map_on');
            id_map.addClass('map_off');

            // Toggle class on/off for list.
            id_list.addClass('list_on');
            id_list.removeClass('list_off');

            // Shows the ad at bottom of page.
            id_btm_ad_unit.css('display', 'block');

        }

    }

//================================================================
//  Returns obj arr for elemenets with specified class name
//  Byron Matto 8/10/2009
//================================================================
function getElemsByClass(tag, name){
    var elemArr = new Array();
    var classArr = new Array();
    elemArr = document.getElementsByTagName(tag);
    
    for(var i=0; i<elemArr.length; i++){
        if(elemArr[i].className.indexOf(name) > -1){
            classArr.push(elemArr[i]);
        }
    }
    return classArr;
}

function setImgHxW(maxW, maxH, image) {
    // <image onload=”setImgHxW(222,297,this)” …/>
    var imageH = image.height;
    var imageW = image.width;

    if (imageH > maxH || imageW > maxW) {
        if (imageH > imageW) {
            //vert
            imageW = (imageW * maxH) / imageH;
            imageH = maxH;
        } else {
            //horz
            imageH = (imageH * maxW) / imageW;
            imageW = maxW;
        }
    }
    image.height = imageH;
    image.width = imageW;
}

function FormatDate(strdate)
{
    var date = strdate.substr(4,2)  + '/' +  strdate.substr(6,2) + '/' + strdate.substr(0,4);
    return date;
}

function validateTheDiv(imageid)
{
    if (gE("gallery_view").style.display == "block")
    {
           setImgHxW(300,225,imageid);
    }
}