//-------------------------------------//
//      Customs Controls global JS.
//-------------------------------------//

//----------------------------------------------------//
//------------- GLOBAL WEB TESTS SCRIPT --------------//
//----------------------------------------------------//

//US-886 header countdown free trial
function renderHeader() {
    var SH_COMMUNITY_DOMAIN = 'community.realtytrac.com';
    var SH_COMMUNITY_DOMAIN_DEV1 = 'dev.community.realtytrac.com';
    var SH_COMMUNITY_DOMAIN_DEV2 = 'local.community.realtytrac.com';
    var SH_COMMUNITY_DOMAIN_INT = 'int.community.realtytrac.com';
    var SH_COMMUNITY_DOMAIN_QA = 'qa.community.realtytrac.com';
    var customDomain = '';
	var serverName = '';
    var curLocation = location.href.toLowerCase();
    if (curLocation.indexOf(SH_COMMUNITY_DOMAIN) > -1) {
		if (curLocation.indexOf(SH_COMMUNITY_DOMAIN_DEV1) > -1 || curLocation.indexOf(SH_COMMUNITY_DOMAIN_DEV2) > -1) {
			customDomain = '//dev.community.realtytrac.com';
			serverName = '//dev';
		}
		else if (curLocation.indexOf(SH_COMMUNITY_DOMAIN_INT) > -1) {
			customDomain = '//int.community.realtytrac.com';
			serverName = '//int';
		}
		else if (curLocation.indexOf(SH_COMMUNITY_DOMAIN_QA) > -1) {
			customDomain = '//qa.community.realtytrac.com';
			serverName = '//qa';
		}
		else {
			customDomain = '//www.realtytrac.com';
			serverName = '//www.realtytrac.com';
			var headerTagHelper = '<iframe width="100%" marginheight="0" marginwidth="0" style="margin-top:0px;" height="0" scrolling="no" frameborder="0" id="frmCommHeaderHelper" name="frmCommHeaderHelper" src="' + serverName + '/communityheaderhelper.htm"></iframe>';
			$(headerTagHelper).prependTo('body');
			return false;
		}
		if (customDomain.length > 0) {
			customDomain = window.location.protocol + customDomain;
			serverName = window.location.protocol + serverName;
		}
	}
	try{
		var rand = Math.random() * 999999;
		$.getJSON(customDomain + "/geo/header/getusercontext?/2313/callback=?/" + rand + "/",
			function (usercontext) {
				//alert(usercontext.ProductContext.is3DayTrial);
				if (usercontext.ProductContext != null) {
					if (usercontext.ProductContext.is3DayTrial) {
						var renderCountdown = '';
						var isexpiration = false;
						var n = parseFloat(usercontext.ProductContext.TimeCountdown);
						if (n >= 0) {
							var dtm = new Date();
							dtm.setTime(n);
							//var d = Math.floor(n / 3600000 / 24);
							var h = Math.floor(n / 3600000); // Total hours
							//var m = dtm.getMinutes();
								//var s = dtm.getSeconds();
								//var cs = Math.round(dtm.getMilliseconds() / 10);

							if (h >= 48 && h <= 72)
								renderCountdown = "3 days.";
							else if (h >= 24 && h < 48)
								renderCountdown = "2 days.";
							else if (h < 24 && h > 0)
								renderCountdown = h + " hours.";
							else
								renderCountdown = "less than 1 hour.";
							if (h == 1)
								renderCountdown = h + " hour.";
						}
						else {
							isexpiration = true;
							renderCountdown = "expired.";
						}
						var headerTag = '<iframe width="100%" marginheight="0" marginwidth="0" style="margin-top:0px;" height="43" scrolling="no" frameborder="0" id="frmCountdown" name="frmCountdown" src="' + serverName + '/HeaderMessage.htm?isexpiration=' + isexpiration + '&message=' + renderCountdown + '"></iframe>';
						$(headerTag).prependTo('body');
					}
				}
			}
		);
	}
	catch(e){
		var err = '<input type="hidden" value="Header countdown message can\'t show because: '+ e.message +'"/>';
		$(err).prependTo('body');
	}
    
}

function resizeHeaderMessage() {
	$('#frmCommHeaderHelper').attr('height','43');
}

//alway show when page include customcontrol.js
$(document).ready(function() {  
	if (window.location.href.toLowerCase().indexOf("/rtracweb/doubleclickbanner.aspx") == -1 &&
	window.location.href.toLowerCase().indexOf("/profile/billinginfov2.aspx") == -1) {
		renderHeader();
	}
});


function ProcessWebTests() {
    try {
        if (typeof (gRTTests) != 'undefined' && gRTTests != null && gRTTests.length > 0) {
            for (var i = 0; i < gRTTests.length; i++) {
                if (gRTTests[i].E) {
                    if (typeof (gRTTests[i].S) != 'undefined' && gRTTests[i].S != '') {
                        $.getScript(gRTTests[i].S);
                    }
                    else {
                        $('.' + gRTTests[i].N.toLowerCase()).each(
                            function () {
                                if ($(this).hasClass('original')) {
                                    $(this).remove();
                                }
                                else if ($(this).hasClass('variation')) {
                                    $(this).show();
                                }
                            });
                    }
                }
                else {
                    $('.' + gRTTests[i].N.toLowerCase()).each(
                        function () {
                            if ($(this).hasClass('variation')) {
                                $(this).remove();
                            }
                        });
                }
            }
        }
    }
    catch (e) { }
}

function ProcessWebTestsASP(webTestsData) {
    if (webTestsData != null && webTestsData.length > 0) {
        gRTTests = new Array();
        var t = null;
        for (var i = 0; i < webTestsData.length; i++) {
            t = new Object();
            t.N = webTestsData[i].Name;
            t.S = webTestsData[i].ScriptPath;
            t.E = webTestsData[i].Enabled;

            gRTTests.push(t);
        }

        ProcessWebTests();
    }
}

if (typeof (gUseASPEvents) != "undefined" && gUseASPEvents) // determine ASP Pages
{
    $.getJSON("/geo/header/getwebtests?callback=?",
        ProcessWebTestsASP);
}
else {
    ProcessWebTests();
}
//----------------------------------------------------//
//----------------- GLOBAL VARIABLES -----------------//
//----------------------------------------------------//

var g_IsFocusOnHeader = false;
var g_HeaderControlHelper;
var g_HeaderSearchBoxFunction;
var g_PassportKey = "";
var g_IsWhiteSite = false;
var g_HeaderEngine;
var g_BirdsEyeDataHelper;
var g_ToggleActiveImageEvent = [];
var g_AppContextHelper = null;
var g_PeelAdsEnable = false;
var g_PeelAdsAcrossAll = false;

//----------------------------------------------------//
//----------------- GLOBAL FUNCTIONS -----------------//
//----------------------------------------------------//

//---- Add load Event
//---- param: function
//---- summary: Adds function to onload event.
//---- Allows to load controls after page is loaded
function addLoadEvent(func) {
    if (func) {
        var oldonload = window.onload;
        if (typeof window.onload != 'function') {
            window.onload = function () {
                func();
                g_onLoadCalled = true;
            };
        }
        else {
            window.onload = function () {
                oldonload();
                func();
                g_onLoadCalled = true;
            };
        }
    }

    if (typeof (CallBirdsEyeAvailabilityCallback) != 'undefined') {
        addBirdsEyeUpdateEvent();
    }
}

function addBirdsEyeUpdateEvent() {
    if (typeof (Sys) !== 'undefined') {
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        prm.add_pageLoaded(pageLoaded);
    }
}

function pageLoaded(args) {
    if (typeof (g_onLoadCalled) !== 'undefined' && !g_onLoadCalled) {
        LoadBirdsEyeControl();
    }
    g_onLoadCalled = false;
}
//---- Close popup
function closePopup() {
    document.getElementById("popupOverlay").style.display = "none";
    document.getElementById("popupContainer").style.display = "none";
}
//---- Cookies
//---- summary: GET/SET/DELETE cookies
function SetCookie(psName, psValue, piExpires, psPath, psDomain, psSecure) {
    var ldToday = new Date();
    ldToday.setTime(ldToday.getTime());

    if (piExpires) { piExpires = piExpires * 1000 * 60 * 60 * 24; }
    var ldExpiresDate = new Date(ldToday.getTime() + (piExpires));

    document.cookie = psName + "=" + escape(psValue) +
				    ((piExpires) ? ";expires=" + ldExpiresDate.toGMTString() : "") +
				    ((psPath) ? ";path=" + psPath : "") +
				    ((psDomain) ? ";domain=" + psDomain : "") +
				    ((psSecure) ? ";secure" : "");
}

function GetCookie(psName) {
    var liStart = document.cookie.indexOf(psName + "=");
    var liLen = liStart + psName.length + 1;
    if ((!liStart) && (psName != document.cookie.substring(0, psName.length))) { return null; }
    if (liStart == -1) { return null; }
    var liEnd = document.cookie.indexOf(";", liLen);
    if (liEnd == -1) {
        liEnd = document.cookie.length;
    }
    return unescape(document.cookie.substring(liLen, liEnd));
}

function DeleteCookie(psName, psPath, psDomain) {
    if (fnGetCookie(psName)) {
        document.cookie = psName + "=" +
	    ((psPath) ? ";path=" + psPath : "") +
	    ((psDomain) ? ";domain=" + psDomain : "") +
	    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
    }
}

//---- Enter Submit
//---- summary: check if enter pressed, than proceed "toDoEvent".
EnterSubmit = function (e, toDoEvent) {
    if (e && e.which) {
        characterCode = e.which;
    }
    else {
        characterCode = e.keyCode;
    }
    if (characterCode == 13) {
        if (toDoEvent) {
            eval(toDoEvent);
        }
    }

    return false;
};

//--- Resize Image
function ResizeImage(loImage, maxWidth, maxHeight) {
    if (loImage) {
        if ((loImage.height > maxHeight) && (loImage.width > maxWidth)) {
            loImage.height = maxHeight;
            loImage.width = maxWidth;
        }
        if ((loImage.height > maxHeight) && (loImage.width < maxWidth)) {
            loImage.height = maxHeight;
        }
        if ((loImage.height < maxHeight) && (loImage.width > maxWidth)) {
            loImage.width = maxWidth;
        }
    }
}

function IsAddressEmpty(address) {
    if (address != null) {
        address = address.replace(/^\s+|\s+$/g, "");
        if (!(address.toLowerCase() == DEFAULT_SEARCH_TEXT.toLowerCase() || address == "")) {
            return false;
        }
    }
    return true;
}

//-----------------------------------------------------------//
//----------------- END GLOBAL FUNCTIONS --------------------//
//-----------------------------------------------------------//

//----------------------------------------------------//
//----------------- BIRDS EYE CONTROL ----------------//
//----------------------------------------------------//

function LoadBirdsEyeControl() {
    if (typeof (g_BirdsEyeDataHelper) != "undefined" && g_BirdsEyeDataHelper != null) {
        LoadBirdsEyeControlV2();
    }
    else {
        if (typeof (CallBirdsEyeAvailabilityCallback) != 'undefined') {
            CallBirdsEyeAvailabilityCallback(-1);
        }
    }
}

// Class that we register on page load to get birdseye data (g_BirdsEyeDataHelper)
function BirdsEyeDataHelper(whiteSiteUpgrade, propertyID, latitude, longitude, hideBirdsEye, hidePhotosTab, hideMapTab, displayAerialView,
    price, upsellImageURL, upsellBYImageURL, upsellImageLink) {
    this.WhiteSiteUpgrade = whiteSiteUpgrade;
    this.PropertyID = (typeof (propertyID) == "undefined") ? 0 : propertyID;
    this.Latitude = (typeof (latitude) == "undefined") ? 0 : latitude;
    this.Longitude = (typeof (longitude) == "undefined") ? 0 : longitude;
    this.HideBirdsEye = (typeof (hideBirdsEye) == "undefined") ? false : hideBirdsEye;
    this.HidePhotosTab = (typeof (hidePhotosTab) == "undefined") ? false : hidePhotosTab;
    this.HideMapTab = (typeof (hideMapTab) == "undefined") ? false : hideMapTab;
    this.DisplayAerialView = (typeof (displayAerialView) == "undefined") ? false : displayAerialView;
    this.Price = (typeof (price) == "undefined") ? 0 : price;
    this.UpsellImageURL = (typeof (upsellImageURL) == "undefined") ? '' : upsellImageURL;
    this.UpsellBYImageURL = (typeof (upsellBYImageURL) == "undefined") ? '' : upsellBYImageURL;
    this.UpsellImageLink = (typeof (upsellImageLink) == "undefined") ? '' : upsellImageLink;
}

function LoadBirdsEyeControlV2() {
    if (typeof (RealtyTrac.BirdsEyeImage.Web.BirdsEyeDataService) != "undefined" && typeof (RealtyTrac.BirdsEyeImage.Web.BirdsEyeDataService.GetBirdsEyeJSData) != "undefined"
       && typeof (g_BirdsEyeDataHelper) != "undefined" && g_BirdsEyeDataHelper != null) {
        RealtyTrac.BirdsEyeImage.Web.BirdsEyeDataService.GetBirdsEyeJSData(g_BirdsEyeDataHelper.WhiteSiteUpgrade,
            g_BirdsEyeDataHelper.PropertyID, g_BirdsEyeDataHelper.Latitude, g_BirdsEyeDataHelper.Longitude,
            g_BirdsEyeDataHelper.HideBirdsEye, g_BirdsEyeDataHelper.HidePhotosTab, g_BirdsEyeDataHelper.HideMapTab,
            g_BirdsEyeDataHelper.DisplayAerialView, g_BirdsEyeDataHelper.Price, g_BirdsEyeDataHelper.UpsellImageURL,
            g_BirdsEyeDataHelper.UpsellBYImageURL, g_BirdsEyeDataHelper.UpsellImageLink, LoadBirdsEyeControl_Continue);
    }
}

function LoadBirdsEyeControl_Continue(birdsEyeDataResponse) {
    if (typeof (birdsEyeDataResponse) != "undefined" && birdsEyeDataResponse != null) {
        if (typeof (birdsEyeDataResponse.d) != "undefined") {
            birdsEyeDataResponse = birdsEyeDataResponse.d;
        }

        InitBEVariables(birdsEyeDataResponse);
        BIInitializeControl();
    }
}

function InitBEVariables(birdsEyeDataResponse) {
    g_BI_hasNorthView = GetSafeBirdsEyeParameter(birdsEyeDataResponse.HasNorthView, false);
    g_BI_hasEastView = GetSafeBirdsEyeParameter(birdsEyeDataResponse.HasEastView, false);
    g_BI_hasSouthView = GetSafeBirdsEyeParameter(birdsEyeDataResponse.HasSouthView, false);
    g_BI_hasWestView = GetSafeBirdsEyeParameter(birdsEyeDataResponse.HasWestView, false);

    g_BI_hasPropertyPhotos = GetSafeBirdsEyeParameter(birdsEyeDataResponse.HasPropertyPhotos, false);
    g_BI_hasBirdsEye = GetSafeBirdsEyeParameter(birdsEyeDataResponse.HasBirdsEye, false);

    g_BI_propertyPhotos = GetSafeBirdsEyeParameter(birdsEyeDataResponse.PropertyPhotos, new Array());
    g_BI_upsellImageLink = GetSafeBirdsEyeParameter(birdsEyeDataResponse.UpsellImageLink, "");
    g_BI_upsellBYPhoto = GetSafeBirdsEyeParameter(birdsEyeDataResponse.UpsellBYPhoto, "");

    g_BI_isMember = GetSafeBirdsEyeParameter(birdsEyeDataResponse.IsMember, false);

    g_BI_PropertyID = GetSafeBirdsEyeParameter(birdsEyeDataResponse.PropertyID, 0);

    g_BI_Longitude = GetSafeBirdsEyeParameter(birdsEyeDataResponse.Longitude, 0);
    g_BI_Latitude = GetSafeBirdsEyeParameter(birdsEyeDataResponse.Latitude, 0);

    g_BI_DisplayAerialView = GetSafeBirdsEyeParameter(birdsEyeDataResponse.DisplayAerialView, false);

    g_BI_DisplaySatelite = GetSafeBirdsEyeParameter(birdsEyeDataResponse.DisplaySatelite, false);

    g_BI_PropertyPrice = GetSafeBirdsEyeParameter(birdsEyeDataResponse.Price, 0);

    g_BI_isGuestMember = GetSafeBirdsEyeParameter(birdsEyeDataResponse.IsGuestMember, false);
    g_BI_isCancelledMember = GetSafeBirdsEyeParameter(birdsEyeDataResponse.IsCancelledMember, false);

    g_BI_RegistrationPage = GetSafeBirdsEyeParameter(birdsEyeDataResponse.RegistrationPage, "");
    g_BI_UpgradePage = GetSafeBirdsEyeParameter(birdsEyeDataResponse.UpgradePage, "");
    g_BI_EditProfilePage = GetSafeBirdsEyeParameter(birdsEyeDataResponse.EditProfilePage, "");
}

function GetSafeBirdsEyeParameter(value, defaultValue) {
    if (typeof (value) != "undefined" && value != null) {
        return value;
    }
    else {
        return defaultValue;
    }
}

//---global vars
//old file: BirdsEyeGlobalVariables.js
// Global variables declaration for the birdseye image control
var g_BI_ViewPoints;
var g_BI_Zooms;
var g_BI_BaseImagePath;
var g_BI_BaseImagePostfix;
var g_BI_ImageNA;
var g_BI_hasAerial;
// toggle buttons
var g_BI_northView;
var g_BI_eastView;
var g_BI_southView;
var g_BI_westView;
var g_BI_zoomIn;
var g_BI_zoomOut;
// property photo browsing
var g_BI_propertyPhotoBrowser = new Array();
// tabs
var g_BI_MapTab;
var g_BI_PhotoTab;
var g_BI_VideoTab;
var g_BI_BirdsEyeTab;
// .NET
var g_BI_hasNorthView;
var g_BI_hasEastView;
var g_BI_hasSouthView;
var g_BI_hasWestView;
var g_BI_hasPropertyPhotos;
var g_BI_hasPropertyVideo;
var g_BI_hasBirdsEye;
var g_BI_propertyPhotos;
var g_BI_propertyVideo;
var g_BI_upsellImageLink;
var g_BI_upsellBYPhoto;

var g_BI_isMember;
var g_BI_isGuestMember;
var g_BI_isCancelledMember;

var g_BI_Longitude;
var g_BI_Latitude;
var g_BI_DisplayAerialView;
var g_BI_DisplaySatelite;

var g_BI_PropertyPrice;

var g_BI_IsBirdsEyeActive = false;

var g_BI_RegistrationPage;
var g_BI_UpgradePage;
var g_BI_EditProfilePage;

var g_isSearchTrends = false;

function GetBirdsEyeSettings(settingName, settings) {
    var i;
    var result = false;

    for (i = 0; i < settings.length; i++) {
        if (settings[i].indexOf("=") > 0) {
            var optionName = settings[i].substring(0, settings[i].indexOf("="));
            var optionValue = settings[i].substring(settings[i].indexOf("=") + 1);
            if (optionName.toString().toLowerCase() == settingName.toString().toLowerCase()) {
                result = optionValue;
                break;
            }
        }
    }

    return result;
}

// misc birdseye image control scripts
// old file: BirdsEyeMain.js
function fnTabSwitch(psSwitchElements, poCurrentElement, psPath) {
    var laSwitchElements = psSwitchElements.split(',');
    var laCurrentElement = poCurrentElement.src.split('.');
    var lsPath = (psPath) ? psPath : '';

    for (var liX = 0; liX < laSwitchElements.length; liX++) {
        var lsSwitchElement = document.getElementById(laSwitchElements[liX]);
        var lsSwitchElementSrc = lsSwitchElement.src.replace('.gif', '');
        var laSwitchElement = lsSwitchElementSrc.split('/');
        var lsSwitchElementSrcPre = laSwitchElement[laSwitchElement.length - 1].replace('_sel', '').replace('_over', '');

        lsSwitchElement.src = (lsSwitchElement == poCurrentElement) ? lsPath + lsSwitchElementSrcPre + "_sel.gif" : lsPath + lsSwitchElementSrcPre + ".gif";
    }
}

function BIGetFirstEnabledItem(container) {
    var item;
    for (item in container) {
        if (container[item].enabled) {
            return container[item];
        }
    }
}

function BIShowUpsell() {
    document.getElementById('mainPhoto_birdseye').style.display = 'none';
    document.getElementById('mainPhoto_promo').style.display = 'none';
    document.getElementById('mainPhoto_upsell').innerHTML = '<a href="' + g_BI_upsellImageLink + '"><img src="' + g_BI_upsellBYPhoto + '"/></a>';
    document.getElementById('mainPhoto_upsell').style.display = 'block';
}

function BIUpdateBirdsEyeImage(isIinteractive) {
    if (isIinteractive && !g_BI_showMap && typeof (g_BI_upsellBYPhoto) != 'undefined' && g_BI_upsellBYPhoto != '') {
        BIShowUpsell();
    }
    else {
        var selectedView = BIGetFirstSelectedItem(g_BI_ViewPoints);
        var selectedZoom = BIGetFirstSelectedItem(g_BI_Zooms);

        if (selectedView != null && selectedZoom != null) {
            // the "mimg" parameter is here solely to avoid image caching in FF
            if (g_BI_showMap) {
                document.getElementById('mapImage').src = g_BI_BaseImagePath + 'house_load_293x188.gif';

                document.getElementById('HiddenImageMap').src =
						'/birdseyeimage/propertyimage.ashx?propid=' + g_BI_PropertyID + '&z=600&ms=r&pi=true' + '&v=' + selectedView.tag + '&latitude=' + g_BI_Latitude + '&longitude=' + g_BI_Longitude + '&displayAerialView=' + g_BI_DisplayAerialView + '&propertyPrice=' + g_BI_PropertyPrice;
            }
            else {
                document.getElementById('PropertyPictures').src = g_BI_BaseImagePath + 'house_load_293x188.gif';

                document.getElementById('HiddenImage').src =
						'/birdseyeimage/propertyimage.ashx?propid=' + g_BI_PropertyID + '&z=' + selectedZoom.tag + '&v=' + selectedView.tag + "&mimg=" + g_BI_isMember + '&latitude=' + g_BI_Latitude + '&longitude=' + g_BI_Longitude + ' &displayAerialView=' + g_BI_DisplayAerialView + '&propertyPrice=' + g_BI_PropertyPrice;
            }
        }
    }
}

function BIShowSampleImage() {
    document.getElementById('mainPhoto_birdseye').style.display = 'none';
    document.getElementById('mainPhoto_promo').style.display = 'block';
    document.getElementById('mainPhoto_upsell').style.display = 'none';
}

function BIPropertyImageLoaded(stubImage, propertyImageID) {
    var propertyImages = document.getElementById(propertyImageID);

    if (propertyImages != null) {
        propertyImages.src = stubImage.src;
    }
}

function BIShowPropertyPhotoTab() {
    g_BI_MapTab.Deselect();
    g_BI_PhotoTab.Select();
    g_BI_VideoTab.Deselect();
    g_BI_BirdsEyeTab.Deselect();

    g_BI_showMap = false;

    document.getElementById('content_birdseye').style.display = 'none';
    document.getElementById('content_photos').style.display = 'block';
    document.getElementById('content_video').style.display = 'none';
    document.getElementById('content_map').style.display = 'none';

    g_BI_propertyPhotoBrowser[0].updateControls();
}

function BIShowBirdsEyeTab() {
    g_BI_MapTab.Deselect();
    g_BI_PhotoTab.Deselect();
    g_BI_VideoTab.Deselect();
    g_BI_BirdsEyeTab.Select();

    if (typeof (g_BI_upsellImageLink) != 'undefined' && g_BI_upsellImageLink != '' &&
        typeof (g_BI_upsellBYPhoto) != 'undefined' && g_BI_upsellBYPhoto != '') {
        document.getElementById('mainPhoto_upsell').innerHTML = '<a href="' + g_BI_upsellImageLink + '"><img src="' + g_BI_upsellBYPhoto + '"/></a>';
        document.getElementById('mainPhoto_birdseye').style.display = 'none';
        document.getElementById('mainPhoto_upsell').style.display = 'block';
    }
    document.getElementById('content_birdseye').style.display = 'block';
    document.getElementById('content_photos').style.display = 'none';
    document.getElementById('content_video').style.display = 'none';
    document.getElementById('content_map').style.display = 'none';

    g_BI_showMap = false;

    //document.getElementById('mainPhoto_upsell').style.display = 'none';
    document.getElementById('content_photos').style.display = 'none';

    if (typeof (g_BI_upsellBYPhoto) != 'undefined' && g_BI_upsellBYPhoto != '')
    {
        $("#perspective_control").hide();
        $("#zoom_control").hide();
    }
    else
    {
        document.getElementById('perspective_control').style.display = 'block';
        document.getElementById('zoom_control').style.display = 'block';   
    }

    BIUpdateBirdsEyeImage(false);
}


function BIShowMapTab() {
    g_BI_MapTab.Select();
    g_BI_PhotoTab.Deselect();
    g_BI_VideoTab.Deselect();
    g_BI_BirdsEyeTab.Deselect();

    document.getElementById('content_birdseye').style.display = 'none';
    document.getElementById('content_photos').style.display = 'none';
    document.getElementById('content_video').style.display = 'none';
    document.getElementById('content_map').style.display = 'block';

    g_BI_showMap = true;

    document.getElementById('mainPhoto_birdseye').style.display = 'block';
    document.getElementById('mainPhoto_promo').style.display = 'none';

    document.getElementById('mainPhoto_upsell').style.display = 'none';
    document.getElementById('content_photos').style.display = 'none';

    document.getElementById('perspective_control').style.display = 'none';
    document.getElementById('zoom_control').style.display = 'none';

    if (g_BI_ViewPoints != null && g_BI_ViewPoints["N"] != null) {
        g_BI_ViewPoints["N"].selected = true;
    }

    BIUpdateBirdsEyeImage(false);
}

function BIInitializeControl() {
    //If BirdsEye control is available we always can get containing control
    //if we don't have this div, than control is not displayed, so we don't need to load it!

    var element = document.getElementById('birdsEyeDiv');

    var seeMorePicsLink = (typeof (BB_ShowSeeMorePicslink) !== "undefined") ? BB_ShowSeeMorePicslink : false;

    if (element) {
        g_BI_IsBirdsEyeActive = true;
    }
    else {
        g_BI_IsBirdsEyeActive = false;
    }

    if (g_BI_IsBirdsEyeActive) {
        document.getElementById('loadingOverlay').style.display = 'block';
        ////////////// Global variable initialization

        g_BI_ViewPoints = new Array();
        g_BI_Zooms = new Array();

        g_BI_BaseImagePath = '/images/birdseye/';
        g_BI_BaseImagePostfix = '_21x21';
        g_BI_ImageNA = '/images/image_na.gif';

        // satellite images are only displayed when there are no property photos and no birdseye
        g_BI_hasAerial = !g_BI_hasPropertyPhotos && !g_BI_hasBirdsEye && g_BI_DisplaySatelite;

        // if there are no birdseye images, then pretend that we have a north view from the satellite
        if (!g_BI_hasBirdsEye && g_BI_DisplaySatelite) {
            g_BI_hasNorthView = true;
        }

        // toggle button initialization area

        g_BI_northView = new ToggleButton('N', g_BI_ViewPoints, 'PD_btn_directionN', 'imgViewN', g_BI_hasNorthView);
        g_BI_eastView = new ToggleButton('E', g_BI_ViewPoints, 'PD_btn_directionE', 'imgViewE', g_BI_hasEastView);
        g_BI_southView = new ToggleButton('S', g_BI_ViewPoints, 'PD_btn_directionS', 'imgViewS', g_BI_hasSouthView);
        g_BI_westView = new ToggleButton('W', g_BI_ViewPoints, 'PD_btn_directionW', 'imgViewW', g_BI_hasWestView);

        g_BI_zoomIn = new ToggleButton('30', g_BI_Zooms, 'PD_btn-zoom+', 'zoomIn', true);
        g_BI_zoomOut = new ToggleButton('60', g_BI_Zooms, 'PD_btn-zoom-', 'zoomOut', true);

        if (typeof (g_BI_upsellBYPhoto) != 'undefined' && g_BI_upsellBYPhoto != null && g_BI_upsellBYPhoto != '') {
            document.getElementById('PropertyPictures').src = g_BI_upsellBYPhoto;
        }

        //Split video and photos
        if (g_BI_propertyPhotos.length > 0) {
            var photos = new Array();
            var video = new Array();
            for (var i = 0; i < g_BI_propertyPhotos.length; i++) {
                var photoObj = g_BI_propertyPhotos[i].split(',');
                if (photoObj.length == 2 && photoObj[1].toLowerCase() == 'true') {
                    video.push(photoObj[0]);
                }
                else {
                    photos.push(photoObj[0]);
                }
            }

            g_BI_propertyPhotos = photos;
            g_BI_propertyVideo = video;
        }

        g_BI_hasPropertyPhotos = typeof g_BI_propertyPhotos != 'undefined' && g_BI_propertyPhotos != null && g_BI_propertyPhotos.length > 0 ? true : false;
        g_BI_hasPropertyVideo = typeof g_BI_propertyVideo != 'undefined' && g_BI_propertyVideo != null && g_BI_propertyVideo.length > 0 ? true : false;

        // initialize the property photo browsing
        g_BI_propertyPhotoBrowser[0] = new PropertyPhotoBrowser(g_BI_propertyPhotos, 'propertyPhotoImage', '', seeMorePicsLink);

        // initialize tab buttons
        g_BI_MapTab = new TriStateImageButton(document.getElementById('BirdsEyeMapTab'), g_BI_BaseImagePath + 'PD_btn-map_61x17.gif', g_BI_BaseImagePath + 'PD_btn-map_61x17_sel.gif', g_BI_BaseImagePath + 'PD_btn-map_61x17_over.gif');
        g_BI_BirdsEyeTab = new TriStateImageButton(document.getElementById('BirdsEyeBirdsEyeTab'), g_BI_BaseImagePath + 'PD_btn-birdseye_61x17.gif', g_BI_BaseImagePath + 'PD_btn-birdseye_61x17_sel.gif', g_BI_BaseImagePath + 'PD_btn-birdseye_61x17_over.gif');
        g_BI_PhotoTab = new TriStateImageButton(document.getElementById('BirdsEyePhotosTab'), g_BI_BaseImagePath + 'PD_btn-photos_61x17.gif', g_BI_BaseImagePath + 'PD_btn-photos_61x17_sel.gif', g_BI_BaseImagePath + 'PD_btn-photos_61x17_over.gif');
        g_BI_VideoTab = new TriStateImageButton(document.getElementById('BirdsEyeVideoTab'), g_BI_BaseImagePath + 'PD_btn-virtualtour_61x17.gif', g_BI_BaseImagePath + 'PD_btn-virtualtour_61x17_sel.gif', g_BI_BaseImagePath + 'PD_btn-virtualtour_61x17_over.gif');

        // select first enabled viewpoint
        g_BI_defaultView = BIGetFirstEnabledItem(g_BI_ViewPoints);
        if (g_BI_defaultView != null) {
            g_BI_defaultView.select();
        }

        // select first enabled zoom
        BIGetFirstEnabledItem(g_BI_Zooms).select();

        // show/hide tabs
        ShowHideTabById('tabPropertyVideo', g_BI_hasPropertyVideo);
        ShowHideTabById('tabPropertyPhotos', g_BI_hasPropertyPhotos);
        ShowHideTabById('tabBirdseye', g_BI_hasBirdsEye);
        ShowHideTabById('tabMap', true);

        if(g_BI_hasPropertyVideo)
        {
            var dialogHeight = 580;
            var dialogWidth = 775;
            var top = (screen.height - dialogHeight - 10) / 2;  // With correction by outer container
            var left = (screen.width - dialogWidth - 10) / 2;  // With correction by outer container
            
            var $dialog = $('#content_video').dialog(
            {
                modal:true,
                //title:'Virtual Tour',
                position:'center', 
                width:dialogWidth, 
                height:dialogHeight,
                autoOpen:false
            });
            
            $('#tabPropertyVideoLink').click(
            function()
            {
                document.getElementById('frmVideoContent').src = g_BI_propertyVideo[0];
                $dialog.dialog('open');
                var parent = $('#content_video').parent();
                var style = parent.attr('style');
                if (style != null)
                { 
                    parent.css({ position:"absolute", top: top, left: left, backgroundColor:"#FFF" });
                }

                $('html, body').animate({scrollTop:0}, 0);

                return false;
            });
        }

        // show hide tab content
        if (g_BI_hasPropertyPhotos) {
            BIShowPropertyPhotoTab();
        }
        else {
            if (g_BI_hasBirdsEye) {
                BIShowBirdsEyeTab();
            }
            else {
                BIShowMapTab();
            }
        }

        document.getElementById('loadingOverlay').style.display = 'none';
    }
}


// property photo browser - used by the birdseye image control
// old file: PropertyDetailsBrowser.js
function PropertyPhotoBrowser(photos, imgControl, ctlIndex, showSeeMorePicslink, isMLSView) {
    var ctlIndexInt;

    if (typeof (ctlIndex) == 'undefined' || ctlIndex == null || ctlIndex == '') {
        ctlIndexInt = 0;
    }
    else {
        ctlIndexInt = ctlIndex;
    }

    if (typeof (photos) != "undefined") {
        this.photos = photos;
        this.currentPhoto = 0;
        this.maxPhotos = Math.min(5, this.photos.length);

        this.firstPhoto = 0;
        this.lastPhoto = this.firstPhoto + this.maxPhotos - 1;
        this.imgControl = imgControl;

        this.isMLSView = (typeof (isMLSView) != "undefined") ? isMLSView : false;

        if (this.photos.length > this.maxPhotos) {
            $("#prevPropertyImage" + ctlIndex).unbind();
            $("#prevPropertyImage" + ctlIndex).click(function () { g_BI_propertyPhotoBrowser[ctlIndexInt].scrollPrev(); return false; });
            $("#nextPropertyImage" + ctlIndex).unbind();
            $("#nextPropertyImage" + ctlIndex).click(function () { g_BI_propertyPhotoBrowser[ctlIndexInt].scrollNext(); return false; });
        }
        else {
            $("#prevPropertyImage" + ctlIndex).unbind();
            $("#prevPropertyImage" + ctlIndex).click(function () { g_BI_propertyPhotoBrowser[ctlIndexInt].prev(); return false; });
            $("#nextPropertyImage" + ctlIndex).unbind();
            $("#nextPropertyImage" + ctlIndex).click(function () { g_BI_propertyPhotoBrowser[ctlIndexInt].next(); return false; });
        }


        this.updateControls = function () {
            if (typeof (this.imgControl) != "undefined") {

                this.firstPhoto = Math.max(0, this.firstPhoto);
                this.lastPhoto = Math.min(this.photos.length - 1, this.lastPhoto);

                $("#ulCarouselImages" + ctlIndex).empty();

                if (this.photos.length > this.maxPhotos) {
                    var photoIndex = this.firstPhoto;
                    for (var i = 0; i < this.maxPhotos; i++) {
                        var selectedClass = photoIndex == this.currentPhoto ? " selectedImg" : "";
                        $("#ulCarouselImages" + ctlIndex).append('<li class="exact' + selectedClass + '"><img src="' + this.photos[photoIndex] + '" width="40" height="30" alt="" onclick="g_BI_propertyPhotoBrowser[' + ctlIndexInt + '].selectPhoto(' + photoIndex + ');"/></li>');

                        photoIndex = this.nextIndex(photoIndex);
                    }

                }
                else {
                    for (var i = this.firstPhoto; i <= this.lastPhoto; i++) {
                        var selectedClass = i == this.currentPhoto ? " selectedImg" : "";
                        $("#ulCarouselImages" + ctlIndex).append('<li class="exact' + selectedClass + '"><img src="' + this.photos[i] + '" width="40" height="30" alt="" onclick="g_BI_propertyPhotoBrowser[' + ctlIndexInt + '].selectPhoto(' + i + ');"/></li>');
                    }
                }

                // if fewer than five photos, center the <ul>
                if (!this.isMLSView) {
                    switch (this.photos.length) {
                        case 2:
                            $("#ulCarouselImages" + ctlIndex).addClass("navigate twoImages");
                            break;
                        case 3:
                            $("#ulCarouselImages" + ctlIndex).addClass("navigate threeImages");
                            break;
                        case 4:
                            $("#ulCarouselImages" + ctlIndex).addClass("navigate fourImages");
                            break;
                    }
                }
                else {
                    switch (this.photos.length) {
                        case 2:
                            $("#ulCarouselImages" + ctlIndex).addClass("navigateMLS twoImagesMLS");
                            break;
                        case 3:
                            $("#ulCarouselImages" + ctlIndex).addClass("navigateMLS threeImagesMLS");
                            break;
                        case 4:
                            $("#ulCarouselImages" + ctlIndex).addClass("navigateMLS fourImagesMLS");
                            break;
                    }
                }

                document.getElementById(this.imgControl).onerror = this.onImageLoadError;

                if (this.photos.length > this.currentPhoto) {
                    document.getElementById(this.imgControl).src = this.photos[this.currentPhoto];
                    if (typeof (g_BI_upsellImageLink) != 'undefined' && g_BI_upsellImageLink != '' &&
                        typeof (g_BI_upsellBYPhoto) != 'undefined' && g_BI_upsellBYPhoto != '') {
                        document.getElementById('main_photo').innerHTML = '<a href="' + g_BI_upsellImageLink + '">' +
                            document.getElementById('main_photo').innerHTML + '</a>';
                    }
                }
                else {
                    document.getElementById(this.imgControl).src = g_BI_ImageNA;
                }

                if (typeof (showSeeMorePicslink) != 'undefined' && showSeeMorePicslink != null && showSeeMorePicslink) {
                    $('#content-propertyphotos-controls' + ctlIndex).hide();
                    $('#divSeeMorePhotos').show();
                }
                else {
                    if (this.photos.length > 1) // do not show carousel for images count = 1
                    {
                        $('#content-propertyphotos-controls' + ctlIndex).show();

                        document.getElementById('propertyImageText' + ctlIndex).innerHTML = (this.currentPhoto + 1) + ' of ' + this.photos.length;

                        document.getElementById('prevPropertyImage' + ctlIndex).style.display = this.photos.length > 1 ? 'block' : 'none';
                        document.getElementById('nextPropertyImage' + ctlIndex).style.display = this.photos.length > 1 ? 'block' : 'none';
                    }
                    else {
                        $('#content-propertyphotos-controls' + ctlIndex).hide();
                    }

                    if (ctlIndexInt == 0) {
                        $('#divSeeMorePhotos').hide();
                    }
                }
            }
        };

        this.onImageLoadError = function () {
            var control = document.getElementById(imgControl);

            if (control != null) {
                document.getElementById(imgControl).src = g_BI_ImageNA;
            }
        };

        this.nextIndex = function (currentIndex) {
            currentIndex++;
            if (currentIndex >= this.photos.length) {
                currentIndex = 0;
            }
            return currentIndex;
        }

        this.prevIndex = function (currentIndex) {
            currentIndex--;
            if (currentIndex < 0) {
                currentIndex = this.photos.length - 1;
            }
            return currentIndex;
        }

        this.next = function () {
            this.currentPhoto++;
            if (this.currentPhoto > this.lastPhoto) {
                this.currentPhoto = this.firstPhoto;
            }
            this.updateControls();
        };

        this.prev = function () {
            this.currentPhoto--;
            if (this.currentPhoto < this.firstPhoto) {
                this.currentPhoto = this.lastPhoto;
            }
            this.updateControls();
        };

        this.scrollNext = function () {
            this.lastPhoto = this.nextIndex(this.lastPhoto);
            this.firstPhoto = this.nextIndex(this.firstPhoto);
            this.currentPhoto = this.nextIndex(this.currentPhoto);

            this.updateControls();
        }

        this.scrollPrev = function () {
            this.lastPhoto = this.prevIndex(this.lastPhoto);
            this.firstPhoto = this.prevIndex(this.firstPhoto);
            this.currentPhoto = this.prevIndex(this.currentPhoto);

            this.updateControls();
        }

        this.selectPhoto = function (photo) {
            this.currentPhoto = photo;
            this.updateControls();
        }

        this.updateControls();
    }
}

// this class encapsulates a toggle image button in a group
// old file: ToggleButton.js
function ToggleButton(tag, container, baseName, controlID, enabled) {
    this.tag = tag;
    this.baseName = baseName;
    this.controlID = controlID;
    this.enabled = enabled;
    this.container = container;
    this.selected = false;

    this.select = function () {
        if (this.enabled && !this.selected) {
            var selectedItem = BIGetFirstSelectedItem(container);
            if (selectedItem != null) {
                selectedItem.deselect();
            }
            this.setButtonImage('_sl');
            this.selected = true;
        }
    };

    this.deselect = function () {
        if (this.enabled && this.selected) {
            this.setButtonImage('');
            this.selected = false;
        }
    };

    this.hoverOver = function () {
        if (this.enabled && !this.selected) {
            this.setButtonImage('_ov');
        }
    };

    this.leave = function () {
        if (this.enabled && !this.selected) {
            this.setButtonImage('');
        }
    };

    this.setButtonImage = function (suffix) {
        document.getElementById(this.controlID).src = g_BI_BaseImagePath + this.baseName + g_BI_BaseImagePostfix + suffix + '.gif';
    };

    this.setButtonCursor = function (cursorStyle) {
        document.getElementById(this.controlID).style.cursor = cursorStyle;
    };

    if (this.enabled) {
        this.setButtonImage('');
        this.setButtonCursor('pointer');
    }
    else {
        this.setButtonImage('');
    }

    container[this.tag] = this;
}

function BIGetFirstSelectedItem(container) {
    var item;
    for (item in container) {
        if (container[item].selected) {
            return container[item];
        }
    }
}

// old file: TriStateImagebutton.js
function TriStateImageButton(element, imageNormal, imageSelected, imageOver) {
    this._imageNormal = imageNormal;
    this._imageSelected = imageSelected;
    this._imageOver = imageOver;
    this._element = element;
    this._selected = false;

    this.Preload = function (src) {
        if (document.images) {
            pic = new Image(10, 10);
            pic.src = src;
        }
    };

    this.SetImage = function (src) {
        this.Preload(src);
        if (element) {
            element.src = src;
        }
    };

    this.Select = function () {
        this.SetImage(this._imageSelected);
        this._selected = true;
    };

    this.Over = function () {
        this.SetImage(this._imageOver);
    };

    this.Out = function () {
        if (this._selected) {
            this.Select();
        }
        else {
            this.Deselect();
        }
    };

    this.Deselect = function () {
        this.SetImage(this._imageNormal);
        this._selected = false;
    };
}


function ToggleBirdsEyeControl(show) {
    var element = document.getElementById('birdsEyeDiv');
    if (element) {
        if (show) {
            element.style.display = "block";
        }
        else {
            element.style.display = "none";
        }
    }
}

//----------------------------------------------------//
//------------- END BIRDS EYE CONTROL ----------------//
//----------------------------------------------------//

// -- banner refresh

/////////////// Start of DoubleClick script //

//Grand function to all all possible refresh internal functions inside the DoubleClick control
function RefreshAllDoubleClickBanner(propertyType, zone) {
    //Generate one single random number for every refresh
    var ord;
    if (Math && Math.random) {
        ord = Math.random() * 10000000000000000;
    }

    //Now pass in the same random number to all DoubleClick ads on the page
    RefreshDoubleClickBanner_leaderboard(ord, propertyType, zone);
    RefreshDoubleClickBanner_popupLarge(ord, propertyType, zone);
    RefreshDoubleClickBanner_mediumRectangle(ord, propertyType, zone);
    RefreshDoubleClickBanner_popupSmall(ord, propertyType, zone);
    RefreshDoubleClickBanner_skyscraper(ord, propertyType, zone);
    RefreshDoubleClickBanner_verticalBanner(ord, propertyType, zone);

    RefreshDoubleClickBanner_halfBannerOdd(ord, propertyType, zone);
    RefreshDoubleClickBanner_fullbannerOdd(ord, propertyType, zone);
    RefreshDoubleClickBanner_rectangleOdd(ord, propertyType, zone);
    RefreshDoubleClickBanner_skyscraperlong(ord, propertyType, zone);
    RefreshDoubleClickBanner_longverticalBanner(ord, propertyType, zone);
    RefreshDoubleClickBanner_bigRectangle(ord, propertyType, zone);
    RefreshDoubleClickBanner_iabBanner(ord, propertyType, zone);
    RefreshDoubleClickBanner_longMegaBanner(ord, propertyType, zone);
    RefreshDoubleClickBanner_rectMegaBanner(ord, propertyType, zone);
    RefreshDoubleClickBanner_newHomeDoubleClickBanner(ord, propertyType, zone);
	RefreshDoubleClickBanner_newSignUpAd(ord, propertyType, zone);
}

function RefreshDoubleClickBanner_newSignUpAd(ord, propertyType, zone) {
    //250x300 WidthXHeight250x300  ad

    //Propertytype could be empty string
    //Zone could be empty string
    //Zone is to be called from inside pages where we have Double-Click Zone enabled
    //PropertyType is to be called from inside Property Details for now
    if (typeof (RefreshDoubleClickBannerInternal_newSignUpAd) !== 'undefined') {
        RefreshDoubleClickBannerInternal_newSignUpAd(ord, propertyType, zone);
    }
}

function RefreshDoubleClickBanner_newHomeDoubleClickBanner(ord, propertyType, zone) {
    //620x90 WidthXHeight620x90  iabBanner

    //Propertytype could be empty string
    //Zone could be empty string
    //Zone is to be called from inside pages where we have Double-Click Zone enabled
    //PropertyType is to be called from inside Property Details for now
    if (typeof (RefreshDoubleClickBannerInternal_newHomeDoubleClickBanner) !== 'undefined') {
        RefreshDoubleClickBannerInternal_newHomeDoubleClickBanner(ord, propertyType, zone);
    }
}

function RefreshDoubleClickBanner_longMegaBanner(ord, propertyType, zone) {
    //234x60 WidthXHeight234x60  iabBanner

    //Propertytype could be empty string
    //Zone could be empty string
    //Zone is to be called from inside pages where we have Double-Click Zone enabled
    //PropertyType is to be called from inside Property Details for now
    if (typeof (RefreshDoubleClickBannerInternal_longMegaBanner) !== 'undefined') {
        RefreshDoubleClickBannerInternal_longMegaBanner(ord, propertyType, zone);
    }
}
function RefreshDoubleClickBanner_rectMegaBanner(ord, propertyType, zone) {
    //234x60 WidthXHeight234x60  iabBanner

    //Propertytype could be empty string
    //Zone could be empty string
    //Zone is to be called from inside pages where we have Double-Click Zone enabled
    //PropertyType is to be called from inside Property Details for now
    if (typeof (RefreshDoubleClickBannerInternal_rectMegaBanner) !== 'undefined') {
        RefreshDoubleClickBannerInternal_rectMegaBanner(ord, propertyType, zone);
    }
}
function RefreshDoubleClickBanner_iabBanner(ord, propertyType, zone) {
    //234x60 WidthXHeight234x60  iabBanner

    //Propertytype could be empty string
    //Zone could be empty string
    //Zone is to be called from inside pages where we have Double-Click Zone enabled
    //PropertyType is to be called from inside Property Details for now
    if (typeof (RefreshDoubleClickBannerInternal_iabBanner) !== 'undefined') {
        RefreshDoubleClickBannerInternal_iabBanner(ord, propertyType, zone);
    }
}

function RefreshDoubleClickBanner_longverticalBanner(ord, propertyType, zone) {
    //120x300 WidthXHeight120x300  verticalBannerLong

    //Propertytype could be empty string
    //Zone could be empty string
    //Zone is to be called from inside pages where we have Double-Click Zone enabled
    //PropertyType is to be called from inside Property Details for now
    if (typeof (RefreshDoubleClickBannerInternal_longverticalBanner) !== 'undefined') {
        RefreshDoubleClickBannerInternal_longverticalBanner(ord, propertyType, zone);
    }
}

function RefreshDoubleClickBanner_bigRectangle(ord, propertyType, zone) {
    //300x350 WidthXHeight300x350  mediumRectangleBig

    //Propertytype could be empty string
    //Zone could be empty string
    //Zone is to be called from inside pages where we have Double-Click Zone enabled
    //PropertyType is to be called from inside Property Details for now
    if (typeof (RefreshDoubleClickBannerInternal_bigRectangle) !== 'undefined') {
        RefreshDoubleClickBannerInternal_bigRectangle(ord, propertyType, zone);
    }
}

function RefreshDoubleClickBanner_leaderboard(ord, propertyType, zone) {

    /* Remove Peel ads */
    //Get cobrand ID
    $.getJSON("/geo/header/getcobrander?callback=?",
            function (response) {
                var showLeaderAd = true;
                if (response != null) {
                    if (ShowPeelAds(response.CoBrandCompanyPK)) {
                        showLeaderAd = false;
                        return;
                    }
                }

                if (showLeaderAd) {
                    //728x90 WidthXHeight728x90  leaderboard

                    //Propertytype could be empty string
                    //Zone could be empty string
                    //Zone is to be called from inside pages where we have Double-Click Zone enabled
                    //PropertyType is to be called from inside Property Details for now
                    if (typeof (RefreshDoubleClickBannerInternal_leaderboard) !== 'undefined') {
                        RefreshDoubleClickBannerInternal_leaderboard(ord, propertyType, zone);
                    }
                }

            });
}

function ShowPeelAds(coBrandPK) {
    //Check cobrandPK, logined users and global config variables
    var visitor = true;
    var enabledPeel = false;
    var isNotInIFrame = (window.location != window.parent.location) ? false : true;
    var isBHD = window.location.hostname.toLowerCase().indexOf("bankhomesdirect") == -1 ? false : true;

    $.getJSON("/geo/header/getusercontext?callback=?",
                function (usercontext) {
                    if (usercontext.Details.FirstName != null)
                    { visitor = false; }
                    //1) only allow visitors
                    //2a) PK is 5/302 AND g_PeelAdsEnable = true
                    //2b) PK is not 755 AND g_PeelAdsAcrossAll = true

                    if (visitor && !isBHD && ((((coBrandPK == 5) || (coBrandPK == 302)) && g_PeelAdsEnable) || (coBrandPK != 755 && g_PeelAdsEnable && g_PeelAdsAcrossAll))) {
                        enabledPeel = true;
                    }

                    var adSection = isNotInIFrame ? GetElementByClass("adbox leaderboard", "div", false) : GetElementByClass("RT_Banner", "div", true);
                    var AltTopAdSection = isNotInIFrame ? GetElementByClass("adSectionTop", "div", false) : null;

                    //check if page has Leaderboard adverts or not
                    if (adSection != null && enabledPeel) {
                        //check if peek back is displayed or not
                        var peelBack = isNotInIFrame ? document.getElementById("peelback") : window.parent.document.getElementById("peelback");

                        if (peelBack == null) {
                            //Add peel ads
                            var peelBody = isNotInIFrame ? $('body') : $('body', window.parent.document)

                            $(function () {
                                peelBody.peelback({
                                    adImage: '/images/rebate-offer/peel-ad.png',
                                    peelImage: '/images/rebate-offer/peel-image.png',
                                    clickURL: '/userprofile/landingpageredirection.aspx?action=subscribe&lid=Peel Away Rebate',
                                    gaTrack: true,
                                    gaLabel: '#1 Stegosaurus',
                                    autoAnimate: true
                                });
                            });

                            //Hide Leaderboard adverts
                            adSection.style.display = "none";

                            //Try to hide outer div if exists
                            if (AltTopAdSection != null) {
                                AltTopAdSection.style.display = "none";
                            }
                        }
                        return true;
                    }
                    else {
                        return false;
                    }
                });
}

function GetElementByClass(searchClass, tag, searchParent) {
    var classElement;
    var els;
    try {
        if (searchParent) {
            els = window.parent.document.getElementsByTagName(tag);
        }
        else {
            els = document.getElementsByTagName(tag);
        }

        var pattern = new RegExp('\\b' + searchClass + '\\b');
        for (var i = 0; i < els.length; i++)
            if (pattern.test(els[i].className)) {
                classElement = els[i];
                break; //only take the very first element
            }
    }
    catch (e) { }
    return classElement;
}

function RefreshDoubleClickBanner_popupLarge(ord, propertyType, zone) {
    //720x300  WidthXHeight720x300  popupLarge

    //Propertytype could be empty string
    //Zone could be empty string
    //Zone is to be called from inside pages where we have Double-Click Zone enabled
    //PropertyType is to be called from inside Property Details for now
    if (typeof (RefreshDoubleClickBannerInternal_popupLarge) !== 'undefined') {
        RefreshDoubleClickBannerInternal_popupLarge(ord, propertyType, zone);
    }
}

function RefreshDoubleClickBanner_mediumRectangle(ord, propertyType, zone) {
    //300x250  WidthXHeight300x250  mediumRectangle

    //Propertytype could be empty string
    //Zone could be empty string
    //Zone is to be called from inside pages where we have Double-Click Zone enabled
    //PropertyType is to be called from inside Property Details for now
    if (typeof (RefreshDoubleClickBannerInternal_mediumRectangle) !== 'undefined') {
        RefreshDoubleClickBannerInternal_mediumRectangle(ord, propertyType, zone);
    }
}

function RefreshDoubleClickBanner_popupSmall(ord, propertyType, zone) {
    //315x152  WidthXHeight315x152  popupSmall

    //Propertytype could be empty string
    //Zone could be empty string
    //Zone is to be called from inside pages where we have Double-Click Zone enabled
    //PropertyType is to be called from inside Property Details for now
    if (typeof (RefreshDoubleClickBannerInternal_popupSmall) !== 'undefined') {
        RefreshDoubleClickBannerInternal_popupSmall(ord, propertyType, zone);
    }
}

function RefreshDoubleClickBanner_skyscraper(ord, propertyType, zone) {
    //120x600  WidthXHeight120x600  skyscraper 

    //Propertytype could be empty string
    //Zone could be empty string
    //Zone is to be called from inside pages where we have Double-Click Zone enabled
    //PropertyType is to be called from inside Property Details for now
    if (typeof (RefreshDoubleClickBannerInternal_skyscraper) !== 'undefined') {
        RefreshDoubleClickBannerInternal_skyscraper(ord, propertyType, zone);
    }
}

function RefreshDoubleClickBanner_verticalBanner(ord, propertyType, zone) {
    //120x240  WidthXHeight120x240  verticalBanner

    //Propertytype could be empty string
    //Zone could be empty string
    //Zone is to be called from inside pages where we have Double-Click Zone enabled
    //PropertyType is to be called from inside Property Details for now
    if (typeof (RefreshDoubleClickBannerInternal_verticalBanner) !== 'undefined') {
        RefreshDoubleClickBannerInternal_verticalBanner(ord, propertyType, zone);
    }
}

function RefreshDoubleClickBanner_halfBannerOdd(ord, propertyType, zone) {
    //247x85  WidthXHeight247x85 halfBannerOdd

    if (typeof (RefreshDoubleClickBannerInternal_halfBannerOdd) !== 'undefined') {
        RefreshDoubleClickBannerInternal_halfBannerOdd(ord, propertyType, zone);
    }
}

function RefreshDoubleClickBanner_fullbannerOdd(ord, propertyType, zone) {
    //505x106  WidthXHeight505x106 fullbannerOdd

    if (typeof (RefreshDoubleClickBannerInternal_fullbannerOdd) !== 'undefined') {
        RefreshDoubleClickBannerInternal_fullbannerOdd(ord, propertyType, zone);
    }
}

function RefreshDoubleClickBanner_rectangleOdd(ord, propertyType, zone) {
    //202x125  WidthXHeight202x125 rectangleOdd

    if (typeof (RefreshDoubleClickBannerInternal_rectangleOdd) !== 'undefined') {
        RefreshDoubleClickBannerInternal_rectangleOdd(ord, propertyType, zone);
    }
}

function RefreshDoubleClickBanner_skyscraperlong(ord, propertyType, zone) {
    //120x875  WidthXHeight120x875	skyscraperlong

    if (typeof (RefreshDoubleClickBannerInternal_skyscraperlong) !== 'undefined') {
        RefreshDoubleClickBannerInternal_skyscraperlong(ord, propertyType, zone);
    }
}


/////////////// end of DoubleClick script //

function RefreshTopBanner(dmaCode) {
    if (typeof (RefreshTopBannerInternal) !== 'undefined') {
        RefreshTopBannerInternal(dmaCode);
    }
}

function RefreshRightBanner(dmaCode) {
    if (typeof (RefreshRightBannerInternal) !== 'undefined') {
        RefreshRightBannerInternal(dmaCode);
    }
}

function RefreshRightMiniSkyBanner(dmaCode) {
    if (typeof (RefreshRightMiniSkyBannerInternal) !== 'undefined') {
        RefreshRightMiniSkyBannerInternal(dmaCode);
    }
}

function RefreshBannerTileCreditReport(dmaCode) {
    if (typeof (RefreshBannerTileCreditReportInternal) !== 'undefined') {
        RefreshBannerTileCreditReportInternal(dmaCode);
    }
}

function RefreshBannerTileEbook(dmaCode) {
    if (typeof (RefreshBannerTileEbookInternal) !== 'undefined') {
        RefreshBannerTileEbookInternal(dmaCode);
    }
}

function ShowHideTabById(tabID, showTab) {
    var tab = document.getElementById(tabID);

    if (tab) {
        tab.style.display = (showTab ? 'block' : 'none');
    }
}

// Validation of Emails in PropertyToolBar
function g_fnCheckEmail(psFieldName) {
    var lsEmail = psFieldName.value;
    var rExp = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i;

    return rExp.test(lsEmail);
}

function LoadDOMScript(src) {
    var document_scripts = document.getElementsByTagName("script");

    for (document_scripts_index = 0; document_scripts_index < document_scripts.length; ++document_scripts_index) {
        var document_script = document_scripts[document_scripts_index];
        if (document_script.src == src) return false;
    }

    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = src;
    document.getElementsByTagName('head')[0].appendChild(script);
}

function CreateAdserImage(containerElementId, imageId, imageUrl, server) {
    var rnd = Math.random();
    var imgArg = 'id=' + imageId + '&rnd=' + rnd;
    var adContainer = document.getElementById(containerElementId);
    if (adContainer) {
        adContainer.innerHTML = '<a href="' + imageUrl + '" target="_blank"><img border="0" src="' + server + '/adser/ImageSrv.ashx?' + imgArg + '"></a><div class="adtext" align="center">advertisement</div>';
    }
}

function CreateAdInContainer(containerElementId, role, group) {
    if (!g_IsWhiteSite) {
        var rnd = Math.random();
        var roleParam = role ? "&role=" + role : "";
        var groupParam = group ? "&group=" + group : "";
        LoadDOMScript("/adser/ImageRef.ashx?id=" + containerElementId + "&rnd=" + rnd + roleParam + groupParam);
    }
}

function ClearAdInContainer(containerElementId) {
    if (!g_IsWhiteSite) {
        var adContainer = document.getElementById(containerElementId);
        if (adContainer) {
            adContainer.innerHTML = '';
        }
    }
}
//----------------------------------
// Agents banner functionality
//----------------------------------

function callNowAgent() {
    window.open('http://www.realping.com/accts/connect.cfm?id=1123&tz=0&src=web&nocache=57987', 'realping', 'width=580,height=580,resize=YES,menubar=no,location=no,toolbar=no,statusbar=no'); return false;
}

AgentsBannerHelper = function (orientation, agentNameElementID, agentImageElementID, agentSpecialityElementID,
    imgContactElementID, contactButtonElementID, navigationUrl, leadSource, hitboxFunction,
    contactCaptionElementID, callNowButtonElementID, callNowHitboxFunction, searchAreaElementID, dispayReserveTerritoryAsDefault) {
    // Constants
    this.Contstants = new function () {
        this.DEFAULT_AGENT_PICTURE = '/images/territoryAgents/silhouette_front_tn.jpg';
        this.DEFAULT_AGENT_NAME = 'RealtyTrac Agent Network';
        this.DEFAULT_CONTACT_LINK = "/Agents/AgentLeadPreLanding.aspx?a=b";
        this.DEFAULT_AGENT_SPECIALITY = "Contact a pre-screened real estate professional in your area.";
        this.DEFAULT_CONTACT_ALT = "Contact Specialist";
        this.CONTACT_ALT = "Local Real Estate Specialist";

        this.BANER_ORIENTATION_HORIZONTAL = "H";
        this.BANER_ORIENTATION_VERTICAL = "V";
        this.BANER_ORIENTATION_HORIZONTAL_EXPANDER = "HE";

        this.DEFAULT_BANNER_SELECTOR = ".bannerDefault";
        this.RESERVE_TERRITORY_SELECTOR = ".bannerTerritory";
    }

    // Banner Orientation
    this.Orientation = (typeof (orientation) == "undefined" || orientation == null || orientation == "")
        ? this.Contstants.BANER_ORIENTATION_HORIZONTAL : orientation;

    // Navigation URL
    this.NavigationURL = navigationUrl;

    // Lead Source
    this.LeadSource = leadSource;

    // Hitbox function for horizontal banner
    this.HitboxFunction = hitboxFunction;

    // Hitbox function for Call Now button
    this.CallNowHitboxFunction = callNowHitboxFunction;

    // Reserve territory for agents
    this.DispayReserveTerritoryAsDefault = dispayReserveTerritoryAsDefault;

    // Elements
    var ElementsDef = function (agentNameElmentID, agentImageElementID, agentSpecialityElementID, imgContactElementID, contactButtonElementID, contactCaptionElementID, callNowButtonElementID, searchAreaElementID) {
        this.AgentNameElementID = agentNameElementID;
        this.AgentImageElementID = agentImageElementID;
        this.AgentSpecialityElementID = agentSpecialityElementID;
        this.ImgContactElementID = imgContactElementID;
        this.ContactButtonElementID = contactButtonElementID;
        this.ContactCaptionElementID = contactCaptionElementID;
        this.CallNowButtonElementID = callNowButtonElementID;
        this.SearchAreaElementID = searchAreaElementID;
    }

    this.ElementIDs = new ElementsDef(agentNameElementID, agentImageElementID, agentSpecialityElementID, imgContactElementID, contactButtonElementID, contactCaptionElementID, callNowButtonElementID, searchAreaElementID);

    // Functionality
    this.SetAgentBanner = function (agentName, agentPictureUrl, agentSpeciality, navigationUrl, callNowFunction, displayCallNow, searchAreaFormatted) {

        // Set agent's name
        if (typeof (agentName) == "undefined" || agentName == null || agentName == "") {
            agentName = this.Contstants.DEFAULT_AGENT_NAME;
        }

        $("#" + this.ElementIDs.AgentNameElementID).attr("innerHTML", agentName);

        // Set agent's picture

        if (typeof (agentPictureUrl) == "undefined" || agentPictureUrl == null || agentPictureUrl == "") {
            agentPictureUrl = this.Contstants.DEFAULT_AGENT_PICTURE;
        }

        if (this.Orientation == this.Contstants.BANER_ORIENTATION_HORIZONTAL || this.Orientation == this.Contstants.BANER_ORIENTATION_HORIZONTAL_EXPANDER) {
            $("#" + this.ElementIDs.AgentImageElementID).attr("src", agentPictureUrl);
        }
        else {
            $("#" + this.ElementIDs.AgentImageElementID).attr("innerHTML", '<img src="' + agentPictureUrl + '">');
        }

        // Set speciality

        if (typeof (this.ElementIDs.AgentSpecialityElementID) != "undefined" && this.ElementIDs.AgentSpecialityElementID != "") {
            if (typeof (agentSpeciality) == "undefined" || agentSpeciality == null || agentSpeciality == "") {
                agentSpeciality = this.Contstants.DEFAULT_AGENT_SPECIALITY;
            }

            $("#" + this.ElementIDs.AgentSpecialityElementID).attr("innerHTML", agentSpeciality);
        }

        // Set search area
        if (typeof (this.ElementIDs.SearchAreaElementID) != "undefined" && this.ElementIDs.SearchAreaElementID != ""
            && typeof (searchAreaFormatted) != "undefined" && searchAreaFormatted != null && searchAreaFormatted != "") {
            $("#" + this.ElementIDs.SearchAreaElementID).html(searchAreaFormatted);
        }

        // Set contact button navigation URL
        if (typeof (navigationUrl) == "undefined" || navigationUrl == null || navigationUrl == "") {
            navigationUrl = (typeof (this.NavigationURL) != "undefined" && this.NavigationURL != null && this.NavigationURL != "")
                ? this.NavigationURL : this.Contstants.DEFAULT_CONTACT_LINK + "&LeadSource=" + this.LeadSource;
        }

        if (this.HitboxFunction != null && this.HitboxFunction != "") {
            navigationUrl = this.HitboxFunction.replace('{0}', navigationUrl);
        }

        $("#" + this.ElementIDs.ContactButtonElementID).attr("href", navigationUrl);

        if (typeof (displayCallNow) != "undefined" && typeof (callNowFunction) != "undefined") {

            if (this.CallNowHitboxFunction != null && this.CallNowHitboxFunction != "") {
                callNowFunction = this.CallNowHitboxFunction.replace('{0}', callNowFunction);
            }

            if (typeof (this.ElementIDs.ContactCaptionElementID) != "undefined" && this.ElementIDs.ContactCaptionElementID != "") {
                $("#" + this.ElementIDs.ContactCaptionElementID).css("display", (displayCallNow ? "" : "none"));
            }

            if (typeof (this.ElementIDs.CallNowButtonElementID) != "undefined" && this.ElementIDs.CallNowButtonElementID != "") {
                $("#" + this.ElementIDs.CallNowButtonElementID).css("display", (displayCallNow ? "" : "none"));
                $("#" + this.ElementIDs.CallNowButtonElementID).attr("href", callNowFunction);
            }

            $("#" + this.ElementIDs.ContactButtonElementID).attr("innerHTML", (displayCallNow ? "<span>E-MAIL ME!</span>" : "<span>Contact</span>"));
        }

        if (this.DispayReserveTerritoryAsDefault
            && $(this.Contstants.DEFAULT_BANNER_SELECTOR).length > 0
            && $(this.Contstants.RESERVE_TERRITORY_SELECTOR).length > 0) {
            if ((agentName == this.Contstants.DEFAULT_AGENT_NAME)
                && (agentPictureUrl == this.Contstants.DEFAULT_AGENT_PICTURE)) {
                $(this.Contstants.DEFAULT_BANNER_SELECTOR).hide();
                $(this.Contstants.RESERVE_TERRITORY_SELECTOR).show();
            }
            else {
                $(this.Contstants.RESERVE_TERRITORY_SELECTOR).hide();
                $(this.Contstants.DEFAULT_BANNER_SELECTOR).show();
            }
        }
    }
}

function SetAgentBanner(agentName, agentPictureUrl, agentSpeciality, navigationUrl, callNowFunction, displayCallNow, searchAreaFormatted) {
    if (typeof (gAgentsBannerHelper) != "undefined" && gAgentsBannerHelper != null) {
        if (typeof (gAgentsBannerHelper.length) == "undefined") {
            gAgentsBannerHelper.SetAgentBanner(agentName, agentPictureUrl, agentSpeciality, navigationUrl, callNowFunction, displayCallNow, searchAreaFormatted);
        }
        else {
            for (var i = 0; i < gAgentsBannerHelper.length; i++) {
                gAgentsBannerHelper[i].SetAgentBanner(agentName, agentPictureUrl, agentSpeciality, navigationUrl, callNowFunction, displayCallNow, searchAreaFormatted);
            }
        }
    }
}

function AddAgentBannerExpanderEvents() {
    $("a.contactAgentExpander").click(function (event) {
        event.preventDefault();
        if ($.browser.msie && parseInt(jQuery.browser.version) < 7) {
            if ($("div.contactAgentBannerContentContainer:hidden").length > 0) {
                noSelects(1);
            }
            else {
                noSelects(0);
            }
        }
        $("div.contactAgentBannerContentContainer").slideToggle("fast");
    });
}

function AddAgentBannerHelper(orientation, agentNameElementID, agentImageElementID, agentSpecialityElementID,
    imgContactElementID, contactButtonElementID, navigationUrl, leadSource, hitboxFunction,
    contactCaptionElementID, callNowButtonElementID, callNowHitboxFunction, searchAreaElementID, dispayReserveTerritoryAsDefault) {
    if (typeof (gAgentsBannerHelper) == "undefined" || gAgentsBannerHelper == null) {
        gAgentsBannerHelper = new Array();
    }

    if (typeof (gAgentsBannerHelper.length) == "undefined") {
        gAgentsBannerHelper = new Array(gAgentsBannerHelper);
    }

    var tmpHelper = new AgentsBannerHelper(orientation, agentNameElementID, agentImageElementID, agentSpecialityElementID,
        imgContactElementID, contactButtonElementID, navigationUrl, leadSource, hitboxFunction,
        contactCaptionElementID, callNowButtonElementID, callNowHitboxFunction, searchAreaElementID, dispayReserveTerritoryAsDefault);

    gAgentsBannerHelper[gAgentsBannerHelper.length] = tmpHelper;
}

function AppContextHelper(isAnonymousUser, isRegisteredUser, isFullAccessMember, isGuestMember, isRegionalWhiteSiteMember, isCancelledMember,
    isAgent, isTrialMember, isBasicMember, isInternational, isBHDMember, isBHDMemberTrial, isBHDAnonymousUser, isBHDTrial,
    isRealtyTrac, isBankHomesDirect, isWhiteSite, isDataLink, isCustomFreeSite) {
    var CheckOnInitValue = function (value) {
        return (typeof (value) != "undefined") ? value : false;
    }

    // User Types
    this.IsAgent = CheckOnInitValue(isAgent);
    this.IsAnonymousUser = CheckOnInitValue(isAnonymousUser);
    this.IsBasicMember = CheckOnInitValue(isBasicMember);
    this.IsBHDAnonymousUser = CheckOnInitValue(isBHDAnonymousUser);
    this.IsBHDMember = CheckOnInitValue(isBHDMember);
    this.IsBHDMemberTrial = CheckOnInitValue(isBHDMemberTrial);
    this.IsBHDTrial = CheckOnInitValue(isBHDTrial);
    this.IsCancelledMember = CheckOnInitValue(isCancelledMember);
    this.IsFullAccessMember = CheckOnInitValue(isFullAccessMember);
    this.IsGuestMember = CheckOnInitValue(isGuestMember);
    this.IsInternational = CheckOnInitValue(isInternational);
    this.IsRegionalWhiteSiteMember = CheckOnInitValue(isRegionalWhiteSiteMember);
    this.IsRegisteredUser = CheckOnInitValue(isRegisteredUser);
    this.IsTrialMember = CheckOnInitValue(isTrialMember);

    // Site Types
    this.IsRealtyTrac = CheckOnInitValue(isRealtyTrac);
    this.IsBankHomesDirect = CheckOnInitValue(isBankHomesDirect);
    this.IsWhiteSite = CheckOnInitValue(isWhiteSite);
    this.IsDataLink = CheckOnInitValue(isDataLink);
    this.IsCustomFreeSite = CheckOnInitValue(isCustomFreeSite);
}

//----------------------------
// Integration with shared.js
//----------------------------

var Dom =
{
    get: function (el) {
        if (typeof el === 'string') {
            return document.getElementById(el);
        }
        else {
            return el;
        }
    },

    add: function (el, dest) {
        var el = this.get(el);
        var dest = this.get(dest);
        dest.appendChild(el);
    },

    remove: function (el) {
        var el = this.get(el);
        el.parentNode.removeChild(el);
    }
};

var Event =
{
    add: function () {
        if (window.addEventListener) {
            return function (el, type, fn) {
                Dom.get(el).addEventListener(type, fn, false);
            };
        }
        else if (window.attachEvent) {
            return function (el, type, fn) {
                var f = function () {
                    fn.call(Dom.get(el), window.event);
                };

                Dom.get(el).attachEvent('on' + type, f);
            };
        }
    } ()
};

function noSelects(state) {
    var f = document.getElementsByTagName('SELECT');
    for (i = 0; i < f.length; i++) {
        if (state > 0) {
            f[i].style.display = 'none';
        }
        else {
            f[i].style.display = 'inline';
        }
    }
}

var Base64 = {

    // private property
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode: function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode: function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode: function (string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode: function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }
        return string;
    }
};

function g_fnValidateSearchSubmit(psButtonClicked, psFormName, psFormFieldName_City, psFormFieldName_State, psFormFieldName_Zip, psFormFieldName_SearchCriteria, psFormFieldDefaultValue_City, psFormFieldDefaultValue_Zip, psViewMapButtonName, piIsForm, psURLDestination, psTemplate) {
    // initialize and set values
    var lsFormFieldCityName = (psFormFieldName_City) ? fnTrim(psFormFieldName_City) : 'frm_City';
    var lsFormFieldStateName = (psFormFieldName_State) ? fnTrim(psFormFieldName_State) : 'frm_State';
    var lsFormFieldZipName = (psFormFieldName_Zip) ? fnTrim(psFormFieldName_Zip) : 'frm_Zip';
    var lsFormFieldCityValueDefaultValue = (psFormFieldDefaultValue_City) ? fnTrim(psFormFieldDefaultValue_City) : 'Enter City';
    var lsFormFieldZipValueDefaultValue = (psFormFieldDefaultValue_Zip) ? fnTrim(psFormFieldDefaultValue_Zip) : 'Enter Zip';
    var lsViewMapButtonName = (psViewMapButtonName) ? fnTrim(psViewMapButtonName) : 'SearchMap';
    var lsFormName = (psFormName) ? fnTrim(psFormName) : 'quickSearchForm';
    var liIsForm = (piIsForm) ? piIsForm : null;
    var lsURLDestination = (psURLDestination) ? psURLDestination : _freeSearchResultUrl;
    var lsButtonToTrack = (psButtonClicked) ? psButtonClicked : null;
    var lsCriteriaValue;
    var lsCriteriaType;
    var lsDefaultButton = 'SearchList';
    var lsTemplate = (psTemplate) ? psTemplate : "MCode";
    var loTemplate = document.getElementById(lsTemplate);
    var lbMember = (psURLDestination) ? 1 : null;
    var lsTemplateComplete;
    var lsErrorMessage = "";
    var loFormFieldCityName = document.getElementById(lsFormFieldCityName);
    var loFormFieldStateName = document.getElementById(lsFormFieldStateName);
    var loFormFieldZipName = document.getElementById(lsFormFieldZipName);
    var lsVariables;

    //Begin Validation
    if ((loFormFieldCityName.value == '' || loFormFieldCityName.value == lsFormFieldCityValueDefaultValue) && loFormFieldStateName.value == '' && (loFormFieldZipName.value == '' || loFormFieldZipName.value == lsFormFieldZipValueDefaultValue)) {
        //No values entered
        lsErrorMessage += "- " + fnErrorNoCity() + "\n";
        lsErrorMessage += "- " + fnErrorNoState() + "\n";
    }
    else if (loFormFieldZipName.value != "" && loFormFieldZipName.value != lsFormFieldZipValueDefaultValue && (loFormFieldZipName.value.length != 5 || isNaN(loFormFieldZipName.value))) {
        //incorrect zip entered
        lsErrorMessage += "- " + fnErrorBadZipCode() + "\n";
    }
    else if (loFormFieldCityName.value != '' && loFormFieldCityName.value != lsFormFieldCityValueDefaultValue && loFormFieldStateName.value == '') {
        //City entered but no state or zip
        lsErrorMessage += "- " + fnErrorNoState() + "\n";
    }
    else if (loFormFieldStateName.value != '' && (loFormFieldCityName.value == lsFormFieldCityValueDefaultValue || loFormFieldCityName.value == '') && (loFormFieldZipName.value == '' || loFormFieldZipName.value == lsFormFieldZipValueDefaultValue)) {
        //State selected but no Zip or City
        lsErrorMessage += "- " + fnErrorNoCity() + "\n";
    }

    if (lsErrorMessage) {
        alert(lsErrorMessage);
    }
    else {
        if (loFormFieldZipName.value != '' && loFormFieldZipName.value != lsFormFieldZipValueDefaultValue) {
            lsVariables = (lbMember) ? 'txtZip=' + loFormFieldZipName.value : "";
            loFormFieldCityName.value = '';
            loFormFieldStateName.value = '';
            lsCriteriaType = 'zip';
            lsCriteriaValue = loFormFieldZipName.value;
        }
        else {
            lsVariables = (lbMember) ? 'txtCity=' + loFormFieldCityName.value + '&txtCity=' + loFormFieldStateName.value : "";
            loFormFieldZipName.value = '';
            lsCriteriaType = 'city';
            lsCriteriaValue = loFormFieldCityName.value + '~' + loFormFieldStateName.value;
        }


        if (psButtonClicked == lsViewMapButtonName) {
            lsTemplateComplete = (lbMember) ? '&code=' + loTemplate.value : "";
            lsVariables = "criteriaType=" + lsCriteriaType + '&criteriaValue=' + lsCriteriaValue + lsTemplateComplete;
            lsURLDestination = _mappingUrl;
        }
        else {
            lsCriteriaValue = lsCriteriaValue.replace('~', ', ');
            lsVariables = (lbMember) ? lsVariables : 'zipcode=' + lsCriteriaValue + "&zipOnly=true";

        }

        // Clear out cookie value
        fnClearSearchRequestCookieValue();

        fnForm('', lsURLDestination, '', lsVariables);

        _hbLink(lsButtonToTrack, 'right', '0,0,30,30');
        return true;
    }
}

function fnForm(paElementIDs, psDestination, psVariableInitialAdditionOverRide, psVariables) {
    // paElementNames are the id's of all elements to be submitted, psDestination is the destination the elements are being submitted to.
    var laElementIDs = paElementIDs.split(", "); // put the Elements into an array called laElementIDs
    var loElementID; 			// used in the loop for the specific element
    var lsVariableInitialAddition = (psVariableInitialAdditionOverRide) ? psVariableInitialAdditionOverRide : "?";
    var lsVariables = (psVariables != null) ? psVariables : ""; // the variables to be listed in the destination URL

    if (paElementIDs) {
        for (var x = 0; x < laElementIDs.length; x++) {
            //cycle through the elements
            var loElementID = document.getElementById(laElementIDs[x]);
            if (x != 0) { lsVariables += "&"; } // check if it's the first addition of a variable: if it's not add an &
            lsVariables += loElementID.name + "=" + loElementID.value; // add on the variable		
        }
    }

    if (lsVariables.toLowerCase().match("password") != null) {
        document.getElementById('ifLogin').src = psDestination + lsVariableInitialAddition + lsVariables;
    }
    else {
        document.location.href = psDestination + lsVariableInitialAddition + lsVariables; // add on the variable to the end of the destination
    }

}

function fnEnterSubmit(psSubmit, psEvent) {
    // check if the key hit is "return," submit via the submit function if it is
    // Usage: pass the name of the button (poSubmit) and an event (psEvent, usually event) when calling this script
    var liCharacter;

    liCharacter = (psEvent && psEvent.which) ? psEvent.which : ((psEvent) ? psEvent.keyCode : null); //determine whether to use the Netscape or IE key character

    if (liCharacter == 13 || psEvent == "enter")	// if the user hits return or clicks the button
    {
        fnActivate(psSubmit);
    }
}

function fnGetCookie(psName) {
    var liStart = document.cookie.indexOf(psName + "=");
    var liLen = liStart + psName.length + 1;

    if ((!liStart) && (psName != document.cookie.substring(0, psName.length))) { return null; }
    if (liStart == -1) { return null; }
    var liEnd = document.cookie.indexOf(";", liLen);
    if (liEnd == -1) {
        liEnd = document.cookie.length;
    }
    return unescape(document.cookie.substring(liLen, liEnd));
}

function fnTrim(psCleanup) {
    while (psCleanup.substring(0, 1) == ' ') {
        psCleanup = psCleanup.substring(1, psCleanup.length);
    }
    while (psCleanup.substring(psCleanup.length - 1, psCleanup.length) == ' ') {
        psCleanup = psCleanup.substring(0, psCleanup.length - 1);
    }
    psCleanup.replace(/^\s*|\s*$/g, "");
    return psCleanup;
}


/*
* jQuery JSON Plugin
* version: 2.1 (2009-08-14)
*
* This document is licensed as free software under the terms of the
* MIT License: http://www.opensource.org/licenses/mit-license.php
*
* Brantley Harris wrote this plugin. It is based somewhat on the JSON.org 
* website's http://www.json.org/json2.js, which proclaims:
* "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.", a sentiment that
* I uphold.
*
* It is also influenced heavily by MochiKit's serializeJSON, which is 
* copyrighted 2005 by Bob Ippolito.
*/

(function ($) {
    /** jQuery.toJSON( json-serializble )
    Converts the given argument into a JSON respresentation.

    If an object has a "toJSON" function, that will be used to get the representation.
    Non-integer/string keys are skipped in the object, as are keys that point to a function.

    json-serializble:
    The *thing* to be converted.
    **/
    $.toJSON = function (o) {
        if (typeof (JSON) == 'object' && JSON.stringify)
            return JSON.stringify(o);

        var type = typeof (o);

        if (o === null)
            return "null";

        if (type == "undefined")
            return undefined;

        if (type == "number" || type == "boolean")
            return o + "";

        if (type == "string")
            return $.quoteString(o);

        if (type == 'object') {
            if (typeof o.toJSON == "function")
                return $.toJSON(o.toJSON());

            if (o.constructor === Date) {
                var month = o.getUTCMonth() + 1;
                if (month < 10) month = '0' + month;

                var day = o.getUTCDate();
                if (day < 10) day = '0' + day;

                var year = o.getUTCFullYear();

                var hours = o.getUTCHours();
                if (hours < 10) hours = '0' + hours;

                var minutes = o.getUTCMinutes();
                if (minutes < 10) minutes = '0' + minutes;

                var seconds = o.getUTCSeconds();
                if (seconds < 10) seconds = '0' + seconds;

                var milli = o.getUTCMilliseconds();
                if (milli < 100) milli = '0' + milli;
                if (milli < 10) milli = '0' + milli;

                return '"' + year + '-' + month + '-' + day + 'T' +
                             hours + ':' + minutes + ':' + seconds +
                             '.' + milli + 'Z"';
            }

            if (o.constructor === Array) {
                var ret = [];
                for (var i = 0; i < o.length; i++)
                    ret.push($.toJSON(o[i]) || "null");

                return "[" + ret.join(",") + "]";
            }

            var pairs = [];
            for (var k in o) {
                var name;
                var type = typeof k;

                if (type == "number")
                    name = '"' + k + '"';
                else if (type == "string")
                    name = $.quoteString(k);
                else
                    continue;  //skip non-string or number keys

                if (typeof o[k] == "function")
                    continue;  //skip pairs where the value is a function.

                var val = $.toJSON(o[k]);

                pairs.push(name + ":" + val);
            }

            return "{" + pairs.join(", ") + "}";
        }
    };

    /** jQuery.evalJSON(src)
    Evaluates a given piece of json source.
    **/
    $.evalJSON = function (src) {
        if (typeof (JSON) == 'object' && JSON.parse)
            return JSON.parse(src);
        return eval("(" + src + ")");
    };

    /** jQuery.secureEvalJSON(src)
    Evals JSON in a way that is *more* secure.
    **/
    $.secureEvalJSON = function (src) {
        if (typeof (JSON) == 'object' && JSON.parse)
            return JSON.parse(src);

        var filtered = src;
        filtered = filtered.replace(/\\["\\\/bfnrtu]/g, '@');
        filtered = filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
        filtered = filtered.replace(/(?:^|:|,)(?:\s*\[)+/g, '');

        if (/^[\],:{}\s]*$/.test(filtered))
            return eval("(" + src + ")");
        else
            throw new SyntaxError("Error parsing JSON, source is not valid.");
    };

    /** jQuery.quoteString(string)
    Returns a string-repr of a string, escaping quotes intelligently.  
    Mostly a support function for toJSON.
    
    Examples:
    >>> jQuery.quoteString("apple")
    "apple"
        
    >>> jQuery.quoteString('"Where are we going?", she asked.')
    "\"Where are we going?\", she asked."
    **/
    $.quoteString = function (string) {
        if (string.match(_escapeable)) {
            return '"' + string.replace(_escapeable, function (a) {
                var c = _meta[a];
                if (typeof c === 'string') return c;
                c = a.charCodeAt();
                return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
            }) + '"';
        }
        return '"' + string + '"';
    };

    var _escapeable = /["\\\x00-\x1f\x7f-\x9f]/g;

    var _meta = {
        '\b': '\\b',
        '\t': '\\t',
        '\n': '\\n',
        '\f': '\\f',
        '\r': '\\r',
        '"': '\\"',
        '\\': '\\\\'
    };
})(jQuery);

// make sure that tootip plugins are loaded 
// !!! This part forces to load same javascript twice if version parameter is used (?v=) !!! 
// so it's better to check that .bt function exists
if (typeof ($(document).bt) == "undefined") {
    LoadDOMScript("/jscript/jquery/jquery.bt.min.js");
}

if ($.browser.msie) {
    LoadDOMScript("/jscript/jquery/excanvas-compressed.js");
    LoadDOMScript("/jscript/jquery/jquery.bgiframe.min.js");
}

(function ($) {
    var __initItems = new Array();

    var settings =
    {
        position: "TopRight",
        element: "span",
        cssClass: "tabCallOut newIcon",
        html: " ",
        customOffset: { top: 0, left: 0 },
        dependsOnParent: false
    };

    var methods =
    {
        init: function (options) {
            if (options) { $.extend(settings, options); }

            return this.each(function () {
                var $this = (settings.dependsOnParent) ? $(this).parent() : $(this);

                if (!$this.hasClass("status-flag-active")) {
                    var flag = $(document.createElement(settings.element));

                    flag.addClass(settings.cssClass)
                        .html(settings.html)
                        .css({ position: "absolute" });

                    if ($this.parent() && $this.parent().length > 0 && $this.parent()[0].tagName.toLowerCase().indexOf("ul") > -1) {
                        flag.insertBefore($this.parent());
                    }
                    else {
                        flag.insertBefore($this);
                    }

                    var position = { top: 0, left: 0 };

                    switch (settings.position) {
                        case "RightTop":
                            position.top = $this.offset().top;
                            position.left = $this.offset().left + $this.width();
                            break;

                        case "RightMiddle":
                            position.top = $this.offset().top + $this.height() / 2 - flag.outerHeight() / 2;
                            position.left = $this.offset().left + $this.width();
                            break;

                        case "RightBottom":
                            position.top = $this.offset().top + $this.height() - flag.outerHeight();
                            position.left = $this.offset().left + $this.width();
                            break;

                        case "BottomRight":
                            position.top = $this.offset().top + $this.height();
                            position.left = $this.offset().left + $this.width() - flag.outerWidth();
                            break;

                        case "BottomMiddle":
                            position.top = $this.offset().top + $this.height();
                            position.left = $this.offset().left + $this.width() / 2 - flag.outerWidth() / 2;
                            break;

                        case "BottomLeft":
                            position.top = $this.offset().top + $this.height();
                            position.left = $this.offset().left;
                            break;

                        case "leftBottom":
                            position.top = $this.offset().top + $this.height() - flag.outerHeight();
                            position.left = $this.offset().left - flag.outerWidth();
                            break;

                        case "leftMiddle":
                            position.top = $this.offset().top + $this.height() / 2 - flag.outerHeight() / 2;
                            position.left = $this.offset().left - flag.outerWidth();
                            break;

                        case "leftTop":
                            position.top = $this.offset().top;
                            position.left = $this.offset().left - flag.outerWidth();
                            break;

                        case "TopLeft":
                            position.top = $this.offset().top - flag.outerHeight();
                            position.left = $this.offset().left;
                            break;

                        case "TopMiddle":
                            position.top = $this.offset().top - flag.outerHeight();
                            position.left = $this.offset().left + $this.width() / 2 - flag.outerWidth() / 2;
                            break;

                        case "TopRight":
                        default:
                            position.top = $this.offset().top - flag.outerHeight();
                            position.left = $this.offset().left + $this.width() - flag.outerWidth();
                            break;
                    }

                    if (settings.customOffset) {
                        if (settings.customOffset.top && settings.customOffset.top != 0) {
                            position.top += settings.customOffset.top;
                        }

                        if (settings.customOffset.left && settings.customOffset.left != 0) {
                            position.left += settings.customOffset.left;
                        }
                    }

                    try {
                        flag.offset(position);
                    }
                    catch (e) { }

                    $this.addClass("status-flag-active");
                }
            });
        }
    };

    $.fn.statusflag = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        }
        else if (typeof method === 'object' || !method) {
            __initItems.push({ Selector: this.selector, Options: arguments });

            return methods.init.apply(this, arguments);
        }
        else {
            // Method doesn't exists 
        }
    };

    $.StatusFlags =
    {
        Refresh: function () {
            $(__initItems).each(function (i, v) {
                $(v.Selector).statusflag((typeof (v.Options[0]) != "undefined") ? v.Options[0] : v.Options);
            });
        }
    };
})(jQuery);


//Start custom functions
function showMenu() {
    if (document.getElementById("UserControlPanel_MenuBox").style.display == "none") {
        document.getElementById("UserControlPanel_MenuBox").style.display = "block";
    }
    else {
        document.getElementById("UserControlPanel_MenuBox").style.display = "none";
    }
}

function getQuerystring(key, default_) {
    if (default_ == null) default_ = "";
    key = key.toLowerCase().replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href.toLowerCase());
    if (qs == null)
        return default_;
    else
        return qs[1];
}


//Load Peel out functions
$.getScript('/jscript/jquery/page_flip.js')


//ModalPopup and auto create iFrame functions
//Load js script for modal
$.getScript('/jscript/jquery/jquery.bpopup-0.5.1.min.js')

//Show model function

function fnShowIframeModal(containerID, containerClass, iFrameID, iFrameClass, width, height, iFrameSrc) {

    containerID = containerID == null || containerID.length == 0 ? "IframeModalcontainer" : containerID;
    containerClass = containerClass == null || containerClass.length == 0 ? "" : containerClass;
    iFrameID = iFrameID == null || iFrameID.length == 0 ? "IframeModal" : iFrameID;
    iFrameClass = iFrameClass == null || iFrameClass.length == 0 ? "" : iFrameClass;
    width = width == null || width.length == 0 ? "auto" : width + "px";
    height = height == null || height.length == 0 ? "auto" : height + "px";
    iFrameSrc = iFrameSrc == null || iFrameSrc.length == 0 ? "http://www.realtytrac.com" : iFrameSrc;

    var ElementString = "";
    ElementString = ElementString + "<div id='" + containerID + "' class='" + containerClass + "' style='display:none;text-align:center'>";
    ElementString = ElementString + "<div class='closeX' id='closeIframeModel' onclick='closePop(\"" + containerID + "\");' />";
    ElementString = ElementString + "<iframe frameborder='0' scrolling='no' id='" + iFrameID + "' name='" + iFrameID + "' class='" + iFrameClass + "' width='" + width + "' height='" + height + "'";
    ElementString = ElementString + "src='" + iFrameSrc + "' style='background:#ffffff url(\"/images/icons/loading-redindicator-48x48.gif\") no-repeat center'/></div>"

    //Append to body
    $(ElementString).appendTo('form');

    $("#" + containerID).bPopup({
        onClose: function () { $('#' + containerID).remove(); },
        escClose: false,
        modalClose: false
    });
    disableFeelAwayAd();
}

function disableFeelAwayAd() {
    try {
        var ctlFeelAwayAd = $('.feelawayad');
        if (ctlFeelAwayAd.attr('id') == 'peelback') {
            ctlFeelAwayAd.attr('id', 'dpeelback');
        }
        else {
            ctlFeelAwayAd.attr('id', 'peelback');
        }
    }
    catch (e) {
    }
}

function setDefaultModelIframe(popContainerID) {
    setCloseVisibility(false);
    bRefreshOnClose = false;
}


function closePop(popContainerID) {
    disableFeelAwayAd();
    $("#" + popContainerID).bPopup().close()
    if (typeof (bRefreshOnClose) != "undefined") {
        if (bRefreshOnClose == true)
            location.reload();
    }
}

function resizeFrame(frameId, width, height) {
    var F = document.getElementsByTagName("iframe");
    $.each(F, function (index, value) {
        if (value.id == frameId) {
            value.height = height;
            value.parentNode.style.height = height;

            if (width != null && width != "") {
                value.width = width;
                value.parentNode.style.width = width;
            }

            setDefaultModelIframe(frameId);
        }
    });
}

function setCloseVisibility(hide) {
    if (typeof (document.getElementById("closeIframeModel")) != "undefined") {
        document.getElementById("closeIframeModel").style.display = "block";
        if (hide == true)
            document.getElementById("closeIframeModel").style.display = "none";
    }
}

