//START RealtyTrac.Common.Web.Scripts.ValueTrac.ValueTrac.js
//---------------------------------------------------------------------------------
//--- Search Request (we have to use it when we call webservices)
//---------------------------------------------------------------------------------
var gSearchRequest = null;
var gGlobalResponse = null;
var gTimeoutId;

var gTemplateLoadTimeoutId;
var gTempTabResponse = null;
var gNeedToRefreshBanners = false;
var gPassportKey = "";
var gHbxCustom2 = "";

var MapService = RealtyTrac.ValueTracMapService;

// -----------------------------------------------------
// Add function that will be called on web-service error
// -----------------------------------------------------

function WebServiceErrorHandler(result)
{
    if (result != null && typeof(RealtyTrac.ValueTracMapService) != "undefined"
        && typeof(RealtyTrac.ValueTracMapService.LogError) != "undefined"
        && typeof(result.get_message) != "undefined")
    {
        RealtyTrac.ValueTracMapService.LogError(result.get_message());
    }
}

function ShowServiceNotAvailableMessage()
{
    $("#divNotAvailableMessage").show();
    ToggleTabOverlay(false);  
    if (typeof (ToggleActivityImage) != "undefined") 
    {
        ToggleActivityImage(false);
    }  
}

//if (typeof(RealtyTrac.ValueTracMapService) != "undefined" && typeof(RealtyTrac.ValueTracMapService.set_defaultFailedCallback) == "function")
//{
//    RealtyTrac.ValueTracMapService.set_defaultFailedCallback(WebServiceErrorHandler);
//}


function SearchRequest(streetPart, cityStateZipPart) 
{
    this.streetPart = streetPart;
    this.cityStateZipPart = cityStateZipPart;
}

//-- CONSTANTS
var WEB_SERVICE_TIMEOUT = 120000; // timeout in milliseconds
var LEFT_COLUMN_SMALL_CLASS = "columnLeft";
var LEFT_COLUMN_LARGE_CLASS = "columnLeftLarge";
var RIGHT_COLUMN_LARGE_CLASS = "columnRight";
var RIGHT_COLUMN_SMALL_CLASS = "columnRight";
var gAddresEmailFriend = '';
var gHTMLTemplatesObj = null;
var zoomLevelAdViews = 5;
var gValueTracResponse = null;
var gIsNewSearch = true;

function ToggleTabOverlay(display)
{
    if (display)
    {
        $("#list_Overlay_Container").innerHTML = "";
        $("#list_Overlay_Container").show();
        if (gIsNewSearch)
        {
            if (!gMember && typeof(CreateAdInContainer) === 'function') 
            {
                CreateAdInContainer('overlayAdContainerDiv');
            }
            gIsNewSearch = false;
        }
    }
    else
    {
        $("#list_Overlay_Container").hide();
        gIsNewSearch = true;
    }
}

function SaveSearchAddress() 
{
    try 
    {
        var hash = "";
        if (gSearchRequest)
         {
            hash = (gSearchRequest.streetPart && gSearchRequest.streetPart.length > 0) ? gSearchRequest.streetPart : "";
            hash += (gSearchRequest.cityStateZipPart) ? gSearchRequest.cityStateZipPart : "";
        }

        if (hash.length > 0) 
        {
            window.location.hash = hash;
        }
    }
    catch (ex) 
    {
        LogErrorMessage("SaveSearchAddress: ", ex, true);
    }
}

///////////////////////////////////////////////////////////////////////////////////
//              MAP Functionality for Value Track Project
///////////////////////////////////////////////////////////////////////////////////
//---------------------------------------------------------------------------------
//--- Variables (used to display map, pushpins, popups)
//---------------------------------------------------------------------------------

//-- CONSTANTS
var ARROW_STYLE_TOPRIGHT = "balloon_top_right";
var ARROW_STYLE_TOPLEFT = "balloon_top_left";
var ARROW_STYLE_BOTTOMRIGHT = "balloon_bottom_right";
var ARROW_STYLE_BOTTOMLEFT = "balloon_bottom_left";

var RETRY_FAILURE_COUNT = 3;

var STYLE_NONE = "none";
var STYLE_BLOCK = "block";
var STYLE_HIDDEN = "hidden";
var STYLE_VISIBLE = "visible";

var MAXIMUM_PROPERTY_COUNT = 300;

var NEIGHBORHOOD_SALES_MAP_CONTAINER = "compSalesMap";
var INTERACTIVE_MAP_CONTAINER = "InteractiveMap";
var NEIGHBORHOOD_FORECLOSURES_MAP_CONTAINER = "NeighborhoodForeclosuresMap";
var NEIGHBORHOOD_FORECLOSURES_LANDING_MAP_CONTAINER = "NeighborhoodForeclosuresMapLanding";

var TOO_MANY_PROP_BALLOON_CONTAINER = "mapNav_TooManyProperties";
var NEIGHBORHOOD_FORECLOSURES_MAP_JOIN_NOW_BALLOON_CONTAINER = "joinNowBalloonCnr";
var INTERACTIVE_MAP_JOIN_NOW_BALLOON_CONTAINER = "fullAccessMsgCnr";
var INTERACTIVE_MAP_MENU_CONTAINER = "interactiveMapCnr";
var INTERACTIVE_MAP_JOIN_NOW_BALLOON_CONTAINER_DEFAULT_LEFT = 280;
var TOO_MANY_PROP_BALLOON_CONTAINER_DEFAULT_RIGHT = 160;

var MAP_HELP_CONTAINER = "help_div_cnr";


var INTERACTIVE_MAP_WIDTH_WITH_MENU = 612;
var INTERACTIVE_MAP_WIDTH_WITHOUT_MENU = 763;
var INTERACTIVE_MAP_HEIGHT = 475;

var INTERACTIVE_MAP_AVAILABLE_PROPERTY_TYPES = "P,A,B,E,G,R,F";

var IMAGE_LINK_NA = "http://www.realtytrac.com/images/image_na.gif";

var ZOOM_LEVEL_300 = "16";
var ZOOM_LEVEL_600 = "15";

var LAYER_NAME_COMPARABLE_PROPERTIES = "CompSalesLayer";
var LAYER_NAME_NEARBY_PROPERTIES = "NearbyHomesLayer";
var LAYER_NAME_RTRAC_PROPERTIES = "RTracLayer";
var LAYER_NAME_MAIN_PROPERTY = "CyberHomesMainProperty";

var DESCRIPTION_DIV_DEFAULT_LEFT = 40;
var DESCRIPTION_DIV_DEFAULT_TOP = 40;

var MAP_HELP_DIV = "mapNav_mapRecenter";
//-- Map variables
var gMember = false;
var gInteractiveMap;
var gNeighborhoodForeclosuresMap;
var gNeighborhoodSalesMap;
var gMapContainer;
var gIsMapVisible;
var gZoomLevel;
var gPushPinLayer;
var gTabType;
var gPassportInitialized;
var gPinLayer;
var gActiveMap;
var gPinList;
var gPinIDList;
var gMainProperty;
var gNearbyHomes;
var gComparables;
var gImageArray = new Array();
var gPinClicked;
var gImageArrayPosition = 0;
var gInteractiveMapCheckBoxPrefix;
var gHomeValueCheckboxID;
var gAreaSalesCheckboxID;
var gNeighborhoodDescriptionPin;

var gLatLong;
var gMapZoom;
var gLatLongOriginal;
var gMapZoomOriginal;

var gCurMap = null;

var ForeclosuresMap = null;
var gPinsPos = null;
var NeighborhoodSalesMap = null;
var InteractiveMap = null;
var availablePropTypes = INTERACTIVE_MAP_AVAILABLE_PROPERTY_TYPES;
var ForeclosuresMapLanding = null;
var ForeclosuresMapInfoTab = null;
var isFirstPageLoad = true;
var gShowForeclosuresMap = false;

var TAB_NEIGHBORHOOD_FORECLOSURE = "nhforeclosures";
var TAB_INTERACTIVE_MAP = 4;
var NEIGHBORHOOD_FORECLOSURES_INFOR_TAB_MAP_CONTAINER = "NeighborhoodForeclosuresMapInfoTab";
var TheMapSmall = null;

var gCurrentTab = null;

var CONST_PAGE_TITLE = "Home Valuation Estimate results for {0} at RealtyTrac.com";
var CONST_DEFAULT_PAGE_TITLE = "Welcome to RealtyTrac";

if (undefined == currentMap) 
{
    var currentMap;
}

//---------------------------------------------------------------------------------
//--- Global Functions (functions to work with map, which are used in all controls)
//---------------------------------------------------------------------------------


function hideBaloon() 
{
    try
    {
        element = document.getElementById("descriptionDIV");
        if (element) 
        {
            element.style.display = "none";
        }
    }
    catch (ex) 
    {
        LogErrorMessage("hideBaloon: ", ex, true);
    }
}

function ToggleMapDisplay(mapName, latitude, longitude, zoom) 
{
    try 
    {
        if (TheMap && TheMap.isMapVisible) 
        {
            TheMap.HideMap();
        }
        else 
        {
            TheMap.ShowMap();
        }
    }
    catch (ex) 
    {
        LogErrorMessage("ToggleMapDisplay: ", ex, true);
    }
}

function CloseZoomLevelAdv() 
{
    try 
    {
        var joinBaloon = document.getElementById(NEIGHBORHOOD_FORECLOSURES_MAP_JOIN_NOW_BALLOON_CONTAINER);
        if (joinBaloon) 
        {
            joinBaloon.style.display = "none";
            var currentMap = GetActiveMap();
            if (currentMap.GetMapStyle() != VEMapStyle.Birdseye) 
            {
                currentMap.SetZoomLevel(ZOOM_LEVEL_600);
            }
        }
    }
    catch (ex) 
    {
        LogErrorMessage("CloseZoomLevelAdv: ", ex, true);
    }
}




//---------------------------------------------------------------------------------
//--- Specific Functions (Specific functions for every map)
//---------------------------------------------------------------------------------

function ToggleImage(bAdvancing) 
{
    try 
    {

        //Get the image div
        var imageDiv = document.getElementById('propertyImageDiv');
        if (imageDiv) 
        {

            if (imageDiv) 
            {
                imageDiv.src = "/images/Loading_Small.gif";
            }

            if (bAdvancing) 
            {
                if (gImageArrayPosition < gImageArray.length - 1) 
                {
                    gImageArrayPosition++;
                }
            }
            else 
            {
                if (gImageArrayPosition > 0) 
                {
                    gImageArrayPosition--;
                }
            }

            var hdnImage = document.getElementById('hiddenImage');
            if (hdnImage) 
            {
                hdnImage.src = gImageArray[gImageArrayPosition];

                if (hdnImage.src) 
                {
                    imageDiv.src = hdnImage.src;
                }
            }

            var imageNextLink = document.getElementById('imageNext');
            var imagePreviousLink = document.getElementById('imagePrev');

            if (imageNextLink) 
            {
                imageNextLink.style.textDecoration = "underline";
                imageNextLink.style.cursor = "pointer";

                if (gImageArrayPosition == (gImageArray.length - 1)) 
                {
                    //We are at the end, disable the next 
                    imageNextLink.style.textDecoration = "none";
                    imageNextLink.style.cursor = "default";
                }
            }

            if (imagePreviousLink) 
            {
                imagePreviousLink.style.textDecoration = "underline";
                imagePreviousLink.style.cursor = "pointer";

                if (gImageArrayPosition == 0) 
                {
                    //we are at the beginning, disable the previous
                    imagePreviousLink.style.textDecoration = "none";
                    imagePreviousLink.style.cursor = "default";
                }
            }
        }

    }
    catch (ex) 
    {
        LogErrorMessage("ToggleImage: ", ex, true);
    }
}

function SetImage(obj) 
{
    try 
    {
        var imageDiv = document.getElementById('propertyImageDiv');

        if (imageDiv) 
        {
            imageDiv.src = obj.src;
        }
    }
    catch (ex) 
    {
        LogErrorMessage("SetImage: ", ex);
    }
}


function GetActiveMap() 
{
    try 
    {
        if (undefined != currentMap && null != currentMap) 
        {
            if (gActiveMap == "NeighborhoodForeclosuresMap") 
            {
                currentMap = gNeighborhoodForeclosuresMap;
            }
            else if (gActiveMap == "InteractiveMap") 
            {
                currentMap = gInteractiveMap;
            }
            else if (gActiveMap == "NeighborhoodSalesMap") 
            {
                currentMap = gNeighborhoodSalesMap;
            }
            return currentMap;
        }
    }
    catch (ex) 
    {
        LogErrorMessage("GetActiveMap: ", ex, true);
    }
}

function DisplayFullAccessPopup() 
{
    try 
    {
        var element = document.getElementById(INTERACTIVE_MAP_JOIN_NOW_BALLOON_CONTAINER);
        if (element) 
        {
            element.style.display = "block";
        }
    }
    catch (ex) 
    {
        LogErrorMessage("DisplayFullAccessPopup: ", ex, true);
    }
}

function CloseFullAccessPopup() 
{
    try 
    {
        var element = document.getElementById(INTERACTIVE_MAP_JOIN_NOW_BALLOON_CONTAINER);
        if (element) 
        {
            document.getElementById(INTERACTIVE_MAP_JOIN_NOW_BALLOON_CONTAINER).style.display = "none";
        }
    }
    catch (ex) 
    {
        LogErrorMessage("CloseFullAccessPopup: ", ex, true);
    }
}

function PropertyTypeSelect(propType, checkBoxID) 
{
    try 
    {
        if (!gMember 
            && propType != "O"
            && propType != "R"
            && propType != "F"
            && propType != "S")
        {
            DisplayFullAccessPopup();
        }
        else
        {
            GetInteractiveMapProperties();
        }
        
        return false;
    }
    catch (ex) 
    {
        LogErrorMessage("PropertyTypeSelect: ", ex, true);
    }
}

function ToggleMapMenuDisplay() 
{
    try 
    {
        var element = document.getElementById(INTERACTIVE_MAP_MENU_CONTAINER);
        var mapContainer = document.getElementById(INTERACTIVE_MAP_CONTAINER);
        var popup7Days = document.getElementById(INTERACTIVE_MAP_JOIN_NOW_BALLOON_CONTAINER);
        var tooManyPropPopup = document.getElementById(TOO_MANY_PROP_BALLOON_CONTAINER);
        var popup7DaysLeft = INTERACTIVE_MAP_JOIN_NOW_BALLOON_CONTAINER_DEFAULT_LEFT;
        var tooManyPropPopupRight = TOO_MANY_PROP_BALLOON_CONTAINER_DEFAULT_RIGHT;
        if (element && mapContainer) 
        {
            if (element.style.display == "block") 
            {
                element.style.display = "none";
                document.getElementById('hideLine').src = '/ValueTrac/images/mapClose.gif';
                popup7DaysLeft -= (INTERACTIVE_MAP_WIDTH_WITHOUT_MENU - INTERACTIVE_MAP_WIDTH_WITH_MENU) / 2;
                tooManyPropPopupRight += (INTERACTIVE_MAP_WIDTH_WITHOUT_MENU - INTERACTIVE_MAP_WIDTH_WITH_MENU) / 2;
            }
            else 
            {
                element.style.display = "block";
                document.getElementById('hideLine').src = '/ValueTrac/images/mapOpen.gif';
            }
            ResizeIntMapContainer();
        }

        if (popup7Days) 
        {
            popup7Days.style.left = popup7DaysLeft + "px";
        }
        if (tooManyPropPopup) 
        {
            tooManyPropPopup.style.right = tooManyPropPopupRight + "px";
        }
    }
    catch (ex) 
    {
        LogErrorMessage("ToggleMapMenuDisplay: ", ex, true);
    }
}

function _ToggleMapMenuDisplay() {

    /* new function to replace ToggleMapMenuDisplay() */
    var element = document.getElementById(INTERACTIVE_MAP_MENU_CONTAINER);
    var mapContainer = document.getElementById(INTERACTIVE_MAP_CONTAINER);
    
    if (element.className == "legend")
    {
        element.className = "legend closed";
        mapContainer.className = "mapContent opened";
        mapContainer.style.width = "915px";
    }
    else
    {
        element.className = "legend";
        mapContainer.className = "mapContent";
        mapContainer.style.width = "724px";
    }
}

function IsCheckboxChecked(id) 
{
    try 
    {
        var element = document.getElementById(id);
        if (element) 
        {
            if (element.checked) 
            {
                return true;
            }
        }
        return false;
    }
    catch (ex) 
    {
        LogErrorMessage("IsCheckboxChecked: ", ex, true);
    }
}

function GetInteractiveMapPropertyTypes() 
{
    try 
    {
        var types = INTERACTIVE_MAP_AVAILABLE_PROPERTY_TYPES.split(',');
        var propTypes = "";
        var element;

        for (var i = 0; i < types.length; i++) 
        {
            element = document.getElementById(gInteractiveMapCheckBoxPrefix + types[i]);
            if (element && element.checked) 
            {
                propTypes += (types[i] + ",");
            }
        }

        if (propTypes.length > 0) 
        {
            propTypes = propTypes.substring(0, propTypes.length - 1);
        }

        return propTypes;
    }
    catch (ex) 
    {
        LogErrorMessage("GetInteractiveMapPropertyTypes: ", ex, true);
    }

}

function SetPropertyCount(propertyCount) 
{
    try 
    {
        var count = propertyCount;
        var map = GetActiveMap();
        if (map) 
        {
            if (map.GetMapStyle() == VEMapStyle.Birdseye || map.GetMapStyle() == VEMapStyle.BirdseyeHybrid) 
            {
                count = GetBirdsEyePropertyCount(map);
            }
        }
        var element = document.getElementById("propertyCount");
        if (element) 
        {
            element.innerHTML = count;
        }
    }
    catch (ex) 
    {
        LogErrorMessage("SetPropertyCount: ", ex, true);
    }
}

function GetBirdsEyePropertyCount(map) 
{
    try 
    {
        var count = 0;
        if (gMainProperty || gNeighborhoodDescriptionPin) 
        {
            count = 1;
        }
        for (i == 0; i < gPinIDList.length; i++) 
        {
            var pin = map.GetShapeByID(gPinIDList[i]);
            if (pin) 
            {
                var birdsEye = map.GetBirdseyeScene();
                var mapPixel = birdsEye.LatLongToPixel(map.GetCenter(), map.GetZoomLevel());
                var pinLatLong = new VELatLong(pin.Latitude, pin.Longitude);
                var pinPixel = birdsEye.LatLongToPixel(pinLatLong, map.GetZoomLevel());
                var mapWidth;

                if (document.getElementById(INTERACTIVE_MAP_MENU_CONTAINER).style.display == "block") 
                {
                    mapWidth = INTERACTIVE_MAP_WIDTH_WITH_MENU;
                }
                else 
                {
                    mapWidth = INTERACTIVE_MAP_WIDTH_WITHOUT_MENU;
                }

                if (pinPixel.x >= (mapPixel.x - (mapWidth + 40) / 2) && pinPixel.x <= (mapPixel.x + (mapWidth + 40) / 2)) 
                {
                    if (pinPixel.y >= (mapPixel.y - (INTERACTIVE_MAP_HEIGHT + 40) / 2) && pinPixel.y <= (mapPixel.y + (INTERACTIVE_MAP_HEIGHT + 40) / 2)) 
                    {
                        count++;
                    }
                }
            }
        }
        return count;
    }
    catch (ex) 
    {
        LogErrorMessage("GetBirdsEyePropertyCount: ", ex, true);
    }
}


function ClosePopups() 
{
    try 
    {
        hideBaloon();
        CloseZoomLevelAdv();
        ToggleTooManyPropPopup(0);
        CloseMapHelp();
    }
    catch (ex) 
    {
        LogErrorMessage("ClosePopups: ", ex, true);
    }
}


function SaveMapState(map) 
{
    try 
    {
        if (map) 
        {
            gLatLong = map.GetCenter();
            gMapZoom = map.GetZoomLevel();
        }
    }
    catch (ex) 
    {
        LogErrorMessage("SaveMapState: ", ex, true);
    }
}

function RestoreMap() 
{

    var map = GetActiveMap();
    if (map) 
    {
        if (gLatLong != null && gMapZoom != null) 
        {
            map.SetCenterAndZoom(gLatLong, gMapZoom);
        }
    }
}

function RestoreOriginalMapPosition() 
{
    var map = GetActiveMap();
    if (map) 
    {
        if (gLatLongOriginal != null) 
        {
            map.SetCenter(gLatLongOriginal);
        }
    }
}

function SaveOriginalMapPosition(latlong, zoom) 
{
    gLatLongOriginal = latlong;
    gMapZoomOriginal = zoom;
}

function HideBirdsEyeBtn() 
{
    try 
    {
        var btnBirdsEye = document.getElementById("MSVE_navAction_ObliqueMapView");
        var btnBirdsEyeSeparator = document.getElementById("MSVE_navAction_separator2");
        var btnLabels = document.getElementById("MSVE_navAction_showLabels");
        var btnLabelsSeparator = document.getElementById("MSVE_navAction_separator3");

        if (btnBirdsEye) 
        {
            btnBirdsEye.style.display = STYLE_NONE;
        }

        if (btnLabels) 
        {
            btnLabels.style.display = STYLE_NONE;
        }

        if (btnBirdsEyeSeparator) 
        {
            btnBirdsEyeSeparator.style.display = STYLE_NONE;
        }

        if (btnLabelsSeparator) 
        {
            btnLabelsSeparator.style.display = STYLE_NONE;
        }
    }
    catch (ex) 
    {
        LogErrorMessage("HideBirdsEyeBtn: ", ex, true);
    }

}

function ShowHideDisclaimer() 
{
    try 
    {
        var parentDiv = document.getElementById("mapNav_TooManyProperties");
        var disclaimer = document.getElementById("disclaimer");
        var sign = document.getElementById("sign");

        var height = "140px";
        var top = "170px";
        var heightVisible = "350px";
        var topVisible = "100px";

        var activeMap = GetActiveMap();
        if (activeMap == gInteractiveMap) 
        {
            heightVisible = "350px";
        }
        else if (activeMap == gNeighborhoodForeclosuresMap) 
        {
            heightVisible = "190px";
            topVisible = "170px";
        }

        if (disclaimer.style.display == "block") 
        {
            parentDiv.style.height = height;
            parentDiv.style.top = top;
            disclaimer.style.display = "none";
            sign.innerText = '+';
        }
        else 
        {
            parentDiv.style.height = heightVisible;
            parentDiv.style.top = topVisible;
            disclaimer.style.display = "block";
            sign.innerText = '-';
        }
    }
    catch (ex) 
    {
        LogErrorMessage("ShowHideDisclaimer: ", ex, true);
    }
}


/* Change "content" div class. None of these containers exist */
function ChangeLeftColumnClass(setLarge) 
{
    try 
    {
        var leftColumn = document.getElementById("innerContentDiv");
        var rightColumn = document.getElementById("rightColumn");
        var birdsEyeCnr = document.getElementById("birdsEyeCnr");

        if (leftColumn && rightColumn) 
        {
            if (setLarge) 
            {
                leftColumn.className = LEFT_COLUMN_LARGE_CLASS;
                rightColumn.className = RIGHT_COLUMN_LARGE_CLASS;
                if (birdsEyeCnr) 
                {
                    birdsEyeCnr.className = STYLE_NONE;
                }
            }
            else 
            {
                leftColumn.className = LEFT_COLUMN_SMALL_CLASS;
                rightColumn.className = RIGHT_COLUMN_SMALL_CLASS;
            }
        }
    }
    catch (ex) 
    {
        LogErrorMessage("ChangeLeftColumnClass: ", ex, true);
    }
}


function Redirect(url) 
{
    try 
    {
        window.location = url;
    }
    catch (ex) 
    {
        LogErrorMessage("Redirect: ", ex, true);
    }
}

/* Mouseover image rolls */
function VT_swapImg(imgObj, idxKey) 
{
    try
    {
        var src = "";
        var pointIndex = 0;

        if (imgObj != null) 
        {
            src = imgObj.src;
            if (src.indexOf(idxKey) >= 0) 
            {
                src = src.replace(idxKey, "");
            }
            else 
            {
                pointIndex = src.indexOf(".");
                if (pointIndex > 0) 
                {
                    var fileType = src.substring(pointIndex);
                    var fileName = src.substring(0, pointIndex);
                    src = fileName + idxKey + fileType;
                }
            }

            imgObj.src = src;
        }
    }
    catch (ex) 
    {
        LogErrorMessage("PD_swapImg: ", ex, true);
    }
}


function SwapImage(elementID, mapDivID) 
{
    try 
    {
        var viewMapHelpCenter = document.getElementById('viewMapHelpCenter');
    
        if (TheMap && TheMap.isMapVisible) 
        {
            if (viewMapHelpCenter != null)
            {
                viewMapHelpCenter.style.display = 'none';
            }
            TheMap.HideMap();
            $('#' + elementID).html('SHOW MAP');
        }
        else 
        {
            if (viewMapHelpCenter != null)
            {
                viewMapHelpCenter.style.display = 'block';
            }
            TheMap.ShowMap();
            $('#' + elementID).html('HIDE MAP');
        }
    }
    catch (ex) 
    {
        LogErrorMessage("SwapImage: ", ex, true);
    }
}

function ChangeMapButtonsVisibility(visible)
{
    try 
    {
        var mapMenuButtons = document.getElementById('mapMenuButtons');
        var mapMenuButtonsDummy = document.getElementById('mapMenuButtonsDummy');
    
        if (mapMenuButtons != null && mapMenuButtonsDummy != null) 
        {
            if (visible)
            {
                    mapMenuButtons.style.display = 'block';
                    mapMenuButtonsDummy.style.display = 'none';
            }
            else
            {
                    mapMenuButtons.style.display = 'none';
                    mapMenuButtonsDummy.style.display = 'block';
            }
        }
     }
    catch (ex) 
    {
        LogErrorMessage("ChangeMapButtonsVisibility: ", ex, true);
    }
}

function SwapImageDiv(elementID) 
{
    try 
    {
        var viewMapHelpCenter = document.getElementById('viewMapHelpCenter');
        
        if (TheMap && TheMap.isMapVisible) 
        {
            if (viewMapHelpCenter != null)
            {
                viewMapHelpCenter.style.display = 'none';
            }
            ChangeMapButtonsVisibility(false);
            TheMap.HideMap();
            $('#balloonDescriptionCnr').hide();
            $('#'+elementID).html('SHOW MAP');
        }
        else 
        {
            if (viewMapHelpCenter != null)
            {
                viewMapHelpCenter.style.display = 'block';
            }
            ChangeMapButtonsVisibility(true);
            TheMap.ShowMap();
            $('#balloonDescriptionCnr').show();
            $('#'+elementID).html('HIDE MAP');
        }
    }
    catch (ex) 
    {
        LogErrorMessage("SwapImageDiv: ", ex, true);
    }
}

function PD_ShowHideQuestion(mDiv, obj, Obx, Oby, Ovr) 
{
    try 
    {
        // Remove any whitespace characters.
        var nDiv = mDiv.replace(/\s/g, '_');

        // position and show.
        var iDiv = document.getElementById(nDiv);

        if (!iDiv) 
        {
            return false;
        }

        var curleft = 0
        var curtop = 0;
        var curwidth = 0;
        var newWidth = 368;
        // retrieves shadow <div>
        var sDiv = iDiv.lastChild;

        if (obj.offsetParent && obj.offsetWidth) 
        {
            curleft = obj.offsetLeft;
            curtop = obj.offsetTop;
            curwidth = obj.offsetWidth;
            while (obj = obj.offsetParent) 
            {
                curleft += obj.offsetLeft;
                curtop += obj.offsetTop;
            }
            curtop += Oby;
            curleft += curwidth - Obx;
        }
        else 
        {
            return false;
        }

        iDiv.style.top = curtop + "px";
        iDiv.style.left = curleft + "px";
        //newWidth -= curleft;

        if (sDiv.tagName == 'DIV') 
        {
            iDiv.style.width = newWidth + "px";
            sDiv.style.width = newWidth + "px";
            iDiv.style.zIndex = 230;
        }

        iDiv.style.display = (iDiv.style.display.indexOf("block") < 0 && Ovr == 1) ? "block" : "none";
    }
    catch (ex) 
    {
        LogErrorMessage("PD_ShowHideQuestion: ", ex, true);
    }
}

function CloseInvalidPopupAddress() 
{
    var popup = document.getElementById("invalidAddressDiv");
    if (popup) 
    {
        popup.style.display = STYLE_NONE;
    }
}

//------------------------------------------------------------------------------------------------------------------------------


function PlaceMapOnPage(containerName) 
{
    try 
    {
        var isMapCreated = false;
        var temp = null;

        temp = new MapSearch(containerName);
        temp.isValueTrac = true;
        temp.pathToImgFolder = '/valuetrac/images/';
        temp.SetMapContainerDivName(containerName);
        isMapCreated = temp.CreateMapSearchMap();

        return temp;
    }
    catch (ex) 
    {
        LogErrorMessage("PlaceMapOnPage: ", ex);
    }
}

function CreateMap(containerName) 
{
    try 
    {
        var tmpMap = null;
        tmpMap = PlaceMapOnPage(containerName);
        if (tmpMap) 
        {
            //once created the Map we show it
            tmpMap.gMapSearchObj.ClearInfoBoxStyles();
            //set path to the Image of Bird eye Loading gif in Pop Ups

            tmpMap.PinsOnMap.PopUpClass.ImgBELoadingPath = tmpMap.pathToImgFolder;
        }
        return tmpMap;
    }
    catch (ex) 
    {
        LogErrorMessage("CreateMap: ", ex);
    }
}

function InitMaps()
{
    TheMap = null;
}

function InitSmallMaps() 
{
    TheMapSmall = null;
    ForeclosuresMapLanding = null;
    ForeclosuresMapInfoTab = null;
}

//---------------------------------------------------------------------------
//--------------- Neighborhood Foreclosures map -----------------------------
//---------------------------------------------------------------------------

function ShowForeclosuresMap(latitude, longitude, zoom) 
{
    try 
    {
        InitMaps();
        var viewMapCnr = document.getElementById('viewMapCnr');
        if (viewMapCnr) 
        {
            viewMapCnr.style.display = 'block';
        }
        gMapContainer = NEIGHBORHOOD_FORECLOSURES_MAP_CONTAINER;
        if (ForeclosuresMap == null)
        {
            ForeclosuresMap = CreateMap(NEIGHBORHOOD_FORECLOSURES_MAP_CONTAINER);
        }
        if (ForeclosuresMap && ForeclosuresMap.isMapCreated) 
        {
            gActiveMap = 'NeighborhoodForeclosuresMap';
            TheMap = ForeclosuresMap;
            TheMap.ShowMap();

            if (latitude != null && longitude != null && zoom != null) 
            {
                var latlong = new VELatLong(latitude, longitude);
                if (typeof (gSearchAddressSerialized) != "undefined" && gSearchAddressSerialized != null)
                {
                    var AddressQualified = DeserializeObject(gSearchAddressSerialized);
                    
                    if(AddressQualified.AddressType == 6)//state level
                    {
                        zoom = 7;
                    }
                    else if (AddressQualified.AddressType == 2)//county level
                    {
                        zoom = 10;
                    }
                    else if (AddressQualified.AddressType == 3 || AddressQualified.AddressType == 4)
                    {
                        zoom = 12;
                    }
                }
                TheMap.gMapSearchObj.SetCenterAndZoom(latlong, zoom);
                TheMap.mapCenterFromSearch = TheMap.gMapSearchObj.GetCenter();
                TheMap.prevLatLong = latlong;
                
                TheMap.prevZoom = zoom;
            }

            hideBaloon();
            GetNeighborhoodForeclosures();
        }
    }
    catch (ex) 
    {
        LogErrorMessage("ShowForeclosuresMap: ", ex, true);
    }
}

function GetNeighborhoodForeclosures() 
{
    try 
    {
        //ForeclosuresMap = TheMap;
        TheMap.GetNeighborhoodForeclosures(gSearchRequest.streetPart,
											gSearchRequest.cityStateZipPart,
											'P,B,A',
											GetNeighborhoodForeclosures_Continue);
    }
    catch (ex) 
    {
        LogErrorMessage("GetNeighborhoodForeclosures: ", ex, true);
    }
}

function GetNeighborhoodForeclosures_Continue(objFullPoiResult) 
{
    try 
    {
        if (objFullPoiResult) 
        {
            //TheMap = ForeclosuresMap;
            var propertyCount = objFullPoiResult.PropertyCount;

            gMainProperty = objFullPoiResult.MainProperty;
            gNeighborhoodDescriptionPin = objFullPoiResult.NeighborhoodDescription;

            GetPins_Continue(objFullPoiResult);
        }
    }
    catch (ex) 
    {
        LogErrorMessage("GetNeighborhoodForeclosures_Continue: ", ex, true);
    }
}

function GetNeighborhoodForeclosuresSmall_Continue(objFullPoiResult) 
{
    try 
    {

        if (objFullPoiResult) 
        {

            var propertyCount = objFullPoiResult.PropertyCount;

            gMainProperty = objFullPoiResult.MainProperty;
            gNeighborhoodDescriptionPin = objFullPoiResult.NeighborhoodDescription;

            GetPinsSmallMap_Continue(objFullPoiResult);
        }
    }
    catch (ex) 
    {
        LogErrorMessage("GetNeighborhoodForeclosuresSmall_Continue: ", ex, true);
    }
}


//-------------------------------------------------------------------------
//----------------------  Pins On Map -------------------------------------
//-------------------------------------------------------------------------

function GetPins() 
{
    try 
    {
        hideBaloon();

        var latLongRect = GetMapCoordinates(GetActiveMap());
        if (TheMap) 
        {
            TheMap.GetValueTracPins(GetVisiblePropertyTypes(), GetPins_Continue);
        }
    }
    catch (ex) 
    {
        LogErrorMessage("GetPins: ", ex, true);
    }
}

function GetPins_Continue(objPoiResult) 
{
    try 
    {
        TheMap.PinsOnMap.ValueTracMainPropData = null;

        if (objPoiResult.AreaCenters == null && objPoiResult.PoiList != undefined) 
        {


            if (!TheMap.IsBirdEyeView() || (TheMap.IsBirdEyeView() && gMember)) 
            {
                //Setting Pins Parameters
                TheMap.PinsOnMap.imgNamePropPin = 'balloon_Map_';
                TheMap.PinsOnMap.imgPinPath = '/valuetrac/images/propertyType/';
                TheMap.PinsOnMap.AddPinsValueTrac(objPoiResult);
            }

            if (objPoiResult.MainProperty != null) 
            {
                TheMap.PinsOnMap.imgNameMainPropPin = 'icon_mapCenter';
                TheMap.PinsOnMap.imgPinPath = '/valuetrac/images/';
                TheMap.PinsOnMap.PopUpClass.ValueTracMainPropData = objPoiResult.MainProperty;
                TheMap.PinsOnMap.DrawMainPropertPin(objPoiResult.MainProperty);
            }
        }

        if (objPoiResult.AreaCenters != null && objPoiResult.AreaCenters.AreaCenter != null) 
        {

            TheMap.PinsOnMap.PopUpClass.GroupedPopup(objPoiResult.AreaCenters.AreaType);
            
            var divGrpPopup = document.getElementById('divGrpPopup');
            var OFFSET_Y = 7;
            var center = TheMap.gMapSearchObj.LatLongToPixel(TheMap.gMapSearchObj.GetCenter());
            if (null != center && center.y > 0)
            {
                var mapH = center.y * 2;
                divGrpPopup.style.top = (parseInt(eval(mapH)) + OFFSET_Y) + 'px';
            }
            
            TheMap.PinsOnMap.DrawGroupedPins(objPoiResult);
        }

        if (TheMap.MapSearchName == NEIGHBORHOOD_FORECLOSURES_MAP_CONTAINER) 
        {
            TheMap.AttachEvents();
        }
        else 
        {
            dissableMouseWheelZoom = function() 
            {
                return true; 
            }
            TheMap.gMapSearchObj.AttachEvent("onmousewheel", dissableMouseWheelZoom);

            dissableEventsOnMap = function(e) 
            {

                if (e.leftMouseButton == true) 
                {
                    return true;
                }

                return false;
            }
            
            TheMap.gMapSearchObj.AttachEvent("onmousemove", dissableEventsOnMap);
            ShowHideOverlayMap(false);
        }
    }
    catch (ex) 
    {
        LogErrorMessage("GetPins_Continue: ", ex, true);
    }
}

function GetPinsSmallMap_Continue(objPoiResult) 
{
    try
    {
        var curMap = null;
        if (null != ForeclosuresMapInfoTab) 
        {
            curMap = ForeclosuresMapInfoTab;
        }

        if (null != ForeclosuresMapLanding) 
        {
            curMap = ForeclosuresMapLanding; 
        }

        curMap.PinsOnMap.ValueTracMainPropData = null;

        if (objPoiResult.AreaCenters == null && objPoiResult.PoiList != undefined) 
        {


            if (!curMap.IsBirdEyeView() || (curMap.IsBirdEyeView() && gMember)) 
            {
                //Setting Pins Parameters
                curMap.PinsOnMap.imgNamePropPin = 'balloon_Map_';
                curMap.PinsOnMap.imgPinPath = '/valuetrac/images/propertyType/';
                curMap.PinsOnMap.AddPinsValueTrac(objPoiResult);
            }

            if (objPoiResult.MainProperty != null) 
            {
                curMap.PinsOnMap.imgNameMainPropPin = 'icon_mapCenter';
                curMap.PinsOnMap.imgPinPath = '/valuetrac/images/';
                curMap.PinsOnMap.PopUpClass.ValueTracMainPropData = objPoiResult.MainProperty;
                curMap.PinsOnMap.DrawMainPropertPin(objPoiResult.MainProperty);
            }

            //CheckBestViewSmallMap(curMap, objPoiResult);
        }

        if (objPoiResult.AreaCenters != null && objPoiResult.AreaCenters.AreaCenter != null) 
        {
            curMap.PinsOnMap.PopUpClass.GroupedPopup(objPoiResult.AreaCenters.AreaType);
            curMap.PinsOnMap.DrawGroupedPins(objPoiResult);
        }

        DissableEventsOnMap(curMap);

        ShowHideOverlayMap(false);
    }
    catch (ex) 
    {
        LogErrorMessage("GetPins_Continue: ", ex, true);
    }
}

function DissableEventsOnMap(curMap) 
{
    dissableMouseWheelZoom = function() { return true; }

    curMap.gMapSearchObj.AttachEvent("onmousewheel", dissableMouseWheelZoom);

    dissableEventsOnMap = function(e) 
    {

        if (e.leftMouseButton == true) 
        {
            return true;
        }

        return false;
    }
    curMap.gMapSearchObj.AttachEvent("onmousemove", dissableEventsOnMap);
}

function CheckBestViewSmallMap(curMap, objPoiResult) 
{

    //we search for the right zoom level to show all the pins
    if (objPoiResult.PoiList != null && objPoiResult.PoiList.length > 0 && isFirstPageLoad) 
    {
        var locs = new Array;
        if (objPoiResult.MainProperty != null) 
        {
            var loc = new VELatLong(curMap.PinsOnMap.PopUpClass.ValueTracMainPropData.Latitude, curMap.PinsOnMap.PopUpClass.ValueTracMainPropData.Longitude);
            locs.push(loc);
        }

        for (var i = 0; i < objPoiResult.PoiList.length; i++) 
        {
            loc = new VELatLong(objPoiResult.PoiList[i].Latitude, objPoiResult.PoiList[i].Longitude);
            locs.push(loc);
        }

        curMap.gMapSearchObj.SetMapView(locs);
    }
}

//---------------------------------------------------------------------------
//--------------- Neighborhood Foreclosures Landing map -----------------------------
//---------------------------------------------------------------------------

//Wait till window load to avoid an error
function ShowForeclosuresMapLanding_check() 
{
    var oldLoad = window.onload;
    
    window.onload = function() 
    {
        if (oldLoad != null) 
        {
            oldLoad();
        }

    }
    ShowForeclosuresMapLanding();
}

function ShowForeclosuresMapLanding() 
{
    try 
    {
        InitSmallMaps();
        ShowHideOverlayDivValues(true);
        ShowHideOverlayMap(true);
        HideContentNoNeed();
        gMapContainer = NEIGHBORHOOD_FORECLOSURES_LANDING_MAP_CONTAINER;
        ForeclosuresMapLanding = CreateMap(NEIGHBORHOOD_FORECLOSURES_LANDING_MAP_CONTAINER);
        if (ForeclosuresMapLanding && ForeclosuresMapLanding.isMapCreated) 
        {
            gActiveMap = 'NeighborhoodForeclosuresMapLanding';
            TheMapSmall = ForeclosuresMapLanding;
            TheMapSmall.ShowMap();
            TheMapSmall.gMapSearchObj.HideDashboard();
            TheMapSmall.gMapSearchObj.HideScalebar();
            TheMapSmall.gMapSearchObj.AttachEvent("onclick", GoToDetailsPage);

            var searchCriteria = 'Irvine, CA';
            if (typeof (gSearchAddressSerialized) != "undefined" && gSearchAddressSerialized != null)
            {
                var AddressQualified = DeserializeObject(gSearchAddressSerialized);
                searchCriteria = AddressQualified.CityName + ',' + AddressQualified.StateCode;
            }
            
            TheMapSmall.gMapSearchObj.Find("city", searchCriteria, VEFindType.Businesses, null, 0, 20, false, false, false, true, ShowForeclosuresMapLanding_Continue);
        }
    }
    catch (ex) 
    {
        LogErrorMessage("ShowForeclosuresMapLanding: ", ex, true);
    }
}

function GoToDetailsPage() 
{
    if (gSearchRequest != null) 
    
    {
        var linkToForeclosuresTab = g_NavigationEngine.ValueTracLinkForeclosuresTab(gSearchRequest.cityStateZipPart, TAB_NEIGHBORHOOD_FORECLOSURE, gSearchRequest);
        window.location = linkToForeclosuresTab;
    }
}

function HideContentNoNeed() 
{
    var mapHelpContainer = document.getElementById('viewMapCnr');
    var mapForecontainer = document.getElementById('NeighborhoodForeclosuresMap');
    var mapLandingPage = document.getElementById('NeighborhoodForeclosuresMapLanding');
    var mapcoveringDiv = document.getElementById('MapCoverOverlay');
    var mapIconsHelp = document.getElementById('balloonDescriptionCnr');

    if (mapHelpContainer != null) 
    {
        mapHelpContainer.style.display = 'none';
    }

    if (mapForecontainer != null) 
    {
        mapForecontainer.style.display = 'none';
    }

    if (mapLandingPage != null) 
    {
        mapLandingPage.style.display = 'block';
        //mapLandingPage.style.top = '-40px';
    }

    if (mapcoveringDiv != null) 
    {
        mapcoveringDiv.style.display = 'block';
    }

    if (mapIconsHelp != null) 
    {
        //mapIconsHelp.style.width = '300px';
        //mapIconsHelp.style.top = '200px';
        //mapIconsHelp.style.position = 'relative';
        //mapIconsHelp.style.zIndex = '2';
    }
}

function ShowForeclosuresMapLanding_Continue() 
{
    var zoomLevel = 15;
    TheMapSmall.gMapSearchObj.SetZoomLevel(zoomLevel);
    TheMapSmall.mapCenterFromSearch = TheMapSmall.gMapSearchObj.GetCenter();
    TheMapSmall.prevLatLong = TheMapSmall.mapCenterFromSearch;
    TheMapSmall.prevZoom = zoomLevel;

    hideBaloon();
    var latLongRect = TheMapSmall.GetMapCoordinates();

    if (TheMapSmall.MapSearchName == NEIGHBORHOOD_FORECLOSURES_LANDING_MAP_CONTAINER) 
    {
        ForeclosuresMapLanding = TheMapSmall;
    }
    if (TheMapSmall.MapSearchName == NEIGHBORHOOD_FORECLOSURES_INFOR_TAB_MAP_CONTAINER) 
    {
        ForeclosuresMapInfoTab = TheMapSmall; 
    }
    
    GetPropertiesAndCityValues(latLongRect.TopLeftLatLong.Latitude, latLongRect.TopLeftLatLong.Longitude, latLongRect.BottomRightLatLong.Latitude, latLongRect.BottomRightLatLong.Longitude, ShowInfoLandingPage);
}

function GetPropertiesAndCityValues(topLeftLat, topLeftLong, bottomRightLat, bottomRightLong, functionReceiver)
{    
    if (typeof (gSearchAddressSerialized) != "undefined" && gSearchAddressSerialized != null)
    {
        RealtyTrac.ValueTracMapService.GetNeighborForeclosuresAndInfo(
        gSearchAddressSerialized,
        topLeftLat,
	    topLeftLong,
	    bottomRightLat,
	    bottomRightLong,
	    'P,B,A',
	    false,
	    false,
	    true,
        gPassportKey,
        true,
        functionReceiver);
    }
}

function ShowInfoLandingPage(result) 
{
    GetNeighborhoodForeclosuresSmall_Continue(result.ListNeighFore);
    SetCityValues(result);
}

function SetCityValues(response) 
{
    var divNHInformation = document.getElementById('divctlNeighborhoodInformation');
    
    if (typeof (response) != "undefined" && response != null &&
        typeof (divNHInformation) != "undefined" && divNHInformation != null)
    {
        var values = response.NeighborhoddEstimatedValues;
        
        if (values.Title != '' && values.EstMedianHomeValue != '' && values.TwelfMonthChange != '' && values.HouseholdCount != '' && values.URLGetMoreInfo)
        {
            divNHInformation.style.display = 'block';
            
            var divValuesTitle = document.getElementById('divValuesTitle');
            var divValuesMedianValue = document.getElementById('divValuesMedianValue');
            var divValues12monthChange = document.getElementById('divValues12monthChange');
            var divValuesHouseholdCount = document.getElementById('divValuesHouseholdCount');
            var anchorNeighborHoodInfo = document.getElementById('anchorNeighborHoodInfo');
            var anchorNeighborHoodDemographics = document.getElementById('anchorNeighborHoodDemographics');

            if (divValuesTitle && typeof (values.Title) != "undefined")
            {
                divValuesTitle.innerHTML = values.Title;
            }

            if (divValuesMedianValue)
            {
                divValuesMedianValue.innerHTML = values.EstMedianHomeValue;
            }

            if (divValues12monthChange)
            {
                divValues12monthChange.innerHTML = values.TwelfMonthChange;
            }

            if (divValuesHouseholdCount)
            {
                divValuesHouseholdCount.innerHTML = values.HouseholdCount;
            }

            if (anchorNeighborHoodInfo)
            {
                anchorNeighborHoodInfo.href = values.URLGetMoreInfo;
            }
            
            if (anchorNeighborHoodDemographics)
            {
                anchorNeighborHoodDemographics.href = values.URLNHDemographics;
            }
            
            ShowHideOverlayDivValues(false);
        }
        else
        {
            divNHInformation.style.display = 'none';
        }
    }
    else
    {
        if (typeof (divNHInformation) != "undefined" && divNHInformation != null)
        {
            divNHInformation.style.display = 'none';
        }
    }
            
}


function ShowMessage(IDelement, showMessage) 
{
    var element = document.getElementById(IDelement);
    if (element) 
    {
        element.innerHTML = (showMessage) ? '<strong>Click map to view details</strong>' : '';
    }
}

//--------------------------------- Pin Pop up creation  ------------------------------------------------------------

function ServResultPinPropType(result) 
{
    try 
    {
        if (result == null || (result.Header == null || result.Details == null)) 
        {
            TheMap.PinsOnMap.PopUpClass.NoDataFoundPopUp();
        }
        else 
        {
            TheMap.PinsOnMap.PopUpClass.PropertyTypePopUp(result);
        }
    }
    catch (ex) 
    {
        LogErrorMessage("ServResultPinPropType: ", ex, true);
    }
}

function DrawAreaBorder(areaPoints) 
{
    try 
    {
        if (TheMap.PinsOnMap) 
        {
            TheMap.PinsOnMap.ShowSelectedGroupedPin(areaPoints);
        }
    }
    catch (ex) 
    {
        LogErrorMessage("DrawAreaBorder: ", ex, true);
    }
}

//-------------------------------------------------------------------------
//---------------------- General functions --------------------------------
//-------------------------------------------------------------------------

function AddCommas(nStr) 
{
    try 
    {
        nStr += '';
        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';

        var rgx = /(\d+)(\d{3})/;

        while (rgx.test(x1)) 
        {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }

        return x1 + x2;
    }
    catch (ex) 
    {
        LogErrorMessage("addCommas: ", ex);
    }
}

function GetVisiblePropertyTypes() 
{
    try 
    {
        var map = GetActiveMap();
        var propTypes = '';
        if (map == gInteractiveMap) 
        {
            propTypes = GetInteractiveMapPropertyTypes();
        }
        else 
        {
            propTypes = 'P,B,A';
        }

        return propTypes;
    }
    catch (ex) 
    {
        LogErrorMessage("GetVisiblePropertyTypes: ", ex, true);
    }

}



//-- Neighborhood sales map

/// 09/10/2008 Modified by Socrates Mejia [calls an added function ShowCompSalesMapSorted(SortBy) 
//  with the same functionality which handles a Sort Parameter]
function ShowCompSalesMap() 
{
    var emptyString = '';
    ShowCompSalesMapSorted(SortBy)
}

//// 09/10/2008 Created by Socrates Mejia
//// This function was created to add a sort Parameter in the Properties before listing them
function ShowCompSalesMapSorted(SortBy) 
{
    try 
    {
        InitMaps();
        if (NeighborhoodSalesMap == null)
        {
            NeighborhoodSalesMap = CreateMap(NEIGHBORHOOD_SALES_MAP_CONTAINER);
            NeighborhoodSalesMap.PinsOnMap.PopUpClass.parentDivContainerID = 'pinDivCompSales';
            NeighborhoodSalesMap.PinsOnMap.PopUpClass.PopupDivTempContainer = 'pinDivCompSales';
        }
        TheMap = NeighborhoodSalesMap;
        if (TheMap) 
        {
            GetCompSalesSorted(SortBy);
        }
    }
    catch (ex) 
    {
        LogErrorMessage("ShowCompSalesMap: ", ex, true);
    }
}

//// 09/10/2008 Modified by Socrates Mejia [calls an added function GetCompSalesSorted(SortBy) 
////  with the same functionality which handles a Sort Parameter]
function GetCompSales() 
{
    var emptyString = '';
    GetCompSalesSorted(emptyString);
}

//// 09/10/2008 Created by Socrates Mejia
//// This function was created to add a sort Parameter in the Properties when calling the Web Service
function GetCompSalesSorted(SortBy) 
{
    try 
    {

        RealtyTrac.ValueTracMapService.GetComsProperties(gSearchRequest.streetPart,
	        gSearchRequest.cityStateZipPart, gPassportKey, SortBy, GetCompSales_Continue);
    }
    catch (ex) 
    {
        LogErrorMessage("GetCompSales: ", ex, true);
    }
}

function GetCompSales_Continue(propDetailReport) 
{
    try 
    {
        if (propDetailReport != null)
        {
            //if there is not a Map instance we create it, but just in that case
            if (NeighborhoodSalesMap == null)
            {
                InitMaps();
                NeighborhoodSalesMap = CreateMap(NEIGHBORHOOD_SALES_MAP_CONTAINER);
                NeighborhoodSalesMap.PinsOnMap.PopUpClass.parentDivContainerID = 'pinDivCompSales';
                NeighborhoodSalesMap.PinsOnMap.PopUpClass.PopupDivTempContainer = 'pinDivCompSales';
            }

            TheMap = NeighborhoodSalesMap;
            if (TheMap)
            {
                TheMap.PinsOnMap.ValueTracMainPropData = propDetailReport.MainProperty;
                gPropDetail = null; //propDetailReport;
                gMainProperty = null; //gPropDetail.Property;
                gCompSalesList = propDetailReport.ComparableSalesPropList; //gPropDetail.Comps;
                if (propDetailReport.ComparableSalesPropList != null)// if (propDetailReport.Property != null)
                {
                    TheMap.PinsOnMap.compSalList = propDetailReport.ComparableSalesPropList; //.Comps;
                    TheMap.PinsOnMap.PopUpClass.ValueTracMainPropData = propDetailReport.MainProperty; //propDetailReport.Property;
                    var latlong = new VELatLong(propDetailReport.MainProperty.Latitude, propDetailReport.MainProperty.Longitude);
                    TheMap.gMapSearchObj.SetCenterAndZoom(latlong, 13);
                    TheMap.mapCenterFromSearch = TheMap.gMapSearchObj.GetCenter();
                    AddCompSalesPins();
                }
            }
        }
    }
    catch (ex) 
    {
        LogErrorMessage("GetCompSales_Continue: ", ex, true);
    }
}

function GetListToPinOnMap(propList) 
{
    var listPinsToMap = new Array();

    if (propList != null && propList.length > 15) 
    {
        for (var i = 0; i < 15; i++) 
        {
            listPinsToMap[i] = propList[i];
        }
    }
    else 
    {
        listPinsToMap = propList;
    }
    return listPinsToMap;
}

function AddCompSalesPins() 
{
    try 
    {
        var objPoiResult = new Object();
        objPoiResult.PoiList = GetListToPinOnMap(TheMap.PinsOnMap.compSalList);

        TheMap.PinsOnMap.isNeighborSalesPin = true;
        if (!TheMap.IsBirdEyeView() || (TheMap.IsBirdEyeView() && gMember)) 
        {
            //Setting Pins Parameters
            TheMap.PinsOnMap.imgNamePropPin = 'numberBalloon_map_';
            TheMap.PinsOnMap.imgPinPath = '/valuetrac/images/';
            TheMap.PinsOnMap.removeShapes = false;
            TheMap.PinsOnMap.isSalesPin = true;
            TheMap.PinsOnMap.AddPinsValueTrac(objPoiResult);
            TheMap.PinsOnMap.isSalesPin = false;
        }

//        if (TheMap.PinsOnMap.PopUpClass.ValueTracMainPropData != null) 
//        {
           // TheMap.PinsOnMap.imgNameMainPropPin = 'icon_mapCenter';
           // TheMap.PinsOnMap.imgPinPath = '/valuetrac/images/';
           // TheMap.PinsOnMap.DrawMainPropertPin(TheMap.PinsOnMap.PopUpClass.ValueTracMainPropData);
           // TheMap.PinsOnMap.removeShapes = true;
//        }
        TheMap.PinsOnMap.isNeighborSalesPin = false;


        //we search for the right zoom level to show all the pins
        if (objPoiResult.PoiList != null && objPoiResult.PoiList.length > 0 && isFirstPageLoad) 
        {
            var locs = new Array;

            var loc;// = new VELatLong(TheMap.PinsOnMap.PopUpClass.ValueTracMainPropData.Latitude, TheMap.PinsOnMap.PopUpClass.ValueTracMainPropData.Longitude);
            //locs.push(loc);

            for (var i = 0; i < objPoiResult.PoiList.length; i++) 
            {
                loc = new VELatLong(objPoiResult.PoiList[i].Latitude, objPoiResult.PoiList[i].Longitude);
                locs.push(loc);
            }

            TheMap.gMapSearchObj.SetMapView(locs);
            isFirstPageLoad = false;
        }

        TheMap.AttachEvents();

    }
    catch (ex) 
    {
        LogErrorMessage("AddCompSalesPins: ", ex, true);
    }
}

function AddRtracPins(result) 
{
    if (result) 
    {
        if (result.AreaCenters == null && result.POIList != undefined) 
        {
            var objPoiResult = new Object();
            objPoiResult.PoiList = result.POIList;

            if (!TheMap.IsBirdEyeView() || (TheMap.IsBirdEyeView() && gMember)) 
            {
                //Setting Pins Parameters
                TheMap.PinsOnMap.removeShapes = false;
                TheMap.PinsOnMap.imgNamePropPin = 'balloon_Map_';
                TheMap.PinsOnMap.imgPinPath = '/valuetrac/images/propertyType/';
                TheMap.PinsOnMap.AddPinsValueTrac(objPoiResult);
                TheMap.PinsOnMap.removeShapes = true;
            }
        }

        if (result.AreaCenters != null && result.AreaCenters.AreaCenter != null) 
        {
            TheMap.PinsOnMap.removeShapes = true;
            TheMap.PinsOnMap.PopUpClass.GroupedPopup(result.AreaCenters.AreaType);
            TheMap.PinsOnMap.DrawGroupedPins(result);
        }

        TheMap.AttachEvents();
    }
}

function DrawAreaBorderCompSalesMap(areaPoints) 
{
    try 
    {
        if (TheMap.PinsOnMap) 
        {
            TheMap.PinsOnMap.ShowSelectedGroupedPin(areaPoints);
        }
    }
    catch (ex) 
    {
        LogErrorMessage("DrawAreaBorder: ", ex, true);
    }
}


function ShowInteractiveMap() 
{
    try 
    {        
        if (typeof (gSearchAddressSerialized) != "undefined" && gSearchAddressSerialized != null)
        {
            var AddressQualified = DeserializeObject(gSearchAddressSerialized);
            var zoom = 15;
            
            if (gMember)
            {   
                zoom = 16;
            }
            
            InitMaps();
            
            if (InteractiveMap == null)
            {
                //get Mapcontainer Dimensions
                ResizeIntMapContainer();
                InteractiveMap = CreateMap(INTERACTIVE_MAP_CONTAINER);
                InteractiveMap.PinsOnMap.PopUpClass.parentDivContainerID = 'pinDivInteractiveMap';
                InteractiveMap.PinsOnMap.PopUpClass.PopupDivTempContainer = 'pinDivInteractiveMap';
            }
            if (InteractiveMap && InteractiveMap.isMapCreated && null != AddressQualified)
            {
                gActiveMap = 'InteractiveMap';
                TheMap = InteractiveMap;
                InteractiveMap.ShowMap();
                    var latlong = new VELatLong(AddressQualified.Latitude, AddressQualified.Longitude);

                InteractiveMap.gMapSearchObj.SetCenterAndZoom(latlong, zoom);
                TheMap.mapCenterFromSearch = TheMap.gMapSearchObj.GetCenter();
                InteractiveMap.prevLatLong = latlong;
                InteractiveMap.prevZoom = zoom;
                GetInteractiveMapProperties();
            }
        }

    }
    catch (ex) 
    {
        LogErrorMessage("ShowInteractiveMap: ", ex, true);
    }
}

function ResizeIntMapContainer() 
{
    var contentResize = document.getElementById('contentResize');
    var mapMenu = document.getElementById(INTERACTIVE_MAP_MENU_CONTAINER);
    var mapContainer = document.getElementById(INTERACTIVE_MAP_CONTAINER);
    if (contentResize != null && mapMenu != null && mapContainer != null) 
    {
        var mapMenuWidth = (mapMenu.display = 'block') ? mapMenu.offsetWidth : 0;
        var contentResizeWidth = contentResize.offsetWidth;
        var mapContainerWidth = contentResizeWidth - mapMenuWidth - 3;
        mapContainer.style.width = mapContainerWidth + 'px';
    }
}

function GetInteractiveMapProperties() 
{
    try 
    {
        if (gMainProperty) 
        {
            getMainProperty = false;
        }
        
        TheMap.GetInteractiveMapProperties(
            gSearchRequest.streetPart,
            gSearchRequest.cityStateZipPart,
            GetInteractiveMapPropertyTypes(),
            IsCheckboxChecked(gAreaSalesCheckboxID),
            GetInteractiveMapProperties_Continue);
    }
    catch (ex) 
    {
        LogErrorMessage("GetInteractiveMapProperties: ", ex, true);
    }
}

function GetInteractiveMapProperties_Continue(interactiveMapResponse) 
{
    try 
    {
        if (interactiveMapResponse) 
        {
            TheMap.PinsOnMap.ClearAllLayers();
            gComparables = interactiveMapResponse.ComparableSales;
            var objPoiResult = new Object;
            objPoiResult.PoiList = interactiveMapResponse.RTracHomes;
            objPoiResult.AreaCenters = interactiveMapResponse.AreaCenters;
            var propertyCount = interactiveMapResponse.PropertyCount;

            gPinList = new Array();
            gPinIDList = new Array();

            //Create shape layer for cyberhomes properties
            if (interactiveMapResponse.ComparableSales) 
            {
                TheMap.PinsOnMap.compSalList = interactiveMapResponse.ComparableSales;

                if (!TheMap.IsBirdEyeView() || (TheMap.IsBirdEyeView() && gMember)) 
                {
                    //Setting Pins Parameters
                    var tmpObjList = new Object;
                    tmpObjList.PoiList = interactiveMapResponse.ComparableSales;
                    TheMap.PinsOnMap.isInteractiveMap = true;
                    TheMap.PinsOnMap.removeShapes = false;
                    TheMap.PinsOnMap.imgNamePropPin = 'house_map_graphic';
                    TheMap.PinsOnMap.imgPinPath = '/valuetrac/images/propertyType/';
                    TheMap.PinsOnMap.AddPinsValueTrac(tmpObjList);
                    TheMap.PinsOnMap.isInteractiveMap = false;
                    tmpObjList = null;
                }
            }

            if (objPoiResult.AreaCenters == null)// || objPoiResult.AreaCenters.AreaType == 1) 
            {


                if (objPoiResult.PoiList != undefined && (!TheMap.IsBirdEyeView() || (TheMap.IsBirdEyeView() && gMember))) 
                {
                    //Setting Pins Parameters
                    TheMap.PinsOnMap.imgNamePropPin = 'balloon_Map_';
                    TheMap.PinsOnMap.imgPinPath = '/valuetrac/images/propertyType/';
                    TheMap.PinsOnMap.AddPinsValueTrac(objPoiResult);
                    TheMap.PinsOnMap.removeShapes = true;
                }
            }

            if (interactiveMapResponse.MainProperty != null) 
            {
                TheMap.PinsOnMap.imgNameMainPropPin = 'icon_mapCenter';
                TheMap.PinsOnMap.imgPinPath = '/valuetrac/images/';
                TheMap.PinsOnMap.PopUpClass.ValueTracMainPropData = interactiveMapResponse.MainProperty;
                TheMap.PinsOnMap.DrawMainPropertPin(interactiveMapResponse.MainProperty);
            }

            if (objPoiResult.AreaCenters != null && objPoiResult.AreaCenters.AreaCenter != null) 
            {
                TheMap.PinsOnMap.removeShapes = true;
                TheMap.PinsOnMap.PopUpClass.GroupedPopup(objPoiResult.AreaCenters.AreaType);
                TheMap.PinsOnMap.DrawGroupedPins(objPoiResult);
            }

            TheMap.AttachEvents();

            SetPropertyCount(propertyCount);
        }
    }
    catch (ex) 
    {
        LogErrorMessage("GetInteractiveMapProperties_Continue: ", ex, true);
    }

}


//----------------------------------------------------------------------------------------------------
//--------------------------------------------- Event Handlers  --------------------------------------
//----------------------------------------------------------------------------------------------------

//--------------------------------------------------
//----------------- On Click  ----------------------
//--------------------------------------------------

function OnPinClick(element) 
{
    try 
    {
        if (element && TheMap != null) 
        {
            var shape = TheMap.GetshapeByID(element.elementID);
            if (shape != null && shape.Id != 0) 
            {
                var shapeId = shape.Id;
                var pinParamters = shapeId.split('|');
                if (pinParamters && shapeId.indexOf(PIN_TYPE_PROPERTY_PIN) > -1) 
                {
                    
                    TheMap.PinsOnMap.PopUpClass.positionX = pinParamters[0];
                    TheMap.PinsOnMap.PopUpClass.positionY = pinParamters[1];
                    TheMap.PinsOnMap.PopUpClass.latitude = pinParamters[2];
                    TheMap.PinsOnMap.PopUpClass.longitude = pinParamters[3];
                    
                    //call the service
                    if (shapeId.indexOf('true') > -1) 
                    {

                        gSubjectProperty = true;
                        TheMap.PinsOnMap.PopUpClass.isSubjectPopUp = true;
                        gSubjectPropertyLon = (TheMap.PinsOnMap.PopUpClass.longitude != '') ? TheMap.PinsOnMap.PopUpClass.longitude : null;
                        gSubjectPropertyLat = (TheMap.PinsOnMap.PopUpClass.latitude != '') ? TheMap.PinsOnMap.PopUpClass.latitude : null;
                        gSubjPropDecodedLatLong._reserved = (pinParamters[7] != '') ? pinParamters[7] : '';
                        TheMap.PinsOnMap.PopUpClass.SubjectPopUp();
                    }
                    else 
                    {
                        if (shapeId.indexOf(COMP_SALES_PIN) > -1 && shapeId.indexOf(PINTYPE_MAIN_PROP_VAL_TRAC) > -1) 
                        {
                            TheMap.PinsOnMap.PopUpClass.ValueTracNeigHoodSalesPopUp(TheMap.PinsOnMap.PopUpClass.ValueTracMainPropData, null);
                        }
                        else if (shapeId.indexOf(COMP_SALES_PIN) > -1 && TheMap.PinsOnMap.compSalList[pinParamters[11]] != null) 
                        {
                            TheMap.PinsOnMap.PopUpClass.ValueTracNeigHoodSalesPopUp(TheMap.PinsOnMap.compSalList[pinParamters[11]], pinParamters[11]);
                        }
                        else if (shapeId.indexOf(INTERACTIVE_MAP) > -1 && shapeId.indexOf(PINTYPE_MAIN_PROP_VAL_TRAC) > -1) 
                        {
                            TheMap.PinsOnMap.PopUpClass.InteractiveMapPopUp(TheMap.PinsOnMap.PopUpClass.ValueTracMainPropData, null);
                        }
                        else if (shapeId.indexOf(INTERACTIVE_MAP) > -1 && TheMap.PinsOnMap.compSalList[pinParamters[11]] != null) 
                        {
                            TheMap.PinsOnMap.PopUpClass.InteractiveMapPopUp(TheMap.PinsOnMap.compSalList[pinParamters[11]], pinParamters[11]);
                        }
                        else if (shapeId.indexOf(PINTYPE_MAIN_PROP_VAL_TRAC) > -1) 
                        {
                            TheMap.PinsOnMap.PopUpClass.ValueTracMainProp();
                        }
                        else 
                        {
                            TheMap.GetPinPopUpInfo(pinParamters, ServResultPinPropType);
                        }
                    }
                }
            }
        }

    }
    catch (ex) 
    {
        LogErrorMessage("OnPinClick: ", ex);
    }
}

//--------------------------------------------------
//----------------- OnViewChanged  -----------------
//--------------------------------------------------

function CenterPopupJoinNow()
{
    var divJoinNowPopUp = document.getElementById('JoinNowPopUp');
    var divJoinNowPopUpContainer = document.getElementById('joinNowPopUpContainer');
    
    if (null != divJoinNowPopUp && null != divJoinNowPopUpContainer)
    {
        var center = TheMap.gMapSearchObj.LatLongToPixel(TheMap.gMapSearchObj.GetCenter());
        if (null != center && center.y > 0)
        {
            TheMap.PinsOnMap.PopUpClass.CenterJoinNowPopUp((TheMap.MapMenu.GetMenuWidth() + 11) * -1);
            divJoinNowPopUp.style.top = '-' + divJoinNowPopUpContainer.offsetHeight + 'px';
            divJoinNowPopUp.style.zIndex = 200;
        }
    }
}

function GetCurrentJoinNowTemplate() 
{
    if (TheMap.MapSearchName == NEIGHBORHOOD_FORECLOSURES_MAP_CONTAINER) 
    {
        TheMap.PinsOnMap.PopUpClass.PopupJoinNowHtmlTemplate = 'HtmlTemplateJoinNowPopUpForecMap';
    }
    else if (TheMap.MapSearchName == NEIGHBORHOOD_SALES_MAP_CONTAINER) 
    {
        TheMap.PinsOnMap.PopUpClass.PopupJoinNowHtmlTemplate = 'HtmlTemplateJoinNowPopUpCompSales';
    }
    else if (TheMap.MapSearchName == INTERACTIVE_MAP_CONTAINER) 
    {
        TheMap.PinsOnMap.PopUpClass.PopupJoinNowHtmlTemplate = 'HtmlTemplateJoinNowPopUpIntMap';
    }
}

function OnViewChanged(event) 
{
    try 
    {
        TheMap.PinsOnMap.PopUpClass.RemoveGroupedPopup();
        
        if ((!TheMap.isMember || gIsGuestMember || gIsCancelledMember) && (event.mapStyle == VEMapStyle.Birdseye || event.mapStyle == VEMapStyle.BirdseyeHybrid) && TheMap.MapSearchName != NEIGHBORHOOD_SALES_MAP_CONTAINER) 
        {

            if (zoomLevelAdViews == MAX_ZOOM_LEVEL_NON_MEMBERS_5) {
                GetCurrentJoinNowTemplate();
                TheMap.PinsOnMap.PopUpClass.JoinNowPopUp();
                CenterPopupJoinNow();
                zoomLevelAdViews = 0;
                return;
            }
            zoomLevelAdViews += 1;
        }
        //if it is not bird Eye view, it is not emmber and zoom excede the zoom limit we show the Banner and no more properties
        if ((!TheMap.isMember || gIsGuestMember || gIsCancelledMember) && !TheMap.IsBirdEyeView() && TheMap.gMapSearchObj.GetZoomLevel() > 15 && TheMap.MapSearchName != NEIGHBORHOOD_SALES_MAP_CONTAINER) 
        {
            if (TheMap.gMapSearchObj.GetZoomLevel() <= 16) 
            {
            GetCurrentJoinNowTemplate();
            TheMap.PinsOnMap.PopUpClass.JoinNowPopUp();
            CenterPopupJoinNow();            
            }
            else 
            {
                //if the map is trying to be zoomed but we have a pop up already there we do not zoom again;
                TheMap.gMapSearchObj.SetZoomLevel(TheMap.gMapSearchObj.GetZoomLevel() - 1);
            }         
            return;
        }


        TheMap.PinsOnMap.PopUpClass.RemovePopupJoinNow();

        if (!TheMap.isCreatingPinsOnMap) 
        {
            if (TheMap.MapSearchName == NEIGHBORHOOD_FORECLOSURES_MAP_CONTAINER) 
            {
                GetNeighborhoodForeclosures();
            }
            else if (TheMap.MapSearchName == NEIGHBORHOOD_SALES_MAP_CONTAINER) 
            {
                AddCompSalesPins();
            }
            else if (TheMap.MapSearchName == INTERACTIVE_MAP_CONTAINER) 
            {
                GetInteractiveMapProperties();
            }

        }
        TheMap.prevMapStyle = event.mapStyle;

    }
    catch (ex) 
    {
        LogErrorMessage("OnViewChanged: ", ex);
    }
}

//--------------------------------------------------
//----------------- On Mouse Over  -----------------
//--------------------------------------------------

function OnMouseOver(mapEvent) 
{
    try 
    {
        if (mapEvent && mapEvent.elementID != undefined && mapEvent.elementID != null) 
        {
            var shape = TheMap.GetshapeByID(mapEvent.elementID);
            if (shape) 
            {
                var shapeId = shape.Id;
                if (shapeId != null && shapeId != '0') 
                {
                    if (shapeId.indexOf(PIN_TYPE_PROPERTY_PIN) == -1) 
                    {
                        if (TheMap.PinsOnMap) 
                        {
                            if (TheMap.PinsOnMap.IsMouseOverPin(mapEvent)) 
                            {
                                if (TheMap.PinsOnMap.currentSelectedPinInfo != undefined && !TheMap.PinsOnMap.isCurShapeSelected) 
                                {
                                    MapData.GetAreaBorder(TheMap.PinsOnMap.currentSelectedPinInfo.areaType, TheMap.PinsOnMap.currentSelectedPinInfo.areaName, TheMap.PinsOnMap.currentSelectedPinInfo.stateCode, DrawAreaBorderCompSalesMap);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    catch (ex) 
    {
        LogErrorMessage("OnMouseOver: ", ex, true);
    }
}

//--------------------------------------------------
//----------------- On Zoom Start  -----------------
//--------------------------------------------------

function OnStartZoom(mapEvent) 
{
    try 
    {
        if (TheMap) 
        {
            TheMap.PinsOnMap.PopUpClass.RemoveGroupedPopup();
            TheMap.PinsOnMap.ClearAllLayers();
        }

        return false;
    }
    catch (ex) 
    {
        LogErrorMessage("OnStartZoom: ", ex, true);
    }
}

//--------------------------------------------------
//----------------- Functionality For Header  ------
//--------------------------------------------------

function ProcessNewValueTracSearch(address) 
{
    var VALUETRAC_DETAILS_PAGE = '/ValueTrac/HomeValues.aspx';
    var PARAMETER_ADDRESS = 'address';
    if (typeof (address) != "undefined"
        && address != null
        && address != "") 
        {
            var headerAddressTxt = document.getElementById(address);
            var addressStr = headerAddressTxt.value;

            var curURL = location.href;
            if (typeof(g_IsLandingPage) != "undefined" && g_IsLandingPage)
            {
                var prot = location.protocol;
                var host = location.host;
                var link = prot + '//' + host + VALUETRAC_DETAILS_PAGE + '?' + PARAMETER_ADDRESS + '=' + addressStr;
                window.location = link;
            }
            else
            {
                ShowHideTabs("");
                ToggleLoadingImages();
                ToggleTabOverlay(true);
                if (typeof (ToggleActivityImage) != "undefined") 
                {
                    ToggleActivityImage(true);
                }

                if (typeof (Autocomplete) != 'undefined' && typeof (Autocomplete.IsAddressValid) === 'function') 
                {
                    gDestinationPage = "ValueTrac";
                    Autocomplete.IsAddressValid(addressStr, gDestinationPage, g_PassportKey, ProcessNewValueTracSearch_Continue);
                }
            }
    }
}

function ToggleLoadingImages()
{
    if (typeof(gValueTracHelper) != "undefined" && gValueTracHelper != null)
    {
        if (gValueTracHelper.Snapshot != undefined && gValueTracHelper.Snapshot != null)
        {
            gValueTracHelper.Snapshot.EnableActivityImages();
        }
    }
}

function ProcessNewValueTracSearch_Continue(address) 
{
    if (address != null && address.Address != null) 
    {
        var customError = "";
        var isValidAddress = address.IsValid;
        var addressType = address.Type;
        var suggestionList = address.Suggestions;
        var addressObj = address.StreetAddressObject;

        var city = "";
        var zip = "";
        var county = "";
        var street = "";
        var lat = 0;
        var lon = 0;
        var state = "";
    
        if (addressObj != null)
        {
            if (isNaN(addressObj.Latitude) || isNaN(addressObj.Longitude))
            {
                addressObj.Latitude = 0;
                addressObj.Longitude = 0;
            }
        }

        if (address.SearchRequest && address.SearchRequest.BasicRequest && typeof (NullToBlank) != "undefined") 
        {
            city = NullToBlank(address.SearchRequest.BasicRequest.City);
            zip = NullToBlank(address.SearchRequest.BasicRequest.Zip);
            county = NullToBlank(address.SearchRequest.BasicRequest.CountyCode);
            street = NullToBlank(address.SearchRequest.BasicRequest.Address);
            lat = NullToBlank(address.SearchRequest.Latitude);
            lon = NullToBlank(address.SearchRequest.Longitude);
        }

        address = address.Address;

        if (address == DEFAULT_SEARCH_TEXT || address == "") 
        {
            isValidAddress = false;
            customError = "Please enter your search criteria";
        }

        if (isValidAddress) 
        {
            if (typeof (SetLastSearchCookie) != "undefined") 
            {
                SetLastSearchCookie(address);
            }
            
            gSearchAddressSerialized = SerializeObject(addressObj);
            
            if (addressObj != null)
            {
                DoNewSearch(addressObj.AddressType == 0, true);                                    
            }
        }
        else 
        {
            if (typeof (ToggleActivityImage) != "undefined") 
            {
                ToggleActivityImage(false);
            }
            
            ToggleTabOverlay(false);
            
            if (typeof (DisplayInvalidAddressPopup) != "undefined") 
            {
                DisplayInvalidAddressPopup(customError, suggestionList, ProcessNewValueTracSearch_Continue);
                UpdatePageTitle();
            }
        }
    }
    
    return false;
}

function LogRecentSearch(address)
{
    RealtyTrac.ValueTracMapService.LogRecentSearch(address);
}

function UpdatePageTitle(address)
{
    var pageTitle = CONST_DEFAULT_PAGE_TITLE;
    
    if (typeof(address) != "undefined" && address != null && address != "")
    {
        pageTitle = CONST_PAGE_TITLE.replace("{0}", address);
    }
    
    document.title = pageTitle;
}

function GetCyberhomesData()
{
    if (typeof(gSearchAddressSerialized) != "undefined" && gSearchAddressSerialized != null)
    {
        var itemsToGet = 2;
        
        if (gGlobalResponse != null)
        {
            itemsToGet = gGlobalResponse.ItemsToGet('homeinfo');
        }
        
        if (typeof(RealtyTrac.ValueTracMapService) != "undefined" && typeof(RealtyTrac.ValueTracMapService.GetCyberhomesData) != "undefined")
        {
            RealtyTrac.ValueTracMapService.GetCyberhomesData(gSearchAddressSerialized, itemsToGet, GetCyberhomesData_Continue);
        }
    }
}

function GetCyberhomesExtendedData()
{
    if (typeof(gSearchAddressSerialized) != "undefined" && gSearchAddressSerialized != null)
    {
        if (typeof(gValueTracHelper) != "undefined" && gValueTracHelper != null && typeof(gValueTracHelper.Snapshot) != "undefined")
        {
            gValueTracHelper.Snapshot.UpdateModeToDisplay(true);
        }
        
        if (typeof(RealtyTrac.ValueTracMapService) != "undefined" && typeof(RealtyTrac.ValueTracMapService.GetCyberhomesData) != "undefined")
        {
            RealtyTrac.ValueTracMapService.GetCyberhomesData(gSearchAddressSerialized, 2, GetCyberhomesDataExtended_Continue);
        }
    }
}

function InitFirstSearch(addressSerialized, isAddressSearch)
{
    ShowHideTabs("");
    gSearchAddressSerialized = addressSerialized;
    gIsNewSearch = true;
    ToggleTabOverlay(true);
    
    var lastSearch = GetLastSearch();
    if (lastSearch != null && lastSearch != "")
    {
        RestoreLastSearch(lastSearch);
    }
    else
    {
        DoNewSearch(isAddressSearch, false);     
    }
}

function RestoreLastSearch(addressStr)
{
    if (typeof (Autocomplete) != 'undefined' && typeof (Autocomplete.IsAddressValid) === 'function') 
    {
        gDestinationPage = "ValueTrac";
        Autocomplete.IsAddressValid(addressStr, gDestinationPage, g_PassportKey, ProcessNewValueTracSearch_Continue);
    }
}

function StoreCurrentSearch()
{
    if (gGlobalResponse != null && gGlobalResponse.SnapshotResponse != null && typeof(Base64) != "undefined")
    {
        var encodedAddress = Base64.encode(gGlobalResponse.SnapshotResponse.AddressStreetPart + gGlobalResponse.SnapshotResponse.AddressAreaPart);
        document.location.hash = encodedAddress;
    }
}

function GetLastSearch()
{
    var lastSearch = null;
    
    if (typeof(Base64) != "undefined" && window.location.href.indexOf("#") > 0)
    {
        var r = window.location.href;
        var i = r.indexOf("#");
        var h = r.substr(i + 1);
        lastSearch = Base64.decode(h);
    }
    
    return lastSearch;
}

function ProcessRecentSearch(encodedAddress, isAddressSearch)
{
    if (typeof(Base64) != "undefined")
    {
        gSearchAddressSerialized = Base64.decode(encodedAddress);
        ShowHideTabs("");
        ToggleLoadingImages();
        ToggleTabOverlay(true);
        if (typeof (ToggleActivityImage) != "undefined") 
        {
            ToggleActivityImage(true);
        }
        DoNewSearch(isAddressSearch, true);        
    }
}

function DoNewSearch(isAddressSearch, needToRefreshBanners)
{
    gIsAddressSearch = isAddressSearch;
    gNeedToRefreshBanners = needToRefreshBanners;
    
    CheckGlobalResponse();
    gGlobalResponse.ClearAllData();
   
    if (typeof(RealtyTrac.ValueTracMapService) != "undefined")
    {
        RealtyTrac.ValueTracMapService.GetDefaultTabData(gSearchAddressSerialized, 2, EnsureTemplatesLoaded);
        gTimeoutId = setTimeout("ProcessWebServiceTimeout()", WEB_SERVICE_TIMEOUT);
    }
}

function EnsureTemplatesLoaded(defaultTabResponse)
{
    if(gHTMLTemplatesObj == null)
    {    
        gTempTabResponse = defaultTabResponse;
        gTemplateLoadTimeoutId = setTimeout("EnsureTemplatesLoaded_Continue", 10);
    }
    else
    {
        DoNewSearch_Continue(defaultTabResponse);
    }
}

function EnsureTemplatesLoaded_Continue()
{
    if(gHTMLTemplatesObj == null)
    {    
        gTemplateLoadTimeoutId = setTimeout("EnsureTemplatesLoaded_Continue", 10);
    }
    else
    {
        DoNewSearch_Continue(gTempTabResponse);
    }
}

function DoNewSearch_Continue(defaultTabResponse)
{
    if (defaultTabResponse != null)
    {                
        if (defaultTabResponse.Address != null)
        {
            if (isNaN(defaultTabResponse.Address.Latitude) || isNaN(defaultTabResponse.Address.Longitude))
            {
                defaultTabResponse.Address.Latitude = 0;
                defaultTabResponse.Address.Longitude = 0;
            }
            
            gSearchAddressSerialized = SerializeObject(defaultTabResponse.Address);
        }
        
        clearTimeout(gTimeoutId); 
        
        LogRecentSearch(gSearchAddressSerialized);
        
        UpdateHitboxData(defaultTabResponse.HBXData);
        
        // we got details for address
        if (defaultTabResponse.HomeInfoResponse != null)
        {
            gCurrentTab = 'homeinfo';
            gIsAddressSearch = true;
            ShowHideTabs(gCurrentTab);
            GetCyberhomesData_Continue(defaultTabResponse.HomeInfoResponse);
        }
        else if (defaultTabResponse.NeighborhoodInfoResponse != null)
        {
            gCurrentTab = 'nhinfo';
            gIsAddressSearch = false;
            ShowHideTabs(gCurrentTab);
            GetNeighborhoodInformationTabData_Continue(defaultTabResponse.NeighborhoodInfoResponse);
        }
        else
        {
            ShowServiceNotAvailableMessage();
            UpdatePageTitle();
            HideRedIndicators();
        }
    }
    
    if(gNeedToRefreshBanners)
    {
        gNeedToRefreshBanners = false;
        
        if (typeof (RefreshDoubleClickBannerUtil) != "undefined")
        {
            RefreshDoubleClickBannerUtil();
        }
    }
    
    StoreCurrentSearch();
    
}

function ProcessWebServiceTimeout()
{
    if (typeof (ToggleActivityImage) != "undefined") 
    {
        ToggleActivityImage(false);
    }
    ToggleTabOverlay(false);
    HideBEOverlay();
    HideRedIndicators();
}

function HideRedIndicators()
{
    CheckGlobalResponse();
    
    if (gGlobalResponse == null || (gGlobalResponse.HomeInformationTabResponse == null && gGlobalResponse.HomeInformationTabResponse == null
        && gGlobalResponse.AreaForeclosuresData == null && gGlobalResponse.NeighborhoodDetailsData == null && gGlobalResponse.InteractiveMapData == null))
    {
        gValueTracHelper.Snapshot.DisableActivityImages();
    }
}

function UpdateBirdsEyeControlInternal(price)
{
    if (gSearchAddressSerialized != null && gSearchAddressSerialized != "" && typeof(BirdsEyeDataHelper) != "undefined")
    {
        var address = DeserializeObject(gSearchAddressSerialized);
        
        if (address != null && address.IsValid)
        {
            g_BirdsEyeDataHelper = new BirdsEyeDataHelper(false); // White site upgrade?

            g_BirdsEyeDataHelper.PropertyID = 0;
            g_BirdsEyeDataHelper.HidePhotosTab = true;
            
            g_BirdsEyeDataHelper.HideMapTab = (gIsAddressSearch) ? true : false;
            g_BirdsEyeDataHelper.Latitude = (typeof(latitude) != "undefined") ? latitude : address.Latitude;
            g_BirdsEyeDataHelper.Longitude = (typeof(longitude) != "undefined") ? longitude : address.Longitude;
            g_BirdsEyeDataHelper.HideBirdsEye = (gIsAddressSearch) ? false : true;
            g_BirdsEyeDataHelper.DisplayAerialView = (gIsAddressSearch) ? false : true;
            
            g_BirdsEyeDataHelper.Price = (typeof(price) != "undefined") ? parseFloat(price.replace("$","").replace(/,/g, "")) : 0;
            
            if (isNaN(g_BirdsEyeDataHelper.Price))
            {
                g_BirdsEyeDataHelper.Price = 0;
            }
            
            if (isNaN(g_BirdsEyeDataHelper.Latitude) || isNaN(g_BirdsEyeDataHelper.Longitude))
            {
                g_BirdsEyeDataHelper.Latitude = 0;
                g_BirdsEyeDataHelper.Longitude = 0;
            }
            
            g_BI_IsPropertyDetail = (gIsAddressSearch) ? true : false;
            
            g_BI_Latitude = address.Latitude;
            g_BI_Longitude = address.Longitude; 
            g_BI_ZoomLevel = 15;
            gSearchRequest = new SearchRequest(address.AddressLine, address.CityName + ", " + address.StateCode);
        
            if (gIsAddressSearch)
            {
                StartShowForeclosureMap();
            }
            else
            {
                ShowNeighborhoodMapBE(g_BI_Latitude, g_BI_Longitude, g_BirdsEyeDataHelper.Price);
            }

            InitializeControlBE();
        }
    }
}

function ShowNeighborhoodMapBE(latitude, longitude, price)
{
    var mapContainer = document.getElementById("imgBENeighborhood");
    var content_map = document.getElementById('content_map');

    if (mapContainer != null)
    {
        $(mapContainer).css('display', 'block');
        $(mapContainer).css('position', 'absolute');
        $(mapContainer).css('top', '0');
        $(mapContainer).css('left', '0');
        
        var imgSource = "/BirdsEyeImage/propertyimage.aspx?propid=0&z=600&ms=r&pi=true&v=N&latitude=" + latitude + "&longitude=" + longitude + "&displayAerialView=true&propertyPrice=" + price;
        mapContainer.src = imgSource;
            
        if (content_map != null)
        {
            $(content_map).css('display', 'none');
        }
        
        $('#content-map-controls').hide();
        $('#content-map-controls').removeClass('controls');
        $('#balloonDescriptionCnrSmall').hide();
        $('#NeighborhoodForeclosuresMapInfoTab').hide();
    }
}

function InitInvalidMessage(serializedResponse)
{
    var response = DeserializeObject(serializedResponse);
    ProcessNewValueTracSearch_Continue(response);
}

function GetTabObj(divName, tabName, partImgName, lnkTabID)
{
    var obj = new Object;
    var classSelTab = 'tabButton tabButtonSelected';
    var classTab = 'tabButton';

    obj.container = document.getElementById(divName);
    obj.tabName = tabName;
    obj.lnkTabID = lnkTabID;
    obj.classSelTab = classSelTab;
    obj.classTab = classTab;
    
    return obj;
}

function TabsDefinition()
{
    var tabs = new Array();

    tabs[0] = GetTabObj('divContentHomeInformationTab', 'homeinfo', '', 'lnkHomeInfo');
    tabs[1] = GetTabObj('divContentNeighborhoodInfoTab', 'nhinfo', '', 'lnkNHInfo');
    tabs[2] = GetTabObj('divContentNeighborhoodForeclosuresTab', 'nhforeclosures', '', 'lnkNHForeclosures');
    tabs[3] = GetTabObj('divContentNeighborhoodSalesTab', 'nhsales', '', 'ImlnkNHSalesg');
    tabs[4] = GetTabObj('divContentInteractiveMap', 'intmap', '', 'lnkIntMap');

    return tabs;
}

function ShowHideTabs(currentTab)
{
    var Tabs = TabsDefinition();
    
    for (var i = 0; i < Tabs.length; i++)
    {
        if (Tabs[i].container != null)
        {
            if (Tabs[i].tabName == currentTab)
            {
                Tabs[i].container.style.display = 'block';
                if (null != document.getElementById(Tabs[i].lnkTabID))
                {
                    document.getElementById(Tabs[i].lnkTabID).className = Tabs[i].classSelTab;
                }
            }
            else
            {
                Tabs[i].container.style.display = 'none';
                if (null != document.getElementById(Tabs[i].lnkTabID))
                {
                    document.getElementById(Tabs[i].lnkTabID).className = Tabs[i].classTab;
                }
            }
        }
    }
    if (currentTab == "intmap")
    {
        /* adjust for wider left column only on interactive map tab */
        $('.tabSet').css("width", "927px");
        $('.actionItemContainer').css("margin-bottom", "724px");
        var menuSlider = document.getElementById('openMenu');
        menuSlider.onclick = function() { _ToggleMapMenuDisplay(); }
        /* IE6 column wrap hack */
        if (jQuery.browser.msie) 
        {
            if (parseInt(jQuery.browser.version) < 7) 
            {
                $('.actionItemContainer').css("margin-bottom", "742px");
                $('.columnRight').css("margin-left", "-340px");
            }
        }      
    }
    else 
    {
        /* adjust for wider left column only on interactive map tab */
        $('.tabSet').css("width", "auto");
        $('.actionItemContainer').css("margin-bottom", "30px");
        /* undo IE6 column wrap hack */
        $('.columnRight').css("margin-left", "");
    }
    
    $("#divNotAvailableMessage").hide();
}

function OnTabClicked(tabID)
{
    if (tabID != null && tabID != '' && gSearchAddressSerialized != null)
    {
        ToggleTabOverlay(true);
        
        tabID = tabID.toLowerCase();
        gCurrentTab = tabID;
        
        ShowHideTabs(gCurrentTab);
        
        CheckGlobalResponse();
        
        var itemsToGet = gGlobalResponse.ItemsToGet(gCurrentTab);
        
        switch (gCurrentTab)
        {
            case 'homeinfo':                
                if (gGlobalResponse.HasCHHomeInformationTabResponse())
                {
                    SetCHHomeInformationTabData();
                }
                else
                {
                    GetCyberhomesData();
                }
                break;
                
            case 'nhinfo':
                if (gGlobalResponse.NeighborhoodDetailsData != null)
                {
                    SetupNeighborhoodDetailsTabData();
                }
                else
                {
                    if (typeof(RealtyTrac.ValueTracMapService) != "undefined" && typeof(RealtyTrac.ValueTracMapService.GetNeighborhoodInformationTabData) != "undefined")
                    {
                        RealtyTrac.ValueTracMapService.GetNeighborhoodInformationTabData(gSearchAddressSerialized, itemsToGet, GetNeighborhoodInformationTabData_Continue);
                    }
                }
                break;
                
                
            case 'nhforeclosures':
                
                if (typeof(gSearchAddressSerialized) != "undefined" && gSearchAddressSerialized != null)
                {
                    var AddressQualified = DeserializeObject(gSearchAddressSerialized);
                    ShowForeclosuresMap(AddressQualified.Latitude, AddressQualified.Longitude, 15);
                    $('#divShowHideMap').html('HIDE MAP');  // set button text
                    ChangeMapButtonsVisibility(true); //show map buttons - center map, show help
                    
                }
                
                if(gGlobalResponse.AreaForeclosuresData != null)
                {
                    SetAreaForeclosuresTabData();
                }
                else
                {
                    if (typeof(RealtyTrac.ValueTracMapService) != "undefined" && typeof(RealtyTrac.ValueTracMapService.GetNeighborhoodForeclosuresTabData) != "undefined")
                    {
                        RealtyTrac.ValueTracMapService.GetNeighborhoodForeclosuresTabData(gSearchAddressSerialized, itemsToGet, GetNeighborhoodForeclosuresTabData_Continue);
                    }
                }
                
                break;


            case 'nhsales':
                /// Load map here and list here   
                
                if (typeof (gSearchAddressSerialized) != "undefined" && gSearchAddressSerialized != null)
                {
                    if (typeof (RealtyTrac.ValueTracMapService) != "undefined")
                    {
                        RealtyTrac.ValueTracMapService.GetComparablesSalesTabData(gSearchAddressSerialized, itemsToGet, GetComparablesSalesTabData_Continue);
                    }
                }
                ToggleTabOverlay(false);
                break;
                
            case 'intmap':
                if (typeof (gSearchAddressSerialized) != "undefined" && gSearchAddressSerialized != null)
                {
                    var AddressQualified = DeserializeObject(gSearchAddressSerialized);
                    ShowInteractiveMap();
               
                    if (!gGlobalResponse.HasChartData() || !gGlobalResponse.HasControlsData)
                    {
                        if (typeof (RealtyTrac.ValueTracMapService) != "undefined" && typeof (RealtyTrac.ValueTracMapService.GetInteractiveMapTabData) != "undefined")
                        {
                            RealtyTrac.ValueTracMapService.GetInteractiveMapTabData(gSearchAddressSerialized, itemsToGet, GetInteractiveMapTabData_Continue);
                        }
                    }
                    else 
                    {
                        SetInteractiveMapTabData();
                    }
                                       
                }
                
                break;
        }
        
        UpdateHitboxData();
        
        if (typeof (RefreshDoubleClickBannerUtil) != "undefined")
        {
            RefreshDoubleClickBannerUtil();
        }
    }
}

function GetNeighborhoodInformationTabData_Continue(response)
{
    if (response != null)
    {
        CheckGlobalResponse();
        
        gGlobalResponse.NeighborhoodDetailsData = response.NeighborhoodInfo;
        
        var address = DeserializeObject(gSearchAddressSerialized);
        if (address != null && address.IsValid && response.Latitude != 0 && response.Longitude != 0)
        {
            address.Latitude = response.NeighborhoodInfo.Latitude;
            address.Longitude = response.NeighborhoodInfo.Longitude;
        }
        
        gGlobalResponse.HomeValueEstimatesChartDataUrl = response.NeighborhoodInfo.HVTChartInfo;

        gGlobalResponse.TCAverageSalesPriceChartDataUrl = response.NeighborhoodInfo.AverageSalesPriceChartData;
        gGlobalResponse.TCAverageSalesPriceChartCriteria = response.NeighborhoodInfo.AverageSalesPriceChartCriteria;
              
        gSearchAddressSerialized = SerializeObject(address);
        
        UpdateControlsData(response.ControlsData);
        
        SetupNeighborhoodDetailsTabData();

        ReloadHomeValueEstimatesChart();
        ReloadTCAverageSalesPriceChart();
        
        UpdateHotPropertyControl();
        
        UpdateAgentBanner();
        
        if (typeof (ToggleActivityImage) != "undefined") 
        {
            ToggleActivityImage(false);
        }
    }
}

function SetupNeighborhoodDetailsTabData()
{
    var section = null;
    
    if(gGlobalResponse != null && gGlobalResponse.NeighborhoodDetailsData != null 
        && gGlobalResponse.NeighborhoodDetailsData.NeighborhoodDetails != null
        && gGlobalResponse.NeighborhoodDetailsData.NeighborhoodDetails.SectionItems != null)
    {
        section = new StandartSection2('divContentNeighborhoodDetails', gHTMLTemplatesObj['divNeighborhoodDetailsTemplate']);
        section.headerTitle = 'Neighborhood Details';
        section.dataSource = gGlobalResponse.NeighborhoodDetailsData.NeighborhoodDetails.SectionItems;
        section.CreateControl();
    }
    
    if(gGlobalResponse != null && gGlobalResponse.NeighborhoodDetailsData != null 
        && gGlobalResponse.NeighborhoodDetailsData.NeighborhoodHomeSales != null
        && gGlobalResponse.NeighborhoodDetailsData.NeighborhoodHomeSales.SectionItems != null)
    {
        section = new StandartSection2('divContentNeighborhoodInfoNeighHomesAvg', gHTMLTemplatesObj['divNeighborhoodInfoNeighHomesAvgTemplate']);
        section.headerTitle = gGlobalResponse.NeighborhoodDetailsData.NeighborhoodHomeSales.SectionHeader + " <a id=\"lnkWhatIsThisNeighborhood\">What is this?</a>";
        section.dataSource = gGlobalResponse.NeighborhoodDetailsData.NeighborhoodHomeSales.SectionItems;
        section.CreateControl();
        
        $('#lnkWhatIsThisNeighborhood').bt({ width: '400px', ajaxPath: '/ValueTrac/TooltipCopy.xml div#whatIsThisNeighborhood' });
    }
    
    if(gGlobalResponse != null && gGlobalResponse.NeighborhoodDetailsData != null 
        && gGlobalResponse.NeighborhoodDetailsData.RecentHomeSold != null
        && gGlobalResponse.NeighborhoodDetailsData.RecentHomeSold.SectionItems != null)
    {
        section = new StandartSection2('divContentNeighborhoodInfoRecentHomes', gHTMLTemplatesObj['divNeighborhoodInfoRecentHomesTemplate']);
        section.headerTitle = gGlobalResponse.NeighborhoodDetailsData.RecentHomeSold.SectionHeader;
        section.dataSource = gGlobalResponse.NeighborhoodDetailsData.RecentHomeSold.SectionItems;
        section.CreateControl();  
    }
    
    ToggleTabOverlay(false);
}

function GetInteractiveMapTabData_Continue(response)
{
    if (response != null)
    {
        CheckGlobalResponse();
        
        gGlobalResponse.InteractiveMapData = response.InteractiveMap;
        UpdateControlsData(response.ControlsData);
        
        if (response.InteractiveMap != null && response.InteractiveMap.AverageSalesPriceChartData != null
            && response.InteractiveMap.AverageSalesPriceChartCriteria != null
            && response.InteractiveMap.ForeclosureActivityChartData != null
            && response.InteractiveMap.ForeclosureActivityChartCriteria != null)
        {
            gGlobalResponse.UpdateChartsData(
                response.InteractiveMap.AverageSalesPriceChartData, 
                response.InteractiveMap.AverageSalesPriceChartCriteria,
                response.InteractiveMap.ForeclosureActivityChartData,
                response.InteractiveMap.ForeclosureActivityChartCriteria);
        }
        
        SetInteractiveMapTabData();   
        
        if (typeof (ToggleActivityImage) != "undefined") 
        {
            ToggleActivityImage(false);
        }     
        
        ToggleTabOverlay(false);
    }
}

function SetInteractiveMapTabData()
{
    
}



function GetComparablesSalesTabData_Continue(response)
{
    if (null != response)
    {
        gGlobalResponse.ComparableSales = response.ComparableSalesTabData;
        PopulateCompSalesList('');
        GetCompSales_Continue(response.ComparableSalesTabData)
    }
    
    SetAreaForeclosuresTabData();
    
    if (typeof (ToggleActivityImage) != "undefined") 
    {
        ToggleActivityImage(false);
    }
   
}

function PopulateCompSalesList(sortBy)
{
    if (null != gGlobalResponse.ComparableSales && null != gGlobalResponse.ComparableSales.ComparableSalesPropList && gGlobalResponse.ComparableSales.ComparableSalesPropList.length > 0)
    {
        var AddressQualified = DeserializeObject(gSearchAddressSerialized);
        var section = new StandartSection2('ListCompSalesProperties',  gHTMLTemplatesObj['divStdSectionListCompSalesPropertiesTemplate']);
        section.headerTitle = 'Comparable Home Sales – ' + AddressQualified.Zip;
        var listSorted = SortCompSalesList(gGlobalResponse.ComparableSales.ComparableSalesPropList, sortBy);
        section.dataSource = FormatcompSalesCharacteristics(listSorted);
        section.CreateControl();
    }
}

function SortCompSalesList(list, sortBy)
{
    var listSorted = list;
    var CONS_PROXIMITY = '0';
    var CONS_MOST_RESENT_SALES_DATE = '1';
    var CONS_PRICE_HIGHEST_LOWEST = '2';
    var CONS_PRICE_LOWEST_HIGHEST = '3';

    if (null != listSorted && listSorted.length > 0)
    {        
        switch (sortBy)
        {
            case CONS_PROXIMITY:
                listSorted.sort(function(a, b) { return a.Distance - b.Distance });
                break;
            case CONS_MOST_RESENT_SALES_DATE:
                listSorted.sort(function(a, b) { return b.SaleDate - a.SaleDate });
                break;
            case CONS_PRICE_HIGHEST_LOWEST:
                listSorted.sort(function(a, b) { return b.SalePrice - a.SalePrice });
                break;
            case CONS_PRICE_LOWEST_HIGHEST:
                listSorted.sort(function(a, b) { return a.SalePrice - b.SalePrice });
                break;
            default:
                listSorted.sort(function(a, b) { return a.Distance - b.Distance });
                break;
        }        
    }

    return listSorted;
}

function FormatcompSalesCharacteristics(list)
{
    var listResult = new Array();
    
    for (var i = 0; i < list.length; i++)
    {
        var prop = new Object();
        var temp = list[i];

        prop.Address = temp.Address;
        prop.Characteristics = GetCharacteristics(temp);
        prop.SalePrice = (temp.SalePrice != null && temp.SalePrice != '') ? '$' + AddCommas(temp.SalePrice) : '';
        prop.SaleDate = GetFormatedDate(temp.SaleDate);

        listResult[i] = prop;
    }

    return listResult;

    function GetCharacteristics(propDetails)
    {        
        var result = '';
        if (null != propDetails) {
            var sqft = (propDetails.UniversalBuildingSqFt != null && propDetails.UniversalBuildingSqFt != '') ? propDetails.UniversalBuildingSqFt + ' sq ft' : '';
            var bed = (propDetails.Bedrooms != null && propDetails.Bedrooms != '') ? propDetails.Bedrooms + ' bed' : '';
            var bath = (propDetails.TotalBaths != null && propDetails.TotalBaths != '') ? propDetails.TotalBaths + ' bath' : '';
            var built = (propDetails.YearBuilt != null && propDetails.YearBuilt != '') ? ' built ' + propDetails.YearBuilt : '';

            var bedsAndBaths = (bed.length > 0 && bath.length > 0) ? bed + '/' + bath : (bed.length > bath.length) ? bed : bath;
            sqft = (sqft.length > 0 && (bedsAndBaths.length > 0 || built.length > 0)) ? sqft + ', ' : sqft;            
            built = (sqft.length > 0 && bedsAndBaths.length > 0 && built.length > 0) ? ', ' + built : built;

            result = sqft + bedsAndBaths + built;
        }
        return result;
    }

    function GetFormatedDate(date)
    {
        return (null != date) ? (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear() : '';
    }
}


function GetNeighborhoodForeclosuresTabData_Continue(response)
{
    if (response != null)
    {
        CheckGlobalResponse();
        
        gGlobalResponse.AreaForeclosuresData = response;
        UpdateControlsData(response.ControlsData);
        
        if (response.NeighborhoodForeclosures != null)
        {
            gGlobalResponse.UpdateChartsData(
                response.NeighborhoodForeclosures.AverageSalesPriceChartData, 
                response.NeighborhoodForeclosures.AverageSalesPriceChartCriteria,
                response.NeighborhoodForeclosures.ForeclosureActivityChartData,
                response.NeighborhoodForeclosures.ForeclosureActivityChartCriteria);
        }
        
        SetAreaForeclosuresTabData(); 
        
        ReloadAverageSalesPriceChart();
        ReloadNewForeclosurePropertiesChart();
        
        if (typeof (ToggleActivityImage) != "undefined") 
        {
            ToggleActivityImage(false);
        }
    }

}
function LoadTabControls()
{
    IniToolBar(gGlobalResponse);
    InitEmailFormSingUp(gGlobalResponse);
    InitLiveRatesControl(gGlobalResponse);
    InitRecentSearches(gGlobalResponse);
    SetCityValues(gGlobalResponse);
    InitForeclosureProperties(gGlobalResponse);
}

function InitForeclosureProperties(response)
{
    if (response != null && response.ForeclosureProperties != null && response.ForeclosureProperties.ForeclosureProperties != null)
    {
        $("#foreclosurePropControl").show();
        var section = new StandartSection2('divForeclosurePropertiesContainer', gHTMLTemplatesObj['divForeclosurePropertiesTemplate']);
        section.dataSource = response.ForeclosureProperties.ForeclosureProperties;
        section.headerTitle = (response.ForeclosureProperties.ForeclosureProperties.length > 0) 
            ? response.ForeclosureProperties.ViewMoreLink : "There are no available properties in your area.  Please select another area or start a new search.";
        section.CreateControl();
       
    }
    else
    {
        $("#foreclosurePropControl").hide();
    }
}

function RegisterControlTemplatesAsync(templatePath)
{
    RealtyTrac.ValueTracMapService.GetControlTemplates(templatePath, RegisterControlTemplatesAsync_Continue);
}

function RegisterControlTemplatesAsync_Continue(templateCode)
{
    if(gTemplateLoadTimeoutId)
    {
        clearTimeout(gTemplateLoadTimeoutId);
    }
    
    var result = new Array();
    var div = document.createElement('div');
    div.innerHTML = templateCode;

    for (var i = 0; i < div.childNodes.length; i++)
    {
        result[div.childNodes[i].id] = div.childNodes[i].innerHTML;
    }

    gHTMLTemplatesObj = result;
}


function GetControlsData_Continue(controlResponse)
{
    if (controlResponse != null)
    {
        UpdateControlsData(controlResponse);
    }
}

function UpdateControlsData(response)
{
    if (!gGlobalResponse.HasControlsData)
    {        
        gGlobalResponse.UpdateControlsData(response);
        LoadTabControls();

        UpdateSnapshotData();
        
        if (gGlobalResponse != null && gGlobalResponse.SnapshotResponse != null)
        {
            var price = (gGlobalResponse.DisplayNeighborhoodTabs) ? gGlobalResponse.SnapshotResponse.MedianEstimatedValue : gGlobalResponse.SnapshotResponse.Value;
            
            if(gHomePrice && document.getElementById(gHomePrice))
            {
            if (gGlobalResponse.DisplayNeighborhoodTabs) {
                document.getElementById(gHomePrice).style.display = "none";
            }
            else {
                document.getElementById(gHomePrice).style.display = "block";
                SetHomePrice(price);
            }
            }
                       
            UpdateBirdsEyeControlInternal(price);
        }
    }
}


function UpdateHotPropertyControl()
{
    
    if (gGlobalResponse != null && gGlobalResponse.HotPropertyData != null && typeof(gHotPropertyHelper) != "undefined")
    {
        gHotPropertyHelper.UpdateControl(gGlobalResponse.HotPropertyData);
    }
}

function UpdateAgentBanner() 
{
    
    if (typeof (gGlobalResponse) != "undefined" && gGlobalResponse.AgentBanner != null) 
    {
        var agentBanner = gGlobalResponse.AgentBanner;

        SetAgentBanner(agentBanner.FullName, agentBanner.ImageUrl, agentBanner.Speciality, agentBanner.NavigationURL);
    }
    else
    {
        SetAgentBanner(null, null, null, 0);
    }
}

function CheckGlobalResponse()
{
    if (typeof(gGlobalResponse) == "undefined" || gGlobalResponse == null)
    {
        gGlobalResponse = new GlobalResponse();
    }
}

function SetHomeInformationTabData()
{
    
    if (typeof(gGlobalResponse) != "undefined" && gGlobalResponse != null && gGlobalResponse.HomeInformationTabResponse != null
        && gGlobalResponse.HomeInformationTabResponse.HomeDetailsResponseCH != null)
    {
        var section = null;
    
        if (gGlobalResponse.HomeInformationTabResponse.HomeDetailsResponseCH.HomeDetails != null)
        {
            var section = new StandartSection2('divHomeDetailsStdSection', gHTMLTemplatesObj['divHomeDetailsStdSectionTemplate']);
            section.headerTitle = 'Home Details';
            section.dataSource = gGlobalResponse.HomeInformationTabResponse.HomeDetailsResponseCH.HomeDetails.SectionItems;
            section.CreateControl();
        }

        if (gGlobalResponse.HomeInformationTabResponse.HomeDetailsResponseCH.SalesAndTax != null)
        {
            section = new StandartSection2('divStdSectionSalesAndTaxDetails', gHTMLTemplatesObj['divStdSectionSalesAndTaxDetailsTemplate']);
            section.headerTitle = 'Sales & Tax Details';
            section.dataSource = gGlobalResponse.HomeInformationTabResponse.HomeDetailsResponseCH.SalesAndTax.SectionItems;
            section.CreateControl();
        }
                
        if (gGlobalResponse.HomeInformationTabResponse.HomeDetailsResponseCH.ComparableHomeSales != null)
        {
            var zip = '';
            var address = DeserializeObject(gSearchAddressSerialized);
            if(address != null && address.Zip != null)
            {
                zip = address.Zip;
            }
            
            section = new StandartSection2('divComparableHomeSales', gHTMLTemplatesObj['divComparableHomeSalesTemplate']);
            section.headerTitle = '<a href="#top" onclick="OnTabClicked(\'nhsales\');">Comparable Home Sales - <span id="divComparableHomeSalesZip">' + zip + '</span></a> <a id="lnkWhatIsThis">What is this?</a>';
            section.dataSource = gGlobalResponse.HomeInformationTabResponse.HomeDetailsResponseCH.ComparableHomeSales.SectionItems;
            section.CreateControl();
            
            $('#lnkWhatIsThis').bt({width: '400px', ajaxPath: '/ValueTrac/TooltipCopy.xml div#whatIsThis'});
            
            section = new StandartSection2('compSalesCompSalePropertyData', gHTMLTemplatesObj['divComparableHomeSalesTemplate']);
            section.dataSource = gGlobalResponse.HomeInformationTabResponse.HomeDetailsResponseCH.ComparableHomeSales.SectionItems;
            section.CreateControl();
        }
    }   
}

function SetContentDivVisible(divName)
{
//    $('#divContentHomeInformationTab').hide();
//    $('#divContentNeighborhoodSalesTab').hide();
//    $('#divContentNeighborhoodForeclosuresTab').hide();
//    $('#divContentInteractiveMap').hide();
//    $('#divContentNeighborhoodInfoTab').hide();

//    $('#' + divName).show();
}

function SetCHHomeInformationTabData()
{
    if(gGlobalResponse != null &&
        gGlobalResponse.HomeInformationTabResponse != null &&
        gGlobalResponse.HomeInformationTabResponse.HomeDetailsResponseCH != null &&
        gGlobalResponse.HomeInformationTabResponse.HomeDetailsResponseCH.HomeValueEstimatesCH != null &&
        gGlobalResponse.HomeInformationTabResponse.HomeDetailsResponseCH.HomeValueEstimatesCH.SectionItems != null)
    {
        var section = new StandartSection2('divHomeValueEstimateCH', gHTMLTemplatesObj['divHomeValueEstimateTemplate']);
        section.headerTitle = '';
        section.dataSource = gGlobalResponse.HomeInformationTabResponse.HomeDetailsResponseCH.HomeValueEstimatesCH.SectionItems;
        section.CreateControl();
    }
    
    ToggleTabOverlay(false);
}

function SetAreaForeclosuresTabData()
{
    if(gGlobalResponse != null && gGlobalResponse.AreaForeclosuresData != null 
        && gGlobalResponse.AreaForeclosuresData.NeighborhoodForeclosures != null
        && gGlobalResponse.AreaForeclosuresData.NeighborhoodForeclosures.ForeclosureActivity != null
        && gGlobalResponse.AreaForeclosuresData.NeighborhoodForeclosures.ForeclosureActivity.SectionItems != null)
    {
        var section = new StandartSection2('divAreaForeclosuresData', gHTMLTemplatesObj['divAreaForeclosuresDataTemplate']);
        section.headerTitle = 'Foreclosure Activity';
        section.dataSource = gGlobalResponse.AreaForeclosuresData.NeighborhoodForeclosures.ForeclosureActivity.SectionItems;
        section.CreateControl();
    }
    
    ToggleTabOverlay(false);
}

function UpdateSnapshotData(displayNeighborhoodTabs, homeValue, homeValueRange, 
    areaPropertyCount, areaUrl, addressStreetPart, addressAreaPart, update12MonthChange)
{
    if (gGlobalResponse != null && gGlobalResponse.SnapshotResponse != null)
    {
        if (typeof(gGlobalResponse.DisplayNeighborhoodTabs) != "undefined")
        {
             gValueTracHelper.Tabs.ToggleTabs(gGlobalResponse.DisplayNeighborhoodTabs);
             gValueTracHelper.Snapshot.UpdateModeToDisplay(gGlobalResponse.DisplayNeighborhoodTabs);
             
             if (gGlobalResponse.DisplayNeighborhoodTabs)
             {
                if (typeof(gGlobalResponse.SnapshotResponse.MedianEstimatedValue) != "undefined")
                {
                    gValueTracHelper.Snapshot.UpdateHomeValue(gGlobalResponse.SnapshotResponse.MedianEstimatedValue);
                }
                
                if (typeof(gGlobalResponse.SnapshotResponse.Appreciation12Month) != "undefined")
                {
                    gValueTracHelper.Snapshot.UpdateValueRange(gGlobalResponse.SnapshotResponse.Appreciation12Month);
                    gValueTracHelper.Snapshot.UpdateTrendArrow(gGlobalResponse.SnapshotResponse.Appreciation12Month, true);
                }
             }
             else
             {
                if (typeof(gGlobalResponse.SnapshotResponse.Value) != "undefined")
                {
                    gValueTracHelper.Snapshot.UpdateHomeValue(gGlobalResponse.SnapshotResponse.Value);
                }
                
                if (typeof(gGlobalResponse.SnapshotResponse.ValueRange) != "undefined")
                {
                    gValueTracHelper.Snapshot.UpdateValueRange(gGlobalResponse.SnapshotResponse.ValueRange);
                    gValueTracHelper.Snapshot.UpdateTrendArrow(gGlobalResponse.SnapshotResponse.ValueRange, false);
                }
             }
        }

        if (typeof(gGlobalResponse.SnapshotResponse.AddressStreetPart) != "undefined" && typeof(gGlobalResponse.SnapshotResponse.AddressAreaPart) != "undefined")
        {
            gValueTracHelper.Snapshot.UpdateSearchAddress(gGlobalResponse.SnapshotResponse.AddressStreetPart, gGlobalResponse.SnapshotResponse.AddressAreaPart);
            
            var addressStr = gGlobalResponse.SnapshotResponse.AddressAreaPart;
            
            if (typeof(gGlobalResponse.SnapshotResponse.AddressStreetPart) != "undefined" && gGlobalResponse.SnapshotResponse.AddressStreetPart != null && gGlobalResponse.SnapshotResponse.AddressStreetPart != "")
            {
                addressStr = gGlobalResponse.SnapshotResponse.AddressStreetPart + ", " + gGlobalResponse.SnapshotResponse.AddressAreaPart;
            }
            
            UpdatePageTitle(addressStr);
        
        }

        if (typeof(gGlobalResponse.SnapshotResponse.AreaPropertyCount) != "undefined")
        {
            gValueTracHelper.Snapshot.UpdateAreaPropertyCount(gGlobalResponse.SnapshotResponse.AreaPropertyCount);
        }
        
        if (typeof(gGlobalResponse.SnapshotResponse.AreaUrl) != "undefined")
        {
            gValueTracHelper.Snapshot.UpdateAreaURL(gGlobalResponse.SnapshotResponse.AreaUrl);
        }
    }
}

function GetCyberhomesData_Continue(valueTracResponse)
{
    if (valueTracResponse != null)
    {
        gGlobalResponse.UpdateHomeInformationTabResponse(valueTracResponse);
        UpdateControlsData(valueTracResponse.ControlsData);
        
        if (valueTracResponse != null)
        {
            if (valueTracResponse.HomeDetailsResponseCH != null && valueTracResponse.HomeDetailsResponseCH.AverageSalesPriceChartData != null
                && valueTracResponse.HomeDetailsResponseCH.AverageSalesPriceChartCriteria != null)
            {
                gGlobalResponse.UpdateChartsData(valueTracResponse.HomeDetailsResponseCH.AverageSalesPriceChartData, valueTracResponse.HomeDetailsResponseCH.AverageSalesPriceChartCriteria, null, null);
            }
            
            gGlobalResponse.HomeValueEstimatesChartDataUrl = valueTracResponse.HomeDetailsResponseCH.HVTChartInfo;
            
            SetHomeInformationTabData();
            SetCHHomeInformationTabData();
            UpdateHotPropertyControl();
            ReloadHomeValueEstimatesChart();
            ReloadAverageSalesPriceChart();
            UpdateAgentBanner();
            if (typeof (ToggleActivityImage) != "undefined") 
            {
                ToggleActivityImage(false);
            }
        }
    }
}

function InitLiveRatesControl(result) 
{
    var liveRatesWidgetContainer = document.getElementById('LiveRatesWidgetContainer');
    var lenderBanner = document.getElementById('LenderBanner');
    var liveRatesBannerCaption = document.getElementById("LiveRatesBannerCaption");
    
    if (null != liveRatesWidgetContainer && null != lenderBanner && null != result) 
    {
        if (result.HasLiveRates)
        {
            liveRatesWidgetContainer.style.display = 'block';
            lenderBanner.style.display = 'none';
            liveRatesBannerCaption.innerHTML = "LIVE Mortgage Rates";
            var lbRatesUpdated = document.getElementById('lbRatesUpdated');
            var lbNextRateUpdate = document.getElementById('lbNextRateUpdate');

            if (lbRatesUpdated != null)
            {
                lbRatesUpdated.innerHTML = 60 - result.LiveRates.NextRateUpdate.replace(' mins.', '');
            }
            if (lbNextRateUpdate != null)
            {
                lbNextRateUpdate.innerHTML = result.LiveRates.NextRateUpdate.replace(' mins.','');
            }

            var section = new StandartSection2('LiveRates', gHTMLTemplatesObj['divLiveRatesTemplate']);
            section.dataSource = result.LiveRates.Rates;
            section.CreateControl();
        }
        else
        {
            liveRatesWidgetContainer.style.display = 'none';
            lenderBanner.style.display = 'block';
            liveRatesBannerCaption.innerHTML = "Local Mortgage Specialist";
            
            var imgMortgage = document.getElementById('imgMortgage');
            var lblMortgage = document.getElementById('lblMortgage');
            var lnkGetRates = document.getElementById('lnkGetRates');

            imgMortgage.src = result.LiveRates.ImgMortgageSrc;
            lblMortgage.innerHTML = result.LiveRates.MortgageText;
            lnkGetRates.href = result.LiveRates.GetRatesURL
        }
    }
}

function GetColValues(propList)
{
    var listPins = new Array();

    if (propList != null && propList.length > 0)
    {
        for (var i = 0; i < propList.length; i++)
        {
            var details = new Object();
            details.ColOne = propList[i].Title;
            details.ColTwo = '';
            details.ColThree = '';
            details.ColFour = propList[i].Value;

            listPins[i] = details;
        }
    }
    
    return listPins;
}

function SerializeObject(object)
{
    var serialized = null;
    
    if (object != null)
    {
        serialized = Sys.Serialization.JavaScriptSerializer.serialize(object).replace('__type','_type');
    }
    
    return serialized;
}

function DeserializeObject(object)
{
    var deserialized = null;
    
    if (object != null)
    {
        deserialized = Sys.Serialization.JavaScriptSerializer.deserialize(object);
    }
    
    return deserialized;
}

function CreateParsedAddress(address, street, city, county, state, zip, lat, lon) 
{
    var addressParts = address;

    if ((typeof (street) != "undefined" && street != null && street != "")
        || (typeof (city) != "undefined" && city != null && city != "")
        || (typeof (county) != "undefined" && county != null && county != "")
        || (typeof (state) != "undefined" && state != null && state != "")
        || (typeof (zip) != "undefined" && zip != null && zip != "")) 
        {
        addressParts = "OriginalAddress=" + address; //Original address string
        addressParts += "&parsed=1"
        addressParts += (typeof (street) != "undefined" && street != null && street != "") ? "&st=" + street : "";
        addressParts += (typeof (city) != "undefined" && city != null && city != "") ? "&ct=" + city : "";
        addressParts += (typeof (county) != "undefined" && county != null && county != "") ? "&cn=" + county : "";
        addressParts += (typeof (state) != "undefined" && state != null && state != "") ? "&stc=" + state : "";
        addressParts += (typeof (zip) != "undefined" && zip != null && zip != "") ? "&zp=" + zip : "";

        addressParts += (typeof (lat) != "undefined" && lat != null && lat != "") ? "&lat=" + lat : "";
        addressParts += (typeof (lon) != "undefined" && lon != null && lon != "") ? "&lon=" + lon : "";

    }

    return addressParts;
}

function submitLoanWebForm() 
{
    window.document.location.href = "/finance/landing.aspx";
}

//-----------------------------------------------------------------------------------------
//----------------------------- Form Change Location Control ------------------------------
//-----------------------------------------------------------------------------------------

function ToogleForms(divaName) 
{

    var divFormContainer = document.getElementById(divaName);

    if (divFormContainer != null) 
    {
        if (divFormContainer.style.display == 'block') 
        {
            divFormContainer.style.display = 'none';
        }
        else 
        {
            divFormContainer.style.display = 'block';
        }
    }
}

function SetChosenCity(source, eventArgs) 
{
    var gtbxChangeLocationID = document.getElementById(gtbxChangeLocationID);

    if (gtbxChangeLocationID != null) 
    {
        gtbxChangeLocationID.value = eventArgs._text;
    }
}

function SendForm() 
{
    var cityState = document.getElementById(gtbxChangeLocationID);

    if (cityState != null) 
    {
        var addressStr = cityState.value;

        ShowHideOverlayDivValues(true);

        if (typeof (Autocomplete) != 'undefined' && typeof (Autocomplete.ValidateCity) === 'function') 
        {
            gDestinationPage = "ValueTrac";
            Autocomplete.IsAddressValid(addressStr, gDestinationPage, g_PassportKey, SendForm_Continue);
        }
    }
}

function SendForm_Continue(address) 
{
    var customError = "";
    var suggestionList = null;
    var isValidAddress = false;
    var addressStr = "";


    if (address != null && address.Address != null) 
    {
        isValidAddress = address.IsValid;
        suggestionList = address.Suggestions;
        addressStr = address.Address;
    }

    if (isValidAddress) 
    {
        CloseSplashScreenInvalidAddressMessage();
        var chBoxDefHomeValueLoc = document.getElementById('chBoxDefHomeValueLoc');
        var txtEnterCityAndState = document.getElementById(gtbxChangeLocationID);

        if (typeof (SetLocationInCookie) != "undefined" && chBoxDefHomeValueLoc != null && chBoxDefHomeValueLoc.checked) 
        {
            SetLocationInCookie(addressStr);
        }
        
        var addressObj = address.StreetAddressObject;
        if (addressObj != null)
        {
            if (isNaN(addressObj.Latitude) || isNaN(addressObj.Longitude))
            {
                addressObj.Latitude = 0;
                addressObj.Longitude = 0;
            }
        }
        gSearchAddressSerialized = SerializeObject(addressObj);
        
        CloseSplashScreenInvalidAddressMessage();
        //gSearchRequest.cityStateZipPart = addressStr;
        ShowForeclosuresMapLanding();
        ToogleForms('divChangeLocationForm');
    }
    else 
    {
        ShowHideOverlayDivValues(false);
        ShowSplashScreenInvalidAddressMessage(suggestionList, SendForm_Continue);
    }
}

function ShowSplashScreenInvalidAddressMessage(suggestionList, SendForm_Continue) 
{
    var errorDiv = document.getElementById("SplashScreenInvalidAddressMessage");
    var suggestionsTitle = document.getElementById("SplashScreenSuggestionLinksTitle");

    if (errorDiv != null) 
    {
        errorDiv.style.display = 'block';

        var locationList = document.getElementById("SplashScreenSuggestionLinks");

        if (locationList != null) 
        {
            while (locationList.childNodes[0]) 
            {
                locationList.removeChild(locationList.childNodes[0]);
            }

            if (suggestionsTitle != null) 
            {
                suggestionsTitle.style.display = (suggestionList != null && suggestionList.length > 0) ? "block" : "none";
            }

            CreateLocationList(suggestionList, SendForm_Continue, "SplashScreenSuggestionLinks");
        }
    }
}

function CloseSplashScreenInvalidAddressMessage() 
{
    var errorDiv = document.getElementById("SplashScreenInvalidAddressMessage");
    if (errorDiv != null) 
    {
        errorDiv.style.display = 'none';
    }
}

function SetLocationInCookie(searchValue) 
{
    if (searchValue != null && searchValue != '' && searchValue != 'Enter a City and State') 
    {
        SetCookie('ChangeLocation', searchValue, 365, '/', '', '');
    }
}

function showHideWaterMark(element, value) 
{
    if (element.value != '') 
    {
        if (element.value == value) 
        {
            element.value = ''; 
        }
    }
    else 
    {
        if (element.value == '')
        {
             element.value = value; 
        }
    }
}

function keyNumPressed(e) 
{
    var keynum;

    if (e.keyCode != null && e.keyCode > 0) // IE
    {
        keynum = e.keyCode;
    }
    else if (e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }

    return keynum;
}

function ShowHideOverlayDivValues(showOverlay) 
{
    var container = document.getElementById('divInfoValuesOverlay');
    if (container && showOverlay) 
    {
        container.style.display = 'block';
    }
    else 
    {
        container.style.display = 'none';
    }
}

function ShowHideOverlayMap(showOverlay) 
{
    var container = document.getElementById('divMapLandingOverlay');
    if (container && showOverlay) 
    {
        container.style.display = 'block';
    }
    else 
    {
        container.style.display = 'none';
    }
}

function ShowDiv(divID) 
{
    var div = document.getElementById(divID);
    if (div != null) 
    {
        div.style.display = 'block';
    }
}

function HideDiv(divID) 
{
    var div = document.getElementById(divID);
    if (div != null) 
    {
        div.style.display = 'none';
    }
}

//-----------------------------------------------------------------------------------------
//----------------------------- End Form Change Location Control --------------------------
//-----------------------------------------------------------------------------------------

function InitNeighborhoodInformation(intMapID) 
{
    
    ShowHideOverlayDivValues(true);
    var divMapNeighborhoodInfo = document.getElementById('divMapNeighborhoodInfo');
    var balloonDescriptionCnr = document.getElementById('balloonDescriptionCnrSmall');
    var content_map = document.getElementById('content_map');
    var neighborhood_map_be = document.getElementById("imgBENeighborhood");
    var divMessage = document.getElementById('divMessage');

    if (content_map != null) 
    {
        content_map.style.display = "block";
        divMessage.setAttribute('onclick', "document.getElementById('" + intMapID + "').click();");
        content_map.setAttribute('onmouseover', "ShowDiv('divMessage')");
        content_map.setAttribute('onmouseout', "HideDiv('divMessage')");
        if (neighborhood_map_be != null)
        {
            neighborhood_map_be.style.display = "none";
        }
    }

    if (balloonDescriptionCnr != null) 
    {
        balloonDescriptionCnr.style.display = 'block';
    }
    
    $('#balloonDescriptionCnrSmall').show();
    $('#content-map-controls').show();
    $('#content-map-controls').addClass('controls');

    if (divMapNeighborhoodInfo != null)
    {
        divMapNeighborhoodInfo.style.left = '0px';
        divMapNeighborhoodInfo.style.width = '297px';
        divMapNeighborhoodInfo.style.position = 'relative';
        divMapNeighborhoodInfo.style.paddingTop = '10px';
    }
    
    InitMapInfoTab(intMapID);
}

function SetMapInfo(intMapID) 
{
    gMapContainer = NEIGHBORHOOD_FORECLOSURES_INFOR_TAB_MAP_CONTAINER;
    ForeclosuresMapInfoTab = CreateMap(NEIGHBORHOOD_FORECLOSURES_INFOR_TAB_MAP_CONTAINER);
    if (ForeclosuresMapInfoTab && ForeclosuresMapInfoTab.isMapCreated) 
    {
        gActiveMap = NEIGHBORHOOD_FORECLOSURES_INFOR_TAB_MAP_CONTAINER;

        TheMapSmall = ForeclosuresMapInfoTab;
        TheMapSmall.ShowMap();
        TheMapSmall.gMapSearchObj.HideDashboard();

        if (intMapID != null)
        {
            onclickfunction = function()
            {
                var element = document.getElementById(intMapID);
                if (null != element && undefined != element)
                {
                    element.click();
                }
                return true;
            }
        }

        TheMapSmall.gMapSearchObj.AttachEvent("onclick", onclickfunction);
        onmouseoutfun = function() { ShowDiv('divMessage'); return true; }
        TheMapSmall.gMapSearchObj.AttachEvent("onmouseover", onmouseoutfun);
        onmouseoverfun = function() { HideDiv('divMessage'); return true; }
        TheMapSmall.gMapSearchObj.AttachEvent("onmouseout", onmouseoverfun);
        ondoubleclickfun = function() { return true; }
        TheMapSmall.gMapSearchObj.AttachEvent("ondoubleclick", ondoubleclickfun);

        var streetPart = '';
        if (null != gSearchRequest.streetPart) 
        {
            streetPart = gSearchRequest.streetPart + ', ';
        }

        var searchCriteria = 'Irvine, CA';
        if (typeof (gSearchAddressSerialized) != "undefined" && gSearchAddressSerialized != null)
        {
            var AddressQualified = DeserializeObject(gSearchAddressSerialized);
            searchCriteria = AddressQualified.CityName + ',' + AddressQualified.StateCode;
        }
        
        TheMapSmall.gMapSearchObj.Find("city", searchCriteria, VEFindType.Businesses, null, 0, 20, false, false, false, true, ShowForeclosuresMapLanding_Continue);
    }
}

function InitMapInfoTab(intMapID) 
{
    InitSmallMaps();

    if (eval(g_BI_IsPropertyDetail)) 
    {
        SetMapInfo(intMapID);
    }
    else 
    {
        GetPropertiesAndCityValues(0, 0, 0, 0, ShowInfoHomeValuePage);
    }

}

function ShowInfoHomeValuePage(result) 
{    
    // SetCityValues(result);
}

function OpenInitMapTab(intMapID) 
{
    var initMapTab = document.getElementById(intMapID);

    if (initMapTab != null) 
    {
        initMapTab.click();
    }
}


////---------------------------------- Bird Eye Control ----------------------------------------------------

var g_BI_IsPropertyDetail = false;
var g_BI_BirdEyeImgNeighborhoodInfo;

function InitializeControlBE()
{
    if (RealtyTrac.BirdsEyeImage != null)
   { 
    if (typeof(RealtyTrac.BirdsEyeImage.Web.BirdsEyeDataService) != "undefined" && typeof(RealtyTrac.BirdsEyeImage.Web.BirdsEyeDataService.GetBirdsEyeJSData) != "undefined"
        && typeof(g_BirdsEyeDataHelper) != "undefined" && g_BirdsEyeDataHelper != null)
    {
        $('#content_birdseye_controls').hide();
        
        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, InitializeControlBE_Continue);
    }
   } 
}

function InitializeControlBE_Continue(birdsEyeDataResponse) 
{
    if (typeof(InitBEVariables) != "undefined")
    {
        InitBEVariables(birdsEyeDataResponse);
    }
    
    //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');

    if (element) 
    {
        g_BI_IsBirdsEyeActive = true;
    }
    else 
    {
        g_BI_IsBirdsEyeActive = false;
    }

    if (g_BI_IsBirdsEyeActive) 
    {
        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, 'zoom-Plus', 'zoomIn', true);
        g_BI_zoomOut = new ToggleButton('60', g_BI_Zooms, 'zoom-Minus', 'zoomOut', true);

        // initialize the property photo browsing
        g_BI_propertyPhotoBrowser = new PropertyPhotoBrowser(g_BI_propertyPhotos);

        // 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-photos_61x17.gif', g_BI_BaseImagePath + 'PD_btn-photos_61x17_sel.gif', g_BI_BaseImagePath + 'PD_btn-photos_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');

        // 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('tabPropertyPhotos', g_BI_hasPropertyPhotos);
        ShowHideTabById('tabBirdseye', g_BI_hasBirdsEye);
        ShowHideTabById('tabMap', true);

        // show hide tab content     
        if(gIsAddressSearch)
        {
            NewBEShowBirdsEyeTab();
        }
        else
        {   
            NewBEShowMapTab();
        }

        $('#content_birdseye_controls').show(); 
    }
    
    HideBEOverlay();
}

function NewBEShowMapTab() 
{
    g_BI_MapTab.Select();
    g_BI_PhotoTab.Deselect();
    g_BI_BirdsEyeTab.Deselect();

    document.getElementById('content_birdseye').style.display = 'none';
    document.getElementById('content_photos').style.display = 'none';
    document.getElementById('content_map').style.display = 'block';

    if (gGlobalResponse.DisplayNeighborhoodTabs) {
        $('.msgContainer').hide();
    }
    else {
        $('.msgContainer').show();
        $('#divMessage .loadingOverlay').click(function() {
            OnTabClicked('intmap'); // reuses OnTabClicked() from the tabset to duplicate clicking the "interactive map" tab.
        }); 
    }

    g_BI_showMap = true;

    document.getElementById('content_photos').style.display = 'none';
    document.getElementById('perspective_control').style.display = 'none';
    document.getElementById('zoom_control').style.display = 'none';

    //NewBEUpdateBirdsEyeImage(false);
}

function NewBEShowBirdsEyeTab() 
{
    g_BI_MapTab.Deselect();
    g_BI_PhotoTab.Deselect();
    g_BI_BirdsEyeTab.Select();

    document.getElementById('content_birdseye').style.display = 'block';
    document.getElementById('content_photos').style.display = 'none';
    document.getElementById('content_map').style.display = 'none';
    $('.msgContainer').hide();

    g_BI_showMap = false;

    document.getElementById('content_photos').style.display = 'none';

    document.getElementById('perspective_control').style.display = 'block';
    document.getElementById('zoom_control').style.display = 'block';

    NewBEUpdateBirdsEyeImage(false);
    
    $('#content_birdseye_controls').show();
    HideBEOverlay();

}

function NewBEUpdateBirdsEyeImage(isIinteractive) 
{
    try
    {
        $('#newPropertyPictures').hide();
        $('#BE_LoadingPhoto').show();
            
    if (isIinteractive && !g_BI_showMap && (!g_BI_isMember || g_BI_isGuestMember || g_BI_isCancelledMember)) 
    {
        // if non-member clicked on any controls then show the upsell image
        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) 
            {
                //if in some moment the Map need to have an action when updating here goes the code   
            }
            else 
            {
                LoadBEImage(selectedZoom, selectedView);
            }
        }
    }
        $('#newPropertyPictures').show();
        $('#BE_LoadingPhoto').hide();
    }
    catch(e)
    {
        $('#newPropertyPictures').attr('src', '/images/image_na.gif');
        $('#newPropertyPictures').hide();
        $('#BE_LoadingPhoto').hide();
    }    
}

function LoadBEImage(selectedZoom, selectedView) 
{
    var propertyImage = $('#newPropertyPictures');

    if (propertyImage != null) 
    {
        propertyImage.attr('src','/BirdsEyeImage/propertyimage.aspx?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);
            
        $('#content-map-controls').show();
        $('#content-map-controls').addClass('controls');
        $('#balloonDescriptionCnrSmall').show();
        $('#NeighborhoodForeclosuresMapInfoTab').show();
    }  
}
//----------------------------------------------------------------------------------------------------------


//------------------------------------------------
//
//  Functionality to work with web-services instead of postbacks
//
//------------------------------------------------

//-- Helper for page elements
//-- Contains controls IDs
ValueTracHelper = function(homeInfoTabID, neighborhoodTabID, neighborhoodForeclosuresTabID, neighborhoodSalesTabID, interactiveMapTabID,
    snapshotAddressFirstLineID, snapshotAddressSecondLineID, homeValueID, valueRangeID, areaForeclosuresID, areaForeclosuresLinkID, homeValueTextID, valueRangeTextID, 
    gainListSalesPriceChangeContainerID, dropListSalesPriceChangeContainerID, gainListSelectID, dropListSelectID)
{
    // Some functionality that is used insede child classes
    this.GetElement = function(elementID)
    {
        if (elementID != undefined && elementID != null && elementID != "")
        {
            return document.getElementById(elementID);
        }
        else
        {
            return null;
        }
    }
    
    this.SafeElementID = function(elementID)
    {
        return (elementID == undefined) ? "" : elementID;
    }
 
    //- 
    //-- Bar loader image html 
    this.BarLoaderHTML = "<img src='/images/icons/loading-RedIndicator-16x16.gif' alt='loading...' />";
    //-- Loading text
    this.LoadingText = "Loading results...";
    
        // ListSalePrice controls IDs
    this.GainListSalesPriceChangeContainerID = gainListSalesPriceChangeContainerID;
    this.GainListSalesPriceChangeContainer = this.GetElement(this.GainListSalesPriceChangeContainerID);
    
    this.DropListSalesPriceChangeContainerID = dropListSalesPriceChangeContainerID;
    this.DropListSalesPriceChangeContainer = this.GetElement(this.DropListSalesPriceChangeContainerID);

    this.GainListSelectID = gainListSelectID;
    this.GainListSelect = this.GetElement(this.GainListSelectID);
    
    this.DropListSelectID = dropListSelectID;
    this.DropListSelect = this.GetElement(this.DropListSelectID);
    
    //-- Tabs
    var CreateTabs = function(homeInfoTabID, neighborhoodTabID, neighborhoodForeclosuresTabID, neighborhoodSalesTabID, interactiveMapTabID, parent)
    {   
        //- elements IDs
        this.HomeInfoTabID =  parent.SafeElementID(homeInfoTabID);    
        this.NeighborhoodInfoTabID = parent.SafeElementID(neighborhoodTabID);
        this.NeighborhoodForeclosuresTabID = parent.SafeElementID(neighborhoodForeclosuresTabID);
        this.NeighborhoodSalesTabID = parent.SafeElementID(neighborhoodSalesTabID);
        this.InteractiveMapTabID = parent.SafeElementID(interactiveMapTabID);
        
        //- elements
        this.HomeInfoTab = parent.GetElement(this.HomeInfoTabID);
        this.NeighborhoodInfoTab = parent.GetElement(this.NeighborhoodInfoTabID);
        this.NeighborhoodForeclosuresTab = parent.GetElement(this.NeighborhoodForeclosuresTabID);
        this.NeighborhoodSalesTab = parent.GetElement(this.NeighborhoodSalesTabID);
        this.InteractiveMapTab = parent.GetElement(this.InteractiveMapTabID);
        
        this.HideTabs = function()
        {
            ToggleElement(this.HomeInfoTab, false);
            ToggleElement(this.NeighborhoodInfoTab, false);
            ToggleElement(this.NeighborhoodForeclosuresTab, false);
            ToggleElement(this.NeighborhoodSalesTab, false);
            ToggleElement(this.InteractiveMapTab, false);
        }
        
        this.ToggleTabs = function(displayNeighborhoodTabs)
        {
            if (this.HomeInfoTab != null && this.NeighborhoodInfoTab != null && this.NeighborhoodForeclosuresTab != null
                && this.NeighborhoodSalesTab != null && this.InteractiveMapTab != null)
            {
                this.HideTabs();
                
                if (!displayNeighborhoodTabs)
                {
                    // Show property detail tabs
                    ToggleElement(this.HomeInfoTab, true);
                    ToggleElement(this.NeighborhoodForeclosuresTab, true);
                    ToggleElement(this.NeighborhoodSalesTab, true);
                    ToggleElement(this.InteractiveMapTab, true);
                }
                else
                {
                    // Show neighborhood detail tabs
                    ToggleElement(this.NeighborhoodInfoTab, true);
                    ToggleElement(this.NeighborhoodForeclosuresTab, true);
                }
            }
        }
        
        // Let's hide all types when creating this object
        // because if address in query string is invalid we don't have to show anything
        this.HideTabs();
    }
    this.Tabs = new CreateTabs(homeInfoTabID, neighborhoodTabID, neighborhoodForeclosuresTabID, neighborhoodSalesTabID, interactiveMapTabID, this);
    
    //- Snapshot 
    var CreateSnapshotData = function(snapshotAddressFirstLineID, snapshotAddressSecondLineID, homeValueID, valueRangeID, areaForeclosuresID, areaForeclosuresLinkID, homeValueTextID, valueRangeTextID, parent)
    {
        this.SnapshotAddressFirstLineID = snapshotAddressFirstLineID;
        this.SnapshotAddressSecondLineID = snapshotAddressSecondLineID;
        this.HomeValueID = homeValueID;
        this.ValueRangeID = valueRangeID;
        this.AreaForeclosuresID = areaForeclosuresID;
        this.AreaForeclosuresLinkID = areaForeclosuresLinkID;
        this.HomeValueTextID = homeValueTextID;
        this.ValueRangeTextID = valueRangeTextID;
        
        this.SnapshotAddressFirstLine = parent.GetElement(this.SnapshotAddressFirstLineID);
        this.SnapshotAddressSecondLine = parent.GetElement(this.SnapshotAddressSecondLineID);
        this.HomeValue = parent.GetElement(this.HomeValueID);
        this.ValueRange = parent.GetElement(this.ValueRangeID);
        this.AreaForeclosures = parent.GetElement(this.AreaForeclosuresID);
        this.AreaForeclosuresLink = parent.GetElement(this.AreaForeclosuresLinkID);
        this.HomeValueText = parent.GetElement(this.HomeValueTextID);
        this.ValueRangeText = parent.GetElement(this.ValueRangeTextID);
        
        
        //-- Trend arrow up image
        this.TrendArrowUp = "<img src=\"/images/icons/trendArrowUp_14x14.gif\" class=\"icon\" />";
        //-- Trend arrow down image
        this.TrendArrowDown = "<img src=\"/images/icons/trendArrowDown_14x14.gif\" class=\"icon\" />";
        //-- Trend Even
        this.TrendEven = "<img src=\"/images/icons/trendEven_20x20.gif\" class=\"icon\" />";
        
        this.EnableActivityImages = function()
        {
            if (this.HomeValue != null)
            {
                this.HomeValue.innerHTML = parent.BarLoaderHTML;
            }
            
            if (this.ValueRange != null)
            {
                this.ValueRange.innerHTML = parent.BarLoaderHTML;
            }
            
            if (this.AreaForeclosures != null)
            {
                this.AreaForeclosures.innerHTML = parent.BarLoaderHTML;
            }
            
            if (this.SnapshotAddressFirstLine != null && this.SnapshotAddressSecondLine != null)
            {
                this.SnapshotAddressFirstLine.innerHTML = "Loading results...";
                this.SnapshotAddressSecondLine.innerHTML = "";
            }
            
            ShowBEOverlay();
        }
        
        this.DisableActivityImages = function()
        {
            if (this.HomeValue != null)
            {
                this.HomeValue.innerHTML = "";
            }
            
            if (this.ValueRange != null)
            {
                this.ValueRange.innerHTML = "";
            }
            
            if (this.AreaForeclosures != null)
            {
                this.AreaForeclosures.innerHTML = "";
            }
            
            if (this.SnapshotAddressFirstLine != null && this.SnapshotAddressSecondLine != null)
            {
                this.SnapshotAddressFirstLine.innerHTML = "";
                this.SnapshotAddressSecondLine.innerHTML = "";
            }
            
            HideBEOverlay();
        }
        
        this.UpdateHomeValue = function(value)
        {
            if (this.HomeValue != null)
            {
                this.HomeValue.innerHTML = value;
                /* when populating data into a span element also set CSS */
                this.HomeValue.setAttribute("class", "ctaText boldtext");
                this.HomeValue.style.cssText = "color:#d37424;";/* temporary fix */
            }
        }
        
        this.UpdateValueRange = function(value)
        {
            if (this.ValueRange != null)
            {
                this.ValueRange.innerHTML = value;
                /* when populating data into a span element also set CSS */
                this.ValueRange.setAttribute("class", "boldtext");
            }
        }
        
        this.UpdateAreaPropertyCount = function(value)
        {
            if (this.AreaForeclosures != null)
            {
                this.AreaForeclosures.innerHTML = value;
            }
        }
        
        this.UpdateAreaURL = function(newUrl)
        {
            if (this.AreaForeclosuresLink != null)
            {
                this.AreaForeclosuresLink.href = newUrl;
            }
        }
        
        this.UpdateSearchAddress = function(addressStreetPart, addressAreaPart)
        {
            var isFullAddress = false;
            // Let's clear address elements
            this.SnapshotAddressFirstLine.innerHTML = "";
            this.SnapshotAddressSecondLine.innerHTML = "";
            
            if (typeof(addressStreetPart) != "undefined" && addressStreetPart != null && addressStreetPart != "")
            {
                this.SnapshotAddressFirstLine.innerHTML = addressStreetPart;
                isFullAddress = true;
            }
            
            if (typeof(addressAreaPart) != "undefined" && addressAreaPart != null && addressAreaPart != "")
            {
                if (isFullAddress)
                {
                    this.SnapshotAddressSecondLine.innerHTML = addressAreaPart;
                }
                else
                {
                    this.SnapshotAddressFirstLine.innerHTML = addressAreaPart;
                }
            }
            
        }
        this.UpdateModeToDisplay = function(displayNeighborhoodData)
        {
            if (displayNeighborhoodData)
            {
                this.HomeValueText.innerHTML = "Median Estimated Value:";
                this.ValueRangeText.innerHTML = this.TrendEven + "12-month Change:";
            }
            else
            {
                this.HomeValueText.innerHTML = "Home Value:";
                this.ValueRangeText.innerHTML = this.TrendEven + "Monthly Change:";
            }
        }
        
        this.UpdateTrendArrow = function(value, isNeighborhoodDetails)
        {
            if (!isNeighborhoodDetails)
            {
                value = value.replace('$',''); // remove '$'
            }
            
            var number = parseFloat(value);
            
            if (number > 0)
            {
                this.ValueRangeText.innerHTML = (isNeighborhoodDetails) ? this.TrendArrowUp + "12-month Change:" : this.TrendArrowUp + "Monthly Change:";
            }
            else if (number < 0)
            {
                this.ValueRangeText.innerHTML = (isNeighborhoodDetails) ? this.TrendArrowDown + "12-month Change:" : this.TrendArrowDown + "Monthly Change:";
            }
            else if (!isNaN(number))
            {
                this.ValueRangeText.innerHTML = (isNeighborhoodDetails) ? this.TrendEven + "12-month Change:" : this.TrendEven + "Monthly Change:";
            }
            
        }
    }
    
    this.Snapshot = new CreateSnapshotData(snapshotAddressFirstLineID, snapshotAddressSecondLineID, homeValueID, valueRangeID, areaForeclosuresID, areaForeclosuresLinkID, homeValueTextID, valueRangeTextID, this);

    this.ListPriceSelectItems = function(stateCode)
    {
        if (this.GainListSelect != null)
        {
            var ind = 0;
            for (i = 0; i < this.GainListSelect.options.length; i++)
            {
                if (this.GainListSelect.options[i].value == stateCode)
                {
                    ind = i;
                    break;
                }
            }
            
            this.GainListSelect.options[ind].selected = true;
            
            if (this.DropListSelect != null)
            {
                this.DropListSelect.options[ind].selected = true;
            }
        }
    }

}

function ShowBEOverlay()
{
    $('#loadingOverlay').show();
}

function HideBEOverlay()
{
    $('#loadingOverlay').hide();
}

function ToggleElement(element, display)
{
    if (element != null)
    {
        element.style.display = (display) ? "block" : "none";
    }
}


//******************* Email Friend functionality ***********************

function ValidateEmailFriendForm(yourEmail, yourName, friendsEmail, copyMe, spanAddress)
{
    var lsYourEmail = document.getElementById(yourEmail);
    var lsFriendsEmail = document.getElementById(friendsEmail);
    var lsYourName = document.getElementById(yourName);
    var lscopyMe = document.getElementById(copyMe);
    var lsAddress = document.getElementById(spanAddress);    
    var addressLine1 = '';
    var addressLine2 = '';
    var propertyAddress = '';
    var lsError = '';

    if (null != lsFriendsEmail && g_fnCheckEmail(lsFriendsEmail) == false)
    {
        lsError += '- You must enter a valid e-mail address for your friend\n';
    }
    if (null != lsYourEmail && g_fnCheckEmail(lsYourEmail) == false)
    {
        lsError += '- You must enter a valid e-mail address for yourself\n';
    }

    if (null != lsYourName && lsYourName.value == '')
    {
        lsError += '- You must enter your name\n';
    }
    
    if(lsAddress != null && lsAddress.childNodes.length > 0)
    {
        addressLine1 = lsAddress.firstChild.data;
    }
    
    if(lsAddress != null && lsAddress.childNodes.length > 1)
    {
        addressLine2 = lsAddress.lastChild.data;
    }
    
    if (lsError != '')
    {
        alert('The following items need to be addressed:\n\n' + lsError);
    }
    else
    {
        RealtyTrac.ValueTracMapService.SendEmailToFriend(lsYourEmail.value, lsYourName.value, lsFriendsEmail.value, lscopyMe.checked, addressLine1, addressLine2, ValidateEmailFriendForm_Continue);
    }
}

function ValidateEmailFriendForm_Continue(isEmailSent)
{
    var tnkDiv = document.getElementById('divThankYou');
    var emailFriendForm = document.getElementById('divEmailForm');
    if (null != tnkDiv && isEmailSent && null != emailFriendForm)
    {
        tnkDiv.style.display = "block";
        ResetEmailFreindForm();
        emailFriendForm.style.display = "none";
    }
}

function EmailSentPopUpClose()
{
    //HideFormEmailFriend();
    var tnkDiv = document.getElementById('divThankYou');
    var emailFriendForm = document.getElementById('divEmailForm');
    if (null != tnkDiv && null != emailFriendForm)
    {
        tnkDiv.style.display = "none";
        emailFriendForm.style.display = "block";
    }
}

function ResetEmailFreindForm()
{
    var lsYourEmail = document.getElementById('YourEmail');
    var lsFriendsEmail = document.getElementById('FriendsEmail');
    var lsYourName = document.getElementById('YourName');
    var lscopyMe = document.getElementById('chkCopyMe');

    if (null != lsYourEmail)
    {
        lsYourEmail.value = '';
    }
    if (null != lsFriendsEmail)
    {
        lsFriendsEmail.value = '';
    }
    if (null != lsYourName)
    {
        lsYourName.value = '';
    }
    if (null != lscopyMe)
    {
        lscopyMe.checked = false;
    }

}

function EnumAddressType()
{
        this.Full = 0;
        this.Street = 1;
        this.County = 2;
        this.Zip = 3;
        this.City = 4;
        this.StateName = 5;
        this.StateCode = 6;
        this.Invalid = 7;
}

function InitRecentSearches(response)
{
    if (response != null && response.RecentSearches != null)
    {            
        var section = new StandartSection2('divRecentProperties', gHTMLTemplatesObj['divRecentPropertiesTemplate']);
        section.headerTitle = 'Your Recent Home Value Searches';
        section.dataSource = response.RecentSearches.RecentSearchesList;
        section.CreateControl();
    }
}

function IniToolBar(response)
{
    //Set Contact Agent Links
    var lnkContactAgent = document.getElementById('lnkContactAgent');
    var lnkContactAgentImg = document.getElementById('lnkContactAgentImg');
    var lnkRateQuoteImg = document.getElementById('lnkRateQuoteImg');
    var AlnkRateQuote1 = document.getElementById('AlnkRateQuote1');
    var SpanAddress = document.getElementById('SpanAddress');

    if (null != response)
    {

        if (lnkRateQuoteImg != null && AlnkRateQuote1 != null)
        {
            lnkRateQuoteImg.style.display = AlnkRateQuote1.style.display = 'block';
            var linkRates = response.HasLiveRates ? response.ToolBar.LiveRateLandingURL : response.ToolBar.FinanceLandingURL;
            AlnkRateQuote1.href = linkRates;
            linkRates = "javascript:_hbLink('rateQuote','right','0,0,30,30'); window.location='" + linkRates + "'";
            lnkRateQuoteImg.setAttribute('onclick', linkRates);
        }
        if (lnkContactAgent != null && lnkContactAgentImg != null)
        {
            lnkContactAgent.style.display = lnkContactAgentImg.style.display = 'block';
            lnkContactAgent.href = response.ToolBar.AgentLeadURL;
            lnkContactAgentImg.onclick = function() { changeWindowLocation(response.ToolBar.AgentLeadURL); }
        }

        //set Emai a Friend Form Information
        if (SpanAddress != null)
        {
            SpanAddress.innerHTML = response.ToolBar.AddressHTML;
        }
    }
    else
    {
        if (null != lnkRateQuoteImg) { lnkRateQuoteImg.style.display = 'none'; }
        if (null != AlnkRateQuote1) { AlnkRateQuote1.style.display = 'none'; }
        if (null != lnkContactAgent) { lnkContactAgent.style.display = 'none'; }
        if (null != lnkContactAgentImg) { lnkContactAgentImg.style.display = 'none'; }
        if (null != SpanAddress) { SpanAddress.style.display = 'none'; }
    }
}

/****************** Starts Functionality Email Alert *******************/

function InitEmailFormSingUp(response)
{
    var CONST_ADDRESS_TYPE_FULL = 0;
    if (null != gSearchAddressSerialized && null != response && null != gTxtAlertEmail_notSignin && null != gLtlAlertEmail_Signin)
    {
        var AddressQualified = DeserializeObject(gSearchAddressSerialized);
        var btnValueTracEmailAlert = document.getElementById(gBtnValueTracEmailAlertID);
        var txtAlertEmail_notSignin = document.getElementById(gTxtAlertEmail_notSignin);
        var ltlAlertEmail_Signin = document.getElementById(gLtlAlertEmail_Signin);
        var spanPropAddress = document.getElementById('spanPropAddress');

        if (AddressQualified.AddressType == CONST_ADDRESS_TYPE_FULL && btnValueTracEmailAlert != null)
        {
            btnValueTracEmailAlert.style.display = 'block';
            txtAlertEmail_notSignin.value = ltlAlertEmail_Signin = response.ToolBar.Email;
            spanPropAddress.innerHTML = response.ToolBar.AddressHTML;
        }
        else
        {
            btnValueTracEmailAlert.style.display = 'none';
        }
    }
}

function ValidateEmailFormSignUp(tbxEmail)
{
    var lsYourEmail = document.getElementById(tbxEmail);
    var lsAcceptOtherAlerts = document.getElementById('acceptOtherAlerts');

    if (null != lsYourEmail && lsYourEmail.style.display == 'block' && g_fnCheckEmail(lsYourEmail) == false)
    {
        alert("You must enter your email.");
    }
    else
    {
        RealtyTrac.ValueTracMapService.GetEmailAlert(lsYourEmail.value, gAddresEmailAlert, gCityEmailAlert, gStateEmailAlert, gZipEmailAlert, lsAcceptOtherAlerts.checked, ValidateEmailFormSignUp_Continue);
    }
}

function ValidateEmailFormSignUp_Continue(url)
{
    if (url != '')
    {
        window.location = url;
    }
}

/****************** Ends Functionality Email Alert *******************/

/****************** Hot Property control helper *******************/
HotPropertyHelper = function(propertyAreaID, propertyPhotoLinkID, propertyPhotoID, propertyAddressLinkID, addressLabelID, cityStateLabelID, bedsAndBathsID,
    foreclosureStatusPanelID, foreclosureStatusLabelID, hotPropertyResaleRatingImgID, listPriceLinkID, lastSoldLinkID, savingsPanelID,
    savingsLabelID, viewPropertyLinkID, morePropertiesLinkID, morePropertiesLabelID, controlDivID, isPrePopulated)
{
    this.GetElement = function(elementID)
    {
        if (elementID != undefined && elementID != null && elementID != "")
        {
            return document.getElementById(elementID);
        }
        else
        {
            return null;
        }
    }
    
    this.SafeElementID = function(elementID)
    {
        return (elementID == undefined) ? "" : elementID;
    }
    
    this.PropertyAreaID = propertyAreaID;
    this.PropertyArea = this.GetElement(this.PropertyAreaID);
    
    this.PropertyPhotoLinkID = propertyPhotoLinkID;
    this.PropertyPhotoLink = this.GetElement(this.PropertyPhotoLinkID);
    
    this.PropertyPhotoID = propertyPhotoID;
    this.PropertyPhoto = this.GetElement(this.PropertyPhotoID);
    
    this.PropertyAddressLinkID = propertyAddressLinkID;
    this.PropertyAddressLink = this.GetElement(this.PropertyAddressLinkID);
    
    this.AddressLabelID  = addressLabelID;
    this.AddressLabel = this.GetElement(this.AddressLabelID);
    
    this.CityStateLabelID = cityStateLabelID;
    this.CityStateLabel = this.GetElement(this.CityStateLabelID);
    
    this.BedsAndBathsID = bedsAndBathsID;
    this.BedsAndBaths = this.GetElement(this.BedsAndBathsID);
    
    this.ForeclosureStatusPanelID = foreclosureStatusPanelID;
    this.ForeclosureStatusPanel = this.GetElement(this.ForeclosureStatusPanelID);
    
    this.ForeclosureStatusLabelID = foreclosureStatusLabelID;
    this.ForeclosureStatusLabel = this.GetElement(this.ForeclosureStatusLabelID);
    
    this.HotPropertyResaleRatingImgID = hotPropertyResaleRatingImgID;
    this.HotPropertyResaleRatingImg = this.GetElement(this.HotPropertyResaleRatingImgID);
    
    this.ListPriceLinkID = listPriceLinkID;
    this.ListPriceLink = this.GetElement(this.ListPriceLinkID);
    
    this.LastSoldLinkID = lastSoldLinkID;
    this.LastSoldLink = this.GetElement(this.LastSoldLinkID);
    
    this.SavingsPanelID = savingsPanelID;
    this.SavingsPanel = this.GetElement(this.SavingsPanelID);
    
    this.SavingsLabelID = savingsLabelID;
    this.SavingsLabel = this.GetElement(this.SavingsLabelID);
    
    this.ViewPropertyLinkID = viewPropertyLinkID;
    this.ViewPropertyLink = this.GetElement(this.ViewPropertyLinkID);
    
    this.MorePropertiesLinkID = morePropertiesLinkID;
    this.MorePropertiesLink = this.GetElement(this.MorePropertiesLinkID);
    
    this.MorePropertiesLabelID = morePropertiesLabelID;
    this.MorePropertiesLabel = this.GetElement(this.MorePropertiesLabelID);
    
    this.ControlDivID = controlDivID;
    this.ControlDiv = this.GetElement(this.ControlDivID);
    
    // this parameter is set to true when registering this class from server side
    // as we populate control during page load we don't have to do something with it 
    
    this.IsPrePopulated = false; //isPrePopulated; 
    
    // Adding tooltips
    $('#divResaleRating').bt({ width: '400px', ajaxPath: '/ValueTrac/TooltipCopy.xml div#resaleRating' });
    $('#compareButtonSalesPrice').bt({ width: '300px', ajaxPath: '/ValueTrac/TooltipCopy.xml div#previewInteractiveTools' });
    $('#compareButtonFcActivity').bt({ width: '300px', ajaxPath: '/ValueTrac/TooltipCopy.xml div#previewInteractiveTools' });

    this.UpdateControl = function(hotPropertyData) {
        if (!this.IsPrePopulated) {
            if (hotPropertyData.HideControl) {
                if (this.ControlDiv != null) {
                    this.ControlDiv.style.display = 'none';
                }
            }
            else {
                if (this.ControlDiv != null) {
                    this.ControlDiv.style.display = 'block';
                }

                if (this.PropertyArea != null) {
                    this.PropertyArea.innerHTML = 'RealtyDeals in ' + hotPropertyData.AreaName;
                }

                if (this.PropertyPhoto != null) {
                    this.PropertyPhoto.src = hotPropertyData.ImageUrl;
                }

                if (this.PropertyPhotoLink != null) {
                    this.PropertyPhotoLink.href = hotPropertyData.PropertyDetailsUrl;
                }

                if (this.PropertyAddressLink != null) {
                    this.PropertyAddressLink.href = hotPropertyData.PropertyDetailsUrl;
                }

                if (this.AddressLabel != null) {
                    this.AddressLabel.innerHTML = hotPropertyData.Address;
                }


                if (this.CityStateLabel != null) {
                    this.CityStateLabel.innerHTML = hotPropertyData.CityState;
                }

                if (this.BedsAndBaths != null) {
                    this.BedsAndBaths.innerHTML = hotPropertyData.BedsAndBaths;
                }

                if (this.ForeclosureStatusPanel != null) {
                    if (hotPropertyData.DisplayForeclosureStatus) {
                        this.ForeclosureStatusLabel.style.display = 'block';
                        this.ForeclosureStatusLabel.innerHTML = hotPropertyData.ForeclosureStatus;
                    }
                    else {
                        this.ForeclosureStatusPanel.style.display = 'none';
                    }
                }

                if (this.HotPropertyResaleRatingImg != null) {
                    this.HotPropertyResaleRatingImg.src = "/images/ResaleTieIn/ms_forsale_star_" + hotPropertyData.ResaleRating + ".gif";
                }

                if (this.ListPriceLink != null) {
                    this.ListPriceLink.href = hotPropertyData.PropertyDetailsUrl;
                    this.ListPriceLink.innerHTML = hotPropertyData.ListPrice;
                }

                if (this.LastSoldLink != null) {
                    this.LastSoldLink.href = hotPropertyData.PropertyDetailsUrl;
                    this.LastSoldLink.innerHTML = hotPropertyData.LastSoldPrice;
                }

                if (this.SavingsPanel != null) {
                    if (hotPropertyData.EnableSavingsPanel) {
                        this.SavingsPanel.style.display = 'block';
                        if (this.SavingsLabel != null) {
                            this.SavingsLabel.innerHTML = hotPropertyData.Savings;
                        }
                    }
                    else {
                        this.SavingsPanel.style.display = 'none';
                    }
                }

                if (this.ViewPropertyLink != null) {
                    this.ViewPropertyLink.href = hotPropertyData.PropertyDetailsUrl;

                    if (!hotPropertyData.DisplayForeclosureStatus) {
                        this.ViewPropertyLink.setAttribute("class", "buttonCTAMedium");
                        this.ViewPropertyLink.innerHTML = "<span>View Now!</span>";
                    }
                    else {
                        this.ViewPropertyLink.setAttribute("class", "buttonSystemSmall");
                        this.ViewPropertyLink.innerHTML = "<span>View Property Now!</span>";
                    }
                }

                if (this.MorePropertiesLink != null) {
                    this.MorePropertiesLink.href = hotPropertyData.MapSearchUrl;
                }

                if (this.MorePropertiesLabel != null) {
                    this.MorePropertiesLabel.innerHTML = hotPropertyData.AreaName;
                }
            }
        }
        else {
            this.IsPrePopulated = false;
        }
    }

}

/****************** End Hot Property control helper *******************/


/****************** Global object for all tabs *******************/

GlobalResponse = function() {
    // Global controls
    this.SnapshotResponse = null;
    this.HotPropertyData = null;
    this.HasLiveRates = false;
    this.LiveRates = null;
    this.ToolBar = null;
    this.RecentSearches = null;
    this.DisplayNeighborhoodTabs = false;
    this.NeighborhoddEstimatedValues = null;
    this.ForeclosureProperties = null;
    this.HitBoxData = null;
    
    // Tabs
    this.HomeInformationTabResponse = null;
    
    this.AreaForeclosuresData = null;
    
    this.NeighborhoodDetailsData = null;
    
    this.InteractiveMapData = null;
    
    // Charts Data
    this.AverageSalesPriceChartData = null;
    this.AverageSalesPriceChartDataUrl = null;
    this.AverageSalesPriceChartCriteria = null;

    this.TCAverageSalesPriceChartData = null;
    this.TCAverageSalesPriceChartDataUrl = null;
    this.TCAverageSalesPriceChartCriteria = null;
    
    this.ForeclosureActivityChartData = null;
    this.ForeclosureActivityChartDataUrl = null;
    this.ForeclosureActivityChartCriteria = null;
    
    this.HomeValueEstimatesChartData = null;
    this.HomeValueEstimatesChartDataUrl = null;

    this.AverageSalesPriceChartReloaded = false;
    this.TCAverageSalesPriceChartReloaded = false;
    this.ForeclosureActivityChartReloaded = false;
    this.HomeValueEstimatesChartReloaded = false;
    
    // Private data
    this.HasControlsData = false;
    
    this.ClearAllData = function() {
        this.SnapshotResponse = null;
        this.HotPropertyData = null;
        this.HasLiveRates = false;
        this.LiveRates = null;
        this.ToolBar = null;
        this.RecentSearches = null;
        this.DisplayNeighborhoodTabs = false;
        this.NeighborhoddEstimatedValues = null;
        this.ForeclosureProperties = null;
        
        this.HomeInformationTabResponse = null;
        this.AreaForeclosuresData = null;
        this.NeighborhoodDetailsData = null;
        this.ComparableSalesData = null;
        this.InteractiveMapData = null;
        
        this.HomeValueEstimatesChartData = null;
        this.HomeValueEstimatesChartDataUrl = null;
        
        this.AverageSalesPriceChartData = null;
        this.AverageSalesPriceChartCriteria = null;

        this.TCAverageSalesPriceChartData = null;
        this.TCAverageSalesPriceChartCriteria = null;
        
        this.ForeclosureActivityChartData = null;
        this.ForeclosureActivityChartDataUrl = null;
        this.ForeclosureActivityChartCriteria = null;

        this.AverageSalesPriceChartReloaded = false;
        this.TCAverageSalesPriceChartReloaded = false;
        this.ForeclosureActivityChartReloaded = false;
        this.HomeValueEstimatesChartReloaded = false;
                
        this.HasControlsData = false;
        
        this.HitBoxData = null;
    }    
    
   
    this.HasFAHomeInformationTabResponse = function() {
        return (this.HomeInformationTabResponse != null && this.HomeInformationTabResponse.HomeDetailsResponse != null);
    }
    this.HasCHHomeInformationTabResponse = function() {
        return (this.HomeInformationTabResponse != null && this.HomeInformationTabResponse.HomeDetailsResponseCH != null);
    }
 
    this.HasChartData = function() {
        return
            (this.AverageSalesPriceChartDataUrl != null && this.AverageSalesPriceChartCriteria != null
            && this.ForeclosureActivityChartDataUrl != null && this.ForeclosureActivityChartCriteria != null
            && this.TCAverageSalesPriceChartDataUrl != null && this.TCAverageSalesPriceChartCriteria != null);
    }
    
    this.UpdateHomeInformationTabResponse = function(response) {
        if (response != null) {
            if (this.HomeInformationTabResponse == null) {
                this.HomeInformationTabResponse = response;
            }
            else {
                if (!this.HasFAHomeInformationTabResponse()) {
                    this.HomeInformationTabResponse.HomeDetailsResponse = response.HomeDetailsResponse;
                }
                
                if (!this.HasCHHomeInformationTabResponse()) {
                    this.HomeInformationTabResponse.HomeDetailsResponseCH = response.HomeDetailsResponseCH;
                }
            }
        }
    }

    this.UpdateChartsData = function(averageSalesPriceChartData, averageSalesPriceChartCriteria, foreclosureActivityChartData, foreclosureActivityChartCriteria) {
        if (averageSalesPriceChartData != null) {
            this.AverageSalesPriceChartDataUrl = averageSalesPriceChartData;
        }
        
        if (averageSalesPriceChartCriteria != null) {
            this.AverageSalesPriceChartCriteria = averageSalesPriceChartCriteria;
        }
        
        if (foreclosureActivityChartCriteria != null) {
            this.ForeclosureActivityChartCriteria = foreclosureActivityChartCriteria;
        }
        
        if (foreclosureActivityChartData != null) {
            this.ForeclosureActivityChartDataUrl = foreclosureActivityChartData;
        }
    }
    
    this.ItemsToGet = function(tabID) {
        
        // enumerator for web-service
        // 0 - to get tab data
        // 1 - to get controls data
        // 2 - to get all data
        
        var itemsToGet = 0;
        var getTabData = false;
        
        if (typeof (tabID) != "undefined" && tabID != "") {
            switch (tabID) {
                case 'homeinfo':
                    getTabData = (!(this.HasFAHomeInformationTabResponse() && this.HasCHHomeInformationTabResponse()));    
                    break;
                    
                case 'nhinfo':
                    getTabData = (this.NeighborhoodDetailsData == null);
                    break;
                    
                case 'nhforeclosures':  
                    getTabData = (this.AreaForeclosuresData == null);
                    break;
                                      
                case 'intmap':
                    getTabData = (this.InteractiveMapData == null);
                    break;
            }
        }
        
        itemsToGet = (!this.HasControlsData && getTabData) ? 2 : (!this.HasControlsData) ? 1 : 0;
        
        return itemsToGet;
    }   
    
    this.UpdateControlsData = function(controlDataResponse) {
        if (controlDataResponse != null && !this.HasControlsData) {
            this.HasLiveRates = controlDataResponse.HasLiveRates;
            this.HotPropertyData = controlDataResponse.HotPropertyData;
            this.LiveRates = controlDataResponse.LiveRates;
            this.SnapshotResponse = controlDataResponse.SnapshotResponse;
            this.ToolBar = controlDataResponse.ToolBar;
            this.DisplayNeighborhoodTabs = controlDataResponse.DisplayNeighborhoodTabs;
            this.RecentSearches = controlDataResponse.RecentSearches;
            this.NeighborhoddEstimatedValues = controlDataResponse.NeighborhoddEstimatedValues;
            this.ForeclosureProperties = controlDataResponse.ForeclosurePropertiesData;
            this.AgentBanner = controlDataResponse.AgentBanner;
             
            this.HasControlsData = true;
        }
     }
     
     this.UpdateHitboxData = function(hbxData)
     {
        if (typeof(hbxData) != "undefined" && hbxData != null)
        {
            this.HitBoxData = hbxData;
        }
     }
}

// Initialize global response
gGlobalResponse = new GlobalResponse();

/****************** End Global object for all tabs  *******************/


///*********** Charts ****************/
function ReloadHomeValueEstimatesChart()
{
    if (gGlobalResponse != null && gGlobalResponse.HomeValueEstimatesChartData 
        && !gGlobalResponse.HomeValueEstimatesChartReloaded)
    {
        var chartImage = document.getElementById("homeValueTrendChartImage");
        if (chartImage != null)
        {
            chartImage.innerHTML = gGlobalResponse.HomeValueEstimatesChartData;
        }
        
        gGlobalResponse.HomeValueEstimatesChartReloaded = true; 
    }
    else
    {
        // chart data is not loaded yet, we only have a url
        if(gGlobalResponse != null 
        && !gGlobalResponse.HomeValueEstimatesChartData 
        && gGlobalResponse.HomeValueEstimatesChartDataUrl)
        {
            $.get(
                  gGlobalResponse.HomeValueEstimatesChartDataUrl, 
                    function(responseText)
                      {
                        gGlobalResponse.HomeValueEstimatesChartData = responseText;
                        ReloadHomeValueEstimatesChart();
                      });
            return;
        }        
    }
    
    CloneHomeValueTrendChart();
} 


function CloneHomeValueTrendChart()
{
    var mainContainer = document.getElementById("homeValueTrendChartSource");
    if (mainContainer != null)
    {
        var source = mainContainer.innerHTML;
       
        var homeDetailsChart = document.getElementById("divContentHomeInfoHomeValueTrend");
        if (homeDetailsChart != null)
        {   
            homeDetailsChart.innerHTML = source;
        }
        
        var neighborhoodDetailsChart = document.getElementById("divContentNeighborhoodInfoHomeValueTrend");
        if (neighborhoodDetailsChart != null)
        {
            neighborhoodDetailsChart.innerHTML = source;
        }
        
    }
}

function ReloadHomeValueEstimatesChartWithParams(newUrl)
{
    if (typeof(newUrl) != "undefined" && newUrl != null && newUrl != "")
    {
        $.get(newUrl, ReloadHomeValueEstimatesChartWithParams_Continue);
    }
}

function ReloadHomeValueEstimatesChartWithParams_Continue(newHtml)
{
    CheckGlobalResponse();
    gGlobalResponse.HomeValueEstimatesChartReloaded = false;
    gGlobalResponse.HomeValueEstimatesChartData = newHtml;
    ReloadHomeValueEstimatesChart();
}

function ReloadTCAverageSalesPriceChart() {

    if (gGlobalResponse != null && gGlobalResponse.TCAverageSalesPriceChartData
        && !gGlobalResponse.TCAverageSalesPriceChartReloaded) {
        var chartImage = document.getElementById("tcAverageSalesPriceChartImage");
        if (chartImage != null) {
            chartImage.innerHTML = gGlobalResponse.TCAverageSalesPriceChartData;
        }


        if (typeof (gTCAverageSalesPriceLabelID) != "undefined" && gTCAverageSalesPriceLabelID != null && gGlobalResponse.TCAverageSalesPriceChartCriteria != null) {
            var label = document.getElementById(gTCAverageSalesPriceLabelID);
            if (label != null) {
                label.innerHTML = gGlobalResponse.TCAverageSalesPriceChartCriteria;
            }
        }

        gGlobalResponse.TCAverageSalesPriceChartReloaded = true;
    }
    else
    {
        // we have a chart url, but not the data
        if(gGlobalResponse != null && !gGlobalResponse.TCAverageSalesPriceChartData
            && gGlobalResponse.TCAverageSalesPriceChartDataUrl)
            {
                $.get(gGlobalResponse.TCAverageSalesPriceChartDataUrl,
                    function(responseText)
                    {
                        gGlobalResponse.TCAverageSalesPriceChartData = responseText;
                        ReloadTCAverageSalesPriceChart();
                    });
                    
                return;
            }
    }

    var mainContainer = document.getElementById("tcAverageSalesPriceChartSource");
    if (mainContainer != null) {
        var source = mainContainer.innerHTML;

        var neighborhoodInfoAvgSalesPriceGraph = document.getElementById("divContentNeighborhoodInfoAvgSalesPriceGraph");
        if (neighborhoodInfoAvgSalesPriceGraph != null) {
            neighborhoodInfoAvgSalesPriceGraph.innerHTML = source;
        }

    }
}

function ReloadAverageSalesPriceChart()
{
    if (gGlobalResponse != null && gGlobalResponse.AverageSalesPriceChartData 
        && !gGlobalResponse.AverageSalesPriceChartReloaded)
    {
        var chartImage = document.getElementById("averageSalesPriceChartImage");
        if (chartImage != null)
        {
            chartImage.innerHTML = gGlobalResponse.AverageSalesPriceChartData;
        }
        
        
        if (typeof(gAverageSalesPriceLabelID) != "undefined" && gAverageSalesPriceLabelID != null && gGlobalResponse.AverageSalesPriceChartCriteria != null)
        {
            var label = document.getElementById(gAverageSalesPriceLabelID);
            if (label != null)
            {
                label.innerHTML = gGlobalResponse.AverageSalesPriceChartCriteria;
            }
        }
        
        gGlobalResponse.AverageSalesPriceChartReloaded = true; 
    }
    else
    {
        // we have a chart url, but not the data
        if(gGlobalResponse != null && !gGlobalResponse.AverageSalesPriceChartData 
            && gGlobalResponse.AverageSalesPriceChartDataUrl)
        {
            $.get(gGlobalResponse.AverageSalesPriceChartDataUrl,
                function(responseText)
                {
                    gGlobalResponse.AverageSalesPriceChartData = responseText;
                    ReloadAverageSalesPriceChart();
                });
            
            return;
        }
    }

        
    var mainContainer = document.getElementById("averageSalesPriceChartSource");
    if (mainContainer != null)
    {
        var source = mainContainer.innerHTML;
       
        var homeDetailsChart = document.getElementById("homeSaleAverageSalesPriceTool");
        if (homeDetailsChart != null)
        {   
            homeDetailsChart.innerHTML = source;
        }
        
        var compSalesAverageSalesPriceChart = document.getElementById("compSalesAverageSalesPriceChart");
        if (compSalesAverageSalesPriceChart != null)
        {
            compSalesAverageSalesPriceChart.innerHTML = source;
        }
        
        var foreclosuresTabChart = document.getElementById("foreclosuresTabAverageSalesChart");
        if (foreclosuresTabChart != null)
        {
            foreclosuresTabChart.innerHTML = source;
        }
        
        var interactiveMapTabChart = document.getElementById("interactiveMapAverageSalesPriceChart");
        if (interactiveMapTabChart != null)
        {
            interactiveMapTabChart.innerHTML = source;
        }
        
    }   
}

function ReloadNewForeclosurePropertiesChart()
{
    if (gGlobalResponse != null && gGlobalResponse.ForeclosureActivityChartData 
        && !gGlobalResponse.ForeclosureActivityChartReloaded)
    {
        var chartImage = document.getElementById("newForeclosurePropertiesChartImage");
        if (chartImage != null)
        {
            chartImage.innerHTML = gGlobalResponse.ForeclosureActivityChartData;
        }
        
        
        if (typeof(gNewForeclosurePropertiesLabelID) != "undefined" && gNewForeclosurePropertiesLabelID != null && gGlobalResponse.ForeclosureActivityChartCriteria != null)
        {
            var label = document.getElementById(gNewForeclosurePropertiesLabelID);
            if (label != null)
            {
                label.innerHTML = gGlobalResponse.AverageSalesPriceChartCriteria;
            }
        }
        
        gGlobalResponse.AverageSalesPriceChartReloaded = true; 
    }
    else
    {
        // only chart url is available, need to load data first
        if (gGlobalResponse != null && !gGlobalResponse.ForeclosureActivityChartData 
            && gGlobalResponse.ForeclosureActivityChartDataUrl)
            {
                $.get(gGlobalResponse.ForeclosureActivityChartDataUrl, 
                    function(responseText)
                    {
                        gGlobalResponse.ForeclosureActivityChartData = responseText;
                        ReloadNewForeclosurePropertiesChart();
                    });
                
                return;
            }
    }
    
    var mainContainer = document.getElementById("foreclosurePropertiesChartSource");
    if (mainContainer != null)
    {
        var source = mainContainer.innerHTML;
       
        var foreclosuresTabChart = document.getElementById("foreclosuresTabNewForeclosuresPropertiesChart");
        if (foreclosuresTabChart != null)
        {
            foreclosuresTabChart.innerHTML = source;
        }
        
        var interactiveMapTabChart = document.getElementById("interactiveMapNewForeclosurePropChart");
        if (interactiveMapTabChart != null)
        {
            interactiveMapTabChart.innerHTML = source;
        }
        
    }
}

function UpdateHitboxData(hitboxResponse)
{
    if (typeof(hitboxResponse) != "undefined" && hitboxResponse != null)
    {
        gGlobalResponse.UpdateHitboxData(hitboxResponse);
    }
    
    if (typeof(ReloadHitboxCompensatorFrame) != "undefined" && gGlobalResponse.HitBoxData != null)
    {
        ReloadHitboxCompensatorFrame(gGlobalResponse.HitBoxData.PageName, gGlobalResponse.HitBoxData.Path, gHbxCustom2);
    }
}

function RefreshDoubleClickBannerUtil()
{    
    if (typeof (RefreshAllDoubleClickBanner) != 'undefined')
    {
        RefreshAllDoubleClickBanner();
    }    
}

function LogErrorMessage(message, exception, rethrowOnly)
{
    if (exception && exception.message)
    {
        message = message + exception.message;
    
        if (rethrowOnly)
        {
            exception.message = message;
            throw exception;
        }
        
        RealtyTrac.ValueTracMapService.LogError(message);   
    }
}

function StartShowForeclosureMap()
{
    if (gShowForeclosuresMap)
    {
        ShowForeclosuresMap(g_BI_Latitude, g_BI_Longitude, g_BI_ZoomLevel);
        gShowForeclosuresMap = false;
    }
    
    if (typeof (g_NeighborhoodTabId) != "undefined")
    {
        InitNeighborhoodInformation(g_NeighborhoodTabId);
    }
}

function ReloadGainListSalesPriceChange(selectedItem)
{
    if (selectedItem != "" && gValueTracHelper.GainListSalesPriceChangeContainer != null 
        && typeof(RealtyTrac.ValueTracMapService.GetListSalePriceData) != "undefined") 
    {
        RealtyTrac.ValueTracMapService.GetListSalePriceData(selectedItem, true, ReloadGainListSalesPriceChange_Continue);
    }
}

function ReloadGainListSalesPriceChange_Continue(datasource)
{
    if (datasource != null)
    {
        var section = new StandartSection2(gValueTracHelper.GainListSalesPriceChangeContainerID, gHTMLTemplatesObj['divGainListPriceStdSectionTemplate']);
        section.dataSource = datasource.SectionItems;
        section.CreateControl();
    }
}

function ReloadDropListSalesPriceChange(selectedItem)
{
    if (selectedItem != "" && gValueTracHelper.DropListSalesPriceChangeContainer != null
        && typeof(RealtyTrac.ValueTracMapService.GetListSalePriceData) != "undefined")
    {
        RealtyTrac.ValueTracMapService.GetListSalePriceData(selectedItem, false, ReloadDropListSalesPriceChange_Continue);
    }
}

function ReloadDropListSalesPriceChange_Continue(datasource)
{
    if (datasource != null)
    {
        var section = new StandartSection2(gValueTracHelper.DropListSalesPriceChangeContainerID, gHTMLTemplatesObj['divGainListPriceStdSectionTemplate']);
        section.dataSource = datasource.SectionItems;
        section.CreateControl();
    }
}

function SelectGainListPriceState(stateCode)
{
    if (gValueTracHelper != null && gValueTracHelper.GainListSelect != null && gValueTracHelper.DropListSelect != null)
    {
        gValueTracHelper.ListPriceSelectItems(stateCode);
    }
}
//END RealtyTrac.Common.Web.Scripts.ValueTrac.ValueTrac.js
//START RealtyTrac.Common.Web.Scripts.ValueTrac.StandartSection.js
Array.prototype.contains = function(element)
{
    for (var i = 0; i < this.length; i++)
    {
        if (this[i] == element)
        {
            return true;
        }
    }
    return false;
}

function jsRepeater()
{
    var CONTS_STRING_EMPTY = '';
    var CONST_REPEATER_CONTENT = ' REPEATER_CONTENT ';
    this.valuesDelimiter = '##';
    this.divRptParentContainer = null;
    this.repeaterDiv = 'divJSRepeater';
    this.rptStartTag = 'START_REPEATER';
    this.rptEndTag = 'END_REPEATER';
    this.rptItemStartTag = 'START_RPT_ITEM';
    this.rptItemEndTag = 'END_RPT_ITEM';
    this.rptAltItemStartTag = 'START_RPT_ALT_ITEM';
    this.rptAltItemEndTag = 'END_RPT_ALT_ITEM';
    this.DataSourse = null;

    this.PopulateRepeater = function() {
        var tempText = this.divRptParentContainer.innerHTML;

        //Get the Repeater as String
        var st = tempText.indexOf(this.rptStartTag, 0);
        var nd = tempText.indexOf(this.rptEndTag, st)
        var rptCon = tempText.substring(st + this.rptStartTag.length, nd);
        //Get the Repeater Item Content
        var itStart = rptCon.indexOf(this.rptItemStartTag, 0);
        var itEndTag = rptCon.indexOf(this.rptItemEndTag, itStart);
        var itInnerContent = rptCon.substring(itStart + this.rptItemStartTag.length, itEndTag);

        var altItmContent = CONTS_STRING_EMPTY;
        if (rptCon.indexOf(this.rptAltItemStartTag, 0) > -1) {
            //Get the Repeater Item Content
            var itAltStart = rptCon.indexOf(this.rptAltItemStartTag, 0);
            var itAltEndTag = rptCon.indexOf(this.rptAltItemEndTag, itAltStart);
            altItmContent = rptCon.substring(itAltStart + this.rptAltItemStartTag.length, itAltEndTag);
        }

        if (itInnerContent != null && rptCon.length > 0 && this.DataSourse != null && this.divRptParentContainer != null) {
            //Get list of Values to be search inside the Repeater
            var values = this.GetValuesList(this.divRptParentContainer.innerHTML);
            var contHTML = CONTS_STRING_EMPTY;

            if (itInnerContent != CONTS_STRING_EMPTY) {
                tempText = tempText.replace(rptCon, CONST_REPEATER_CONTENT);
                tempText = tempText.replace(this.rptStartTag, CONTS_STRING_EMPTY);
                tempText = tempText.replace(this.rptEndTag, CONTS_STRING_EMPTY);
                tempText = tempText.replace(this.rptItemStartTag, CONTS_STRING_EMPTY);
                tempText = tempText.replace(this.rptItemEndTag, CONTS_STRING_EMPTY);
                tempText = tempText.replace(this.rptAltItemStartTag, CONTS_STRING_EMPTY);
                tempText = tempText.replace(this.rptAltItemEndTag, CONTS_STRING_EMPTY);


                this.divRptParentContainer.innerHTML = tempText;
                var x = CONTS_STRING_EMPTY;

                for (var cnt = 0; cnt < this.DataSourse.length; cnt++) {
                    if (altItmContent != CONTS_STRING_EMPTY) {
                        x = (cnt % 2 == 0) ? itInnerContent : altItmContent;
                    }
                    else {
                        x = itInnerContent;
                    }

                    /* include a count for unique items (table rows) in the array */
                    var itemct = cnt + 1;
                    x = x.replace(this.valuesDelimiter + 'COUNT' + this.valuesDelimiter, itemct.toString());

                    for (var i = 0; i < values.length; i++) {
                        var valueName = values[i];
                        var valToReplace = this.valuesDelimiter + valueName + this.valuesDelimiter;
                        x = x.replace(valToReplace, this.DataSourse[cnt][valueName]);
                    }

                    contHTML = contHTML + x;
                }

                //we add the Repeater Content
                this.divRptParentContainer.innerHTML = this.divRptParentContainer.innerHTML.replace(/REPEATER_CONTENT/g, contHTML);
            }
            else {
                this.divRptParentContainer.innerHTML = CONTS_STRING_EMPTY;
            }
        }
    }

    this.GetValuesList = function(innerHTML)
    {
        var tempString = innerHTML;
        var valuesArray = new Array();

        if (innerHTML != CONTS_STRING_EMPTY)
        {
            var stringLenght = tempString.length;
            var lastPosition = tempString.lastIndexOf(this.valuesDelimiter);
            var currentPosition = 0;
            var index = 0;
            var counter = 0;
            if (lastPosition > 0)
            {
                while (counter < stringLenght && currentPosition <= lastPosition && currentPosition > -1)
                {
                    var valStart = tempString.indexOf(this.valuesDelimiter, currentPosition);
                    var valEnds = tempString.indexOf(this.valuesDelimiter, valStart + this.valuesDelimiter.length);
                    currentPosition = valEnds + this.valuesDelimiter.length;

                    if (valEnds > 0 && valEnds > valStart)
                    {
                        var tempVal = tempString.substring(valStart + this.valuesDelimiter.length, valEnds);
                        if (!valuesArray.contains(tempVal))
                        {
                            valuesArray[index] = tempVal;
                        }
                        index = index + 1;
                    }

                    counter = counter + 1;

                }
            }
        }

        return valuesArray;
    }

}

function StandartSection2(divContainerName, HTMLTemplateName)
{
    var STRING_EMPTY = '';
    this.divContainerName = divContainerName;
    this.hTMLTemplateName = HTMLTemplateName;
    this.divContainer = document.getElementById(this.divContainerName);
    this.controlID = "StandartSectionCtl_" + this.divContainerName;
    this.hTMLTemplateDiv = HTMLTemplateName;
    this.headerTitle = STRING_EMPTY;
    this.dataSource = null;


    this.CreateControl = function()
    {
        if (this.divContainer != null && this.hTMLTemplateDiv != null)
        {
            this.RemoveAllFromDivContainer();
            
            var tempDiv = document.createElement('div');
            tempDiv.setAttribute('id', this.controlID);

            var tempHTML = this.hTMLTemplateDiv;
            tempHTML = tempHTML.replace(/HEADER_TITLE/g, this.headerTitle);

            tempDiv.innerHTML = tempHTML;

            //this.divContainer.appendChild(tempDiv);
            this.divContainer.innerHTML = tempHTML;

            var rpt = new jsRepeater();
            rpt.divRptParentContainer = this.divContainer;
            rpt.DataSourse = this.dataSource;
            rpt.PopulateRepeater();
        }
    }

    this.RemoveAllFromDivContainer = function()
    {
        var divCont = document.getElementById(this.divContainer);

        if (this.divContainer != null && this.divContainer.childNodes != null)
        {
            while (this.divContainer.childNodes.length > 0)
            {
                this.divContainer.removeChild(this.divContainer.childNodes[0]);
            }
        }
    }
}
//END RealtyTrac.Common.Web.Scripts.ValueTrac.StandartSection.js
//START RealtyTrac.Common.Web.Scripts.MapSearch.framework.js

function ConfigureFramework()
{
    // AJAX framework replacements
    if(gSetWebServiceTimeouts)
    {   
        if(gWebServiceQueueManage)
        {
            QueueManage();
        }
        else
        {
            NotQueueManage();
        }
        
        // Webservice configuration                
        ConfigureWebService('SearchService', SearchService);
        ConfigureWebService('MapService', MapService);
        //ConfigureWebService('MLSService', MLSService);        
    }
}
    
function NotQueueManage()
{
    Sys.Net.WebServiceProxy.retryOnFailure = 
            function(result, userContext, methodName, retryParams, onFailure, numberOfRetries)
        {   
            if( result.get_timedOut() )
            {
                if( typeof retryParams != "undefined" )
                {
                    var servicePath = retryParams.length > 0 ? retryParams[0] : '';
                    var config = GetWebServiceConfig(servicePath);
                    var reportRetries = gReportRetries;
                    
                    if(config)
                    {
                        reportRetries = config.reportRetries;
                    }
                    
                    if(reportRetries)
                    {
                        MapService.LogClientException("Web method call retried: " + servicePath + "." + methodName);
                    }
                    
                    Sys.Net.WebServiceProxy.invoke.apply(this, retryParams );
                }
                else
                {
                    if( onFailure ) 
                    {
                        onFailure(result, userContext, methodName);
                    }
                }
            }
            else
            {
                if( onFailure )
                {
                    onFailure(result, userContext, methodName);
                }
            }
        }

        Sys.Net.WebServiceProxy.original_invoke = Sys.Net.WebServiceProxy.invoke;
        Sys.Net.WebServiceProxy.invoke = 
            function Sys$Net$WebServiceProxy$invoke(servicePath, methodName, useGet, 
                params, onSuccess, onFailure, userContext, timeout, numberOfRetries)
        {      
            if(!numberOfRetries)
            {
                var config = GetWebServiceConfig(servicePath);
                
                if(config)
                {
                    numberOfRetries = config.retries;
                }
                else
                {
                    numberOfRetries = gNumberOfRetries;
                }
            }
            else
            {
                numberOfRetries--;
            }
            
            var retryParams = [ servicePath, methodName, useGet, params, 
                onSuccess, onFailure, userContext, timeout, numberOfRetries ];
                    
            // Call original invoke but with a new onFailure
            // handler which does the auto retry
            var newOnFailure = Function.createDelegate( this, 
                function(result, userContext, methodName) 
                { 
                    Sys.Net.WebServiceProxy.retryOnFailure(result, userContext, 
                        methodName, retryParams, onFailure, numberOfRetries); 
                } );
            
            if(!timeout && timeout != 0)
            {
                timeout = GetWebServiceConfig(servicePath).timeout;
            }
            
            if(numberOfRetries > 0)
            {
                Sys.Net.WebServiceProxy.original_invoke(servicePath, methodName, useGet, 
                    params, onSuccess, newOnFailure, userContext, timeout);
            }
            else
            {
                Sys.Net.WebServiceProxy.original_invoke(servicePath, methodName, useGet, 
                    params, onSuccess, onFailure, userContext, timeout);
            }
        }
}
    
function DefaultWebServiceErrorHandler(result, userContext, methodName, servicePath)
{
    HideSearchOverlay();
	
	if(TheMap && TheMap.isMapVisible)
	{
		TheMap.HideOverLay();
	}
    
    if(result === null)
    {
        return;
    }
    
    var timedOut = result.get_timedOut();   
    var stackTrace = result.get_stackTrace();
    var message = result.get_message();
    var statusCode = result.get_statusCode();
    var exceptionType = result.get_exceptionType();

    // Display the error.    
    var formattedMessage = 
        "Stack Trace: " +  stackTrace + " | " +
        "Service Error: " + message + " | " +
        "Status Code: " + statusCode + " | " +
        "Exception Type: " + exceptionType;   
        
    var config = GetWebServiceConfig(servicePath);
    
    var reportTimeouts = gReportTimeOuts;
    var reportWebServiceErrors = gReportWebServiceErrors;
    
    if(config)
    {
        reportTimeouts = config.reportTimeouts;
        reportWebServiceErrors = config.reportErrors;
    }
    
    if( timedOut )
    {
        if( reportTimeouts )
        {
            MapService.LogClientException( "Web method call timed out: " + servicePath + "." + methodName + " : " + formattedMessage);
        }
    }
    else
    {
        if( reportWebServiceErrors )
        {
            MapService.LogClientException( "Web method call error: " + servicePath + "." + methodName  + " : " + formattedMessage);
        }
    }    
}  
    
// Hitbox dynamic loading    

// temporary stub for hitbox function - will be replaced by hitbox native call when it's loaded
function _hbLink(a,b,c)
{
}

function LoadHitboxScript()
{
    LoadDOMScript('/jscript/hbx.js');
}

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 GetWebServiceConfig(servicePath)
{
    var idx = 0;
    
    for(idx = 0; idx < gWebServiceConfig.length; idx++)
    {
        if(servicePath.indexOf(gWebServiceConfig[idx].service) >= 0)
        {
            return gWebServiceConfig[idx];
        }
    }
    
    // if web sertvice is not configured, then return default (first entry)
    if(gWebServiceConfig.length > 0)
    {
        return gWebServiceConfig[0];
    }
    
    return null;
}

function ConfigureWebService(servicePath, serviceProxy)
{
    var config = GetWebServiceConfig(servicePath);
    
    if(config)
    {
         serviceProxy.set_timeout(config.timeout);       
         
         var failedCallback = Function.createDelegate( this, 
            function(result, userContext, methodName) 
            { 
                DefaultWebServiceErrorHandler(result, userContext, 
                    methodName, servicePath); 
            } );
                
        serviceProxy.set_defaultFailedCallback(failedCallback);
    }        
}

function LogErrorMessage(message, exception, rethrowOnly)
{
    if(exception && exception.message)
    {
        if(exception.message != 'Failed')
        {        
            message = message + exception.message;
        
            if(rethrowOnly)
            {
                throw new Error(message);
            }
            
            MapService.LogClientException(message);   
        
            if(gThrowJavascriptExceptions)
            {
                throw exception;
            }
        }
    }
}

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 QueueManage()
{       
    var GlobalCallQueue = {
        _callQueue : [],    // Maintains the list of webmethods to call
        _callInProgressNames : [],    // Maintains webmethods names in progress by browser
        _callInProgress : 0,    // Number of calls currently in progress by browser
        _maxConcurrentCall : 2, // Max number of calls to execute at a time
        call : function(servicePath, methodName, useGet, 
            params, onSuccess, onFailure, userContext, timeout)
        {
            var queuedCall = new QueuedCall(servicePath, methodName, useGet, 
                params, onSuccess, onFailure, userContext, timeout);

            //if method name is already waiting then remove from queue then add the new call
            for (var x=0;x<GlobalCallQueue._callQueue.length;x++)
            {
                if (GlobalCallQueue._callQueue[x]._methodName==queuedCall._methodName)
                {
                    Array.removeAt( GlobalCallQueue._callQueue, x);
                    gWasDeletedFromQueue++;
                    break;
                }
            }   

            Array.add(GlobalCallQueue._callQueue,queuedCall);
            GlobalCallQueue.run();
        },
        run : function()
        {
            /// Execute a call from the call queue
            if (GlobalCallQueue._callInProgress < GlobalCallQueue._maxConcurrentCall)
            {
                if( 0 == GlobalCallQueue._callQueue.length ) 
                {
                    return;
                } 
                           
                GlobalCallQueue._callInProgress ++;
            
                //get first index that is not already in progess
                var runIndex = -1;
                for (var x=0;x<GlobalCallQueue._callQueue.length;x++)
                {
                    var found=false;
                    for (var y=0;y<GlobalCallQueue._callInProgressNames.length;y++)
                    {
                        if (GlobalCallQueue._callQueue[x]._methodName==GlobalCallQueue._callInProgressNames[y])
                        {
                            found=true;
                            break;
                        }
                    }  
                    if (!found)
                    {
                        runIndex = x;
                        break;
                    }
                }
                if (runIndex!=-1)
                {
                    var queuedCall = GlobalCallQueue._callQueue[runIndex];
                    Array.removeAt( GlobalCallQueue._callQueue, runIndex );             
                    
                    //set name in progress
                    Array.add(GlobalCallQueue._callInProgressNames,queuedCall._methodName);
                    
                    // Call the web method
                    queuedCall.execute();
                }else
                {
                    GlobalCallQueue._callInProgress --;
                }
            }          
        },
        callComplete : function(methodName)
        {
            GlobalCallQueue._callInProgress --;
            //remove name in progress
            for (var x=0;x<GlobalCallQueue._callInProgressNames.length;x++)
            {
                if (GlobalCallQueue._callInProgressNames[x]==methodName)
                {
                    Array.removeAt( GlobalCallQueue._callInProgressNames, x );
                    break;
                }
            }
            GlobalCallQueue.run();
        }
    };

    QueuedCall = function( servicePath, methodName, useGet, params, 
        onSuccess, onFailure, userContext, timeout )
    {
        this._servicePath = servicePath;
        this._methodName = methodName;
        this._useGet = useGet;
        this._params = params;
        
        this._onSuccess = onSuccess;
        this._onFailure = onFailure;
        this._userContext = userContext;
        this._timeout = timeout;
    }

    QueuedCall.prototype = 
    {
        execute : function()
        {
            Sys.Net.WebServiceProxy.original_invoke( 
                this._servicePath, this._methodName, this._useGet, this._params,  
                Function.createDelegate(this, this.onSuccess), // Handle call complete
                Function.createDelegate(this, this.onFailure), // Handle call complete
                this._userContext, this._timeout );
        },
        onSuccess : function(result, userContext, methodName)
        {
            this._onSuccess(result, userContext, methodName);
            GlobalCallQueue.callComplete(methodName);            
        },        
        onFailure : function(result, userContext, methodName)
        {
            this._onFailure(result, userContext, methodName);
            GlobalCallQueue.callComplete(methodName);            
        }        
    };

    //override invoke
    Sys.Net.WebServiceProxy.original_invoke = Sys.Net.WebServiceProxy.invoke;

    Sys.Net.WebServiceProxy.invoke = 
                function Sys$Net$WebServiceProxy$invoke(servicePath, methodName, useGet, 
                    params, onSuccess, onFailure, userContext, timeout, numberOfRetries)
            {       
                if(!numberOfRetries)
                {
                    var config = GetWebServiceConfig(servicePath);
                    
                    if(config)
                    {
                        numberOfRetries = config.retries;
                    }
                    else
                    {
                        numberOfRetries = gNumberOfRetries;
                    }
                }
                else
                {
                    numberOfRetries--;
                }
                
                var retryParams = [ servicePath, methodName, useGet, params, 
                    onSuccess, onFailure, userContext, timeout, numberOfRetries ];
                        
                // Call original invoke but with a new onFailure
                // handler which does the auto retry
                var newOnFailure = Function.createDelegate( this, 
                    function(result, userContext, methodName) 
                    { 
                        Sys.Net.WebServiceProxy.retryOnFailure(result, userContext, 
                            methodName, retryParams, onFailure, numberOfRetries); 
                    } );
                
                if(numberOfRetries > 0)
                {
                    GlobalCallQueue.call(servicePath, methodName, useGet, params, 
                        onSuccess, newOnFailure, userContext, timeout);
                }
                else
                {
                    GlobalCallQueue.call(servicePath, methodName, useGet, params, 
                        onSuccess, onFailure, userContext, timeout);
                }
            }

     Sys.Net.WebServiceProxy.retryOnFailure = 
        function(result, userContext, methodName, retryParams, onFailure, numberOfRetries)
    {
        if( result.get_timedOut() )
        {
            if( typeof retryParams != "undefined" )
            {
                var servicePath = retryParams.length > 0 ? retryParams[0] : '';
                var config = GetWebServiceConfig(servicePath);
                var reportRetries = gReportRetries;
                
                if(config)
                {
                    reportRetries = config.reportRetries;
                }
                
                if(reportRetries)
                {
                    MapService.LogClientException("Web method call retried: " + servicePath + "." + methodName);
                }
                
                Sys.Net.WebServiceProxy.invoke.apply(this, retryParams );
            }
            else
            {
                if( onFailure ) 
                {
                    onFailure(result, userContext, methodName);
                }
            }
        }
        else
        {
            if( onFailure )
            {
                onFailure(result, userContext, methodName);
            }
        }
    }
}

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/

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;
    }

}

//END RealtyTrac.Common.Web.Scripts.MapSearch.framework.js
//START RealtyTrac.Common.Web.Scripts.MapSearch.navigation.js
 


function NavigationEngine(isMember, isWhiteSite, isDataLink, useNewPropertyDetails, freeTrialLink, moreDetailLink, isCustomFreeSite)
{
    this._isMember = isMember;
    this._isWhiteSite = isWhiteSite;
    this._isDataLink = isDataLink;
    this._useNewPropertyDetails = useNewPropertyDetails;    
    this._freeTrialLink = freeTrialLink;
    this._moreDetailLink = moreDetailLink;
    this._isCustomFreeSite = (typeof(isCustomFreeSite) == 'undefined' || isCustomFreeSite == null) ? false : isCustomFreeSite;
    this._oodleAccount = null;
    this.WhiteSitePath = '/WhiteSite/';    
    this.MainSitePath = '/';
    this.NewPropDetailsPath = '/PropertyDetails/';
    
    this._propertyIDs = null;
    
    this.PropertyIDs = function()
    {
        if(this._propertyIDs)
        {
            return '&propids=' + this._propertyIDs;
        }
        
        return '';
    }
    
    this.ReturnPage = function()
    {
        var r = window.location.href;
        var i = r.indexOf("#");
	    
	    if(i >= 0)
	    {
            return '&back=' + escape(r.substr(i+1));
         }

        return '';
    }
    
    this.PropertyDetailsExtra = function()
    {
        return this.ReturnPage() + this.PropertyIDs();
    }
    
    this.Flags = function()
    {
        var flags = '';
        
        if(this._isWhiteSite && !this._isCustomFreeSite)
        {
            flags += '&ws=true';
        }
        
        return flags;
    }
    
    this.Target = function()
    {
        if(this._isDataLink)
        {
            return '_blank';            
        }            
        else
        {
            return '_self';
        }
    }
        
    this.PropertyDetailsPage = function(propertyID)
    {
        return this.PropertyDetailsPageForPropertyType(propertyID, 'd');
    }
    
    this.CreatePropertyDetailsLink = function(propertyID, linkText, hitboxName)
    {
        return this.CreateLink(this.PropertyDetailsPage(propertyID), linkText, hitboxName);
    }
    
    this.CreateLink = function(linkUrl, linkText, hitboxName)
    {
        if(hitboxName)
        {
			var link = "<a href=\"" + linkUrl + "\"";
			link += " onclick=\"_hbLink('" + hitboxName + "','right','0,0,30,30');";
			
			if(this.Target() == "_self")
			{
			    link += "window.location.href='" + linkUrl + "';";
			}
			else
			{
			    link += "window.open('" + linkUrl + "', '_blank');return false;";
			}
			
			link += "\">" + linkText + "</a>";
						
			return link;
        }
        else
        {
            return "<a href='" + linkUrl + "' target='" + this.Target() + "'>" + linkText + "</a>";
        }
    }
    
    this.IsNewPropertyDetails = function(propertyType)
    {
        return this._useNewPropertyDetails 
    }
    
    this.WhiteSitePropertyDetailsPage = function(propertyID, propertyType, reportTab)
    {
        var reportTabParam = '';
        if(typeof(reportTab) != 'undefined' && reportTab != null)
        {
            reportTabParam = '&reportTab=' + reportTab;
        }
        if(this.IsNewPropertyDetails(propertyType))
        {
            return this.NewPropDetailsPath + 'PropertyDetails.aspx?propid=' + propertyID + reportTabParam + this.Flags() + this.PropertyDetailsExtra();
        }
        else
        {
            return this.WhiteSitePath + 'PropertyDetails.aspx?propid=' + propertyID + reportTabParam + this.Flags() + this.PropertyDetailsExtra();
        }
    }
    
    this.SafeAddUrlParameter = function(url, parameter)
    {
        if(url.indexOf('?') >= 0)
        {
            return url + '&' + parameter;
        }
        else
        {
            return url + '?' + parameter;
        }
    }
    
    this.REDCPropertyDetailsPage = function(propertyID)
    {
        if(!this._isMember)
        {
            return this.MainSitePath + 'freePropDetails.asp?propid=' + propertyID;
        }
        else
        {
            return this.MainSitePath + 'Database/propDetails.asp?propid=' + propertyID;
        }                
    }   

    this.PropertyDetailsPageForPropertyType = function(propertyID, propertyType, reportTab)
    {       
        var reportTabParam = ''; 
        if(typeof(reportTab) != 'undefined' && reportTab != null)
        {
            reportTabParam = '&reportTab=' + reportTab;
        }
        if('' != this._moreDetailLink && this._moreDetailLink != null)
        {
            return this.SafeAddUrlParameter(this._moreDetailLink, 'propid=' + propertyID + reportTabParam);
        }
        else
        {
            if(this._isWhiteSite)
            {
                return this.WhiteSitePropertyDetailsPage(propertyID, propertyType, reportTab);
            }
        }
        
        return this.NewPropDetailsPath + 'PropertyDetails.aspx?propid=' + propertyID + reportTabParam + this.Flags() + this.PropertyDetailsExtra();
    }

    this.CreatePropertyDetailsLinkForPropertyType = function(property, linkText, hitboxName, reportTab) {
        var propertyID = property.CombineKeyID;

        var properyType = property.PropertyType;

        if (linkText == "" || linkText == null) {
            linkText = property.AddressDisplay;
        }

        if (propertyID == null || propertyID == 'undefined') {
            propertyID = property.PropID;
        }
        if (properyType == null || properyType == 'undefined') {
            properyType = property.PropertyStatus;
        }
        if (property.Supplier.toLowerCase() == "oodle") {

            return this.CreateGatewayLink(property, property.Supplier + hitboxName, linkText);
        }
        return this.CreateLink(this.PropertyDetailsPageForPropertyType(propertyID, properyType, reportTab), linkText, hitboxName);

    }

    this.PropertyDetailsPageURL = function(property) {
        if (property != null || property != 'undefined') {
            if (property.Supplier.toLowerCase() == "oodle") {
                return this.GetGatewayURL(property);
            }
            else {
                return this.PropertyDetailsPageForPropertyType(property.CombineKeyID, property.RecordTypeRaw);
            }
        }
        else {
            return "";
        }
    }
    
    this.GetGatewayURL = function(property)
    {
        var propertyID = property.CombineKeyID;
        
        if (propertyID == null || propertyID == 'undefined')
        {
            propertyID = property.PropID;
        }
        return "/gateway_CO.asp?accnt=" + property.SupplierAccountNumber + "&supplier=" + property.Supplier + "&propertyID=" + propertyID + "&linktosupplier=" + property.LinkToSupplier;
    }

    this.CreateGatewayLink = function(property, hitboxName, displayText) {
        var gatewayLink = "/PropertyDetails/PropertyDetails.aspx?propid=" + property.CombineKeyID;

        if (displayText == "") {
            displayText = property.AddressDisplay;
        }
        var link = "";
        
        if (hitboxName) {
            link = " onclick=\"_hbLink('" + hitboxName + "','right','0,0,30,30');\"";
        }
        return "<a href=\"" + gatewayLink + "\" " + link + " target=\"_blank\">" + displayText + "</a>";

    }
    
    this.PropertyDetailsNewHomePage = function(propertyID)
    {
        if(this._isWhiteSite)
        {
            return this.WhiteSitePropertyDetailsPage(propertyID, 'w');
        }
        else
        {
            if(!this._isMember)
            {
                return this.NewPropDetailsPath + 'PropertyDetails.aspx?propid=' + propertyID;
            }
            else
            {
                return this.MainSitePath + 'Database/propDetails.asp?propid=' + propertyID;
            }
        }
    }

    this.PropertyReportsPage = function(propertyID, propertyType, reportTab)
    {
        if(this.IsNewPropertyDetails(propertyType))
        {
            return this.NewPropDetailsPath + 'PropertyDetails.aspx?propid=' + propertyID + '&reportTab=' + reportTab + this.Flags() + this.PropertyDetailsExtra();
        }
        else
        {
            if(!this._isMember)
            {
                return this.MainSitePath + 'database/freePropDetailsReports.asp?propId=' + propertyID + '&reportTab=' + reportTab;
            }
            else
            {
                return this.MainSitePath + 'database/propDetailsReports.asp?propId=' + propertyID + '&reportTab=' + reportTab;
            }
        }
    }
    
    this.CreatePropertyReportsLink = function(propertyID, propertyType, reportTab, linkText, hitboxName)
    {
        return this.CreateLink(this.PropertyReportsPage(propertyID, propertyType, reportTab), linkText, hitboxName);
    }

    this.UpgradeLanding = function(propertyID)
    {
        var propIDParameter = 'a=b';
        
        if(propertyID != null)
        {
            propIDParameter = 'propid=' + propertyID;
        }
        
        return this.SafeAddUrlParameter(this.MainSitePath + "database/upgradelanding.asp", propIDParameter); 
    }

    this.GuestMemberUpgrade = function(propertyID)
    {
        var propIDParameter = 'a=b';
        
        if(propertyID != null)
        {
            propIDParameter = 'propid=' + propertyID;
        }
        
        return this.SafeAddUrlParameter(this.MainSitePath + "UserProfile/Signup/Upgrade/Account.aspx", propIDParameter);
    }
    
    this.ModifyAccount = function(propertyID)
    {
        var propIDParameter = 'a=b';
        
        if(propertyID != null)
        {
            propIDParameter = 'propid=' + propertyID;
        }
        
        return this.SafeAddUrlParameter(this.MainSitePath + "subscript/noframes/modifyaccount.asp", propIDParameter);
    }

    this.RegistrationPage = function(propertyID)
    {
        var propIDParameter = 'a=b';
        
        
        if(propertyID != null)
        {
            propIDParameter = 'propid=' + propertyID;
        }
        
        if(this._freeTrialLink != null && this._freeTrialLink != '')
        {
            return this.SafeAddUrlParameter(this._freeTrialLink, 'propid=' + propertyID);
        }
        else
        {
            if(this._isWhiteSite)
            {
                return this.WhiteSitePath + 'SignUp.aspx?' + propIDParameter;
            }
            else
            {
                return this.MainSitePath + 'reg1of2.asp?' + propIDParameter;
            }
        }    
    }

    this.UpgradePage = function(propertyID)
    {
        var propIDParameter = 'a=b';
               
        if(propertyID != null)
        {
            propIDParameter = 'propid=' + propertyID;
        }
        
        return this.WhiteSitePath + 'Upgrade.aspx?' + propIDParameter;
    }
    
    this.CreateRegistrationPageLink = function(propertyID, linkText, hitboxName)
    {
        return this.CreateLink(this.RegistrationPage(propertyID), linkText, hitboxName);
    }    

    this.CreateUpgradePageLink = function(propertyID, linkText, hitboxName)
    {
        return this.CreateLink(this.UpgradePage(propertyID), linkText, hitboxName);
    }    
    
    this.CreatePropertyBidLink = function(propertyID, linkText, hitboxName)
    {
        return this.CreateLink(this.PropertyBidPage(propertyID), linkText, hitboxName);
    }
    
    this.CreateMakeOfferLink = function(propertyID, linkText, hitboxName)
    {
        return this.CreateLink(this.PropertyMakeOfferLink(propertyID), linkText, hitboxName);
    }
    
    this.PropertyBidPage = function(propertyID)
    {
        return this.MainSitePath + 'database/propBidConfirm.asp?propId=' + propertyID;
    }
    
    this.PropertyMakeOfferLink = function(propertyID)
    {
        return this.MainSitePath + 'MakeOffer/GoToaspx.aspx?destpage=OfferForm.aspx%3FpropId%3D' + propertyID;
    }
    
    this.SubjectImageLink = function(latitude, longitude)
    {
        var link = this.MainSitePath + 'birdseyeimage/propertyimage.ashx?v=N&z=30&src=mp&tn=true&Latitude=' + latitude + '&Longitude=' + longitude;
        
        return link;
    }
    
    this.ValueTracPropFullDetails = function(address, linkText, hitboxName)
    {
        var link = this.MainSitePath + 'ValueTrac/HomeValues.aspx?address=' + address;
        return this.CreateLink(link, linkText, hitboxName);
    }   
    
    this.CreateMLSDetailsLink = function(propertyID, address, zip, city, state)
    {
        var link = this.MainSitePath + "database/noframes/mlssearch.asp?stype=0";
        
        if (typeof(propertyID) != "undefined" && propertyID != null && propertyID != 0)
        {
            link = this.SafeAddUrlParameter(link, "propID=" + propertyID);
        }
        if (typeof(address) != "undefined" && address != null && address != "")
        {
            link = this.SafeAddUrlParameter(link, "address=" + address);
        }
        
        if (typeof(zip) != "undefined" && zip != null && zip != "")
        {
            link = this.SafeAddUrlParameter(link, "zip=" + zip);
        }
        if (typeof(city) != "undefined" && city != null && city != "")
        {
            link = this.SafeAddUrlParameter(link, "city=" + city);
        }
        if (typeof(state) != "undefined" && state != null && state != "")
        {
            link = this.SafeAddUrlParameter(link, "state=" + state);
        }
        return link;
    }
    
    this.ValueTracLinkForeclosuresTab = function(address, tab)
    {
        var link = this.MainSitePath + 'ValueTrac/HomeValues.aspx?tab=' + tab + '&address=' + address;
        return link;
    }
 
}

//------------------------
// Seo Navigation Engine
//------------------------

SEONavigationEngine = function(propertyDetailsSEOPattern, propertyDetailsSEOPatternWithTab, propertyDetailsDefaultPattern,
    valueTracSEOPatternCity, valueTracSEOPatternCounty, valueTracSEOPatternFull, valueTracSEOPatternState, valueTracSEOPatternZip, valueTracSEOPatternDefault,
    mapSearchSEOPatternCity, mapSearchSEOPatternCounty, mapSearchSEOPatternFull, mapSearchSEOPatternState, mapSearchSEOPatternZip, mapSearchSEOPatternDefault)
{
    //-------- Global functions and variables
    
    // Function that will get pattern and replace tags with real values
    var GetUrlInternal = function(pattern, tagsToReplace, values)
    {
        var url = pattern.toLowerCase();
        
        if (typeof(pattern) != "undefined" && pattern != ""
            && typeof(tagsToReplace) != "undefined" && tagsToReplace.length > 0
            && typeof(values) != "undefined" && values.length > 0
            && tagsToReplace.length == values.length)
        {
            for (var i = 0; i < tagsToReplace.length; i++)
            {
                url = url.replace(tagsToReplace[i].toLowerCase(), values[i].toString().toLowerCase());
            }
        }
        
        return (url == pattern) ? "" : url;
    }

    this.CreateLink = function(url, linkText, hitboxName, openInNewWindow, createOnClickEvent)
    {
        if (typeof(openInNewWindow) == "undefined")
        {
            openInNewWindow = false;
        }
        
        if (typeof(createOnClickEvent) == "undefined")
        {
            createOnClickEvent = false;
        }
        
        var link = "<a onclick=\"_hbLink('" + hitboxName + "','right','0,0,30,30');";
        
        if (openInNewWindow)
        {
            link += "window.open('" + url + "', '_blank');";
        }        
        
        if (createOnClickEvent)
        {
            link += "window.location = '" + url + "';";
        }
        
        link += "\" href=\"" + url + "\">" + linkText + "</a>";
        
        return link;
    }
    
    this.SafeAddUrlParameter = function(url, parameters)
    {
        if (parameters != null && parameters != "" && parameters.length > 0)
        {
            if (url.indexOf('?') > 0)
            {
                url += "&" + parameters;
            }
            else
            {
                url += "?" + parameters;
            }
        }
        
        return url;
    }
    var SafeAddUrlParameterInternal = this.SafeAddUrlParameter;
    
    var FixStreetAddress = function(addressLine)
    {
        return addressLine.replace(/#/g, "").replace(/&/g, "");
    }
    
    //-------- Pages that can use seo friendly urls
    
    // PropertyDetails Link generation
    var PropertyDetailsPageInit = function(propertyDetailsSEOPattern, propertyDetailsSEOPatternWithTab, propertyDetailsDefaultPattern)
    {
        var _seoPattern = propertyDetailsSEOPattern;
        var _defaultPattern = propertyDetailsDefaultPattern;
        var _seoPatternWithTab = propertyDetailsSEOPatternWithTab;
        
        var _backParameter = "";
        var _propertyIDsParameter = "";
        
        var GetSeoTagsToReplace = function()
        {
            return new Array("[street]", "[city]", "[state]", "[zip]", "[propertyID]");
        }
        
        var GetDefaultTagsToReplace = function()
        {
            return new Array("[propertyID]");
        }
        
        
    
        this.GetUrl = function(propertyID, street, city, stateCode, zip, tabType)
        {   
            var url = "";
            
            if (propertyID > 0)
            {
                if (typeof(street) != "undefined" && typeof(city) != "undefined" && typeof(stateCode) != "undefined" && typeof(zip) != "undefined"
                    && street != "" && city != "" && stateCode != "" && zip != "" && street != null && city != null && stateCode != null && zip != null)
                {
                    var tags = GetSeoTagsToReplace();
                    var values = new Array(FixStreetAddress(street), city, stateCode, zip, propertyID);
                    var pattern = _seoPattern;
                    
                    if (typeof(tabType) != "undefined" && tabType != "")
                    {
                        tags[tags.length] = "[tabtype]";
                        values[values.length] = tabType;
                        pattern = _seoPatternWithTab;
                    }
                    
                    url = GetUrlInternal(pattern, tags, values);
                }
                
                if (url == "")
                {
                    url = GetUrlInternal(_defaultPattern, GetDefaultTagsToReplace(), new Array(propertyID.toString()));
                }
                
                if (_backParameter != null && _backParameter != "")
                {
                    url = SafeAddUrlParameterInternal(url, "back=" + _backParameter);
                }
                
                if (_propertyIDsParameter != null && _propertyIDsParameter != "")
                {
                    url = SafeAddUrlParameterInternal(url, "propids=" + _propertyIDsParameter);
                }
                
            }
            
            return url;
        }
        
        this.UpdateAdditionalParameters = function(backParameter, propertyIDsParameter)
        {
            _backParameter = backParameter;
            _propertyIDsParameter = propertyIDsParameter;
        }
    }
    
    this.PropertyDetailsPage = new PropertyDetailsPageInit(propertyDetailsSEOPattern, propertyDetailsSEOPatternWithTab, propertyDetailsDefaultPattern);
    
    var ValueTracPageInit = function(valueTracSEOPatternCity, valueTracSEOPatternCounty, valueTracSEOPatternFull, valueTracSEOPatternState, valueTracSEOPatternZip, valueTracSEOPatternDefault)
    {
        var _seoPatternCity = valueTracSEOPatternCity;
        var _seoPatternCounty = valueTracSEOPatternCounty;
        var _seoPatternFull = valueTracSEOPatternFull;
        var _seoPatternState = valueTracSEOPatternState;
        var _seoPatternZip = valueTracSEOPatternZip;
        var _seoPatternDefault = valueTracSEOPatternDefault;
        
        var GetSeoTagsToReplace = function(type)
        {
            switch (type)
            {
                case 1: //full address
                    return new Array("[state]", "[city]", "[address]");
                    
                case 2: // Zip
                    return new Array("[state]", "[zip]");
                    
                case 3: // city
                    return new Array("[state]", "[city]");
                    
                case 4: // county
                    return new Array("[state]", "[county]");      
                    
                case 5: // state
                    return new Array("[state]");              
                
            }
        }
        
        this.GetUrl = function(stateCode, countyName, city, zip, addressLine)
        {
            var url = "";
            var values = null;
            var tags = null;
            var pattern = null;
            
            if (typeof(addressLine) != "undefined" && addressLine != ""
                && typeof(city) != "undefined" && city != ""
                && typeof(stateCode) != "undefined" && stateCode != ""
                && addressLine != null && city != null && stateCode != null)
            {
                pattern = _seoPatternFull;
                tags = GetSeoTagsToReplace(1);
                values = new Array(stateCode, city, FixStreetAddress(addressLine));
            }
            else if (typeof(zip) != "undefined" && zip != ""
                && typeof(stateCode) != "undefined" && stateCode != ""
                && zip != null && stateCode != null)
            {
                pattern = _seoPatternZip;
                tags = GetSeoTagsToReplace(2);
                values = new Array(stateCode, zip);
            }
            else if (typeof(city) != "undefined" && city != ""
                && typeof(stateCode) != "undefined" && stateCode != ""
                && city != null && stateCode != null)
            {
                pattern = _seoPatternCity;
                tags = GetSeoTagsToReplace(3);
                values = new Array(stateCode, city);
            }
            else if (typeof(countyName) != "undefined" && countyName != ""
                && typeof(stateCode) != "undefined" && stateCode != ""
                && countyName != null && stateCode != null)
            {
                if (countyName.indexOf("county") == -1)
                {
                    countyName = countyName.Trim() + "-county";
                }
                
                pattern = _seoPatternCounty;
                tags = GetSeoTagsToReplace(4);
                values = new Array(stateCode, countyName);
            }
            else if (typeof(stateCode) != "undefined" && stateCode != "" && stateCode != null)
            {
                pattern = _seoPatternState;
                tags = GetSeoTagsToReplace(5);
                values = new Array(stateCode);
            }
            
            
            if (values != null && tags != null && pattern != null)
            {
                url = GetUrlInternal(pattern, tags, values);
            }
            
            if (url == "")
            {
                url = _seoPatternDefault;
            }
            
            return url;
        }
        
    }
    
    this.ValueTracPage = new ValueTracPageInit(valueTracSEOPatternCity, valueTracSEOPatternCounty, valueTracSEOPatternFull, valueTracSEOPatternState, valueTracSEOPatternZip, valueTracSEOPatternDefault);
    
    var MapSearchPageInit = function(mapSearchSEOPatternCity, mapSearchSEOPatternCounty, mapSearchSEOPatternFull, mapSearchSEOPatternState, mapSearchSEOPatternZip, mapSearchSEOPatternDefault)
    {
        var _mapSearchSEOPatternCity = mapSearchSEOPatternCity;
        var _mapSearchSEOPatternCounty = mapSearchSEOPatternCounty;
        var _mapSearchSEOPatternFull = mapSearchSEOPatternFull;
        var _mapSearchSEOPatternState = mapSearchSEOPatternState;
        var _mapSearchSEOPatternZip = mapSearchSEOPatternZip;
        var _mapSearchSEOPatternDefault = mapSearchSEOPatternDefault;
        
        var GetSeoTagsToReplace = function(type)
        {
            switch (type)
            {
                case 1: // full address
                    return new Array("[state]", "[city]", "[address]", "[propertytype]");
                
                case 2: // zip
                    return new Array("[state]", "[zip]", "[propertytype]");
                
                case 3: // city
                    return new Array("[state]", "[city]", "[propertytype]");
                    
                case 4: // county
                    return new Array("[state]", "[county]", "[propertytype]");
                    
                case 5: // state
                    return new Array("[state]", "[propertytype]");
            }
        }
        
        var FixPropertyType = function(propertyType)
        {
            if (typeof(propertyType) != "undefined" && propertyType != "")
            {
                return "-" + propertyType;
            }
            else
            {
                return "";
            }
        }
        
        this.GetUrl = function(stateCode, countyName, city, zip, addressLine, stateName, propertyType)
        {
            var url = "";
            var values = null;
            var tags = null;
            var pattern = null;
            
            propertyType = FixPropertyType(propertyType);
            
            if (typeof(addressLine) != "undefined" && addressLine != ""
                && typeof(city) != "undefined" && city != ""
                && typeof(stateCode) != "undefined" && stateCode != ""
                && addressLine != null && city != null && stateCode != null)
            {
                pattern = _mapSearchSEOPatternFull;
                tags = GetSeoTagsToReplace(1);
                values = new Array(stateCode, city, FixStreetAddress(addressLine), propertyType);
            }
            else if (typeof(zip) != "undefined" && zip != ""
                && typeof(stateCode) != "" && stateCode != ""
                && zip != null && stateCode != null)
            {
                pattern = _mapSearchSEOPatternZip;
                tags = GetSeoTagsToReplace(2);
                values = new Array(stateCode, zip, propertyType);
            }
            else if (typeof(city) != "undefined" && city != ""
                && typeof(stateCode) != "undefined" && stateCode != ""
                && city != null && stateCode != null)
            {
                pattern = _mapSearchSEOPatternCity;
                tags = GetSeoTagsToReplace(3);
                values = new Array(stateCode, city, propertyType);
            }
            else if (typeof(countyName) != "undefined" && countyName != ""
                && typeof(stateCode) != "undefined" && stateCode != ""
                && countyName != null && stateCode != null)
            {
                if (countyName.indexOf("county") == -1)
                {
                    countyName = countyName + "-county";
                }
                
                pattern = _mapSearchSEOPatternCounty;
                tags = GetSeoTagsToReplace(4);
                values = new Array(stateCode, countyName, propertyType);
            }
            else if (typeof(stateName) != "undefined" && stateName != "" && stateName != null)
            {
                pattern = _mapSearchSEOPatternState;
                tags = GetSeoTagsToReplace(5);
                values = new Array(stateName, propertyType);
            }
            
            if (values != null && tags != null && pattern != null)
            {
                url = GetUrlInternal(pattern, tags, values);
            }
            
            if (url == "")
            {
                url = _mapSearchSEOPatternDefault;
            }
        }
    }
    
    this.MapSearchPage = new MapSearchPageInit();
}
//END RealtyTrac.Common.Web.Scripts.MapSearch.navigation.js
//START RealtyTrac.Common.Web.Scripts.MapSearch.MapPopUpClass.js
// Global Constants
var GEO_INITIAL_ZIP_ZOOM_LEVEL = 13;
var GEO_INITIAL_CITY_ZOOM_LEVEL = 12;
var GEO_INITIAL_COUNTY_ZOOM_LEVEL = 10;
var GEO_INITIAL_STATE_ZOOM_LEVEL = 7;
var GEO_INITIAL_NATIONAL_ZOOM_LEVEL = 3;

var GEO_SEARCH_ZIP_ZOOM_LEVEL = 10;
var GEO_SEARCH_CITY_ZOOM_LEVEL = 9;
var GEO_SEARCH_COUNTY_ZOOM_LEVEL = 6;
var GEO_SEARCH_STATE_ZOOM_LEVEL = 4;
var GEO_SEARCH_NATIONAL_ZOOM_LEVEL = 3;

var GEO_AREA_TYPE_NATIONAL = 5;
var GEO_AREA_TYPE_STATE = 4;
var GEO_AREA_TYPE_COUNTY = 3;
var GEO_AREA_TYPE_CITY = 2;
var GEO_AREA_TYPE_ZIP = 1;
var GEO_AREA_TYPE_POI = 0;

//Declaring the Class PopUp on the Map
var STRING_EMPTY = '';

var PROPERTY_TYPE_AUCTION = 'A';
var PROPERTY_TYPE_BANK_OWNED = 'B';
var PROPERTY_TYPE_FSBO = 'F';
var PROPERTY_TYPE_NEW = 'N';
var PROPERTY_TYPE_PREFORECLOSURE = 'P';
var PROPERTY_TYPE_RESALE = 'R';
var PROPERTY_TYPE_GOVERMENT = 'G';
var PROPERTY_TYPE_FSBO_O = 'O';
var PROPERTY_TYPE_RESALE_L = 'L';
var PROPERTY_TYPE_ONLINE_AUCTION = 'E';
var PRICE_ZERO = '$0.00';
var MAIN_DIVISION_POP_UP_CONTAINER_ID = 'pinDiv';
var ELEMENT_DIVISION = 'div';
var STRING_TEXT_UNDEFINED = 'undefined';
var ELEMENT_OPEN_TAG_LI = '<li>';
var ELEMENT_CLOSE_TAG_LI = '</li>';
var DIV_PROPERTYDETAILS_POUP_CONTAINER = 'pinPropertyDetails';
var DEFAULT_CURRENT_POPUP_ID = 'DefaultPopUp';
var PARENT_DIV_POPUP_CONTAINER_DEFAULT = 'pinDiv';

/*
Styles to Apply
*/
var STYLE_NONE = "none";
var STYLE_BLOCK = "block";
var STYLE_HIDDEN = "hidden";
var STYLE_VISIBLE = "visible";
var STYLE_POSITION_ABSOLUTE = 'absolute';

/*
Layers Name Declaration
*/
var LAYER_NAME_PROPERTY_TYPE_POPUP = 'PropertyTypePopUpLayer';
var LAYER_NAME_GROUPED_POPUP = 'GroupedPopUpLayer';
var LAYER_NAME_SELECTED_GROUPED_PIN = 'SelectedGroupedPin';
var LAYER_NAME_POLYGONS_POPUP = 'PolygonPopUpLayer';
var LAYER_NAME_PINS = 'PinsLayer';
var LAYER_NAME_PINS_MAIN_PROPERTY = 'MainPropertyPinLayer';
var LAYER_NAME_AREA_POPUP = 'AreaPopupLayer';

/*
Area types
*/
var AREA_TYPE_ZIP = 'ZIP';
var AREA_TYPE_CITY = 'City';
var AREA_TYPE_COUNTY = 'County';
var AREA_TYPE_STATE = 'State';
var AREA_TYPE_NATION = 'Nation';

var AREA_TYPE_NAME_US = 'U.S.';

var AREA_TYPE_ZIP_CODE_1 = '1';
var AREA_TYPE_CITY_CODE_2 = '2';
var AREA_TYPE_COUNTY_CODE_3 = '3';
var AREA_TYPE_STATE_CODE_4 = '4';
var AREA_TYPE_NATIONAL_CODE_5 = '5';

var ADDRESS_SEARCH_NON_MEMBER_ZOOM = 15;
var ADDRESS_SEARCH_MEMBER_ZOOM = 16;

var ZOOM_LEVEL_STATE_LIMIT_6 = 6;
var MAX_ZOOM_LEVEL_NON_MEMBERS_5 = 5;

var EXISTING_PROPERTY_TYPES;

var CRITERIA_TYPE_ZIP = "zip";
var CRITERIA_TYPE_ADDRESS = 'address';

//----- temp variables to be moved
var PIN_TYPE_PROPERTY_PIN = 'propPin';
var PINTYPE_MAIN_PROP_VAL_TRAC = 'VTMPPin'; //Value trac main property pin
var COMP_SALES_PIN = 'compSales';
var INTERACTIVE_MAP = 'InterMap';
var gSubjectProperty = false;
var gSubjectPropertyID = null;
var gSubjectPropertyLat = null;
var gSubjectPropertyLon = null;
var gSubjectPropertyLat = null;
var gSubjPropDecodedLatLong = new Object;
gSubjPropDecodedLatLong._reserved = '';
var BALOON_POPUP_LEFT_DEFAULT = 313;
var BALOON_POPUP_LEFT_LARGE_MAP = 315;
var BALOON_POPUP_LEFT = BALOON_POPUP_LEFT_DEFAULT;
var DIV_NAME_MAP_CONTAINER_MAP_ALL = 'mapAll';

//-----------------------------------

//----------------------------  Map Class --------------------------------------------------

function MapSearch(mapName) {
    var MSVE_NAV_ACTION_OBLIQUE_MAP_VIEW = 'MSVE_navAction_ObliqueMapView';
    var DEFAULT_BIRDEYE_BTN_WIDTH = '80';
    var DEFAULT_MAP_NAME = 'myMap';
    var DIV_ID_CONTAINER_MAP = 'myMapContainer';
    var DEFAULT_MESSAGE_MAP_NOT_CREATED = 'Can\'t create map. Most likely your browser is not compatible with Microsoft Virtual Earth or it was blocked by your firewall.';
    var OVERLAY_DIV_CONTAINER_ID_DEFAULT = 'map_Overlay_Container';
    var OVERLAY_ID_DEFAULT = 'map_Overlay';
    var OVERLAY_AD_DIV_CONTAINER_ID_DEFAULT = 'overlayMapAdContainerDiv';


    this.MapSearchName = (mapName != STRING_EMPTY) ? mapName : DEFAULT_MAP_NAME;
    this.isMapCreated = false;
    this.gMapSearchObj;
    this.MapMenu = new MapSearchMenu();
    this.PinsOnMap;
    this.isMember;
    this.currentPinsObj;
    this.isMapVisible = false;
    this.prevMapStyle;
    this.mapCenterFromSearch = null;
    this.mapZoomLevelfSearch = 13;
    this.isCreatingPinsOnMap = false;
    this.prevLatLong = null;
    this.prevZoom = null;
    this.isValueTrac = false;
    this.pathToImgFolder = '/mapsearch/images/';
    this.divMapContainer = DIV_NAME_MAP_CONTAINER_MAP_ALL;
    this.overlayDivID = OVERLAY_ID_DEFAULT;
    this.overlayContainerDivID = OVERLAY_DIV_CONTAINER_ID_DEFAULT;
    this.divExtPopUpsContainer = PARENT_DIV_POPUP_CONTAINER_DEFAULT;
    this.overlayAdContainerDivID = OVERLAY_AD_DIV_CONTAINER_ID_DEFAULT;

    //---------------------- map create object  ------------------------

    MapSearch.prototype.CreateMap = function() {
        if (isFunctDef('VEMap')) {
            this.gMapSearchObj = new VEMap(this.MapSearchName);
            this.gMapSearchObj.LoadMap(new VELatLong(0, 0), this.mapZoomLevelfSearch);
        }
    }

    MapSearch.prototype.SetMapContainerDivName = function(divName) {
        if (divName) {
            this.divMapContainer = divName;

            if (this.PinsOnMap != undefined && this.PinsOnMap != null) {
                this.PinsOnMap.divMapContainer = dicName;
                if (this.PinsOnMap.PopUpClass != undefined && this.PinsOnMap.PopUpClass != null) {
                    this.PinsOnMap.PopUpClass.divMapContainer = dicName;
                }
            }
        }
    }

    MapSearch.prototype.CreateMapSearchMap = function() {
        try {
            this.gMapSearchObj = null;
            var retries = 0;

            while (!this.gMapSearchObj) {
                try {
                    this.ShowMap();
                    this.isMapVisible = true;
                    this.CreateMap();

                    if (this.gMapSearchObj) {
                        this.SetBirdEyeBtnWidth(DEFAULT_BIRDEYE_BTN_WIDTH);
                        this.isMapCreated = true;
                        this.prevMapStyle = this.gMapSearchObj.GetMapStyle();
                        gMap = this.gMapSearchObj;

                        //Create the instance of Pins an set the start values
                        this.PinsOnMap = new PinsOnMap();
                        this.isMember = gMember;
                        this.PinsOnMap.pinsPos = gPinsPos;
                        this.PinsOnMap.SetIsBirdEyeview(this.IsBirdEyeView());
                        this.PinsOnMap.SetIsMember(this.isMember);
                        this.PinsOnMap.SetInstanceCurMap(this.gMapSearchObj);
                        this.PinsOnMap.RemoveUnderlineFromAnchors = this.RemoveUnderlineFromAnchors;
                        this.PinsOnMap.PopUpClass.RemoveUnderlineFromAnchors = this.RemoveUnderlineFromAnchors;
                        this.PinsOnMap.isValueTrac = this.isValueTrac;
                        this.PinsOnMap.pathToImgFolder = this.pathToImgFolder;
                        this.PinsOnMap.PopUpClass.pathToImgFolder = this.pathToImgFolder;
                        this.PinsOnMap.PopUpClass.isValueTrac = this.isValueTrac;
                        this.PinsOnMap.divMapContainer = this.PinsOnMap.PopUpClass.divMapContainer = this.divMapContainer;
                        //Success, get out of the loop
                        break;
                    }
                }
                catch (error) {
                    //we don't want to do anything
                    this.gMapSearchObj = null;
                    this.isMapCreated = false;
                }

                //Advance the counter
                retries++;

                //Check if we have reached the threshold
                if (retries > RETRY_FAILURE_COUNT) {
                    // too many retries, exits the loop
                    //this.gMapSearchObj = null;
                    this.isMapCreated = false;
                    break;
                }
            }

            if (this.gMapSearchObj) {
                //gCreateMap = false;
                //gMapInitialized = true;
                this.isMapCreated = true;

                return true;
            }
            else {
                // can't create map for any reason	                
                this.MapMenu.HideMenu();
                this.SetNoMapCreatedMessage(''); //empty message set the default existing Message;

                this.gMapSearchObj = null;
                this.isMapCreated = false;
                return false;
            }

        }
        catch (ex) {
            LogErrorMessage("CreateMap: ", ex);
        }
    }

    MapSearch.prototype.SetNoMapCreatedMessage = function(message) {
        try {
            var height = this.GetMapContainerHeight();
            var width = this.GetMapContainerWidth();
            var messageToShow = (message == STRING_EMPTY) ? DEFAULT_MESSAGE_MAP_NOT_CREATED : message;
            var parentContainer = document.getElementById(this.divMapContainer);

            if (this.MapMenu) {
                this.MapMenu.HideMenuBtn();
            }

            if (parentContainer) {
                var divPopupContainer = document.createElement(ELEMENT_DIVISION);
                divPopupContainer.innerHTML = messageToShow;
                divPopupContainer.style.backgroundColor = 'white';
                divPopupContainer.style.verticalAlign = 'middle';
                divPopupContainer.style.textAlign = 'center';
                divPopupContainer.style.position = 'absolute';
                divPopupContainer.style.width = width + 'px';
                divPopupContainer.style.height = height + 'px';
                divPopupContainer.style.border = '3px solid #dcdcdc';
                divPopupContainer.style.paddingTop = eval(height) / 2 + 'px';
                parentContainer.appendChild(divPopupContainer);
            }
            else {
                alert(messageToShow);
            }
        }
        catch (ex) {
            LogErrorMessage("SetNoMapCreatedPopUp: ", ex);
        }
    }

    //---------------------- Handling MiniMap ----------------------

    MapSearch.prototype.ShowMiniMap = function() {
        try {
            var closeBtn = document.getElementById('miniMapClose');

            if (closeBtn) {
                closeBtn.style.display = STYLE_BLOCK;
            }
            this.gMapSearchObj.ShowMiniMap(MINIMAP_CURRENT_LOCATION, 25);
            document.getElementById('MSVE_minimap_resize').style.display = STYLE_NONE;
            document.getElementById('miniMapOpen').style.display = STYLE_NONE;
        }
        catch (ex) {
            LogErrorMessage("MapSearch.prototype.ShowMiniMap: ", ex);
        }
    }

    MapSearch.prototype.HideMiniMap = function() {
        try {
            var closeBtn = document.getElementById('miniMapClose');
            var btnOpen = document.getElementById('miniMapOpen');
            if (closeBtn) {
                closeBtn.style.display = STYLE_NONE;
            }
            if (btnOpen) {
                btnOpen.style.display = STYLE_BLOCK;
            }

            this.gMapSearchObj.HideMiniMap();
        }
        catch (ex) {
            LogErrorMessage("MapSearch.prototype.HideMiniMap: ", ex);
        }
    }

    MapSearch.prototype.UpdateMiniMap = function() {
        try {
            var minBtnClose = document.getElementById('miniMapClose');
            if (minBtnClose && minBtnClose.style.display == STYLE_BLOCK) {
                this.gMapSearchObj.HideMiniMap();
                this.gMapSearchObj.ShowMiniMap(MINIMAP_CURRENT_LOCATION, 25);
            }
        }
        catch (ex) {
            LogErrorMessage("MapSearch.prototype.UpdateMiniMap: ", ex);
        }
    }

    //---------------------- map save current Search ---------------

    MapSearch.prototype.StoreMapSettingsInSearchRequest = function() {
        try {
            //external function on searchresult file 
            var searchRequestObject = GetSearchRequest();

            if (searchRequestObject) {
                searchRequestObject.ZoomLevel = this.gMapSearchObj.GetZoomLevel();
                var center = this.gMapSearchObj.GetCenter();
                searchRequestObject.MapPosition = center.Latitude + ',' + center.Longitude;
                searchRequestObject.IsMapVisible = this.isMapVisible;
                searchRequestObject.CheckedTypes = this.MapMenu.GetCheckedPropertyTypes();

                //external function on searchresult file                    
                SetSearchRequest(searchRequestObject);
            }

        }
        catch (ex) {
            LogErrorMessage("MapSearch.prototype.StoreMapSettingsInSearchRequest: ", ex, true);
        }
    }

    //---------------------- map bird eye  ------------------------

    MapSearch.prototype.IsBirdEyeView = function() {
        try {
            if (this.gMapSearchObj) {
                var mapViewMode = this.gMapSearchObj.GetMapStyle();

                return mapViewMode == VEMapStyle.Birdseye || mapViewMode == VEMapStyle.BirdseyeHybrid;
            }

            return false;
        }
        catch (ex) {
            LogErrorMessage("MapSearch.prototype.IsBirdEyeView: ", ex);
        }
    }

    MapSearch.prototype.GetBirdEyeBtnWidth = function() {
        try {
            var btnBirdEye = document.getElementById(MSVE_NAV_ACTION_OBLIQUE_MAP_VIEW);
            var btnWidth;
            if (btnBirdEye) {
                btnWidth = btnBirdEye.width;
            }
            return btnWidth;
        }
        catch (ex) {
            LogErrorMessage("GetBirdEyeBtnWidth: ", ex);
        }
    }

    MapSearch.prototype.SetBirdEyeBtnWidth = function(width) {
        try {
            if (width == STRING_EMPTY) {
                var btnBirdEye = document.getElementById(MSVE_NAV_ACTION_OBLIQUE_MAP_VIEW);
                if (btnBirdEye) {
                    btnBirdEye.width = width + 'px';
                }
            }
        }
        catch (ex) {
            LogErrorMessage("SetBirdEyeBtnWidth: ", ex);
        }
    }

    //---------------------- map centering ------------------------

    MapSearch.prototype.GetMapCenterPixels = function() {
        try {
            if (this.gMapSearchObj) {
                var mapPixCenter;
                mapPixCenter = this.gMapSearchObj.LatLongToPixel(this.gMapSearchObj.GetCenter(), this.gMapSearchObj.GetZoomLevel());
                return mapPixCenter;
            }
        }
        catch (ex) {
            LogErrorMessage("MapSearch.prototype.GetMapCenterPixels: ", ex);
        }
    }

    MapSearch.prototype.SetMapCenterPixels = function(coordenateX, coordenateY) {
        try {
            if (this.gMapSearchObj) {
                var pixel = new VEPixel(coordenateX, coordenateY);
                this.gMapSearchObj.SetCenter(this.gMapSearchObj.PixelToLatLong(pixel));
            }
        }
        catch (ex) {
            LogErrorMessage("MapSearch.prototype.SetMapCenterPixels: ", ex);
        }
    }

    MapSearch.prototype.SetMapCenter = function() {
        try {
            if (this.gMapSearchObj && this.mapCenterFromSearch != null) {
                this.gMapSearchObj.SetCenter(this.mapCenterFromSearch);
            }
        }
        catch (ex) {
            LogErrorMessage("MapSearch.prototype.SetMapCenter: ", ex);
        }
    }

    //----------------------- map on the page --------------------

    MapSearch.prototype.ScrollPageToMap = function() {
        try {
            var map = document.getElementById(this.divMapContainer);
            if (map) {
                var pos = getElementVertPosOnPage(map);
                window.scrollTo(0, pos);
            }
        }
        catch (ex) {
            LogErrorMessage("MapSearch.prototype.ScrollPageToMap: ", ex);
        }
    }

    //---------------------- map size ------------------------

    MapSearch.prototype.GetMapWidth = function() {
        try {
            if (this.gMapSearchObj) {
                var centerPixels = this.GetMapCenterPixels();
                var width;

                if (centerPixels) {
                    width = centerPixels.x * 2;
                }

                return width;
            }
        }
        catch (ex) {
            LogErrorMessage("GetMapWidth: ", ex);
        }
    }

    MapSearch.prototype.SetMapWidth = function(width) {
        try {
            if (this.gMapSearchObj && width) {
                var mapContainer = document.getElementById(this.MapSearchName);
                if (mapContainer) {
                    mapContainer.style.width = width + 'px';
                    this.gMapSearchObj.Resize();
                }
            }

        }
        catch (ex) {
            LogErrorMessage("SetMapWidth: ", ex);
        }
    }

    MapSearch.prototype.GetMapHeight = function() {
        try {
            if (this.gMapSearchObj) {
                var centerPixels = this.GetMapCenterPixels();
                var height;

                if (centerPixels) {
                    height = centerPixels.y * 2;
                }

                return height;
            }
        }
        catch (ex) {
            LogErrorMessage("GetMapHeight: ", ex);
        }
    }

    MapSearch.prototype.SetMapHeight = function(height) {
        try {
            if (this.gMapSearchObj && height) {
                var mapContainer = document.getElementById(this.MapSearchName);
                if (mapContainer) {
                    mapContainer.style.height = height + 'px';
                    this.gMapSearchObj.Resize();
                }
            }

        }
        catch (ex) {
            LogErrorMessage("SetMapHeight: ", ex);
        }
    }

    MapSearch.prototype.SetMapFullSize = function() {
        try {
            var height = this.GetMapContainerHeight();
            var width = this.GetMapContainerWidth();
            if (this.gMapSearchObj && height && width) {
                this.SetMapHeight(height);
                this.SetMapWidth(width);
            }
        }
        catch (ex) {
            LogErrorMessage("SetMapFullSize: ", ex);
        }
    }

    MapSearch.prototype.ResizeMapOnMenuShowHide = function() {
        try {
            if (this.gMapSearchObj) {
                var divMenuContainer = document.getElementById('SR_mapItems');
                var offSet = 10;
                if (divMenuContainer && divMenuContainer.style.display == STYLE_BLOCK) {
                    this.SetMapWidth(this.GetMapContainerWidth() - divMenuContainer.offsetWidth - offSet);
                }
                if (divMenuContainer && divMenuContainer.style.display == STYLE_NONE) {
                    this.SetMapWidth(this.GetMapContainerWidth() + divMenuContainer.offsetWidth - offSet);
                }
            }
        }
        catch (ex) {
            LogErrorMessage("ResizeMapOnMenuShoHide: ", ex);
        }
    }

    MapSearch.prototype.GetMapContainerWidth = function() {
        try {
            var divContainer = document.getElementById(this.divMapContainer);
            var width;
            if (divContainer) {
                width = divContainer.offsetWidth;
            }

            return width;
        }
        catch (ex) {
            LogErrorMessage("GetMapContainerWidth: ", ex);
        }
    }

    MapSearch.prototype.GetMapContainerHeight = function() {
        try {
            var divContainer = document.getElementById(this.divMapContainer);
            var height;
            if (divContainer) {
                height = divContainer.offsetHeight;
            }

            return height;
        }
        catch (ex) {
            LogErrorMessage("GetMapContainerHeight: ", ex);
        }
    }


    //---------------------- map show and hide  ------------------------

    MapSearch.prototype.ToggleGroupedPopup = function(display) {
        if (typeof (display) == "undefined" || display == null) {
            display = false;
        }

        var groupedPopUp = document.getElementById('divGrpPopup');

        if (groupedPopUp != null) {
            groupedPopUp.style.display = (display) ? "block" : "none";
        }
    }

    MapSearch.prototype.HideMap = function() {
        try {
            this.HideOverLay();
            this.ToggleGroupedPopup(false);
            HideDivByID(this.divMapContainer);
            gIsMapVisible = false;
            this.isMapVisible = false;
        }
        catch (ex) {
            LogErrorMessage("HideMap: ", ex);
        }
    }

    MapSearch.prototype.ShowMap = function() {
        try {
            ShowDivByID(this.divMapContainer);
            this.ToggleGroupedPopup(true);
            gIsMapVisible = true;
            this.isMapVisible = true;
        }
        catch (ex) {
            LogErrorMessage("ShowMap: ", ex);
        }
    }

    MapSearch.prototype.HideOverLay = function() {
        try {
            if (typeof (ClearAdInContainer) === 'function') {
                ClearAdInContainer(this.overlayAdContainerDivID);
            }

            HideDivByID(this.overlayContainerDivID);
        }
        catch (ex) {
            LogErrorMessage("MapSearch.prototype.HideOverLay: ", ex);
        }
    }

    MapSearch.prototype.ShowOverLay = function() {
        try {
            if (!this.isMember && typeof (CreateAdInContainer) === 'function' && !IsDivVisbleByID(this.overlayContainerDivID)) {
                CreateAdInContainer(this.overlayAdContainerDivID);
            }

            ShowDivByID(this.overlayContainerDivID);
            var resizeOverlay = document.getElementById(this.overlayDivID);
            if (resizeOverlay) {
                resizeOverlay.style.width = this.GetMapWidth() + 'px';
                resizeOverlay.style.height = this.GetMapHeight() + 'px';
            }
        }
        catch (ex) {
            LogErrorMessage("MapSearch.prototype.ShowOverLay: ", ex);
        }
    }

    //---------------------- map Zoom handling  ------------------------

    MapSearch.prototype.GetMapZoomLevel = function() {
        try {
            if (this.gMapSearchObj) {
                return this.gMapSearchObj.GetZoomLevel();
            }
        }
        catch (ex) {
            LogErrorMessage("GetMapZoomLevel: ", ex);
        }
    }

    MapSearch.prototype.RestoreZoomAndPosition = function(searchRequest) {
        try {
            var isRestored = false;
            var mapPositionCookie;
            var zoom;

            if (searchRequest) {
                try {
                    zoom = searchRequest.ZoomLevel;

                    if (zoom != null) {
                        if (parseInt(zoom) > 0) {
                            this.mapZoomLevelfSearch = parseInt(zoom);
                        }
                    }

                    mapPositionCookie = searchRequest.MapPosition;
                    if (mapPositionCookie != null) {
                        mapPosition = mapPositionCookie.split(",");
                        gMapCenter = new VELatLong(mapPosition[0], mapPosition[1]);
                        this.mapCenterFromSearch = new VELatLong(mapPosition[0], mapPosition[1]);

                        this.AttachEvents();
                        this.gMapSearchObj.SetCenterAndZoom(this.mapCenterFromSearch, this.mapZoomLevelfSearch);
                        this.HideOverLay();

                        isRestored = true;
                    }

                    return isRestored;
                }
                catch (err) {
                    return false;
                }
            }
        }
        catch (ex) {

        }
    }

    MapSearch.prototype.SetCenterAndZoom = function(lat, lon) {
        try {
            if (lat && lon) {
                var mapCenter = new VELatLong(lat, lon);
                var zoomLevel = ADDRESS_SEARCH_NON_MEMBER_ZOOM;

                if (!this.isMember || gIsGuestMember || gIsCancelledMember) {
                    zoomLevel = ADDRESS_SEARCH_NON_MEMBER_ZOOM;
                }
                else {
                    zoomLevel = ADDRESS_SEARCH_MEMBER_ZOOM;
                }
                this.gMapSearchObj.SetCenterAndZoom(mapCenter, zoomLevel);
            }
        }
        catch (ex) {
            LogErrorMessage("MapSearch.prototype.SetLatLongAndZoom: ", ex);
        }
    }

    //---------------------- map General Methods  ------------------------

    MapSearch.prototype.GetMapCoordinates = function() {
        try {
            var latLonCoord = null;
            if (this.IsBirdEyeView()) {
                var bEScene = this.gMapSearchObj.GetBirdseyeScene();
                latLonCoord = bEScene.GetBoundingRectangle();
            }
            else {
                latLonCoord = this.gMapSearchObj.GetMapView();
            }
            return latLonCoord;
        }
        catch (ex) {
            LogErrorMessage("MapSearch.prototype.GetMapCoordinates: ", ex);
        }
    }

    MapSearch.prototype.GetStartAreaType = function() {
        try {
            var areaType = GEO_AREA_TYPE_POI;
            if (!this.IsBirdEyeView() && this.gMapSearchObj.GetZoomLevel() <= GEO_SEARCH_NATIONAL_ZOOM_LEVEL) {
                areaType = GEO_AREA_TYPE_NATIONAL;
            }

            return areaType;
        }
        catch (ex) {
            LogErrorMessage("MapSearch.prototype.GetStartAreaType: ", ex, true);
        }
    }

    MapSearch.prototype.GetshapeByID = function(shapeID) {
        try {
            var shapeFound = null;
            if (this.gMapSearchObj) {
                shapeFound = this.gMapSearchObj.GetShapeByID(shapeID);
            }
            return shapeFound;
        }
        catch (ex) {
            LogErrorMessage("GetshapeByID: ", ex);
        }
    }

    //---------------------- map events  ------------------------

    MapSearch.prototype.AttachEvents = function() {
        try {
            this.gMapSearchObj.AttachEvent("onchangeview", OnViewChanged);
            this.gMapSearchObj.AttachEvent("onclick", OnPinClick);
            this.gMapSearchObj.AttachEvent("onmouseover", OnMouseOver);
            this.gMapSearchObj.AttachEvent("onstartzoom", OnStartZoom);
        }
        catch (ex) {
            LogErrorMessage("MapSearch.prototype.AttachEvents: ", ex, true);
        }
    }

    MapSearch.prototype.DeAttachEvents = function() {
        try {
            this.gMapSearchObj.DetachEvent("onchangeview", OnViewChanged);
            this.gMapSearchObj.DetachEvent("onclick", OnPinClick);
            this.gMapSearchObj.DetachEvent("onmouseover", OnMouseOver);
            this.gMapSearchObj.DetachEvent("onstartzoom", OnStartZoom);
        }
        catch (ex) {
            LogErrorMessage("MapSearch.prototype.DeAttachEvents: ", ex, true);
        }
    }

    //------------------------ Map Session ----------------------

    MapSearch.prototype.InvalidPassportReloadPage = function() {
        try {
            alert("Your map session has expired. Click OK to reload your browser.");
            window.location.reload();
        }
        catch (ex) {
            LogErrorMessage("MapSearch.prototype.InvalidPassportReloadPage: ", ex);
        }
    }

    //----------------------------  Map Services Calls --------------------------------------------------

    MapSearch.prototype.GetPinsByMapLatLon = function(functionName) {
        try {
            var latLong = this.GetMapCoordinates();
            if (latLong) {
                MapService.GetPropertySearchResultByRange(gPassportKey,
															gSearchRequest,
															latLong.TopLeftLatLong.Latitude,
															latLong.TopLeftLatLong.Longitude,
															latLong.BottomRightLatLong.Latitude,
															latLong.BottomRightLatLong.Longitude,
															this.MapMenu.GetVisiblePropertyTypes(),
															this.GetStartAreaType(),
															functionName);
            }
        }
        catch (ex) {
            LogErrorMessage("MapSearch.prototype.GetPinsByLatLon: ", ex, true);
        }
    }

    MapSearch.prototype.AddMainProperty = function(mainPropertyId, functionName) {
        try {
            if (mainPropertyId) {
                MapService.GetPOI(gPassportKey, mainPropertyId, false, functionName);
            }
        }
        catch (ex) {
            LogErrorMessage("MapSearch.prototype.AddMainProperty: ", ex);
        }
    }

    MapSearch.prototype.GetPinPopUpInfo = function(pinParamters, functionName) {
        try {

            //set parameters x, y in case we return no datafor positioning the No data found pop up.
            this.PinsOnMap.PopUpClass.positionX = pinParamters[0]; //X coordinate
            this.PinsOnMap.PopUpClass.positionY = pinParamters[1]; // Y coordinate
            //[4] Prop ID
            //set the view
            this.PinsOnMap.PopUpClass.isMapBirdsEyeView = this.IsBirdEyeView();
            this.PinsOnMap.PopUpClass.isMember = this.isMember;

            if (this.isValueTrac) {
                RealtyTrac.ValueTracMapService.GetPOI(gPassportKey, eval(pinParamters[4]), true, functionName);
            }
            else {
                MapService.GetPOI(gPassportKey, eval(pinParamters[4]), true, functionName);
            }
        }
        catch (ex) {
            LogErrorMessage("MapSearch.prototype.GetPinPopUpInfo: ", ex);
        }
    }


    MapSearch.prototype.GetNeighborhoodForeclosures = function(street, cityStateZip, propTypes, getResultFunctionName) {
        try {
            var latLongRect = this.GetMapCoordinates();
            RealtyTrac.ValueTracMapService.GetPoiListWithMainProperty(
	            street,
	            cityStateZip,
	            latLongRect.TopLeftLatLong.Latitude,
			    latLongRect.TopLeftLatLong.Longitude,
			    latLongRect.BottomRightLatLong.Latitude,
			    latLongRect.BottomRightLatLong.Longitude,
			    propTypes,
			    false,
			    false,
			    true,
	            gPassportKey,
	            getResultFunctionName);
        }
        catch (ex) {
            LogErrorMessage("MapSearch.prototype.GetNeighborhoodForeclosures: ", ex);
        }
    }

    MapSearch.prototype.GetInteractiveMapProperties = function(street, cityStateZip, propTypes, isCheckboxChecked, getResultFunctionName) {
        try {
            var latLongRect = this.GetMapCoordinates();
            RealtyTrac.ValueTracMapService.GetInteractiveMapProperties(
	            street,
	            cityStateZip,
	            latLongRect.TopLeftLatLong.Latitude,
			    latLongRect.TopLeftLatLong.Longitude,
			    latLongRect.BottomRightLatLong.Latitude,
			    latLongRect.BottomRightLatLong.Longitude,
			    propTypes,
			    isCheckboxChecked,
			    true,
	            true,
	            gPassportKey,
	            getResultFunctionName);
        }
        catch (ex) {
            LogErrorMessage("MapSearch.prototype.GetInteractiveMapProperties: ", ex);
        }
    }

    MapSearch.prototype.GetValueTracPins = function(propTypes, getResultFunctionName) {
        try {
            var latLongRect = this.GetMapCoordinates();
            if (latLongRect) {
                RealtyTrac.ValueTracMapService.GetPropertySearchResultByRange(gPassportKey,
															'',
															latLongRect.TopLeftLatLong.Latitude,
															latLongRect.TopLeftLatLong.Longitude,
															latLongRect.BottomRightLatLong.Latitude,
															latLongRect.BottomRightLatLong.Longitude,
															propTypes,
															this.GetStartAreaType(),
															getResultFunctionName);
            }
        }
        catch (ex) {
            LogErrorMessage("MapSearch.prototype.GetValueTracPins: ", ex);
        }
    }

    MapSearch.prototype.ShowMapHelp = function() {
        try {
            divMapHelp = document.getElementById('help_div_cnr');
            if (divMapHelp) {
                divMapHelp.style.display = STYLE_BLOCK;
                divMapHelp.style.visibility = STYLE_VISIBLE;
            }
        }
        catch (ex) {
            LogErrorMessage("MapSearch.prototype.ShowMapHelp: ", ex);
        }
    }

    MapSearch.prototype.CloseMapHelp = function() {
        try {
            divMapHelp = document.getElementById('help_div_cnr');
            if (divMapHelp && divMapHelp.style.display == STYLE_BLOCK) {
                divMapHelp.style.display = STYLE_NONE;
                divMapHelp.style.visibility = STYLE_HIDDEN;
            }
        }
        catch (ex) {
            LogErrorMessage("MapSearch.prototype.CloseMapHelp: ", ex);
        }
    }

    MapSearch.prototype.StickHelpLinksToRight = function() {
        try {
            divMapHelp = document.getElementById('mapNav_mapHelp');
            mapXY = this.GetMapCenterPixels();

            if (divMapHelp) {
                divMapHelp.style.left = (mapXY.x * 2) - divMapHelp.offsetWidth + 'px';
            }
        }
        catch (ex) {
            LogErrorMessage("MapSearch.prototype.StickHelpLinksToRight: ", ex);
        }
    }

    //------------------------ Mpa Special Functions ----------------------------------------

    MapSearch.prototype.RemoveUnderlineFromAnchors = function(divID) {
        try {
            var currentElement = document.getElementById(divID);

            if (currentElement && currentElement.lastChild != null) {
                currentElement.lastChild.style.textDecoration = 'none';
            }
        }
        catch (ex) {
            LogErrorMessage("MapSearch.prototype.RemoveUnderlineFromAnchors: ", ex);
        }
    }

    function HideDivByID(divID) {
        try {
            var divToHide = document.getElementById(divID);
            if (divToHide) {
                divToHide.style.visibility = STYLE_HIDDEN;
                divToHide.style.display = STYLE_NONE;
            }
        }
        catch (ex) {
            LogErrorMessage("HideDivByID: ", ex);
        }
    }

    function ShowDivByID(divID) {
        try {
            var divToShow = document.getElementById(divID);
            if (divToShow) {
                divToShow.style.visibility = STYLE_VISIBLE;
                divToShow.style.display = STYLE_BLOCK;
            }
        }
        catch (ex) {
            LogErrorMessage("ShowDivByID: ", ex);
        }
    }

    function IsDivVisbleByID(divID) {
        try {
            var divToCheck = document.getElementById(divID);
            if (divToCheck) {
                return divToCheck.style.visibility == STYLE_VISIBLE || divToCheck.style.display == STYLE_BLOCK;
            }
            return false;
        }
        catch (ex) {
            LogErrorMessage("IsDivVisbleByID: ", ex);
        }
    }

    function getElementVertPosOnPage(element) {
        var offsetY = -10;
        while (element != null) {
            offsetY += element.offsetTop;
            element = element.offsetParent;
        }
        return offsetY;
    }
}

//----------------------------  Map Menu Class --------------------------------------------------

function MapSearchMenu() {
    var OPEN_MAP_MENU_IMAGE_PATH = '/mapsearch/images/mapOpen.gif';
    var CLOSE_MAP_MENU_IMAGE_PATH = '/mapsearch/images/mapClose.gif';
    var DIV_MENUBTN_ID = 'hideLine';
    var DIV_MENU_CONTAINER_NAME = 'SR_mapItems';
    var DIV_MENU_BTN_CONTAINER_ID = 'openMenu';
    var DIV_MENU_BTN_OPEN_CLOSE_DIV = 'openMenu';
    var DIV_MAP_CONTAINER = 'Map_Container';
    var DIV_MAP_CONATINER_ALL = 'mapAll';
    var DEFAULT_MAP_CONTAINER_WIDTH = '474px';

    MapSearchMenu.prototype.ShowMenu = function() {
        try {
            var divImageBtnOpen = document.getElementById(DIV_MENUBTN_ID);
            var divMenuContainer = document.getElementById(DIV_MENU_CONTAINER_NAME);

            if (divMenuContainer && divMenuContainer.style.display == STYLE_NONE) {
                if (divImageBtnOpen) {
                    divImageBtnOpen.src = OPEN_MAP_MENU_IMAGE_PATH;
                }

                divMenuContainer.style.display = STYLE_BLOCK;
            }
        }
        catch (ex) {
            LogErrorMessage("MapSearchMenu.prototype.ShowMenu: ", ex);
        }
    }

    MapSearchMenu.prototype.OnTogMenuResizeMapContainer = function() {
        try {
            var divMapContainer = document.getElementById(DIV_MAP_CONTAINER);
            var divMapContainerAll = document.getElementById(DIV_MAP_CONATINER_ALL);

            if (divMapContainer && this.IsMenuOpen()) {
                var width = DEFAULT_MAP_CONTAINER_WIDTH.replace(/px/g, '');
                divMapContainer.style.width = eval(width) - 10 + 'px';
            }
            else {
                divMapContainer.style.width = divMapContainerAll.offsetWidth - 10 + 'px';
            }
        }
        catch (ex) {
            LogErrorMessage("MapSearchMenu.prototype.OnTogMenuResizeMapContainer: ", ex);
        }
    }

    MapSearchMenu.prototype.HideMenu = function() {
        try {
            var divImageBtnOpen = document.getElementById(DIV_MENUBTN_ID);
            var divMenuContainer = document.getElementById(DIV_MENU_CONTAINER_NAME);

            if (divMenuContainer && divMenuContainer.style.display == STYLE_BLOCK) {
                if (divImageBtnOpen) {
                    divImageBtnOpen.src = CLOSE_MAP_MENU_IMAGE_PATH;
                }
                divMenuContainer.style.display = STYLE_NONE;
            }
        }
        catch (ex) {
            LogErrorMessage("HideMenu: ", ex);
        }
    }

    MapSearchMenu.prototype.ShowMenuBtn = function() {
        try {
            var divMenuBtnOpen = document.getElementById(DIV_MENU_BTN_OPEN_CLOSE_DIV);
            if (ivMenuBtnOpen) {
                divMenuContainer.style.display = STYLE_BLOCK;
            }
        }
        catch (ex) {
            LogErrorMessage("ShowMenuBtn: ", ex);
        }
    }

    MapSearchMenu.prototype.HideMenuBtn = function() {
        try {
            var divMenuBtnOpen = document.getElementById(DIV_MENU_BTN_OPEN_CLOSE_DIV);
            if (divMenuBtnOpen) {
                divMenuBtnOpen.style.display = STYLE_NONE;
            }
        }
        catch (ex) {
            LogErrorMessage("HideMenuBtn: ", ex);
        }
    }

    MapSearchMenu.prototype.IsMenuOpen = function() {
        try {
            var divMenuContainer = document.getElementById(DIV_MENU_CONTAINER_NAME);
            var isMenuOpen = false;
            if (divMenuContainer && divMenuContainer.style.display == STYLE_BLOCK) {
                isMenuOpen = true;
            }

            return isMenuOpen;
        }
        catch (ex) {
            LogErrorMessage("IsMenuOpen: ", ex);
        }
    }

    MapSearchMenu.prototype.ShowHideMenu = function() {
        try {
            if (this.IsMenuOpen()) {
                this.HideMenu();
            }
            else {
                this.ShowMenu();
            }
            this.OnTogMenuResizeMapContainer();
        }
        catch (ex) {
            LogErrorMessage("ShowHideMenu: ", ex);
        }
    }

    MapSearchMenu.prototype.SetHeightToOpenBtn = function() {
        try {
            var divMenuContainer = document.getElementById(DIV_MENU_CONTAINER_NAME);
            var divMenuBtnOpen = document.getElementById(DIV_MENU_BTN_OPEN_CLOSE_DIV);
            if (divMenuContainer && divMenuBtnOpen) {
                divMenuContainer.style.height = divMenuBtnOpen.offsetHeight + 'px';
            }
        }
        catch (ex) {
            LogErrorMessage("SetHeightToOpenBtn: ", ex);
        }
    }

    MapSearchMenu.prototype.GetVisiblePropertyTypes = function() {
        try {
            if (typeof (checkBoxNamePrefix) == "undefined") {
                return;
            }

            var types = availablePropTypes.split('');
            var visiblePropertyTypes = '';

            for (var i = 0; i < types.length; i++) {
                if (document.getElementById(checkBoxNamePrefix + types[i]).checked) {
                    visiblePropertyTypes += (types[i] + ',');
                }
            }
            if (visiblePropertyTypes.length > 0) {
                visiblePropertyTypes = visiblePropertyTypes.substring(0, visiblePropertyTypes.length - 1);
            }

            return visiblePropertyTypes;
        }
        catch (ex) {
            LogErrorMessage("MapSearchMenu.prototype.GetVisiblePropertyTypes: ", ex, true);
        }
    }

    MapSearchMenu.prototype.ShowAvailableTabsAndCheckboxes = function() {
        try {
            var list;
            var name;
            var tab;
            var types = availablePropTypes.split('');
            var chkbox;
            var checkedTypes = null;

            if (gSearchRequestObject) {
                checkedTypes = gSearchRequestObject.CheckedTypes;
            }

            for (i = 0; i < types.length; i++) {
                if (types[i] != '') {
                    name = 'list' + types[i];
                    list = document.getElementById(name);
                    if (list) {
                        list.checked = false;
                        list.style.display = "block";

                        switch (types[i]) {
                            case 'P': tab = document.getElementById('propTabPreForeclosures');
                                break;
                            case 'A': tab = document.getElementById('propTabAuction');
                                break;
                            case 'B': tab = document.getElementById('propTabBankOwned');
                                break;
                            case 'G': tab = document.getElementById('propTabG'); //TODO: change tab name
                                break;
                            case 'F': tab = document.getElementById('propTabHomesForSale');
                                break;
                            case 'R': tab = document.getElementById('propTabM'); //TODO: change tab name
                                break;
                        }

                        if (tab != null) {
                            tab.style.display = "block";
                        }

                        if (checkedTypes) {
                            if (typeof (checkBoxNamePrefix) == "undefined") {
                                return;
                            }
                            chkbox = document.getElementById(checkBoxNamePrefix + types[i]);
                            if (chkbox) {
                                if (checkedTypes.indexOf(types[i]) >= 0) {
                                    chkbox.checked = true;
                                }
                                else {
                                    chkbox.checked = false;
                                }
                            }
                        }
                    }
                }
            }
        }
        catch (ex) {
            LogErrorMessage("ShowAvailableTabsAndCheckboxes: ", ex, true);
        }
    }

    MapSearchMenu.prototype.OffsetBtnTogMenuMap = function() {
        try {
            divMenuTogBtn = document.getElementById(DIV_MENUBTN_ID);
            if (divMenuTogBtn) {
                if (divMenuTogBtn.parentNode.style.marginLeft == '-8px') {
                    divMenuTogBtn.parentNode.style.marginRight = '-8px';
                    divMenuTogBtn.parentNode.style.marginLeft = '0';
                }
                else {
                    divMenuTogBtn.parentNode.style.marginRight = '0';
                    divMenuTogBtn.parentNode.style.marginLeft = '-8px';
                    divMenuTogBtn.parentNode.style.left = '0px';
                }
            }
        }
        catch (ex) {
            LogErrorMessage("MapSearchMenu.prototype.OffsetBtnTogMenuMap: ", ex, true);
        }
    }

    MapSearchMenu.prototype.GetCheckedPropertyTypes = function() {
        var typesString = '';
        var chkbox;
        var types;

        try {
            if (EXISTING_PROPERTY_TYPES) {
                types = EXISTING_PROPERTY_TYPES.split('');

                if (typeof (checkBoxNamePrefix) == "undefined") {
                    return EXISTING_PROPERTY_TYPES;
                }

                for (i = 0; i < types.length; i++) {
                    if (types[i] != '') {
                        name = checkBoxNamePrefix + types[i];
                        chkbox = document.getElementById(name);
                        if (chkbox && chkbox.checked) {
                            typesString += types[i];
                        }
                    }
                }
            }
            return typesString;
        }
        catch (ex) {
            LogErrorMessage("MapSearchMenu.prototype.GetCheckedPropertyTypes: ", ex, true);
        }
    }

    MapSearchMenu.prototype.GetMenuWidth = function() {
        try {
            var divMenuContainer = document.getElementById(DIV_MENU_CONTAINER_NAME);
            var menuWidth = 0;

            if (divMenuContainer) {
                menuWidth = divMenuContainer.offsetWidth;
            }
            return menuWidth;
        }
        catch (ex) {
            LogErrorMessage("MapSearchMenu.prototype.GetMenuWidth: ", ex, true);
        }
    }

}


//----------------------------  Pin  Class ------------------------------------------------------

function PinsOnMap() {

    this.isMember = false;
    this.isMapBirdEyeView = false;
    this.curMapObject;
    this.pinsArray;
    this.PropertyCountToShow;
    this.pinLlayerName = STRING_EMPTY;
    this.pinLayerPopUpContainer;
    this.pinLayerPopUpID = STRING_EMPTY;
    this.areaCenter;
    this.currentSelectedPinShape;
    this.currentSelectedPinInfo;
    this.lastSelectedPinShape;
    this.currentAreaType;
    this.curOnMouseOverElemtID;
    this.curOnMouseOverShapeID;
    this.isCurShapeSelected;
    this.isMouseOverCurrentPin;
    this.pinMainPropLayerContainer;
    this.pinMainPropLlayerName;
    this.pinMainPropLayerID;
    this.mainPropertyID = null;
    this.mainPropertyPinID = null;
    this.mainPropertyShown = true;
    this.pinsPos = null;
    this.RemoveUnderlineFromAnchors;
    this.pinsDrawn = false;
    this.subjectPropPinOnMap = false;
    this.isValueTrac = false;
    this.imgNamePropPin = 'balloon_Map_';
    this.imgNameMainPropPin = 'property_pin';
    this.imgPinPath = '/mapsearch/images/';
    this.ValueTracMainPropData = null;
    this.isSalesPin = false;
    this.compSalList = null;
    this.isNeighborSalesPin = false;
    this.isInteractiveMap = false;
    this.divMapContainer = DIV_NAME_MAP_CONTAINER_MAP_ALL;
    ///// Create instanse of popups
    this.PopUpClass = new PopUp();
    this.PopUpClass.SetIsBirdEyeview(this.isMember);
    this.PopUpClass.SetIsMember(this.isMapBirdEyeView);
    this.PopUpClass.SetInstanceCurMap(this.curMapObject);
    this.drawingSubjectPin = false;
    this.PinsOnBirdEyeview = 0;
    this.removeShapes = true;
    this.pathToImgFolder = '/mapsearch/images/';

    PinsOnMap.prototype.ReIniClassVariables = function() {
        this.mainPropertyPinID = null;
        this.mainPropertyID = null;
        this.mainPropertyShown = true;
        this.subjectPropPinOnMap = false;
        this.pinsDrawn = false;
    }

    PinsOnMap.prototype.IsBirdEyeView = function() {
        return this.curMapObject.GetMapStyle() == VEMapStyle.Birdseye || this.curMapObject.GetMapStyle() == VEMapStyle.BirdseyeHybrid;
    }

    PinsOnMap.prototype.GetLayerContainer = function(layerID) {
        try {
            var layer = new LayersHandling(layerID, this.curMapObject);
            if (layer.layerExist) {
                if (this.removeShapes) {
                    layer.DeleteAllShapesFromLayer();
                }
            }
            else {
                layer.CreateNewLayer();
            }
            return layer;
        }
        catch (ex) {
            LogErrorMessage("PinsOnMap.prototype.GetGroupedPopUpLayer: ", ex, true);
        }
    }

    PinsOnMap.prototype.SetIsMember = function(isMember) {
        this.isMember = isMember;
        this.PopUpClass.SetIsBirdEyeview(this.isMember);
    }

    PinsOnMap.prototype.SetIsBirdEyeview = function(isBirdEyeView) {
        this.isMapBirdsEyeView = isBirdEyeView;
        this.PopUpClass.SetIsMember(this.isMapBirdEyeView);
    }

    PinsOnMap.prototype.SetInstanceCurMap = function(mapObj) {
        this.curMapObject = mapObj;
        this.PopUpClass.SetInstanceCurMap(this.curMapObject);
    }

    PinsOnMap.prototype.IsMouseOverPin = function(mapEvent) {
        var isMouseOverPin = false;
        this.isCurShapeSelected = false;

        if (mapEvent && null != this.curMapObject) {
            var shape = this.curMapObject.GetShapeByID(mapEvent.elementID);

            if (this.pinLayerPopUpID != undefined && shape != undefined) {
                isMouseOverPin = IsSelectedShapeInLayer(shape.iid, this.pinLayerPopUpID);
            }

            if (this.currentSelectedPinShape != undefined && this.currentSelectedPinShape.Id == shape.Id) {
                this.isCurShapeSelected = true;
            }

            if (isMouseOverPin && !this.isCurShapeSelected) {
                var pinParameters = GetSelectedPinParameters(shape.Id);
                this.curOnMouseOverElemtID = mapEvent.elementID;
                this.currentSelectedPinInfo = pinParameters;
                this.curOnMouseOverShapeID = shape.Id;
            }
            else {
                this.currentSelectedPinInfo = undefined;
            }
        }

        this.isMouseOverCurrentPin = isMouseOverPin;

        return isMouseOverPin;
    }

    PinsOnMap.prototype.ClearAllLayers = function() {
        if (this.curMapObject) {
            var noLayers = this.curMapObject.GetShapeLayerCount();
            var currentLayer = STRING_EMPTY;
            for (var i = 0; i < noLayers; i++) {
                currentLayer = this.curMapObject.GetShapeLayerByIndex(i);
                if (currentLayer) {
                    currentLayer.DeleteAllShapes();
                }
            }
        }
    }


    PinsOnMap.prototype.DrawMainPropertPin = function(MainPropInfo) {
        this.pinMainPropLlayerName = LAYER_NAME_PINS_MAIN_PROPERTY;
        this.pinMainPropLayerContainer = this.GetLayerContainer(LAYER_NAME_PINS_MAIN_PROPERTY);
        this.pinMainPropLayerID = this.pinMainPropLayerContainer.layerID;
        var pinShape = this.GetPinShape(MainPropInfo, true, 0);
        this.pinMainPropLayerContainer.AddShapeToLayer(pinShape);
        this.mainPropertyPinID = pinShape.Id;
        //return pinShape.Id;
    }

    PinsOnMap.prototype.DrawPins = function(objSearchResult) {
        this.AddPins(objSearchResult, this.isValueTrac);
    }

    PinsOnMap.prototype.AddPinsValueTrac = function(objSearchResult) {
        this.AddPins(objSearchResult, this.isValueTrac);
    }

    PinsOnMap.prototype.AddPins = function(objSearchResult) {
        this.pinLlayerName = LAYER_NAME_PINS;
        this.pinLayerPopUpContainer = this.GetLayerContainer(LAYER_NAME_PINS);
        this.pinLayerPopUpID = this.pinLayerPopUpContainer.layerID;
        this.pinsArray = (this.isValueTrac) ? objSearchResult.PoiList : objSearchResult.POIList;
        this.isMainProperty = false;
        this.PropertyCountToShow = objSearchResult.PropertyCountToShow;
        this.currentAreaType = undefined;
        this.PopUpClass.GroupedPopUpAreaType = this.currentAreaType;
        this.mainPropertyPinID = null;
        this.PinsOnBirdEyeview = 0;

        if (!this.isValueTrac) {
            this.PropertyCountToShow = objSearchResult.PropertyCountToShow;
            this.currentAreaType = undefined;
            this.PopUpClass.GroupedPopUpAreaType = this.currentAreaType;

            if (objSearchResult.AreaCenters != null) {
                this.areaCenter = objSearchResult.AreaCenters.AreaCenter;
            }
        }

        if (this.pinsArray.length != 0) {
            var currentPin;
            var be;
            var latlong;
            for (var pinIndex = 0; pinIndex < this.pinsArray.length; pinIndex++) {

                currentPin = this.pinsArray[pinIndex];

                if (this.mainPropertyID && this.mainPropertyID == currentPin.PropID) {
                    this.isMainProperty = true;
                }
                else {
                    this.isMainProperty = false;
                }

                if (this.isMember || !this.isMapBirdEyeView) {
                    if (this.isMainProperty) {
                        this.DrawMainPropertPin(currentPin);
                    }
                    else {
                        this.pinLayerPopUpContainer.AddShapeToLayer(this.GetPinShape(currentPin, this.isMainProperty, pinIndex));
                    }
                }

                if (this.IsBirdEyeView()) {

                    if (this.curMapObject.IsBirdseyeAvailable()) {
                        be = this.curMapObject.GetBirdseyeScene();
                        latlong = new VELatLong(currentPin.Latitude, currentPin.Longitude);
                        if (be && be.ContainsLatLong(latlong)) {
                            this.PinsOnBirdEyeview++;
                        }
                    }
                    this.PrepareBirdeyeViewToProperty(currentPin.Latitude, currentPin.Longitude);
                }
            }

        }

        if (!this.isValueTrac) {
            if (this.isMapBirdEyeView) {
                SetCount(gPinsPos.length, this.PropertyCountToShow);
            }
            else {
                SetCount(this.pinsArray.length, this.PropertyCountToShow);
            }
        }

    }

    PinsOnMap.prototype.PrepareBirdeyeViewToProperty = function(latitude, longitude) {
        if (this.curMapObject) {
            var birdEyeViewScene = this.curMapObject.GetBirdseyeScene();
            var mapCenter = this.curMapObject.GetCenter();
            var mapZoomLevel = this.curMapObject.GetZoomLevel();
            var mapWidth = mapCenter.x;
            var mapHeight = mapCenter.y;

            var mapPixelPos = birdEyeViewScene.LatLongToPixel(mapCenter, mapZoomLevel);
            var pinLatLong = new VELatLong(latitude, longitude);
            var pinPixelPos = birdEyeViewScene.LatLongToPixel(pinLatLong, mapZoomLevel);
            var pinPos = pinPixelPos.x + ' ' + pinPixelPos.y;

            if (pinPixelPos.x >= (mapPixelPos.x - mapWidth) && mapPixelPos.x <= (mapPixelPos.x + mapWidth)) {
                if (pinPixelPos.y >= (mapPixelPos.y - mapHeight) && pinPixelPos.y <= (mapPixelPos.y + mapHeight)) {
                    AddPinPos(pinPos, this.pinsPos);
                }
            }
        }

        function AddPinPos(pinPos, aPinsPos) {
            try {
                notInArray = true;
                for (i = 0; i <= aPinsPos.length - 1; i++) {
                    if (aPinsPos[i] == pinPos) {
                        notInArray = false;
                    }

                }

                if (notInArray) {
                    i = aPinsPos.length;
                    aPinsPos[i] = pinPos;
                }
            }
            catch (ex) {
                LogErrorMessage("AddPinPos: ", ex, true);
            }
        }

    }

    PinsOnMap.prototype.GetPinShape = function(pin, isMainProp, counter) {
        var shapeIcon;
        var pixPos = null;
        var encodLatLon = STRING_EMPTY;
        var shape = null;

        if (this.curMapObject.IsBirdseyeAvailable() && this.IsBirdEyeView() && this.drawingSubjectPin && pin.PropID == 0) {

            be = this.curMapObject.GetBirdseyeScene();
            if (be && gSubjPropDecodedLatLong._reserved == '') {
                pixPos = be.LatLongToPixel(this.curMapObject.GetCenter(), this.curMapObject.GetZoomLevel());
                gSubjPropDecodedLatLong = be.PixelToLatLong(pixPos, this.curMapObject.GetZoomLevel());
            }
            encodLatLon = gSubjPropDecodedLatLong._reserved;
            pixPos = this.curMapObject.LatLongToPixel(gSubjPropDecodedLatLong);
            shape = new VEShape(VEShapeType.Pushpin, gSubjPropDecodedLatLong);
        }
        else {
            var latLong = new VELatLong(pin.Latitude, pin.Longitude);
            pixPos = this.curMapObject.LatLongToPixel(latLong);
            shape = new VEShape(VEShapeType.Pushpin, latLong);
        }

        var pinID = 0;
        var pinType = (this.isValueTrac && isMainProp) ? PINTYPE_MAIN_PROP_VAL_TRAC : STRING_EMPTY;
        var pinTabType = STRING_EMPTY;
        pinTabType = (this.isNeighborSalesPin) ? COMP_SALES_PIN : pinTabType;
        pinTabType = (this.isInteractiveMap) ? INTERACTIVE_MAP : pinTabType;

        if (pin.PropID != null && pin.PropID != undefined)
        { pinID = pin.PropID; }

        var arguments = parseInt(pixPos.x) +
	                    ',' +
	                    parseInt(pixPos.y) +
	                    ',' +
	                    pin.Latitude +
	                    '|' +
	                    pin.Longitude +
	                    ',' +
	                    pinID +
	                    '|' +
	                    pin.PropertyStatus +
	                    '|' +
	                    pin.isSubjectProperty +
	                    '|' +
	                     encodLatLon +
	                    '|' +
	                    PIN_TYPE_PROPERTY_PIN +
	                    '|' +
	                    pinType +
	                    '|' +
	                    pinTabType +
	                    '|' +
	                    counter;


        var newArguments = parseInt(pixPos.x) +
	                    '|' +
	                    parseInt(pixPos.y) +
	                    '|' +
	                    pin.Latitude +
	                    '|' +
	                    pin.Longitude +
	                    '|' +
	                    pinID +
	                    '|' +
	                    pin.PropertyStatus +
	                    '|' +
	                    pin.isSubjectProperty +
	                    '|' +
	                    encodLatLon +
	                    '|' +
	                    PIN_TYPE_PROPERTY_PIN +
	                    '|' +
	                    pinType +
	                    '|' +
	                    pinTabType +
	                    '|' +
	                    counter;

        if (isMainProp) {
            shapeIcon = "<img src='" + this.imgPinPath + this.imgNameMainPropPin + ".gif' title='Click for details' args='" + arguments + "'/>";
        }
        else {
            if (this.isSalesPin) {
                shapeIcon = "<img src='" + this.imgPinPath + this.imgNamePropPin + (counter + 1) + ".gif' title='Click for details'/>";
            }
            else {
                shapeIcon = "<img src='" + this.imgPinPath + this.imgNamePropPin + pin.PropertyStatus + ".gif' title='Click for details'/>";
            }
        }

        shape.Id = newArguments;
        shape.SetCustomIcon(shapeIcon);

        return shape;
    }

    PinsOnMap.prototype.ClearSelectedDrawnPin = function() {
        try {
            if (eval('LayersHandling')) {
                var polygonLayer = new LayersHandling(LAYER_NAME_SELECTED_GROUPED_PIN, mapObj);
                if (polygonLayer != undefined && polygonLayer.layerExist) {
                    polygonLayer.DeleteAllShapesFromLayer();
                }
            }
        }
        catch (ex) {
            LogErrorMessage("PinsOnMap.prototype.ClearSelectedDrawnPin: ", ex);
        }
    }

    PinsOnMap.prototype.DrawGroupedPins = function(objSearchResult) {
        this.pinLlayerName = LAYER_NAME_PINS;
        this.pinLayerPopUpContainer = this.GetLayerContainer(LAYER_NAME_PINS);
        this.pinLayerPopUpID = this.pinLayerPopUpContainer.layerID;
        this.pinsArray = objSearchResult.POIList;
        this.PropertyCountToShow = objSearchResult.PropertyCountToShow;

        function compareShapeIDs(fId, sId) {
            try {
                var separator = '|';
                var IdsEquals = false;
                //we take the index away because might vary if the Map position was moved
                var firstID = fId.substring(fId.indexOf(separator));
                var secondID = sId.substring(sId.indexOf(separator));
                if (firstID == secondID) {
                    IdsEquals = true;
                }
                return IdsEquals;
            }
            catch (ex) {
                LogErrorMessage("compareShapeIDs: ", ex);
            }
        }

        if (objSearchResult.AreaCenters != null) {
            this.areaCenter = objSearchResult.AreaCenters.AreaCenter;
            this.currentAreaType = objSearchResult.AreaCenters.AreaType;
            this.PopUpClass.GroupedPopUpAreaType = this.currentAreaType;
        }
        var pinShape = null;
        for (var i = 0; i < this.areaCenter.length; i++) {
            pinShape = null;
            pinShape = this.GetPolygonPinShape(this.areaCenter[i], i);
            if (pinShape != null) {

                this.pinLayerPopUpContainer.AddShapeToLayer(pinShape);
                if (this.curMapObject.GetZoomLevel() >= ZOOM_LEVEL_STATE_LIMIT_6) {
                    CenterGroupPinContent(this.pinLayerPopUpContainer.layerID, false);
                }

                this.RemoveUnderlineFromAnchors(this.pinLayerPopUpContainer.layerID);
                if (!(this.curMapObject.GetZoomLevel() < ZOOM_LEVEL_STATE_LIMIT_6)) {
                    ResizePinAnchors(this.pinLayerPopUpContainer.layerID, '128');
                }
                if (this.curOnMouseOverShapeID != null && compareShapeIDs(this.curOnMouseOverShapeID, pinShape.Id)) {

                    this.currentSelectedPinShape = pinShape;
                    this.isMouseOverCurrentPin = true;
                    pinShape.Hide();
                }
            }
        }
    }

    PinsOnMap.prototype.ShowSelectedGroupedPin = function(areaPoints) {
        if (this.isMouseOverCurrentPin) {
            var shape = this.curMapObject.GetShapeByID(this.curOnMouseOverElemtID);

            if (shape) {
                //will show the Polygin Aera for the selected Pin
                if (areaPoints != STRING_EMPTY) {
                    this.PopUpClass.PolygonPopUp(areaPoints);
                }

                if (this.currentSelectedPinShape && this.currentSelectedPinShape.Id != shape.Id) {
                    this.currentSelectedPinShape.Show();
                    //We want everytime a new Layer to a asure that it will be on the Top
                    //in this line we delete the current Polygon and its Layer 
                    this.DeleteLayer(LAYER_NAME_SELECTED_GROUPED_PIN);

                    this.RemoveUnderlineFromAnchors(this.pinLayerPopUpContainer.layerID);
                    if (!(this.curMapObject.GetZoomLevel() < ZOOM_LEVEL_STATE_LIMIT_6)) {
                        ResizePinAnchors(this.pinLayerPopUpContainer.layerID, '128');
                    }

                    this.lastSelectedPinShape = this.currentSelectedPinShape;
                    if (this.curMapObject.GetZoomLevel() >= ZOOM_LEVEL_STATE_LIMIT_6) {
                        CenterGroupPinContent(this.pinLayerPopUpContainer.layerID, false);
                    }
                }

                if (this.currentSelectedPinShape == undefined || shape.Id != this.currentSelectedPinShape.Id) {


                    this.currentSelectedPinShape = shape;
                    this.currentSelectedPinShape.Hide();

                    this.CreateSelectedPin(shape, this.currentSelectedPinInfo);

                    this.currentAreaType = this.currentSelectedPinInfo.areaType;
                    this.PopUpClass.GroupedPopUpAreaType = this.currentAreaType;
                }
            }
        }
    }

    function CenterGroupPinContent(divID, selected) {
        try {
            var currentElement = document.getElementById(divID);
            if (currentElement && currentElement.lastChild != null) {
                var left = eval(currentElement.lastChild.offsetLeft) - 36;
                var top = eval(currentElement.lastChild.offsetTop) - 11;
                currentElement.lastChild.style.left = left + 'px';
                currentElement.lastChild.style.top = top + 'px';

                if (selected) {
                    currentElement.lastChild.style.backgroundColor = 'white';
                }
                else {
                    currentElement.lastChild.style.backgroundColor = 'transparent';
                }
            }
        }
        catch (ex) {
            LogErrorMessage("CenterGroupPinContent: ", ex);
        }
    }

    PinsOnMap.prototype.CreateSelectedPin = function(shape, pinParameters) {
        try {

            var tempLayer = this.GetLayerContainer(LAYER_NAME_SELECTED_GROUPED_PIN);
            var points = shape.GetPoints();

            if (points.length < 3) {
                return;
            }

            var pinShape = new VEShape(VEShapeType.Polygon, points);

            var divPopupContainer = document.createElement(ELEMENT_DIVISION);
            divPopupContainer.innerHTML = GetPinShapeHTMLContentMOver(pinParameters, this.curMapObject.GetZoomLevel());

            pinShape.Id = shape.Id;

            pinShape.SetCustomIcon(divPopupContainer.innerHTML);

            pinShape.SetFillColor(new VEColor(255, 255, 255, 1.0));
            pinShape.SetLineColor(new VEColor(0, 100, 150, 0.7));

            tempLayer.AddShapeToLayer(pinShape);
            if (this.curMapObject.GetZoomLevel() >= ZOOM_LEVEL_STATE_LIMIT_6) {
                CenterGroupPinContent(tempLayer.layerID, true);
            }

            this.RemoveUnderlineFromAnchors(tempLayer.layerID);
            if (!(this.curMapObject.GetZoomLevel() < ZOOM_LEVEL_STATE_LIMIT_6)) {
                ResizePinAnchors(tempLayer.layerID, '128');
            }
        }
        catch (ex) {
            LogErrorMessage("PinsOnMap.prototype.CreateSelectedPin: ", ex);
        }
    }

    function GetOnPinClickZoomFunc(latitude, longitude) {
        try {
            var zoomFunction = 'TheMap.gMapSearchObj.SetCenterAndZoom(' +
                'new VELatLong(' +
                latitude +
                ',' +
                longitude +
                '),' +
                'TheMap.gMapSearchObj.GetZoomLevel()+1' +
                ');';

            return zoomFunction;
        }
        catch (ex) {
            LogErrorMessage("GetOnPinClickZoomFunc: ", ex);
        }
    }

    function IsSelectedShapeInLayer(shapeID, layerID) {
        try {
            var isShapeInLayer = false;

            if (shapeID.indexOf(layerID) > -1) {
                isShapeInLayer = true;
            }

            return isShapeInLayer;
        }
        catch (ex) {
            LogErrorMessage("IsSelectedShapeInLayer: ", ex);
        }


    }

    function GetSelectedPinParameters(parArray) {
        try {
            var pinDetails = null;
            if (parArray != undefined || parArray != null) {
                pinDetails = new Object;
                var arrayParams = parArray.split('|');
                pinDetails.areaIndex = arrayParams[0];
                pinDetails.areaName = arrayParams[1];
                pinDetails.areaType = arrayParams[2];
                pinDetails.cityName = arrayParams[3];
                pinDetails.stateCode = arrayParams[4];
                pinDetails.latitude = arrayParams[5];
                pinDetails.longitude = arrayParams[6];
                pinDetails.zoomLevel = arrayParams[7];
                pinDetails.totalCount = arrayParams[8];
            }
            return pinDetails;
        }
        catch (ex) {
            LogErrorMessage("GetSelectedPinParameters: ", ex);
        }
    }

    PinsOnMap.prototype.MapSubjectPropPin = function() {
        try {
            var pinargs = new Object;
            var showInitPopUp = false;

            if ((this.IsBirdEyeView() && gSubjPropDecodedLatLong._reserved == '') || (!this.IsBirdEyeView() && gSubjectPropertyLon == null && gSubjectPropertyLat == null)) {
                if (this.curMapObject.IsBirdseyeAvailable() && this.IsBirdEyeView()) {

                    if (this.curMapObject.IsBirdseyeAvailable()) {
                        be = this.curMapObject.GetBirdseyeScene();

                        if (be) {
                            var pixPos = be.LatLongToPixel(this.curMapObject.GetCenter(), this.curMapObject.GetZoomLevel());
                            var encLatLong = be.PixelToLatLong(pixPos, this.curMapObject.GetZoomLevel());
                            pixPos = this.curMapObject.LatLongToPixel(encLatLong);
                            gSubjPropDecodedLatLong = encLatLong;
                            gSubjectPropertyLat = null;
                            gSubjectPropertyLon = null;
                        }
                    }
                }
                else {
                    var latLong = this.curMapObject.GetCenter();
                    gSubjectPropertyLat = latLong.Latitude;
                    gSubjectPropertyLon = latLong.Longitude;
                    showInitPopUp = true;
                }
            }

            pinargs.Latitude = gSubjectPropertyLat;
            pinargs.Longitude = gSubjectPropertyLon;

            pinargs.PropID = gSubjectPropertyID;
            pinargs.PropertyStatus = STRING_EMPTY;
            pinargs.isSubjectProperty = true;

            this.drawingSubjectPin = true;
            this.DrawMainPropertPin(pinargs);
            this.drawingSubjectPin = false;
            if (showInitPopUp) {
                var latLonSubPin = new VELatLong(gSubjectPropertyLat, gSubjectPropertyLon);
                var pixXY = this.curMapObject.LatLongToPixel(latLonSubPin);
                this.PopUpClass.positionX = parseInt(pixXY.x);
                this.PopUpClass.positionY = parseInt(pixXY.y);
                this.PopUpClass.longitude = gSubjectPropertyLon;
                this.PopUpClass.latitude = gSubjectPropertyLat;

                this.PopUpClass.SubjectPopUp();
            }
            this.subjectPropPinOnMap = true;
        }
        catch (ex) {
            //LogErrorMessage("PinsOnMap.prototype.MapSubjectPropPin: ", ex);
        }
    }

    PinsOnMap.prototype.GetPolygonPinShape = function(areaInformation, index) {

        var divPopupContainer = document.createElement(ELEMENT_DIVISION);
        var spanPopupContainer = document.createElement('span');

        spanPopupContainer.innerHTML = GetPinshapeHTMLContent(areaInformation, this.curMapObject.GetZoomLevel());

        var polygonContainer = this.GetPolContVertexes(areaInformation);
        var pinShape = null;

        if (polygonContainer != null && polygonContainer != undefined) {
            pinShape = new VEShape(VEShapeType.Polygon, polygonContainer);

            pinShape.SetCustomIcon(spanPopupContainer.innerHTML);

            pinShape.Id = index + '|' +
	                areaInformation.AreaName +
	                '|' +
	                areaInformation.AreaType +
	                '|' +
	                areaInformation.CityName +
	                '|' +
	                areaInformation.StateCode +
	                '|' +
	                areaInformation.AreaCenter.Latitude +
	                '|' +
	                areaInformation.AreaCenter.Longitude +
	                '|' +
	                this.curMapObject.GetZoomLevel() +
	                '|' +
	                areaInformation.TotalCount;
            pinShape.SetLineWidth(2);
            pinShape.symbolUrl = STRING_EMPTY;
            pinShape.SetFillColor(new VEColor(0, 100, 150, 0.6));
            pinShape.SetLineColor(new VEColor(255, 255, 255, 0.8));
        }

        return pinShape;
    }

    function GetPinshapeHTMLContent(areaInformation, zoomLevel) {
        try {
            var propertyType = 'foreclosure';
            var divPopupContainer;
            divPopupContainer = HTMLTemplateGroupedPin();

            var areaName = GetAreaName(areaInformation, zoomLevel);

            if (zoomLevel < ZOOM_LEVEL_STATE_LIMIT_6) {
                divPopupContainer = divPopupContainer.replace(/AREA_NAME/g, areaName);
                divPopupContainer = divPopupContainer.replace(/NUMBER_PROPERTIES/g, STRING_EMPTY);
                divPopupContainer = divPopupContainer.replace(/PROPERTY_TYPE/g, STRING_EMPTY);
                divPopupContainer = divPopupContainer.replace(/CLASS/g, 'geoPinStyleSmall');
            }
            else
                if (areaName != STRING_EMPTY && (areaInformation.TotalCount == 0 || areaInformation.TotalCount != STRING_EMPTY)) {
                propertyType = areaInformation.TotalCount != 1 ? propertyType + 's' : propertyType;
                divPopupContainer = divPopupContainer.replace(/AREA_NAME/g, areaName);
                divPopupContainer = divPopupContainer.replace(/NUMBER_PROPERTIES/g, AddCommas(areaInformation.TotalCount));
                divPopupContainer = divPopupContainer.replace(/PROPERTY_TYPE/g, propertyType);
                divPopupContainer = divPopupContainer.replace(/CLASS/g, 'geoPinStyle');
            }

            var zoomFunction = GetOnPinClickZoomFunc(areaInformation.AreaCenter.Latitude, areaInformation.AreaCenter.Longitude);
            divPopupContainer = divPopupContainer.replace(/ZOOM/g, zoomFunction);

            return divPopupContainer;
        }
        catch (ex) {
            LogErrorMessage("GetPinshapeHTMLContent: ", ex);
        }
    }

    function GetPinShapeHTMLContentMOver(pinParameter, zoomLevel) {
        try {
            var propertyType = 'foreclosure';
            var divPopupContainer;
            divPopupContainer = HTMLTemplateGroupedPinMouseOver();

            if (zoomLevel < ZOOM_LEVEL_STATE_LIMIT_6) {
                divPopupContainer = divPopupContainer.replace(/AREA_NAME/g, pinParameter.stateCode);
                divPopupContainer = divPopupContainer.replace(/NUMBER_PROPERTIES/g, STRING_EMPTY);
                divPopupContainer = divPopupContainer.replace(/PROPERTY_TYPE/g, STRING_EMPTY);
                divPopupContainer = divPopupContainer.replace(/CLASS/g, 'geoPinStyleOverSmall');
            }
            else
                if (pinParameter.areaName != STRING_EMPTY && (pinParameter.TotalCount == 0 || pinParameter.totalCount != STRING_EMPTY)) {
                propertyType = pinParameter.TotalCount != 1 ? propertyType + 's' : propertyType;
                divPopupContainer = divPopupContainer.replace(/AREA_NAME/g, pinParameter.areaName);
                divPopupContainer = divPopupContainer.replace(/NUMBER_PROPERTIES/g, pinParameter.totalCount);
                divPopupContainer = divPopupContainer.replace(/PROPERTY_TYPE/g, propertyType);
                divPopupContainer = divPopupContainer.replace(/CLASS/g, 'geoPinStyleOver');
            }

            var zoomFunction = GetOnPinClickZoomFunc(pinParameter.latitude, pinParameter.longitude);
            divPopupContainer = divPopupContainer.replace(/ZOOM/g, zoomFunction);

            return divPopupContainer;
        }
        catch (ex) {
            LogErrorMessage("GetPinShapeHTMLContentMOver: ", ex);
        }
    }

    PinsOnMap.prototype.GetPolContVertexes = function(centerPoint) {

        var startPixel = this.curMapObject.LatLongToPixel(new VELatLong(centerPoint.AreaCenter.Latitude, centerPoint.AreaCenter.Longitude));
        var pinWidth = 106;
        var pinHeight = 47;
        var offSet = 14;

        //Set size for the PopUp
        if (centerPoint.StateCode != null && this.curMapObject.GetZoomLevel() < ZOOM_LEVEL_STATE_LIMIT_6) {
            pinWidth = 28;
            pinHeight = 41;
        }

        var polygonPins = [this.curMapObject.PixelToLatLong(new VEPixel(startPixel.x, startPixel.y)), this.curMapObject.PixelToLatLong(new VEPixel(startPixel.x - offSet, startPixel.y - offSet)), this.curMapObject.PixelToLatLong(new VEPixel(startPixel.x - (offSet * 2), startPixel.y - offSet)), this.curMapObject.PixelToLatLong(new VEPixel(startPixel.x - (offSet * 2), startPixel.y - pinHeight)), this.curMapObject.PixelToLatLong(new VEPixel(startPixel.x + pinWidth, startPixel.y - pinHeight)), this.curMapObject.PixelToLatLong(new VEPixel(startPixel.x + pinWidth, startPixel.y - offSet)), this.curMapObject.PixelToLatLong(new VEPixel(startPixel.x + offSet, startPixel.y - offSet))];

        return polygonPins;
    }

    function GetAreaName(areaInformation, zoomLevel) {
        try {
            areaName = STRING_EMPTY;
            if (areaInformation.AreaType) {
                if (areaInformation.AreaType == AREA_TYPE_NATIONAL_CODE_5) {
                    areaName = AREA_TYPE_NAME_US;
                }
                else
                    if (areaInformation.AreaType == AREA_TYPE_STATE_CODE_4) {
                    if (zoomLevel < ZOOM_LEVEL_STATE_LIMIT_6) {
                        areaName = areaInformation.StateCode;
                    }
                    else {
                        areaName = areaInformation.AreaName.substr(0, 20);
                    }
                }
                else {
                    areaName = areaInformation.AreaName.substr(0, 20);
                }
            }

            return areaName;
        }
        catch (ex) {
            LogErrorMessage("GetAreaName: ", ex);
        }
    }

    function HTMLTemplateGroupedPinMouseOver() {
        try {
            var divContainer; // = document.createElement(ELEMENT_DIVISION);
            divContainer = '<span class="CLASS" style="left: 0px; top: 0px;" onclick="javascript:ZOOM">' +
	            '<span class="cityFlagCityTextOn">' +
	            'AREA_NAME' +
	            '</span><br />' +
	            '<span class="cityFlagForeclosureTextOn">' +
	            'NUMBER_PROPERTIES PROPERTY_TYPE' +
	            '</span>' +
	            '</span>';

            return divContainer;
        }
        catch (ex) {
            LogErrorMessage("HTMLTemplateGroupedPinMouseOver: ", ex);
        }
    }

    function HTMLTemplateGroupedPin() {
        try {
            var divContainer; // = document.createElement(ELEMENT_DIVISION);
            divContainer = '<span class="CLASS" style="left: 0px; top: 0px;" onclick="javascript:ZOOM">' +
	            '<span class="cityFlagCityTextOff">' +
	            'AREA_NAME' +
	            '</span><br />' +
	            '<span class="cityFlagForeclosureTextOff">' +
	            'NUMBER_PROPERTIES PROPERTY_TYPE' +
	            '</span>' +
	            '</span>';

            return divContainer;
        }
        catch (ex) {
            LogErrorMessage("HTMLTemplateGroupedPin: ", ex);
        }
    }

    function ResizePinAnchors(divID, size) {
        try {
            var currentElement = document.getElementById(divID);

            if (currentElement && currentElement.lastChild != null) {
                currentElement.lastChild.style.width = size + 'px';
            }
        }
        catch (ex) {
            LogErrorMessage("ResizePinAnchors: ", ex);
        }
    }

    PinsOnMap.prototype.DeleteLayer = function(layerID) {
        try {
            var layer = new LayersHandling(layerID, this.curMapObject);
            if (layer.layerExist) {
                layer.DeleteCurrentLayer();
            }
        }
        catch (ex) {
            LogErrorMessage("DeleteLayer: ", ex, true);
        }
    }
}

//----------------------------  PopUps  Class --------------------------------------------------

function PopUp() {

    var HTML_TEMPLATE_POPUP_PROPERTY_TYPE = 'HmltTemplatePropertyTypePopUp';
    var HTML_TEMPLATE_POPUP_NO_DATA_FOUND = 'HmltTemplatePropertyPopUpNoData';
    var HTML_TEMPLATE_POPUP_INVALID_PASS = 'HmltTemplatePropertyPopUpInvalidPass';
    var HTML_TEMPLATE_POPUP_GROUPED = 'HtmlTemplateGroupedPopUp';
    var HTML_TEMPLATE_POPUP_UPTADE_NOW = 'HtmlTemplateUpdateNowPopUp';
    var HTML_TEMPLATE_POPUP_JOIN_NOW = 'HtmlTemplateJoinNowPopUp';

    this.currentPopup;
    this.currentPopUpID = DEFAULT_CURRENT_POPUP_ID;
    this.parentDivContainerID = PARENT_DIV_POPUP_CONTAINER_DEFAULT;
    this.isMapBirdsEyeView = false;
    this.isMember = false;
    this.positionX = null;
    this.positionY = null;
    this.latitude = null;
    this.longitude = null;
    this.layerPopUpContainer;
    this.layerPopUpID;
    this.layerName;
    this.GroupedPopUpAreaType;
    this.currentPOIResult;
    this.curMapObject = null;
    this.isSubjectPopUp = false;
    this.RemoveUnderlineFromAnchors;
    this.ValueTracMainPropData = null;
    this.removeShapes = true;
    this.isValueTrac = false;
    this.ImgBELoadingPath = '/mapsearch/images/';
    this.ImgBELoadingName = 'loading_small';
    this.pathToImgFolder = '/mapsearch/images/';
    this.PopupDivTempContainer = MAIN_DIVISION_POP_UP_CONTAINER_ID;
    this.PopupJoinNowHtmlTemplate = HTML_TEMPLATE_POPUP_JOIN_NOW;
    this.isCopyRightsLblShown = true;
    this.divMapContainer = DIV_NAME_MAP_CONTAINER_MAP_ALL;

    PopUp.prototype.IsBirdEyeView = function() {
        return this.curMapObject.GetMapStyle() == VEMapStyle.Birdseye || this.curMapObject.GetMapStyle() == VEMapStyle.BirdseyeHybrid;
    }

    PopUp.prototype.SetIsMember = function(isMember) {
        this.isMember = isMember;
    }

    PopUp.prototype.SetIsBirdEyeview = function(isBirdEyeView) {
        this.isMapBirdsEyeView = isBirdEyeView;
    }

    PopUp.prototype.SetInstanceCurMap = function(mapObj) {
        this.curMapObject = mapObj;
    }

    PopUp.prototype.SetPositionX = function(x) {
        try {
            var currentPopUp = document.getElementById(this.currentPopUpID);

            if (currentPopUp) {
                currentPopUp.style.left = x + 'px';
                this.positionX = x;
            }
        }
        catch (ex) {
            LogErrorMessage("SetPositionX: ", ex);
        }

    }

    PopUp.prototype.SetPositionY = function(y) {
        try {
            var currentPopUp = document.getElementById(this.currentPopUpID);

            if (currentPopUp) {
                currentPopUp.style.top = y + 'px';
                this.positionY = y;
            }
        }
        catch (ex) {
            LogErrorMessage("SetPositionY: ", ex, true);
        }

    }

    PopUp.prototype.ShowPopup = function() {
        try {
            if (this.layerPopUpContainer) {
                this.layerPopUpContainer.layer.Show();
            }
        }
        catch (ex) {
            LogErrorMessage("Show_CurrentPopUp: ", ex, true);
        }
    }

    PopUp.prototype.HidePopUp = function() {
        try {
            if (this.layerPopUpContainer) {
                this.layerPopUpContainer.layer.Hide();
            }
        }
        catch (ex) {
            LogErrorMessage("HidePopUp: ", ex, true);
        }
    }

    PopUp.prototype.GetLayerContainer = function(layerID) {
        try {
            var layer = new LayersHandling(layerID, this.curMapObject);
            if (layer.layerExist) {
                if (this.removeShapes) {
                    layer.DeleteAllShapesFromLayer();
                }
            }
            else {
                layer.CreateNewLayer();
            }
            return layer;
        }
        catch (ex) {
            LogErrorMessage("PopUp.prototype.GetGroupedPopUpLayer: ", ex, true);
        }
    }

    PopUp.prototype.RemoveCurrentPopUp = function() {
        try {
            if (this.layerPopUpContainer) {
                this.layerPopUpContainer.layer.DeleteAllShapes();
            }
        }
        catch (ex) {
            LogErrorMessage("RemoveCurrentPopUp: ", ex, true);
        }
    }

    PopUp.prototype.ClearPolygonPopUp = function() {
        try {
            var polygonLayer = new LayersHandling(LAYER_NAME_POLYGONS_POPUP, this.curMapObject);
            if (polygonLayer.layerExist) {
                polygonLayer.DeleteAllShapesFromLayer();
            }
        }
        catch (ex) {
            LogErrorMessage("ClearPolygonPopUp: ", ex);
        }
    }

    PopUp.prototype.AddPopUpToParentDiv = function(popUpContent) {
        try {
            var currentPopUp = document.getElementById(this.parentDivContainerID);
            if (null != currentPopUp) {
                currentPopUp.appendChild(popUpContent);
            }
        }
        catch (ex) {
            LogErrorMessage("PopUp.prototype.AddPopUpToParentDiv: ", ex);
        }
    }

    PopUp.prototype.RemoveAllFromDivContainer = function() {
        try {
            var balloon = document.getElementById(this.parentDivContainerID);

            if (null != balloon && balloon.childNodes) {
                while (balloon.childNodes.length > 0) {
                    balloon.removeChild(balloon.childNodes[0]);
                }
            }
        }
        catch (ex) {
            LogErrorMessage("RemoveAllFromDivContainer: ", ex);
        }
    }

    PopUp.prototype.RemovePopUpDivInContainer = function(poUpID) {
        try {
            var balloon = document.getElementById(this.parentDivContainerID);
            var currentPopUp = document.getElementById(poUpID);

            if (null != balloon && balloon.childNodes) {
                if (null != currentPopUp && null != currentPopUp.parentNode && currentPopUp.parentNode.id == balloon.id) {
                    balloon.removeChild(currentPopUp);
                }
            }
        }
        catch (ex) {
            LogErrorMessage("RemovePopUpDivInContainer: ", ex);
        }
    }

    PopUp.prototype.RemoveGroupedPopup = function() {
        try {
            var balloon = document.getElementById(this.parentDivContainerID);
            var groupedPopUp = document.getElementById('divGrpPopup');

            if (null != balloon && balloon.childNodes) {
                if (null != groupedPopUp && null != groupedPopUp.parentNode && groupedPopUp.parentNode.id == balloon.id) {
                    balloon.removeChild(groupedPopUp);
                }
            }
        }
        catch (ex) {
            LogErrorMessage("PopUp.prototype.RemoveGroupedPopup: ", ex);
        }
    }

    PopUp.prototype.RePosGroupedPopUp = function() {
        try {
            var divGrpPopup = document.getElementById('divGrpPopup');
            var divMenu = document.getElementById('SR_mapItems');

            if (divGrpPopup && divMenu) {
                var constantToAdd = divGrpPopup.offsetHeight;
                var top = this.curMapObject.LatLongToPixel(this.curMapObject.GetCenter(), this.curMapObject.GetZoomLevel());
                constantToAdd = (top.y * 2) - constantToAdd;

                divGrpPopup.style.top = constantToAdd + "px";
                if (divMenu.offsetWidth > 0) {
                    divGrpPopup.style.left = top.x - (eval(divGrpPopup.offsetWidth) / 2) - (divMenu.offsetWidth / 2) + 'px';
                }
                else {
                    divGrpPopup.style.left = top.x - (eval(divGrpPopup.offsetWidth) / 2) + 'px';
                }
            }
        }
        catch (ex) {
            LogErrorMessage("PopUp.prototype.RePosGroupedPopUp: ", ex);
        }
    }

    PopUp.prototype.GroupedPopup = function(areaType) {

        this.currentPopUpID = 'divGrpPopup';
        this.RemoveGroupedPopup();
        this.areaType = areaType;
        this.areaTypeName = Get_AreaTypeName(this.areaType);

        var divPopupContainer = document.createElement(ELEMENT_DIVISION);
        divPopupContainer.setAttribute('id', 'divGrpPopup');
        divPopupContainer.innerHTML = this.GetPopUpHtmlTemplate(HTML_TEMPLATE_POPUP_GROUPED);

        divPopupContainer.style.position = STYLE_POSITION_ABSOLUTE;
        divPopupContainer.innerHTML = divPopupContainer.innerHTML.replace(/AREA_NAME/g, this.areaTypeName);
        divPopupContainer.innerHTML = divPopupContainer.innerHTML.replace(/POPUPID/g, this.currentPopUpID);

        this.AddPopUpToParentDiv(divPopupContainer);

        var mapCenter = this.curMapObject.LatLongToPixel(this.curMapObject.GetCenter());
        
        var mapOnlyContainer = document.getElementById(this.parentDivContainerID);
        var mapContainer = document.getElementById(this.divMapContainer);
        if (mapOnlyContainer != null && mapContainer != null) {
            divPopupContainer.style.left = (eval(mapContainer.offsetWidth) / 2) - (eval(divPopupContainer.offsetWidth) / 2) + 'px';
            divPopupContainer.style.top = eval(mapContainer.offsetHeight) - eval(divPopupContainer.offsetHeight) + 'px';
        }
        ///  Private Functions

        function Get_AreaTypeName(Type) {
            try {
                var areaName = STRING_EMPTY;
                switch (Type.toString()) {
                    case AREA_TYPE_ZIP_CODE_1:
                        areaName = AREA_TYPE_ZIP;
                        break;
                    case AREA_TYPE_CITY_CODE_2:
                        areaName = AREA_TYPE_CITY;
                        break;
                    case AREA_TYPE_COUNTY_CODE_3:
                        areaName = AREA_TYPE_COUNTY;
                        break;
                    case AREA_TYPE_STATE_CODE_4:
                        areaName = AREA_TYPE_STATE;
                        break;
                    default:
                        areaName = AREA_TYPE_NATION;
                        break;
                }

                return areaName;
            }
            catch (ex) {
                LogErrorMessage("Get_AreaTypeName: ", ex);
            }
        }

        //// End Private functions	

    }

    PopUp.prototype.PassWordExpiredPopUp = function() {

        this.currentPopUpID = 'divPswExpired';
        var divPopupContainer = document.createElement(ELEMENT_DIVISION);
        var divMapAll = document.getElementById('mapAll');
        divPopupContainer.setAttribute('id', 'divPswExpired');

        divPopupContainer.innerHTML = this.GetPopUpHtmlTemplate(HTML_TEMPLATE_POPUP_INVALID_PASS);

        divPopupContainer.style.position = STYLE_POSITION_ABSOLUTE;
        divPopupContainer.innerHTML = divPopupContainer.innerHTML.replace(/POPUPID/g, this.currentPopUpID);

        this.AddPopUpToParentDiv(divPopupContainer);

        var mapCenter = this.curMapObject.LatLongToPixel(this.curMapObject.GetCenter());

        //Popup Positioning				
        divPopupContainer.style.height = (mapCenter.y * 2) + 'px';
        divPopupContainer.style.width = (mapCenter.x * 2) + 'px';
        divPopupContainer.style.left = '0px';
        divPopupContainer.style.top = '0px';

        var divPopUpFormContainer = document.getElementById('popUpContainerPswExpired');
        if (divPopUpFormContainer) {
            divPopUpFormContainer.style.position = 'relative';
            divPopUpFormContainer.style.backgroundColor = 'White';
            divPopUpFormContainer.style.width = '250px';
            divPopUpFormContainer.style.padding = '10px';
            divPopUpFormContainer.style.top = (mapCenter.y - (divPopUpFormContainer.offsetHeight / 2)) + 'px';
            divPopUpFormContainer.style.left = (mapCenter.x - (divPopUpFormContainer.offsetWidth / 2)) + 'px';
        }
    }

    PopUp.prototype.AddPropertyimageLink = function(property) {
        try {
            var imageLink = STRING_EMPTY;

            var propertyID = property.PropID;

            var propertyType = property.PropertyStatus;

            var propertyImageTag = "<img id='propertyImageDiv' src='" + this.ImgBELoadingPath + this.ImgBELoadingName + ".gif' width='103' height='82' alt='Property' style='border:0'>";
            var link = STRING_EMPTY;
            var hitboxName = "details";

            if (propertyID != null && propertyID != undefined && propertyID != STRING_EMPTY) {
                var propertyType = this.GetPropertyTabTypeByPropertyStatus(propertyType);
                propertyImageTag = "<img id='propertyImageDiv' src='" + this.ImgBELoadingPath + this.ImgBELoadingName + ".gif' width='103' height='82' alt='Property' style='border:0'>";
                if (typeof (property.Supplier) != "undefined" && property.Supplier != null && property.Supplier != "") {
                    if (property.Supplier.toLowerCase() == "oodle") {
                        hitboxName = "details_Map";
                        if (property.ImageLink != "undefined" && property.ImageLink != null) {
                            propertyImageTag = "<img id='propertyImageDiv1' src='" + property.ImageLink + "' width='103' height='82' alt='Property' style='border:0'>";
                        }
                    }
                }
                imageLink = g_NavigationEngine.CreatePropertyDetailsLinkForPropertyType(property, propertyImageTag, hitboxName);
            }
            else {
                propertyImageTag = "<img id='propertyImageDiv' src='" + g_NavigationEngine.SubjectImageLink(this.latitude, this.longitude) + "' width='103' height='82' alt='Property' style='border:0'>";
                imageLink = propertyImageTag;
            }

            return imageLink;
        }
        catch (ex) {
            LogErrorMessage("PopUp.prototype.AddPropertyimageLink: ", ex);
        }
    }

    PopUp.prototype.GetPropertyTabTypeByPropertyStatus = function(propertyStatus) {
        try {
            switch (propertyStatus) {
                case 'P':
                    return 'D'; // pre-foreclosure
                case 'B':
                    return 'R'; // REO		        
                case 'A':
                    return 'T'; // auction
                case 'F':
                case 'O':
                    return 'F'; // FSBO
                case 'R':
                case 'L':
                    return 'M'; // resale
                case 'G':
                    return 'G'; // government
                case 'E':
                    return 'E'; // Online Auction
            }
        }
        catch (ex) {
            LogErrorMessage("PopUp.prototype.GetPropertyTabTypeByPropertyStatus: ", ex);
        }
    }


    PopUp.prototype.AddHiddenImageLinkArray = function(propertyID, imageLink, latitude, longitude, isSubjectProperty) {
        try {
            gImageArrayPosition = 0;
            var iDCondition = (propertyID == 0 || propertyID == null || propertyID == STRING_EMPTY);
            if ((this.isValueTrac && iDCondition) || (isSubjectProperty && iDCondition)) {
                gImageArray[0] = "/birdseyeimage/propertyimage.ashx?v=N&z=30&src=mp&tn=true&Latitude=" + latitude + "&Longitude=" + longitude;
                gImageArray[1] = "/birdseyeimage/propertyimage.ashx?v=E&z=30&src=mp&tn=true&Latitude=" + latitude + "&Longitude=" + longitude;
                gImageArray[2] = "/birdseyeimage/propertyimage.ashx?v=S&z=30&src=mp&tn=true&Latitude=" + latitude + "&Longitude=" + longitude;
                gImageArray[3] = "/birdseyeimage/propertyimage.ashx?v=W&z=30&src=mp&tn=true&Latitude=" + latitude + "&Longitude=" + longitude;
            }
            else {
                if (imageLink == "" || imageLink == IMAGE_LINK_NA) {
                    gImageArray[0] = "/birdseyeimage/propertyimage.ashx?v=N&z=30&src=mp&tn=true&propid=" + propertyID;
                    gImageArray[1] = "/birdseyeimage/propertyimage.ashx?v=E&z=30&src=mp&tn=true&propid=" + propertyID;
                    gImageArray[2] = "/birdseyeimage/propertyimage.ashx?v=S&z=30&src=mp&tn=true&propid=" + propertyID;
                    gImageArray[3] = "/birdseyeimage/propertyimage.ashx?v=W&z=30&src=mp&tn=true&propid=" + propertyID;
                }
                else {
                    gImageArray[0] = imageLink;//"/birdseyeimage/propertyimage.ashx?v=N&z=30&src=mp&tn=true&Latitude=" + latitude + "&Longitude=" + longitude;
                    gImageArray[1] = "/birdseyeimage/propertyimage.ashx?v=N&z=30&src=mp&tn=true&propid=" + propertyID;
                    gImageArray[2] = "/birdseyeimage/propertyimage.ashx?v=E&z=30&src=mp&tn=true&propid=" + propertyID;
                    gImageArray[3] = "/birdseyeimage/propertyimage.ashx?v=S&z=30&src=mp&tn=true&propid=" + propertyID;
                    gImageArray[4] = "/birdseyeimage/propertyimage.ashx?v=W&z=30&src=mp&tn=true&propid=" + propertyID;
                }
            }
            imageLink = gImageArray[gImageArrayPosition];

            //PT: 08/26/2007 When in Dev, if the imageLink which takes its value from
            //gImageArray array object, and if the gImageArray obj cannt referecen the
            //valid image url generation box, we'll get "Stack Overflow at line 0"
            //However, good thing, this wont happen in Prod or anything that has the /BirdEyesView/ app running
            //So, for now, comment this out so that it works in IE in DEV
            document.getElementById('hiddenImage').src = imageLink;

        }
        catch (ex) {
            LogErrorMessage("PopUp.prototype.AddHiddenImageLinkArray: ", ex);
        }
    }
    //.SalePrice, this.propDetails.SoldPrice, this.propDetails.PropID, this.propDetails.PropertyStatus
    PopUp.prototype.AddPropertyDetailsLink = function(propDetails) {
        try {
            var hitboxName = "details";
            if (typeof PopUp._initialized == STRING_TEXT_UNDEFINED) {
                var linkCreated = STRING_EMPTY;

                if (propDetails.SoldPrice == PRICE_ZERO) {
                    linkCreated = '<b>More Details</b>';
                }
                else {
                    linkCreated = '<b><font color="#DD001B">Sold&nbsp;Data</font></b>';
                }
                //this.propDetails.Supplier;
                if (typeof (propDetails.Supplier) != "undefined" && propDetails.Supplier != null && propDetails.Supplier != "") {
                    if (propDetails.Supplier.toLowerCase() == "oodle") {
                        hitboxName = "details_Map";
                    }
                }

                linkCreated = g_SEONavigationEngine.CreateLink(g_SEONavigationEngine.PropertyDetailsPage.GetUrl(propDetails.PropID, propDetails.Details[0].FieldValue, 
                                    propDetails.Details[1].FieldValue, propDetails.Details[2].FieldValue, propDetails.Details[3].FieldValue, 'details'),
                                linkCreated, hitboxName, false, true); 
                
                //g_NavigationEngine.CreatePropertyDetailsLinkForPropertyType(propDetails, linkCreated, hitboxName);

                return linkCreated;
            }
        }
        catch (ex) {
            LogErrorMessage("PopUp.prototype.AddPropertyDetailsLink: ", ex);
        }

    }

    PopUp.prototype.AddBidLink = function(propertyType, propertyID, supplier) {
        try {

            if (typeof PopUp._initialized == STRING_TEXT_UNDEFINED) {
                var bidLink = STRING_EMPTY;

                if (propertyType == PROPERTY_TYPE_ONLINE_AUCTION) {
                    if (typeof (gIsInternationalUser) != "undefined" && gIsInternationalUser != null && gIsInternationalUser
	                                && typeof (supplier) != "undefined" && supplier != null && supplier.toLowerCase() == "bid4assets") {
                        bidLink = "<a href='javascript:alert(\"We are sorry, our bid partners currently only accepts online bids from consumers residing within the United States.\");' onclick='javascript:alert(\"We are sorry, our bid partners currently only accepts online bids from consumers residing within the United States.\");'><b><font color='#DD001B'>Bid&nbsp;Now</font></b></a>";
                    }
                    else {
                        bidLink = g_NavigationEngine.CreatePropertyBidLink(propertyID, '<b><font color="#DD001B">Bid&nbsp;Now</font></b>', 'bid');
                    }
                }

                return bidLink;
            }
        }
        catch (ex) {
            LogErrorMessage("PopUp.prototype.AddBidLink: ", ex);
        }
    }

    PopUp.prototype.AddComparableSalesLink = function(propertyType, propertyDetails, hasComparableSales, isMakeOffer) {
        try {
            if (typeof PopUp._initialized == STRING_TEXT_UNDEFINED) {
                var comparableSalesLink;

                if (hasComparableSales && propertyType != PROPERTY_TYPE_ONLINE_AUCTION && isMakeOffer == 0) {
                    comparableSalesLink = 
                        g_SEONavigationEngine.CreateLink(g_SEONavigationEngine.PropertyDetailsPage.GetUrl(propertyDetails.PropID, propertyDetails.Details[0].FieldValue, 
                                    propertyDetails.Details[1].FieldValue, propertyDetails.Details[2].FieldValue, propertyDetails.Details[3].FieldValue, 'comparable-sales'),
                                '<b>Comp Sales</b>', 'comps', false, true); 
                    //g_NavigationEngine.CreatePropertyReportsLink(propertyID, this.GetPropertyTabTypeByPropertyStatus(propertyType), 1, '<b>Comp Sales</b>', 'comps');
                }
                if (comparableSalesLink == undefined) {
                    comparableSalesLink = STRING_EMPTY;
                }

                return comparableSalesLink;
            }
        }
        catch (ex) {
            LogErrorMessage("PopUp.prototype.AddComparableSalesLink: ", ex);
        }
    }

    PopUp.prototype.AddMakeOfferLink = function(propertyType, propertyID, isMakeOffer, isSold) {
        try {
            if (typeof PopUp._initialized == STRING_TEXT_UNDEFINED) {
                var makeOfferLink = STRING_EMPTY;

                if (propertyType == 'B' && isMakeOffer && !isSold) {
                    makeOfferLink = g_NavigationEngine.CreateMakeOfferLink(propertyID, '<b>Make Offer</b>', 'makeoffer');
                }

                return makeOfferLink;
            }
        }
        catch (ex) {
            LogErrorMessage("AddMakeOfferLink: ", ex);
        }
    }

    PopUp.prototype.AddLienLoanHistory = function(propertyType, propertyID, hasLien, isMakeOffer) {
        try {
            if (typeof PopUp._initialized == STRING_TEXT_UNDEFINED) {
                var lienLoanHistoryLink;

                if (hasLien && propertyType != PROPERTY_TYPE_ONLINE_AUCTION && !isMakeOffer) {
                    lienLoanHistoryLink = g_NavigationEngine.CreatePropertyReportsLink(propertyID, this.GetPropertyTabTypeByPropertyStatus(propertyType), 2, '<b>Lien&nbsp;&amp;&nbsp;Loan&nbsp;History</b>', 'loanHistory');
                }
                if (lienLoanHistoryLink == undefined) {
                    lienLoanHistoryLink = STRING_EMPTY;
                }

                return lienLoanHistoryLink;
            }
        }
        catch (ex) {
            LogErrorMessage("PopUp.prototype.AddLienLoanHistory: ", ex);
        }

    }

    PopUp.prototype.AddLinkRepairCost = function(repairCost, propertyID) {
        var link = STRING_EMPTY;
        if (null != repairCost && repairCost > 0) {
            var url = '/PropertyDetails/PropertyDetails.aspx?propid=' + propertyID + '&reportTab=4';
            link = '<li>Est. Cost to Restore: <span onclick="javascript:window.location=\'' + url + '\';"><a href="' + url + '" style="width:60px;">$' +
                            AddCommas(Math.round(repairCost)) + '</a></span></li>';
        }
        return link;
    }

    //This function was added to add Free trial link according new mapping functional requirements
    //10/21/2008
    PopUp.prototype.AddLinkFreeTrial = function(propertyId, isMember, propertyType, IsFreeTrialLinkFull) {
        try {
            var registrationLink = STRING_EMPTY;
            if (typeof PopUp._initialized == STRING_TEXT_UNDEFINED) {

                if (!isMember) {
                    var link = g_NavigationEngine.RegistrationPage(propertyId);
                    GetCompleteAddressWithALink = '';

                    if (IsFreeTrialLinkFull) {
                        GetCompleteAddressWithALink = "<div style='width:100%; color:red; font-size:small; font-weight:bolder; font-style:italic; margin:15px 0px 0px 0px;padding-bottom:5px; text-align:center; background-color:#FEF9D9;'>Get complete address with a</div>";
                    }
                    registrationLink = GetCompleteAddressWithALink + "<div style='width:100%; font-size:small; font-weight:bolder; margin:0px 0px 10px 0px; text-align:center; background-color:#FEF9D9;'>" +
	                            "<a name='7DayFreeTrial' href='" +
	                            link +
	                            "' target='" +
	                            g_NavigationEngine.Target() +
	                            "' onclick='javascript:window.location=\"" + link + "\";'>" +
	                            "<b>7-Day FREE Trial</b></a></div>";

                }
            }
            return registrationLink;
        }
        catch (ex) {
            LogErrorMessage("PopUp.prototype.AddLinkFreeTrial: ", ex);
        }
    }

    PopUp.prototype.AddLinkUpgradeFreeTrial = function(propertyId, propertyType, isMember, isWhiteSiteRegionalUpgrade) {
        try {
            if (typeof PopUp._initialized == STRING_TEXT_UNDEFINED) {
                if (!isMember && propertyType != PROPERTY_TYPE_ONLINE_AUCTION) {
                    var registrationLink = STRING_EMPTY;
                    registrationLink = g_NavigationEngine.RegistrationPage(propertyId);
                    return LinkFreeTrial(registrationLink);
                }
                else
                    if (isWhiteSiteRegionalUpgrade) {
                    var upgradeLink = STRING_EMPTY;
                    upgradeLink = g_NavigationEngine.RegistrationPage(propertyId);
                    return LinkUpgrade(upgradeLink);
                }
            }
        }
        catch (ex) {
            LogErrorMessage("PopUp.prototype.AddLinkUpgradeFreeTrial: ", ex);
        }
    }

    PopUp.prototype.LinkFreeTrial = function(registrationLink) {
        try {
            if (typeof PopUp._initialized == STRING_TEXT_UNDEFINED) {
                var joinNowLink = STRING_EMPTY;
                joinNowLink = "<div class='txt_highlight bold'>Complete&nbsp;Address&nbsp;FREE&nbsp;with&nbsp;7-Day&nbsp;Trial!</div>";
                joinNowLink += "<a name='&amp;lid=getStarted' href='" + registrationLink + "' class='get_started_lnk' target='" + g_NavigationEngine.Target() + "'><strong>GET&nbsp;STARTED!</strong></a>";
                joinNowLink += "<a name='&amp;lid=joinNow' href='" + registrationLink + "' target='" + g_NavigationEngine.Target() + "'><img src='/mapsearch/images/button_JoinNow_Blue_84x21.gif' width='84' height='21' alt='Join NOW' class='join_now_btn'></a></div>";
                return joinNowLink;
            }
        }
        catch (ex) {
            LogErrorMessage("PopUp.prototype.LinkFreeTrial: ", ex);
        }
    }

    PopUp.prototype.LinkUpgrade = function(upgradeLink) {
        try {
            if (typeof PopUp._initialized == STRING_TEXT_UNDEFINED) {
                var joinNowLink = STRING_EMPTY;
                joinNowLink = "<div class='txt_highlight bold'>Complete&nbsp;Address&nbsp;FREE&nbsp;with&nbsp;Upgrade!</div>";
                joinNowLink += "<a name='&amp;lid=upgrade' href='" + upgradeLink + "' class='get_started_lnk' target='" + g_NavigationEngine.Target() + "'><strong>GET&nbsp;STARTED!</strong></a>";
                joinNowLink += "<a name='&amp;lid=upgradeNow' href='" + upgradeLink + "' target='" + g_NavigationEngine.Target() + "'><img src='/mapsearch/images/buttons/upgrade_button_small.gif' width='87' height='23' alt='Upgrade NOW' class='join_now_btn'></a></div>";
                return joinNowLink;
            }
        }
        catch (ex) {
            LogErrorMessage("PopUp.prototype.LinkUpgrade: ", ex);
        }
    }
    PopUp.prototype.SubjectPopUpDetailsValues = function(fieldName, fieldValue) {
        try {
            var parameters = new Object();

            parameters.FieldValue = fieldValue;
            parameters.FieldName = fieldName;

            return parameters;
        }
        catch (ex) {
            LogErrorMessage("PopUp.prototype.SubjectPopUpDetails: ", ex);
        }
    }

    PopUp.prototype.SubjectPopUpDetails = function() {
        try {
            var addressToShow = gCriteriaValue;
            var partAddress = addressToShow.substring(0, addressToShow.indexOf(','));
            var tempString = addressToShow.substring(addressToShow.indexOf(',') + 1);
            var partCity = tempString.substring(0, tempString.indexOf(','));
            var partStateZip = tempString.substring(tempString.indexOf(',') + 1);

            var Details = new Array();

            Details[0] = this.SubjectPopUpDetailsValues('PROPERTY_ADDRESS_TOKEN', partAddress);
            Details[1] = this.SubjectPopUpDetailsValues('PROPERTY_CITY_TOKEN', partCity);
            Details[2] = this.SubjectPopUpDetailsValues('PROPERTY_STATE_TOKEN', partStateZip);
            return Details;
        }
        catch (ex) {
            LogErrorMessage("PopUp.prototype.SubjectPopUpDetails: ", ex);
        }
    }

    PopUp.prototype.SubjectPopUpHeader = function() {
        try {
            var Header = new Object;
            Header.Text = 'Subject Property';
            Header.CssClass = 'preForeclosure bold';

            return Header;
        }
        catch (ex) {
            LogErrorMessage("PopUp.prototype.SubjectPopUpHeader: ", ex);
        }
    }

    PopUp.prototype.GetSubjectPropertyPopUpInfo = function() {
        try {
            var pix = new VEPixel(this.positionX, this.positionY);
            var latLong = this.curMapObject.PixelToLatLong(pix);

            var result = new Object;
            result.Details = this.SubjectPopUpDetails();
            result.Header = this.SubjectPopUpHeader();
            result.ImageLink = STRING_EMPTY;
            result.SanitizeType = null;
            result.InvalidPassport = this.isInvalidPassport;
            return result;
        }
        catch (ex) {
            LogErrorMessage("PopUp.prototype.GetSubjectPropertyPopUpInfo: ", ex);
        }
    }

    PopUp.prototype.SubjectPopUp = function() {
        this.UpdateCoordPix();
        this.currentPopUpID = DIV_PROPERTYDETAILS_POUP_CONTAINER + 'SubjectProperty';
        this.propDetails = this.GetSubjectPropertyPopUpInfo();

        this.layerName = LAYER_NAME_PROPERTY_TYPE_POPUP;
        this.layerPopUpContainer = this.GetLayerContainer(LAYER_NAME_PROPERTY_TYPE_POPUP);
        this.layerPopUpID = this.layerPopUpContainer.layerID;
        this.isSubjectProperty = false;
        this.isWhiteSiteRegionalUpgrade = false;

        this.RemoveAllFromDivContainer();

        if (this.InvalidPassport) {

            this.PassWordExpiredPopUp();
            return;
        }

        this.htmlContent = document.createElement(ELEMENT_DIVISION);

        this.isSubjectProperty = true;
        gSubjectProperty = false;

        this.htmlContent.innerHTML = this.GetPopUpHtmlTemplate('HmltTemplateSubjectPopUp');

        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/POPUPID/g, this.layerPopUpContainer.layerID);
        this.birdEyeSectionContent = this.AddPropertyimageLink(this.propDetails);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/REPLACE_BIRDEYECONTENT/g, this.birdEyeSectionContent);

        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/HEADER_TOKEN/g, (this.propDetails.Header.Text != null) ? this.propDetails.Header.Text : 'Subject Property');
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/class_token/g, (this.propDetails.Header.CssClass != null) ? ('class="' + this.propDetails.Header.CssClass + '"') : STRING_EMPTY);
        for (var i = 0; i <= this.propDetails.Details.length - 1; i++) {
            this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(this.propDetails.Details[i].FieldName, (this.propDetails.Details[i].FieldValue != null && this.propDetails.Details[i].FieldValue != '0' && this.propDetails.Details[i].FieldValue != '0.0' && this.propDetails.Details[i].FieldValue != STRING_EMPTY) ? this.propDetails.Details[i].FieldValue : 'NA');
        }
        var arrowPos = this.AddArrows(this.isMapBirdsEyeView, this.latitude, this.longitude, this.positionX, this.positionY, this.curMapObject);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/REPLACE_ARROWS/g, arrowPos);

        var linkToProp = null;

        if (typeof (hideViewHomeValue) == "undefined" || !hideViewHomeValue) {
            linkToProp = g_SEONavigationEngine.CreateLink(
                g_SEONavigationEngine.ValueTracPage.GetUrl(this.propDetails.StateCode, "", this.propDetails.CityName, this.propDetails.Zip, this.propDetails.StreetAddress),
                'View Home Value', 'linkPropFullDetails', false, true);
            //linkToProp = g_NavigationEngine.ValueTracPropFullDetails(gCriteriaValue, 'View Home Value', 'linkPropFullDetails');
        }


        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/LINK_VALUE_TRAC_TOKEN/g, (linkToProp != null) ? linkToProp : STRING_EMPTY);

        this.AddPopupToMap(this.htmlContent);
        this.AddHiddenImageLinkArray(this.propDetails.PropID, this.propDetails.ImageLink, this.latitude, this.longitude, this.isSubjectProperty);
    }

    PopUp.prototype.NoDataFoundPopUp = function() {
        this.UpdateCoordPix();
        this.currentPopUpID = DIV_PROPERTYDETAILS_POUP_CONTAINER;
        this.layerName = LAYER_NAME_PROPERTY_TYPE_POPUP;
        this.layerPopUpContainer = this.GetLayerContainer(LAYER_NAME_PROPERTY_TYPE_POPUP);
        this.layerPopUpID = this.layerPopUpContainer.layerID;
        this.htmlContent = document.createElement(ELEMENT_DIVISION);

        this.htmlContent.innerHTML = this.GetPopUpHtmlTemplate(HTML_TEMPLATE_POPUP_NO_DATA_FOUND);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/REPLACE_ARROWS/g, this.AddArrows(false, '', '', this.positionX, this.positionY, this.curMapObject));
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/POPUPID/g, this.layerPopUpContainer.layerID);

        this.AddPopupToMap(this.htmlContent, this.propDetails);
    }

    PopUp.prototype.UpdateCoordPix = function() {
        if (this.latitude != null && this.longitude != null && this.latitude != 'null' && this.longitude != 'null') {
            var pixels = this.curMapObject.LatLongToPixel(new VELatLong(this.latitude, this.longitude));

            this.positionX = pixels.x;
            this.positionY = pixels.y;
        }
    }

    PopUp.prototype.InteractiveMapPopUp = function(pinPropertyData, id) {


        this.currentPopUpID = DIV_PROPERTYDETAILS_POUP_CONTAINER;
        this.UpdateCoordPix();
        this.propDetails = pinPropertyData;
        this.layerName = LAYER_NAME_PROPERTY_TYPE_POPUP;
        this.layerPopUpContainer = this.GetLayerContainer(LAYER_NAME_PROPERTY_TYPE_POPUP);
        this.layerPopUpID = this.layerPopUpContainer.layerID;

        this.htmlContent = document.createElement(ELEMENT_DIVISION);
        this.htmlContent.innerHTML = this.GetPopUpHtmlTemplate('HmltTemplateInteractiveMapPopUp');

        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/POPUPID/g, this.layerPopUpContainer.layerID);

        this.birdEyeSectionContent = this.AddPropertyimageLink(this.propDetails);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/REPLACE_BIRDEYECONTENT/g, this.birdEyeSectionContent);

        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/DEFAULT_PRICE_TOKEN/g, (this.propDetails.EstimatedValue.EstimateValue != null) ? AddCommas(this.propDetails.EstimatedValue.EstimateValue) : STRING_EMPTY);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/PROPERTY_ADDRESS_TOKEN/g, (this.propDetails.StreetAddress != null) ? this.propDetails.StreetAddress : STRING_EMPTY);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/PROPERTY_CITY_STATE_ZIP_TOKEN/g, (this.propDetails.CityStateZip != null) ? this.propDetails.CityStateZip : STRING_EMPTY);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/PROPERTY_BEDS_TOKEN/g, (this.propDetails.Beds != null && this.propDetails.Beds > 0) ? '<li>' + this.propDetails.Beds + '</li>' : STRING_EMPTY);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/PROPERTY_BATHS_TOKEN/g, (this.propDetails.Baths != null && this.propDetails.Baths > 0) ? '<li>' + this.propDetails.Baths + '</li>' : STRING_EMPTY);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/PROPERTY_SQFEET_TOKEN/g, (this.propDetails.SquareFeet != null && this.propDetails.SquareFeet > 0) ? '<li>' + AddCommas(this.propDetails.SquareFeet) + ' sq. ft.</li>' : STRING_EMPTY);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/ESTIMATED_VALUE_TOKEN/g, (this.propDetails.EstimatedValue != null) ? '<li><span class="blue">Est Value $' + AddCommas(this.propDetails.EstimatedValue) + '</strong></span></li>' : STRING_EMPTY);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/LAST_SALE_TOKEN/g, (this.propDetails.FormattedPrice != null) ? '<li><span class="red"><strong>Last Sale</strong></span> $' + this.propDetails.FormattedPrice + '</li>' : STRING_EMPTY);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/DATE_SALE_TOKEN/g, (this.propDetails.SaleDate != null) ? '<li><span class="red"><strong> Sale Date</strong></span> ' + this.propDetails.SaleDate.format('MM/dd/yyyy') + '</li>' : STRING_EMPTY);
        var FormatedAddress = this.propDetails.StreetAddress + ', ' + this.propDetails.CityStateZip;
        
        var linkToProp = g_SEONavigationEngine.CreateLink(
                g_SEONavigationEngine.ValueTracPage.GetUrl(this.propDetails.StateCode, "", this.propDetails.CityName, this.propDetails.Zip, this.propDetails.StreetAddress),
                'View Home Value', 'linkPropFullDetails', false, true);
        
        //var linkToProp = g_NavigationEngine.ValueTracPropFullDetails(FormatedAddress, 'See Full Details', 'linkPropFullDetails');
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/REPLACE_LINK_FULL_DETAILS/g, (linkToProp != null) ? linkToProp : STRING_EMPTY);

        var arrowPos = this.AddArrows(this.isMapBirdsEyeView, this.latitude, this.longitude, this.positionX, this.positionY, this.curMapObject);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/REPLACE_ARROWS/g, arrowPos);

        this.AddHiddenImageLinkArray(this.propDetails.PropID, this.propDetails.ImageLink, this.latitude, this.longitude, this.isSubjectProperty);

        this.AddPopupToMap(this.htmlContent, this.propDetails);

    }

    PopUp.prototype.ValueTracNeigHoodSalesPopUp = function(pinPropertyData, id) {

        this.currentPopUpID = DIV_PROPERTYDETAILS_POUP_CONTAINER;
        this.UpdateCoordPix();
        this.propDetails = pinPropertyData;
        this.layerName = LAYER_NAME_PROPERTY_TYPE_POPUP;
        this.layerPopUpContainer = this.GetLayerContainer(LAYER_NAME_PROPERTY_TYPE_POPUP);
        this.layerPopUpID = this.layerPopUpContainer.layerID;

        this.htmlContent = document.createElement(ELEMENT_DIVISION);
        this.htmlContent.innerHTML = this.GetPopUpHtmlTemplate('HmltTemplateNeighborhoodSalesValPopUp_B');

        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/POPUPID/g, this.layerPopUpContainer.layerID);

        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/IMAGE_TOKEN/g, (id != null) ? '<img src="/mapsearch/images/numberBalloon_map_' + (eval(id) + 1) + '.gif" alt="" />' : STRING_EMPTY);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/PROPERTY_ADDRESS_TOKEN/g, (this.propDetails.Address != null) ? this.propDetails.Address : STRING_EMPTY);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/PROPERTY_CITY_TOKEN/g, (this.propDetails.City != null) ? this.propDetails.City : STRING_EMPTY);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/PROPERTY_STATE_TOKEN/g, (this.propDetails.State != null) ? this.propDetails.State : STRING_EMPTY);
        var zipCode = this.propDetails.Zip;
        if (zipCode != null && zipCode.length > 5) {
            zipCode = zipCode.substring(0, 5);
        }
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/PROPERTY_ZIP_TOKEN/g, (zipCode != null) ? zipCode : STRING_EMPTY);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/PROPERTY_BEDS_TOKEN/g, (this.propDetails.Bedrooms != null && this.propDetails.Bedrooms > 0) ? this.propDetails.Bedrooms : 'NA');
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/PROPERTY_BATHS_TOKEN/g, (this.propDetails.TotalBaths != null && this.propDetails.TotalBaths > 0) ? this.propDetails.TotalBaths : 'NA');
        var saleDate = this.propDetails.SaleDate;
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/DATE_SALE_TOKEN/g, (this.propDetails.SaleDate != null) ? this.propDetails.SaleDate.format('MM/dd/yyyy') : STRING_EMPTY);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/PRICE_SALES_TOKEN/g, (this.propDetails.SalePrice != null) ? '$' + AddCommas(this.propDetails.SalePrice) : STRING_EMPTY);
        var arrowPos = this.AddArrows(this.isMapBirdsEyeView, this.latitude, this.longitude, this.positionX, this.positionY, this.curMapObject);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/REPLACE_ARROWS/g, arrowPos);

        this.AddHiddenImageLinkArray(this.propDetails.PropID, this.propDetails.ImageLink, this.latitude, this.longitude, this.isSubjectProperty);

        this.AddPopupToMap(this.htmlContent, this.propDetails);
    }

    PopUp.prototype.ValueTracMainProp = function() {

        if (this.ValueTracMainPropData == null) {
            this.NoDataFoundPopUp();
            return;
        }
        this.currentPopUpID = DIV_PROPERTYDETAILS_POUP_CONTAINER;
        this.UpdateCoordPix();
        this.propDetails = this.ValueTracMainPropData;
        this.layerName = LAYER_NAME_PROPERTY_TYPE_POPUP;
        this.layerPopUpContainer = this.GetLayerContainer(LAYER_NAME_PROPERTY_TYPE_POPUP);
        this.layerPopUpID = this.layerPopUpContainer.layerID;

        this.htmlContent = document.createElement(ELEMENT_DIVISION);
        this.htmlContent.innerHTML = this.GetPopUpHtmlTemplate('HmltTemplateMainPropNeightborHValPopUp');

        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/POPUPID/g, this.layerPopUpContainer.layerID);
        this.birdEyeSectionContent = this.AddPropertyimageLink(this.propDetails);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/REPLACE_BIRDEYECONTENT/g, this.birdEyeSectionContent);

        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/DEFAULT_PRICE_TOKEN/g, (this.propDetails.EstimatedValue.EstimateValue != null) ? AddCommas(this.propDetails.EstimatedValue.EstimateValue) : STRING_EMPTY);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/PROPERTY_ADDRESS_TOKEN/g, (this.propDetails.Address.StreetAddress != null) ? this.propDetails.Address.StreetAddress : STRING_EMPTY);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/PROPERTY_CITY_TOKEN/g, (this.propDetails.Address.City != null) ? this.propDetails.Address.City : STRING_EMPTY);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/PROPERTY_STATE_TOKEN/g, (this.propDetails.Address.State != null) ? this.propDetails.Address.State : STRING_EMPTY);
        var zipCode = this.propDetails.Address.Zip;
        if (zipCode != null && zipCode.length > 5) {
            zipCode = zipCode.substring(0, 5);
        }
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/PROPERTY_ZIP_TOKEN/g, (zipCode != null) ? zipCode : STRING_EMPTY);

        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/PROPERTY_BEDS_TOKEN/g, (this.propDetails.Beds != null && this.propDetails.Beds > 0) ? '<li>' + this.propDetails.Beds + '</li>' : STRING_EMPTY);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/PROPERTY_BATHS_TOKEN/g, (this.propDetails.Baths != null && this.propDetails.Baths > 0) ? '<li>' + this.propDetails.Baths + '</li>' : STRING_EMPTY);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/PROPERTY_SQFEET_TOKEN/g, (this.propDetails.SquareFeet != null && this.propDetails.LivingArea > 0) ? '<li>' + AddCommas(this.propDetails.LivingArea) + ' sq. ft.</li>' : STRING_EMPTY);

        var addressFormated = this.propDetails.Address.StreetAddress + ', ' + this.propDetails.Address.City + ', ' + this.propDetails.Address.State + ' ' + this.propDetails.Address.Zip;
        
        var linkToProp = g_SEONavigationEngine.CreateLink(
                g_SEONavigationEngine.ValueTracPage.GetUrl(this.propDetails.Address.State, "", this.propDetails.Address.City, this.propDetails.Address.Zip.substring(0,5), this.propDetails.Address.StreetAddress),
                'View Home Value', 'linkPropFullDetails', false, true);
        //var linkToProp = g_NavigationEngine.ValueTracPropFullDetails(addressFormated, 'See Full Details', 'linkPropFullDetails');
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/REPLACE_LINK_FULL_DETAILS/g, (linkToProp != null) ? linkToProp : STRING_EMPTY);



        var arrowPos = this.AddArrows(this.isMapBirdsEyeView, this.latitude, this.longitude, this.positionX, this.positionY, this.curMapObject);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/REPLACE_ARROWS/g, arrowPos);

        this.AddHiddenImageLinkArray(this.propDetails.PropID, this.propDetails.ImageLink, this.latitude, this.longitude, this.isSubjectProperty);

        this.AddPopupToMap(this.htmlContent, this.propDetails);
    }

    PopUp.prototype.PropertyTypePopUp = function(pinPropertyData) {
        
        this.currentPopUpID = DIV_PROPERTYDETAILS_POUP_CONTAINER;
        this.UpdateCoordPix();
        this.posX = this.positionX;
        this.posY = this.positionY;

        this.propDetails = pinPropertyData;

        this.layerName = LAYER_NAME_PROPERTY_TYPE_POPUP;
        this.layerPopUpContainer = this.GetLayerContainer(LAYER_NAME_PROPERTY_TYPE_POPUP);
        this.layerPopUpID = this.layerPopUpContainer.layerID;
        this.isSubjectProperty = false;
        this.isWhiteSiteRegionalUpgrade = false;

        if (typeof PopUp._initialized != STRING_TEXT_UNDEFINED) {
            PopUp._initialized = undefined;
            this.RemoveAllFromDivContainer();
        }

        if (this.isInvalidPassport) {
            this.PassWordExpiredPopUp();
            return;
        }
        this.propDetails = pinPropertyData;
        this.htmlContent = document.createElement(ELEMENT_DIVISION);
        ///////////////// Start Generation of Content ////////////////////////

        if (this.propDetails.SanitizeType != null) {
            this.isWhiteSiteRegionalUpgrade = (this.propDetails.SanitizeType == 2);
        }

        this.isInvalidPassport = this.propDetails.InvalidPassport;

        this.htmlContent.innerHTML = this.GetPopUpHtmlTemplate(HTML_TEMPLATE_POPUP_PROPERTY_TYPE);

        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/POPUPID/g, this.layerPopUpContainer.layerID);
        this.birdEyeSectionContent = this.AddPropertyimageLink(this.propDetails);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/REPLACE_BIRDEYECONTENT/g, this.birdEyeSectionContent);

        if (this.propDetails.Header != null) {
            this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/HEADER_TOKEN/g, '<li class_token>' + ((this.propDetails.Header.Text != null) ? this.propDetails.Header.Text : 'Subject Property') + '</li>');
            this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/class_token/g, (this.propDetails.Header.CssClass != null) ? ('class="' + this.propDetails.Header.CssClass + '"') : STRING_EMPTY);
        }
        if (this.propDetails.Details != null) {
            var addSlash = false;
            var tempText;
            var beds;
            var bath;
            var isNotEmptyValue;
            var currentDetail;
            var skipReplace;
            var city = STRING_EMPTY;
            var state = STRING_EMPTY;
            var zip = STRING_EMPTY;

            var supplier = null;
            var addresInfo = STRING_EMPTY;
            var cityStateZipInfo = STRING_EMPTY;

            if (typeof (this.propDetails.Supplier) != "undefined" && this.propDetails.Supplier != null && this.propDetails.Supplier != "") {
                supplier = this.propDetails.Supplier;
            }

            for (var i = 0; i <= this.propDetails.Details.length - 1; i++) {
                skipReplace = false;
                tempText = STRING_EMPTY;
                currentDetail = this.propDetails.Details[i];

                switch (currentDetail.FieldName) {
                    case 'DEFAULT_PRICE_TOKEN':
                        if (this.propDetails.SoldPrice == PRICE_ZERO) {
                            tempText = currentDetail.FieldValue;

                            if (supplier.toLowerCase() == "oodle") {
                                tempText = g_NavigationEngine.CreatePropertyDetailsLinkForPropertyType(this.propDetails, tempText, "details_Map");
                            }

                            tempText = ELEMENT_OPEN_TAG_LI + 'Amount: ' + tempText + ELEMENT_CLOSE_TAG_LI;
                        }
                        else {
                            tempText = ELEMENT_OPEN_TAG_LI + 'Amount: <b><font color="#DD001B">SOLD</font></b>';
                            if (this.isMember && !this.isWhiteSiteRegionalUpgrade) {
                                tempText = tempText + ELEMENT_OPEN_TAG_LI + ' <div class="txt_highlight bold">Sales&nbsp;Price:&nbsp;' + this.propDetails.SoldPrice + ' </div>' + ELEMENT_CLOSE_TAG_LI + ELEMENT_CLOSE_TAG_LI;
                            }
                        }
                        break;

                    case 'DEFAULT_DATE_TOKEN':
                        if (supplier.toLowerCase() != "oodle") {
                            tempText = (currentDetail.FieldValue == STRING_EMPTY || currentDetail.FieldValue == '1/1/0001') ? STRING_EMPTY : ELEMENT_OPEN_TAG_LI + currentDetail.Title + ': ' + currentDetail.FieldValue + ELEMENT_CLOSE_TAG_LI;
                        }
                        break;

                    case 'PROPERTY_BEDS_TOKEN':
                        beds = (eval(currentDetail.FieldValue) == 1) ? ' bed' : ' beds';
                        tempText = (currentDetail.FieldValue == STRING_EMPTY || currentDetail.FieldValue == '0.0' || currentDetail.FieldValue == '0') ? STRING_EMPTY : ELEMENT_OPEN_TAG_LI + currentDetail.FieldValue + beds;
                        addSlash = (tempText != STRING_EMPTY);
                        break;

                    case 'PROPERTY_SQFEET_TOKEN':
                        tempText = (currentDetail.FieldValue == STRING_EMPTY || currentDetail.FieldValue == '0.0' || currentDetail.FieldValue == '0') ? STRING_EMPTY : ELEMENT_OPEN_TAG_LI + AddCommas(currentDetail.FieldValue) + ' sq. ft.' + ELEMENT_CLOSE_TAG_LI;
                        break;

                    case 'PROPERTY_BATHS_TOKEN':
                        bath = (eval(currentDetail.FieldValue) > 1) ? ' baths' : ' bath';

                        if (addSlash && currentDetail.FieldValue != STRING_EMPTY && currentDetail.FieldValue != '0.0' && currentDetail.FieldValue != '0') {
                            tempText = ' / ' + currentDetail.FieldValue + bath + ELEMENT_CLOSE_TAG_LI;
                        }
                        else if (addSlash && (currentDetail.FieldValue == STRING_EMPTY || currentDetail.FieldValue == '0.0' || currentDetail.FieldValue == '0')) {
                            tempText = ELEMENT_CLOSE_TAG_LI;
                        }
                        else if (!addSlash && currentDetail.FieldValue != STRING_EMPTY && currentDetail.FieldValue != '0.0' && currentDetail.FieldValue != '0') {
                            tempText = ELEMENT_OPEN_TAG_LI + currentDetail.FieldValue + bath + ELEMENT_CLOSE_TAG_LI;
                        }
                        else {
                            tempText = STRING_EMPTY;
                        }
                        break;

                    default:
                        if (currentDetail.FieldName == 'PROPERTY_CITY_TOKEN') {
                            city = currentDetail.FieldValue;
                            continue; // do not replace token until loops end                               
                        }
                        else if (currentDetail.FieldName == 'PROPERTY_STATE_TOKEN') {
                            state = currentDetail.FieldValue;
                            continue; // do not replace token until loops end
                        }
                        else if (currentDetail.FieldName == 'PROPERTY_ZIP_TOKEN') {
                            zip = currentDetail.FieldValue;
                            continue; // do not replace token until loops end
                        }
                        else if (currentDetail.FieldName == 'PROPERTY_ADDRESS_TOKEN') {
                            addresInfo = currentDetail.FieldValue;

                            if (supplier.toLowerCase() == "oodle") {
                                addresInfo = g_NavigationEngine.CreatePropertyDetailsLinkForPropertyType(this.propDetails, addresInfo, "details_Map");
                            }
                            tempText = ELEMENT_OPEN_TAG_LI + addresInfo + ELEMENT_CLOSE_TAG_LI;
                        }
                        else {
                            tempText = ELEMENT_OPEN_TAG_LI + currentDetail.FieldValue + ELEMENT_CLOSE_TAG_LI;
                        }
                        break;
                }

                isNotEmptyValue = (currentDetail.FieldValue != null && currentDetail.FieldValue != '0' && currentDetail.FieldValue != '0.0' && currentDetail.FieldValue != STRING_EMPTY && currentDetail.FieldValue != PRICE_ZERO);

                this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(currentDetail.FieldName, (isNotEmptyValue) ? tempText : STRING_EMPTY);

            }
            this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/PROPERTY_CITY_TOKEN/g, city);
            this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/PROPERTY_STATE_TOKEN/g, state);
            this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/PROPERTY_ZIP_TOKEN/g, zip);

            this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/PROPERTY_CITY_STATE_ZIP_TOKEN/g, ELEMENT_OPEN_TAG_LI + city + ', ' + state + ' ' + zip + ELEMENT_CLOSE_TAG_LI);
            this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/REPAIR_COST/g, this.AddLinkRepairCost(this.propDetails.RepairCost, this.propDetails.PropID));
            this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/REPLACE_FREETRIAL_LINK/g, this.AddLinkFreeTrial(this.propDetails.PropID, this.isMember, this.propDetails.PropertyStatus, this.propDetails.IsFreeTrialLinkFull));
            this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/REPLACE_LINK_MORE_DETAILS/g, this.AddPropertyDetailsLink(this.propDetails));
            this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/REPLACE_LINK_MAKE_OFFER/g, this.AddMakeOfferLink(this.propDetails.PropertyStatus, this.propDetails.PropID, this.propDetails.IsMakeOffer, this.propDetails.SoldPrice != PRICE_ZERO));

            this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/POWERED_BY_TOKEN/g, this.IsPoweredbySomeone(supplier));

            this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/REPLACE_LINK_BID_NOW/g, this.AddBidLink(this.propDetails.PropertyStatus, this.propDetails.PropID, supplier));

            this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/REPLACE_LINK_COMP_SALES/g, this.AddComparableSalesLink(this.propDetails.PropertyStatus, this.propDetails, this.propDetails.HasComps, this.propDetails.IsMakeOffer));
            this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/REPLACE_LINK_LIEN_LOAN/g, this.AddLienLoanHistory(this.propDetails.PropertyStatus, this.propDetails.PropID, this.propDetails.HasLien, this.propDetails.IsMakeOffer));
        }

        var arrowPos = this.AddArrows(this.isMapBirdsEyeView, this.latitude, this.longitude, this.positionX, this.positionY, this.curMapObject);
        this.htmlContent.innerHTML = this.htmlContent.innerHTML.replace(/REPLACE_ARROWS/g, arrowPos);

        this.AddHiddenImageLinkArray(this.propDetails.PropID, this.propDetails.ImageLink, this.latitude, this.longitude, this.isSubjectProperty);

        this.AddPopupToMap(this.htmlContent, this.propDetails);

        PopUp._initialized = true;
    }

    PopUp.prototype.IsPoweredbySomeone = function(supplier) {
        if (supplier.toLowerCase() == "oodle") {
            return '<br /><span style="margin:0 0 0 35px;font-size:9pxcolor:#939393">powered by Oodle</span>';
        }
        else {
            return "";
        }
    }
    PopUp.prototype.AddPopupToMap = function(htmlContent, pinPropertyData) {
        this.AddPopUpToParentDiv(htmlContent);

        //Set the Bird eye Image in the PopUp
        if (null != pinPropertyData || undefined != pinPropertyData) {
            this.SetFirstBirdEyeImg();
        }

        var popUpHeight = htmlContent.offsetHeight;
        var popUpWidth = htmlContent.offsetWidth;

        //this will get the values for Fire Fox
        if (null != htmlContent.firstChild.nextSibling && null != htmlContent.firstChild.nextSibling.offsetWidth && null != htmlContent.firstChild.nextSibling.offsetHeight) {
            popUpHeight = htmlContent.firstChild.nextSibling.offsetHeight;
            popUpWidth = htmlContent.firstChild.nextSibling.offsetWidth;
        }

        //this condition will correct the width on IE
        if (null != htmlContent.firstChild.offsetWidth && null != htmlContent.firstChild.offsetHeight) {
            popUpHeight = htmlContent.firstChild.offsetHeight;
            popUpWidth = htmlContent.firstChild.offsetWidth;
        }

        var positionXY = this.GetPositionXY(this.positionX, this.positionY, popUpWidth, popUpHeight, 22, 22);
        this.RemoveAllFromDivContainer();

        var shapePopup = new VEShape(VEShapeType.Pushpin, this.curMapObject.PixelToLatLong(new VEPixel(positionXY.X, positionXY.Y)));
        shapePopup.SetCustomIcon(this.htmlContent.innerHTML);
        this.layerPopUpContainer.AddShapeToLayer(shapePopup);

        //we remove the text decoration that automatically will be added by Virtual Earth Map
        this.RemoveUnderlineFromAnchors(this.layerPopUpContainer.layerID);

        this.positionX = positionXY.X;
        this.positionY = positionXY.Y;
    }

    PopUp.prototype.SetFirstBirdEyeImg = function() {
        try {
            //If we have images for this link then we show the firs one
            //Get the image div
            if (gImageArray.length > 0) {
                var imageDiv = document.getElementById('propertyImageDiv');
                if (null != imageDiv) {
                    imageDiv.src = gImageArray[0];
                }
            }
        }
        catch (ex) {
            LogErrorMessage("SetFirstBirdEyeImg: ", ex);
        }
    }

    PopUp.prototype.GetPositionXY = function(posX, posY, popupWidth, popupHeight, offsetX, offsetY) {
        try {
            var posPix = this.curMapObject.LatLongToPixel(this.curMapObject.GetCenter());

            var offsetXY = new Object;
            var left = ((parseInt(eval(posX)) < parseInt(posPix.x)) || (parseInt(eval(posX)) == parseInt(posPix.x)));
            var top = ((parseInt(eval(posY)) < parseInt(posPix.y)) || (parseInt(eval(posY)) == parseInt(posPix.y)));
            var offset_X = offsetX;
            var offset_Y = offsetY;
            var x = eval(posX);
            var y = eval(posY);
            var zindex = 1;

            if (top && left) {
                offsetXY.X = x - 3;
                offsetXY.Y = y + offset_Y;
                if (((parseInt(posPix.y) * 2) - 5) < (eval(offsetXY.Y) + popupHeight)) {
                    zindex = -1;
                }
            }
            else
                if (top && !left)//TR
            {
                offsetXY.X = x - popupWidth + offset_X;
                offsetXY.Y = y + offset_Y;
            }
            else
                if (!top && left)//BL
            {
                offsetXY.X = x - 3;
                offsetXY.Y = y - popupHeight - 2;
                if (((parseInt(posPix.y) * 2) - 5) < (eval(offsetXY.Y) + popupHeight)) {
                    zindex = -1;
                }
            }
            else
                if (!top && !left)//BR
            {
                offsetXY.X = x - popupWidth + offset_X;
                offsetXY.Y = y - popupHeight - 2;
            }

            /*
            if (this.isCopyRightsLblShown && zindex == -1) 
            {
            //we hide the google copyrights and scale bar
            this.curMapObject.HideScalebar();
            ChangeCssClassAttrib('#myMap .MSVE_CopyrightForeground', 'display', 'none');
            ChangeCssClassAttrib('#myMap .MSVE_CopyrightBackground', 'display', 'none');
            this.isCopyRightsLblShown = false;
            }
            if (!this.isCopyRightsLblShown && zindex == 1) 
            {
            //we show the google copyrights and scale bar
            this.curMapObject.ShowScalebar();
            ChangeCssClassAttrib('#myMap .MSVE_CopyrightForeground', 'display', 'block');
            ChangeCssClassAttrib('#myMap .MSVE_CopyrightBackground', 'display', 'block');
            this.isCopyRightsLblShown = true;
            }
            */

            return offsetXY;

        }
        catch (ex) {
            LogErrorMessage("GetXOffSet: ", ex, true);
        }
    }

    PopUp.prototype.AddArrows = function(isMapBirdsEyeView, latitude, longitude, x, y, mapObj) {
        try {
            var top;
            var left;
            var xOff = x;
            var yOff = y;
            var tlShow = "tl_arrow hide";
            var trShow = "tr_arrow hide";
            var blShow = "bl_arrow hide";
            var brShow = "br_arrow hide";

            var posPix = this.curMapObject.LatLongToPixel(this.curMapObject.GetCenter());

            left = ((parseInt(eval(x)) < parseInt(posPix.x)) || (parseInt(eval(x)) == parseInt(posPix.x)));
            top = ((parseInt(eval(y)) < parseInt(posPix.y)) || (parseInt(eval(y)) == parseInt(posPix.y)));

            if (top && left)//TL
            {
                tlShow = "tl_arrow show";
            }
            else
                if (top && !left)//TR
            {
                trShow = "tr_arrow show";
            }
            else
                if (!top && left)//BL
            {
                blShow = "bl_arrow show'";
            }
            else
                if (!top && !left)//BR
            {
                //tlShow = "tl_arrow show";
                brShow = "br_arrow show";
            }

            var arrows = "<img src='" + this.pathToImgFolder + "tl_arrow.gif' alt='' class='" + tlShow + "' height='15' width='18'>" +
	                        "<img src='" + this.pathToImgFolder + "tr_arrow.gif' alt='' class='" +
	                        trShow +
	                        "' height='15' width='18'>" +
	                        "<img src='" + this.pathToImgFolder + "bl_arrow.gif' alt='' class='" +
	                        blShow +
	                        "' height='15' width='18'>" +
	                        "<img src='" + this.pathToImgFolder + "br_arrow.gif' alt='' class='" +
	                        brShow +
	                        "' height='15' width='18'>";
            return arrows;
        }
        catch (ex) {
            LogErrorMessage("AddArrows: ", ex);
        }
    }




    PopUp.prototype.PolygonPopUp = function(areaBorder) {
        this.layerName = LAYER_NAME_POLYGONS_POPUP;
        this.layerPopUpContainer = this.GetLayerContainer(LAYER_NAME_POLYGONS_POPUP);
        this.layerPopUpID = this.layerPopUpContainer.layerID;

        if (areaBorder) {
            //get the set of Polygon's points
            var polygonPoints = areaBorder.Polygons;
            var currentVertex;
            var curVerPoints;
            var pointIndex;
            var curVerShape;

            //Start drawing the Polygon
            for (var vertexIndex = 0; vertexIndex < polygonPoints.length; vertexIndex++) {
                currentVertex = polygonPoints[vertexIndex].Vertexes;
                curVerPoints = new Array(currentVertex.length);
                pointIndex = 0;

                if (currentVertex.length > 0) {
                    //add Points for the current vertex
                    for (var vertexPointIndex = 0; vertexPointIndex < currentVertex.length; vertexPointIndex++) {
                        curVerPoints[pointIndex++] = new VELatLong(currentVertex[vertexPointIndex].Latitude, currentVertex[vertexPointIndex].Longitude);
                    }

                    //we close the polygon form going to the origin					
                    curVerPoints[pointIndex++] = curVerPoints[0];

                    //Add thepolygon into a Shape
                    curVerShape = new VEShape(VEShapeType.Polygon, curVerPoints);
                    //shape Format

                    curVerShape.SetLineWidth(2);
                    curVerShape.SetLineColor(new VEColor(0, 100, 150, 0.6));
                    curVerShape.SetFillColor(new VEColor(0, 100, 150, 0.2));
                    curVerShape.HideIcon();
                    curVerShape.SetZIndex(19, 18);

                    //Add shape on the Polygon layer
                    this.layerPopUpContainer.AddShapeToLayer(curVerShape);
                }
            }
        }

    }

    PopUp.prototype.JoinNowPopUp = function() {
        this.currentPopUpID = 'JoinNowPopUp';
        this.RemovePopUpDivInContainer(this.currentPopUpID);

        var divPopupContainer = document.createElement(ELEMENT_DIVISION);
        divPopupContainer.setAttribute('id', this.currentPopUpID);
        divPopupContainer.innerHTML = this.GetPopUpHtmlTemplate(this.PopupJoinNowHtmlTemplate);
        divPopupContainer.innerHTML = divPopupContainer.innerHTML.replace(/POPUPID/g, this.currentPopUpID);
        divPopupContainer.style.position = STYLE_POSITION_ABSOLUTE;

        this.AddPopUpToParentDiv(divPopupContainer);
    }

    PopUp.prototype.CenterJoinNowPopUp = function(offsetX) {

        var divPopUpJoinNow = document.getElementById('joinNowBalloonCnr');
        var divJoinNowPopUpConatiner = document.getElementById('joinNowPopUpContainer');
        var mapCenter = this.curMapObject.LatLongToPixel(this.curMapObject.GetCenter());
        var divMapAll = document.getElementById('mapAll');
        var offset = 0;


        if (divJoinNowPopUpConatiner) {
            divJoinNowPopUpConatiner.style.visibility = 'visible';
            divJoinNowPopUpConatiner.style.position = 'relative';

            if (divMapAll) {
                divJoinNowPopUpConatiner.style.left = divMapAll.offsetLeft + offsetX + 'px';
                divJoinNowPopUpConatiner.style.width = divMapAll.offsetWidth + 'px';
                divJoinNowPopUpConatiner.style.height = divMapAll.offsetHeight + 'px';
            }
            SetMenusBehind();
        }
        if (divPopUpJoinNow && divMapAll) {
            divPopUpJoinNow.style.left = (divMapAll.offsetWidth / 2) - (divPopUpJoinNow.offsetWidth / 2) + offsetX + 'px';
            SetMenusBehind();
        }

        function SetMenusBehind() {
            var divMenuOpen = document.getElementById('openMenu');
            var divMenuHelp = document.getElementById('mapNav_mapHelp');

            if (divMenuOpen) {
                divMenuOpen.style.zIndex = '0';
            }
            if (divMenuHelp) {
                divMenuHelp.style.zIndex = '0';
            }
        }

    }

    PopUp.prototype.RemovePopupJoinNow = function() {
        this.RemovePopUp('JoinNowPopUp');
        SetMenusFront();

        function SetMenusFront() {
            var divMenuOpen = document.getElementById('openMenu');
            var divMenuHelp = document.getElementById('mapNav_mapHelp');

            if (divMenuOpen) {
                divMenuOpen.style.zIndex = '20';
            }
            if (divMenuHelp) {
                divMenuHelp.style.zIndex = '20';
            }
        }
    }

    PopUp.prototype.GetPopUpHtmlTemplate = function(templateName) {

        var result = STRING_EMPTY;

        if (typeof (gHTMLTemplatesObj) != "undefined" && gHTMLTemplatesObj != null) {
            result = gHTMLTemplatesObj[templateName];

        }
        if (templateName != STRING_EMPTY && (result == null || result == STRING_EMPTY)) {
            var htmlTemplate = document.getElementById(templateName);
            if (null != htmlTemplate) {
                result = htmlTemplate.innerHTML;
            }
        }
        return result;

    }

    PopUp.prototype.RemovePopUp = function(popupID) {
        var mainDiv = document.getElementById(this.PopupDivTempContainer);
        var currentPopUp = document.getElementById(popupID);

        if (mainDiv && mainDiv.childNodes) {
            if (currentPopUp) {
                mainDiv.removeChild(currentPopUp);
            }
        }
    }

    PopUp.prototype.RemoveJoinNowPopUp = function(popupID) {
        try {
            this.RemovePopUp(popupID);
            if
					(this.curMapObject.GetMapStyle() == VEMapStyle.Birdseye || this.curMapObject.GetMapStyle() == VEMapStyle.BirdseyeHybrid);
            {

            }
            if (!this.isMapBirdsEyeView) {
                this.curMapObject.SetZoomLevel(15);
            }

        }
        catch (ex) {
            LogErrorMessage("RemoveJoinNowPopUp: ", ex);
        }
    }

    PopUp.prototype.RemovePopUpFromLayer = function(PopUpID) {
        try {
            var divContainer = document.getElementById(PopUpID);

            if (divContainer && divContainer.childNodes) {
                while (divContainer.childNodes.length > 0) {
                    divContainer.removeChild(divContainer.childNodes[0]);
                }
            }
        }
        catch (ex) {
            LogErrorMessage("PopUp.prototype.RemovePropDetBaloon: ", ex);
        }
    }
}


//----------------------------  Layers On Map Handling --------------------------------------------------

function LayersHandling(layerName, mapObj) {
    this.layerName = layerName;
    this.mapObj = mapObj;

    if (this.mapObj == null || this.mapObj == undefined || this.layerName == null || this.layerName == undefined) {
        return;
    }

    LayersHandling.prototype.GetLayerID = function() {
        try {
            var layerID = null;

            if (this.layer != null) {
                layerID = this.layer.iid;
            }
            return layerID;
        }
        catch (ex) {
            LogErrorMessage("LayersHandling.prototype.GetLayerID: ", ex, true);
        }
    }

    LayersHandling.prototype.LayerExist = function() {
        try {
            var layerExist = false;

            if (this.layer != null) {
                layerExist = true;
            }
            return layerExist;
        }
        catch (ex) {
            LogErrorMessage("LayersHandling.prototype.LayerExist: ", ex, true);
        }
    }

    LayersHandling.prototype.GetLayer = function() {
        try {
            var layerFound = null;
            if (this.mapObj) {
                var currentLayer;
                var noLayersInMap = this.mapObj.GetShapeLayerCount();
                var layerTitle;

                for (var i = 0; i < noLayersInMap; i++) {
                    currentLayer = this.mapObj.GetShapeLayerByIndex(i);
                    layerTitle = currentLayer.GetTitle();
                    if (layerTitle == this.layerName) {
                        layerFound = currentLayer;
                        break;
                    }
                }
            }
            return layerFound;
        }
        catch (ex) {
            LogErrorMessage("LayersHandling.prototype.GetLayer: ", ex, true);
        }
    }

    this.layer = this.GetLayer();
    this.layerExist = this.LayerExist();
    this.layerID = this.GetLayerID();

    LayersHandling.prototype.CreateNewLayer = function() {
        try {
            if (this.mapObj != null && !this.layerExist) {

                var newLayer;

                newLayer = new VEShapeLayer();
                newLayer.SetTitle(this.layerName);
                this.mapObj.AddShapeLayer(newLayer);

                this.layerID = newLayer.iid;
                this.layer = newLayer;
                this.layerExist = true;
            }
        }
        catch (ex) {
            LogErrorMessage("LayersHandling.prototype.CreateNewLayer: ", ex, true);
        }
    }

    LayersHandling.prototype.HideLayer = function() {
        try {
            if (this.layer) {
                this.layer.Hide();
            }
        }
        catch (ex) {
            LogErrorMessage("LayersHandling.prototype.HideLayer: ", ex, true);
        }
    }

    LayersHandling.prototype.ShowLayer = function() {
        try {
            if (this.layer) {
                this.layer.Show();
            }
        }
        catch (ex) {
            LogErrorMessage("LayersHandling.prototype.ShowLayer", ex, true)
        }
    }

    LayersHandling.prototype.DeleteAllShapesFromLayer = function() {
        try {
            if (this.layer != null) {
                this.layer.DeleteAllShapes();
            }
        }
        catch (ex) {
            LogErrorMessage("LayersHandling.prototype.DeleteShapesAllFromLayer: ", ex, true);
        }
    }

    LayersHandling.prototype.DeleteCurrentLayer = function() {
        try {
            if (this.layer != null) {
                this.mapObj.DeleteShapeLayer(this.layer);
                this.layer = undefined;
                this.layerExist = false;
                this.layerID = undefined;
            }
        }
        catch (ex) {
            LogErrorMessage("LayersHandling.prototype.DeleteCurrentLayer: ", ex, true);
        }
    }

    LayersHandling.prototype.ClearAllLayers = function() {
        try {
            if (this.mapObj != null && this.mapObj != undefined) {
                var noLayers = this.mapObj.GetShapeLayerCount();
                var currentLayer;

                for (var i = 0; i < noLayers; i++) {
                    currentLayer = this.mapObj.GetShapeLayerByIndex(i);
                    if (currentLayer) {
                        currentLayer.DeleteAllShapes();
                    }
                }
            }
        }
        catch (ex) {
            LogErrorMessage("LayersHandling.prototype.ClearAllLayers: ", ex, true);
        }
    }

    LayersHandling.prototype.AddShapeToLayer = function(shape) {
        try {
            if (this.layer) {
                this.layer.AddShape(shape);
            }
        }
        catch (ex) {
            LogErrorMessage("LayersHandling.prototype.AddShapeToLayer: ", ex, true);
        }
    }

    ///////// End Private functions //////////////
}


//---------------------------- Eval if function exist -------------------------------------

function isFunctDef(funcName) {
    var isDefined = false;
    if (typeof funcName == 'string' && eval('typeof ' + funcName) == 'function') {
        isDefined = true;
    }
    return isDefined;
}

//ChangeCssClassAttrib(cssClassName, element, value)
//this function will change the style of any class on the page
// cssClassName = '.divBlaBlabla'
// element = 'color'
// value = 'red'
function ChangeCssClassAttrib(cssClassName, element, value) {

    var cssFFOrIE = '';
    var cssFF = 'rules';
    var cssIE = 'cssRules';
    try {
        for (var cssSheetIndex = 0; cssSheetIndex < document.styleSheets.length; cssSheetIndex++) {
            //Check the classes rules type;
            if (document.styleSheets[cssSheetIndex][cssFF]) {
                cssFFOrIE = cssFF;
            }
            else if (document.styleSheets[cssSheetIndex][cssIE]) {
                cssFFOrIE = cssIE;
            }

            for (var cssRuleIndex = 0; cssRuleIndex < document.styleSheets[cssSheetIndex][cssFFOrIE].length; cssRuleIndex++) {
                if (document.styleSheets[cssSheetIndex][cssFFOrIE][cssRuleIndex].selectorText == cssClassName) {
                    if (document.styleSheets[cssSheetIndex][cssFFOrIE][cssRuleIndex].style[element]) {
                        document.styleSheets[cssSheetIndex][cssFFOrIE][cssRuleIndex].style[element] = value;
                        break;
                    }
                }
            }
        }
    }
    catch (ex) {
        //LogErrorMessage("ChangeCssClassAttrib: ", ex, true);
    }
}

//END RealtyTrac.Common.Web.Scripts.MapSearch.MapPopUpClass.js
//START AjaxControlToolkit.Common.Common.js
Type.registerNamespace('AjaxControlToolkit');AjaxControlToolkit.BoxSide = function() {
}
AjaxControlToolkit.BoxSide.prototype = {
Top : 0,
Right : 1,
Bottom : 2,
Left : 3
}
AjaxControlToolkit.BoxSide.registerEnum("AjaxControlToolkit.BoxSide", false);AjaxControlToolkit._CommonToolkitScripts = function() {
}
AjaxControlToolkit._CommonToolkitScripts.prototype = {
_borderStyleNames : ["borderTopStyle","borderRightStyle","borderBottomStyle","borderLeftStyle"],
_borderWidthNames : ["borderTopWidth", "borderRightWidth", "borderBottomWidth", "borderLeftWidth"],
_paddingWidthNames : ["paddingTop", "paddingRight", "paddingBottom", "paddingLeft"],
_marginWidthNames : ["marginTop", "marginRight", "marginBottom", "marginLeft"],
getCurrentStyle : function(element, attribute, defaultValue) {
var currentValue = null;if (element) {
if (element.currentStyle) {
currentValue = element.currentStyle[attribute];} else if (document.defaultView && document.defaultView.getComputedStyle) {
var style = document.defaultView.getComputedStyle(element, null);if (style) {
currentValue = style[attribute];}
}
if (!currentValue && element.style.getPropertyValue) {
currentValue = element.style.getPropertyValue(attribute);}
else if (!currentValue && element.style.getAttribute) {
currentValue = element.style.getAttribute(attribute);} 
}
if ((!currentValue || currentValue == "" || typeof(currentValue) === 'undefined')) {
if (typeof(defaultValue) != 'undefined') {
currentValue = defaultValue;}
else {
currentValue = null;}
} 
return currentValue;},
getInheritedBackgroundColor : function(element) {
if (!element) return '#FFFFFF';var background = this.getCurrentStyle(element, 'backgroundColor');try {
while (!background || background == '' || background == 'transparent' || background == 'rgba(0, 0, 0, 0)') {
element = element.parentNode;if (!element) {
background = '#FFFFFF';} else {
background = this.getCurrentStyle(element, 'backgroundColor');}
}
} catch(ex) {
background = '#FFFFFF';}
return background;},
getLocation : function(element) {
if (element === document.documentElement) {
return new Sys.UI.Point(0,0);}
if (Sys.Browser.agent == Sys.Browser.InternetExplorer && Sys.Browser.version < 7) {
if (element.window === element || element.nodeType === 9 || !element.getClientRects || !element.getBoundingClientRect) return new Sys.UI.Point(0,0);var screenRects = element.getClientRects();if (!screenRects || !screenRects.length) {
return new Sys.UI.Point(0,0);}
var first = screenRects[0];var dLeft = 0;var dTop = 0;var inFrame = false;try {
inFrame = element.ownerDocument.parentWindow.frameElement;} catch(ex) {
inFrame = true;}
if (inFrame) {
var clientRect = element.getBoundingClientRect();if (!clientRect) {
return new Sys.UI.Point(0,0);}
var minLeft = first.left;var minTop = first.top;for (var i = 1;i < screenRects.length;i++) {
var r = screenRects[i];if (r.left < minLeft) {
minLeft = r.left;}
if (r.top < minTop) {
minTop = r.top;}
}
dLeft = minLeft - clientRect.left;dTop = minTop - clientRect.top;}
var ownerDocument = element.document.documentElement;return new Sys.UI.Point(first.left - 2 - dLeft + ownerDocument.scrollLeft, first.top - 2 - dTop + ownerDocument.scrollTop);}
return Sys.UI.DomElement.getLocation(element);},
setLocation : function(element, point) {
Sys.UI.DomElement.setLocation(element, point.x, point.y);},
getContentSize : function(element) {
if (!element) {
throw Error.argumentNull('element');}
var size = this.getSize(element);var borderBox = this.getBorderBox(element);var paddingBox = this.getPaddingBox(element);return {
width : size.width - borderBox.horizontal - paddingBox.horizontal,
height : size.height - borderBox.vertical - paddingBox.vertical
}
},
getSize : function(element) {
if (!element) {
throw Error.argumentNull('element');}
return {
width: element.offsetWidth,
height: element.offsetHeight
};},
setContentSize : function(element, size) {
if (!element) {
throw Error.argumentNull('element');}
if (!size) {
throw Error.argumentNull('size');}
if(this.getCurrentStyle(element, 'MozBoxSizing') == 'border-box' || this.getCurrentStyle(element, 'BoxSizing') == 'border-box') {
var borderBox = this.getBorderBox(element);var paddingBox = this.getPaddingBox(element);size = {
width: size.width + borderBox.horizontal + paddingBox.horizontal,
height: size.height + borderBox.vertical + paddingBox.vertical
};}
element.style.width = size.width.toString() + 'px';element.style.height = size.height.toString() + 'px';},
setSize : function(element, size) {
if (!element) {
throw Error.argumentNull('element');}
if (!size) {
throw Error.argumentNull('size');}
var borderBox = this.getBorderBox(element);var paddingBox = this.getPaddingBox(element);var contentSize = {
width: size.width - borderBox.horizontal - paddingBox.horizontal,
height: size.height - borderBox.vertical - paddingBox.vertical
};this.setContentSize(element, contentSize);},
getBounds : function(element) {
var offset = $common.getLocation(element);return new Sys.UI.Bounds(offset.x, offset.y, element.offsetWidth || 0, element.offsetHeight || 0);}, 
setBounds : function(element, bounds) {
if (!element) {
throw Error.argumentNull('element');}
if (!bounds) {
throw Error.argumentNull('bounds');}
this.setSize(element, bounds);$common.setLocation(element, bounds);},
getClientBounds : function() {
var clientWidth;var clientHeight;switch(Sys.Browser.agent) {
case Sys.Browser.InternetExplorer:
clientWidth = document.documentElement.clientWidth;clientHeight = document.documentElement.clientHeight;break;case Sys.Browser.Safari:
clientWidth = window.innerWidth;clientHeight = window.innerHeight;break;case Sys.Browser.Opera:
clientWidth = Math.min(window.innerWidth, document.body.clientWidth);clientHeight = Math.min(window.innerHeight, document.body.clientHeight);break;default: 
clientWidth = Math.min(window.innerWidth, document.documentElement.clientWidth);clientHeight = Math.min(window.innerHeight, document.documentElement.clientHeight);break;}
return new Sys.UI.Bounds(0, 0, clientWidth, clientHeight);},
getMarginBox : function(element) {
if (!element) {
throw Error.argumentNull('element');}
var box = {
top: this.getMargin(element, AjaxControlToolkit.BoxSide.Top),
right: this.getMargin(element, AjaxControlToolkit.BoxSide.Right),
bottom: this.getMargin(element, AjaxControlToolkit.BoxSide.Bottom),
left: this.getMargin(element, AjaxControlToolkit.BoxSide.Left)
};box.horizontal = box.left + box.right;box.vertical = box.top + box.bottom;return box;},
getBorderBox : function(element) {
if (!element) {
throw Error.argumentNull('element');}
var box = {
top: this.getBorderWidth(element, AjaxControlToolkit.BoxSide.Top),
right: this.getBorderWidth(element, AjaxControlToolkit.BoxSide.Right),
bottom: this.getBorderWidth(element, AjaxControlToolkit.BoxSide.Bottom),
left: this.getBorderWidth(element, AjaxControlToolkit.BoxSide.Left)
};box.horizontal = box.left + box.right;box.vertical = box.top + box.bottom;return box;},
getPaddingBox : function(element) {
if (!element) {
throw Error.argumentNull('element');}
var box = {
top: this.getPadding(element, AjaxControlToolkit.BoxSide.Top),
right: this.getPadding(element, AjaxControlToolkit.BoxSide.Right),
bottom: this.getPadding(element, AjaxControlToolkit.BoxSide.Bottom),
left: this.getPadding(element, AjaxControlToolkit.BoxSide.Left)
};box.horizontal = box.left + box.right;box.vertical = box.top + box.bottom;return box;},
isBorderVisible : function(element, boxSide) {
if (!element) {
throw Error.argumentNull('element');}
if(boxSide < AjaxControlToolkit.BoxSide.Top || boxSide > AjaxControlToolkit.BoxSide.Left) {
throw Error.argumentOutOfRange(String.format(Sys.Res.enumInvalidValue, boxSide, 'AjaxControlToolkit.BoxSide'));}
var styleName = this._borderStyleNames[boxSide];var styleValue = this.getCurrentStyle(element, styleName);return styleValue != "none";},
getMargin : function(element, boxSide) {
if (!element) {
throw Error.argumentNull('element');}
if(boxSide < AjaxControlToolkit.BoxSide.Top || boxSide > AjaxControlToolkit.BoxSide.Left) {
throw Error.argumentOutOfRange(String.format(Sys.Res.enumInvalidValue, boxSide, 'AjaxControlToolkit.BoxSide'));}
var styleName = this._marginWidthNames[boxSide];var styleValue = this.getCurrentStyle(element, styleName);try { return this.parsePadding(styleValue);} catch(ex) { return 0;}
},
getBorderWidth : function(element, boxSide) {
if (!element) {
throw Error.argumentNull('element');}
if(boxSide < AjaxControlToolkit.BoxSide.Top || boxSide > AjaxControlToolkit.BoxSide.Left) {
throw Error.argumentOutOfRange(String.format(Sys.Res.enumInvalidValue, boxSide, 'AjaxControlToolkit.BoxSide'));}
if(!this.isBorderVisible(element, boxSide)) {
return 0;} 
var styleName = this._borderWidthNames[boxSide];var styleValue = this.getCurrentStyle(element, styleName);return this.parseBorderWidth(styleValue);},
getPadding : function(element, boxSide) {
if (!element) {
throw Error.argumentNull('element');}
if(boxSide < AjaxControlToolkit.BoxSide.Top || boxSide > AjaxControlToolkit.BoxSide.Left) {
throw Error.argumentOutOfRange(String.format(Sys.Res.enumInvalidValue, boxSide, 'AjaxControlToolkit.BoxSide'));}
var styleName = this._paddingWidthNames[boxSide];var styleValue = this.getCurrentStyle(element, styleName);return this.parsePadding(styleValue);},
parseBorderWidth : function(borderWidth) {
if (!this._borderThicknesses) {
var borderThicknesses = { };var div0 = document.createElement('div');div0.style.visibility = 'hidden';div0.style.position = 'absolute';div0.style.fontSize = '1px';document.body.appendChild(div0)
var div1 = document.createElement('div');div1.style.height = '0px';div1.style.overflow = 'hidden';div0.appendChild(div1);var base = div0.offsetHeight;div1.style.borderTop = 'solid black';div1.style.borderTopWidth = 'thin';borderThicknesses['thin'] = div0.offsetHeight - base;div1.style.borderTopWidth = 'medium';borderThicknesses['medium'] = div0.offsetHeight - base;div1.style.borderTopWidth = 'thick';borderThicknesses['thick'] = div0.offsetHeight - base;div0.removeChild(div1);document.body.removeChild(div0);this._borderThicknesses = borderThicknesses;}
if (borderWidth) {
switch(borderWidth) {
case 'thin':
case 'medium':
case 'thick':
return this._borderThicknesses[borderWidth];case 'inherit':
return 0;}
var unit = this.parseUnit(borderWidth);Sys.Debug.assert(unit.type == 'px', String.format(AjaxControlToolkit.Resources.Common_InvalidBorderWidthUnit, unit.type));return unit.size;}
return 0;},
parsePadding : function(padding) {
if(padding) {
if(padding == 'inherit') {
return 0;}
var unit = this.parseUnit(padding);Sys.Debug.assert(unit.type == 'px', String.format(AjaxControlToolkit.Resources.Common_InvalidPaddingUnit, unit.type));return unit.size;}
return 0;},
parseUnit : function(value) {
if (!value) {
throw Error.argumentNull('value');}
value = value.trim().toLowerCase();var l = value.length;var s = -1;for(var i = 0;i < l;i++) {
var ch = value.substr(i, 1);if((ch < '0' || ch > '9') && ch != '-' && ch != '.' && ch != ',') {
break;}
s = i;}
if(s == -1) {
throw Error.create(AjaxControlToolkit.Resources.Common_UnitHasNoDigits);}
var type;var size;if(s < (l - 1)) {
type = value.substring(s + 1).trim();} else {
type = 'px';}
size = parseFloat(value.substr(0, s + 1));if(type == 'px') {
size = Math.floor(size);}
return { 
size: size,
type: type
};},
getElementOpacity : function(element) {
if (!element) {
throw Error.argumentNull('element');}
var hasOpacity = false;var opacity;if (element.filters) {
var filters = element.filters;if (filters.length !== 0) {
var alphaFilter = filters['DXImageTransform.Microsoft.Alpha'];if (alphaFilter) {
opacity = alphaFilter.opacity / 100.0;hasOpacity = true;}
}
}
else {
opacity = this.getCurrentStyle(element, 'opacity', 1);hasOpacity = true;}
if (hasOpacity === false) {
return 1.0;}
return parseFloat(opacity);},
setElementOpacity : function(element, value) {
if (!element) {
throw Error.argumentNull('element');}
if (element.filters) {
var filters = element.filters;var createFilter = true;if (filters.length !== 0) {
var alphaFilter = filters['DXImageTransform.Microsoft.Alpha'];if (alphaFilter) {
createFilter = false;alphaFilter.opacity = value * 100;}
}
if (createFilter) {
element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + (value * 100) + ')';}
}
else {
element.style.opacity = value;}
},
getVisible : function(element) {
return (element &&
("none" != $common.getCurrentStyle(element, "display")) &&
("hidden" != $common.getCurrentStyle(element, "visibility")));},
setVisible : function(element, value) {
if (element && value != $common.getVisible(element)) {
if (value) {
if (element.style.removeAttribute) {
element.style.removeAttribute("display");} else {
element.style.removeProperty("display");}
} else {
element.style.display = 'none';}
element.style.visibility = value ? 'visible' : 'hidden';}
},
resolveFunction : function(value) {
if (value) {
if (value instanceof Function) {
return value;} else if (String.isInstanceOfType(value) && value.length > 0) {
var func;if ((func = window[value]) instanceof Function) {
return func;} else if ((func = eval(value)) instanceof Function) {
return func;}
}
}
return null;},
addCssClasses : function(element, classNames) {
for(var i = 0;i < classNames.length;i++) {
Sys.UI.DomElement.addCssClass(element, classNames[i]);}
},
removeCssClasses : function(element, classNames) {
for(var i = 0;i < classNames.length;i++) {
Sys.UI.DomElement.removeCssClass(element, classNames[i]);}
},
setStyle : function(element, style) {
$common.applyProperties(element.style, style);},
removeHandlers : function(element, events) {
for (var name in events) {
$removeHandler(element, name, events[name]);}
},
overlaps : function(r1, r2) {
return r1.x < (r2.x + r2.width)
&& r2.x < (r1.x + r1.width)
&& r1.y < (r2.y + r2.height)
&& r2.y < (r1.y + r1.height);},
containsPoint : function(rect, x, y) {
return x >= rect.x && x < (rect.x + rect.width) && y >= rect.y && y < (rect.y + rect.height);},
isKeyDigit : function(keyCode) { 
return (0x30 <= keyCode && keyCode <= 0x39);},
isKeyNavigation : function(keyCode) { 
return (Sys.UI.Key.left <= keyCode && keyCode <= Sys.UI.Key.down);},
padLeft : function(text, size, ch, truncate) { 
return $common._pad(text, size || 2, ch || ' ', 'l', truncate || false);},
padRight : function(text, size, ch, truncate) { 
return $common._pad(text, size || 2, ch || ' ', 'r', truncate || false);},
_pad : function(text, size, ch, side, truncate) {
text = text.toString();var length = text.length;var builder = new Sys.StringBuilder();if (side == 'r') {
builder.append(text);} 
while (length < size) {
builder.append(ch);length++;}
if (side == 'l') {
builder.append(text);}
var result = builder.toString();if (truncate && result.length > size) {
if (side == 'l') {
result = result.substr(result.length - size, size);} else {
result = result.substr(0, size);}
}
return result;},
__DOMEvents : {
focusin : { eventGroup : "UIEvents", init : function(e, p) { e.initUIEvent("focusin", true, false, window, 1);} },
focusout : { eventGroup : "UIEvents", init : function(e, p) { e.initUIEvent("focusout", true, false, window, 1);} },
activate : { eventGroup : "UIEvents", init : function(e, p) { e.initUIEvent("activate", true, true, window, 1);} },
focus : { eventGroup : "UIEvents", init : function(e, p) { e.initUIEvent("focus", false, false, window, 1);} },
blur : { eventGroup : "UIEvents", init : function(e, p) { e.initUIEvent("blur", false, false, window, 1);} },
click : { eventGroup : "MouseEvents", init : function(e, p) { e.initMouseEvent("click", true, true, window, 1, p.screenX || 0, p.screenY || 0, p.clientX || 0, p.clientY || 0, p.ctrlKey || false, p.altKey || false, p.shiftKey || false, p.metaKey || false, p.button || 0, p.relatedTarget || null);} },
dblclick : { eventGroup : "MouseEvents", init : function(e, p) { e.initMouseEvent("click", true, true, window, 2, p.screenX || 0, p.screenY || 0, p.clientX || 0, p.clientY || 0, p.ctrlKey || false, p.altKey || false, p.shiftKey || false, p.metaKey || false, p.button || 0, p.relatedTarget || null);} },
mousedown : { eventGroup : "MouseEvents", init : function(e, p) { e.initMouseEvent("mousedown", true, true, window, 1, p.screenX || 0, p.screenY || 0, p.clientX || 0, p.clientY || 0, p.ctrlKey || false, p.altKey || false, p.shiftKey || false, p.metaKey || false, p.button || 0, p.relatedTarget || null);} },
mouseup : { eventGroup : "MouseEvents", init : function(e, p) { e.initMouseEvent("mouseup", true, true, window, 1, p.screenX || 0, p.screenY || 0, p.clientX || 0, p.clientY || 0, p.ctrlKey || false, p.altKey || false, p.shiftKey || false, p.metaKey || false, p.button || 0, p.relatedTarget || null);} },
mouseover : { eventGroup : "MouseEvents", init : function(e, p) { e.initMouseEvent("mouseover", true, true, window, 1, p.screenX || 0, p.screenY || 0, p.clientX || 0, p.clientY || 0, p.ctrlKey || false, p.altKey || false, p.shiftKey || false, p.metaKey || false, p.button || 0, p.relatedTarget || null);} },
mousemove : { eventGroup : "MouseEvents", init : function(e, p) { e.initMouseEvent("mousemove", true, true, window, 1, p.screenX || 0, p.screenY || 0, p.clientX || 0, p.clientY || 0, p.ctrlKey || false, p.altKey || false, p.shiftKey || false, p.metaKey || false, p.button || 0, p.relatedTarget || null);} },
mouseout : { eventGroup : "MouseEvents", init : function(e, p) { e.initMouseEvent("mousemove", true, true, window, 1, p.screenX || 0, p.screenY || 0, p.clientX || 0, p.clientY || 0, p.ctrlKey || false, p.altKey || false, p.shiftKey || false, p.metaKey || false, p.button || 0, p.relatedTarget || null);} },
load : { eventGroup : "HTMLEvents", init : function(e, p) { e.initEvent("load", false, false);} },
unload : { eventGroup : "HTMLEvents", init : function(e, p) { e.initEvent("unload", false, false);} },
select : { eventGroup : "HTMLEvents", init : function(e, p) { e.initEvent("select", true, false);} },
change : { eventGroup : "HTMLEvents", init : function(e, p) { e.initEvent("change", true, false);} },
submit : { eventGroup : "HTMLEvents", init : function(e, p) { e.initEvent("submit", true, true);} },
reset : { eventGroup : "HTMLEvents", init : function(e, p) { e.initEvent("reset", true, false);} },
resize : { eventGroup : "HTMLEvents", init : function(e, p) { e.initEvent("resize", true, false);} },
scroll : { eventGroup : "HTMLEvents", init : function(e, p) { e.initEvent("scroll", true, false);} }
},
tryFireRawEvent : function(element, rawEvent) {
try {
if (element.fireEvent) {
element.fireEvent("on" + rawEvent.type, rawEvent);return true;} else if (element.dispatchEvent) {
element.dispatchEvent(rawEvent);return true;}
} catch (e) {
}
return false;}, 
tryFireEvent : function(element, eventName, properties) {
try {
if (document.createEventObject) {
var e = document.createEventObject();$common.applyProperties(e, properties || {});element.fireEvent("on" + eventName, e);return true;} else if (document.createEvent) {
var def = $common.__DOMEvents[eventName];if (def) {
var e = document.createEvent(def.eventGroup);def.init(e, properties || {});element.dispatchEvent(e);return true;}
}
} catch (e) {
}
return false;},
wrapElement : function(innerElement, newOuterElement, newInnerParentElement) {
var parent = innerElement.parentNode;parent.replaceChild(newOuterElement, innerElement);(newInnerParentElement || newOuterElement).appendChild(innerElement);},
unwrapElement : function(innerElement, oldOuterElement) {
var parent = oldOuterElement.parentNode;if (parent != null) {
$common.removeElement(innerElement);parent.replaceChild(innerElement, oldOuterElement);}
},
removeElement : function(element) {
var parent = element.parentNode;if (parent != null) {
parent.removeChild(element);}
},
applyProperties : function(target, properties) {
for (var p in properties) {
var pv = properties[p];if (pv != null && Object.getType(pv)===Object) {
var tv = target[p];$common.applyProperties(tv, pv);} else {
target[p] = pv;}
}
},
createElementFromTemplate : function(template, appendToParent, nameTable) {
if (typeof(template.nameTable)!='undefined') {
var newNameTable = template.nameTable;if (String.isInstanceOfType(newNameTable)) {
newNameTable = nameTable[newNameTable];}
if (newNameTable != null) {
nameTable = newNameTable;}
}
var elementName = null;if (typeof(template.name)!=='undefined') {
elementName = template.name;}
var elt = document.createElement(template.nodeName);if (typeof(template.name)!=='undefined' && nameTable) {
nameTable[template.name] = elt;}
if (typeof(template.parent)!=='undefined' && appendToParent == null) {
var newParent = template.parent;if (String.isInstanceOfType(newParent)) {
newParent = nameTable[newParent];}
if (newParent != null) {
appendToParent = newParent;}
}
if (typeof(template.properties)!=='undefined' && template.properties != null) {
$common.applyProperties(elt, template.properties);}
if (typeof(template.cssClasses)!=='undefined' && template.cssClasses != null) {
$common.addCssClasses(elt, template.cssClasses);}
if (typeof(template.events)!=='undefined' && template.events != null) {
$addHandlers(elt, template.events);}
if (typeof(template.visible)!=='undefined' && template.visible != null) {
this.setVisible(elt, template.visible);}
if (appendToParent) {
appendToParent.appendChild(elt);}
if (typeof(template.opacity)!=='undefined' && template.opacity != null) {
$common.setElementOpacity(elt, template.opacity);}
if (typeof(template.children)!=='undefined' && template.children != null) {
for (var i = 0;i < template.children.length;i++) {
var subtemplate = template.children[i];$common.createElementFromTemplate(subtemplate, elt, nameTable);}
}
var contentPresenter = elt;if (typeof(template.contentPresenter)!=='undefined' && template.contentPresenter != null) {
contentPresenter = nameTable[contentPresenter];}
if (typeof(template.content)!=='undefined' && template.content != null) {
var content = template.content;if (String.isInstanceOfType(content)) {
content = nameTable[content];}
if (content.parentNode) {
$common.wrapElement(content, elt, contentPresenter);} else {
contentPresenter.appendChild(content);}
}
return elt;},
prepareHiddenElementForATDeviceUpdate : function () {
var objHidden = document.getElementById('hiddenInputToUpdateATBuffer_CommonToolkitScripts');if (!objHidden) {
var objHidden = document.createElement('input');objHidden.setAttribute('type', 'hidden');objHidden.setAttribute('value', '1');objHidden.setAttribute('id', 'hiddenInputToUpdateATBuffer_CommonToolkitScripts');objHidden.setAttribute('name', 'hiddenInputToUpdateATBuffer_CommonToolkitScripts');if ( document.forms[0] ) {
document.forms[0].appendChild(objHidden);}
}
},
updateFormToRefreshATDeviceBuffer : function () {
var objHidden = document.getElementById('hiddenInputToUpdateATBuffer_CommonToolkitScripts');if (objHidden) {
if (objHidden.getAttribute('value') == '1') {
objHidden.setAttribute('value', '0');} else {
objHidden.setAttribute('value', '1');}
}
}
}
var CommonToolkitScripts = AjaxControlToolkit.CommonToolkitScripts = new AjaxControlToolkit._CommonToolkitScripts();var $common = CommonToolkitScripts;Sys.UI.DomElement.getVisible = $common.getVisible;Sys.UI.DomElement.setVisible = $common.setVisible;Sys.UI.Control.overlaps = $common.overlaps;AjaxControlToolkit._DomUtility = function() {
}
AjaxControlToolkit._DomUtility.prototype = {
isDescendant : function(ancestor, descendant) {
for (var n = descendant.parentNode;n != null;n = n.parentNode) {
if (n == ancestor) return true;}
return false;},
isDescendantOrSelf : function(ancestor, descendant) {
if (ancestor === descendant) 
return true;return AjaxControlToolkit.DomUtility.isDescendant(ancestor, descendant);},
isAncestor : function(descendant, ancestor) {
return AjaxControlToolkit.DomUtility.isDescendant(ancestor, descendant);},
isAncestorOrSelf : function(descendant, ancestor) {
if (descendant === ancestor)
return true;return AjaxControlToolkit.DomUtility.isDescendant(ancestor, descendant);},
isSibling : function(self, sibling) {
var parent = self.parentNode;for (var i = 0;i < parent.childNodes.length;i++) {
if (parent.childNodes[i] == sibling) return true;}
return false;}
}
AjaxControlToolkit._DomUtility.registerClass("AjaxControlToolkit._DomUtility");AjaxControlToolkit.DomUtility = new AjaxControlToolkit._DomUtility();AjaxControlToolkit.TextBoxWrapper = function(element) {
AjaxControlToolkit.TextBoxWrapper.initializeBase(this, [element]);this._current = element.value;this._watermark = null;this._isWatermarked = false;}
AjaxControlToolkit.TextBoxWrapper.prototype = {
dispose : function() {
this.get_element().AjaxControlToolkitTextBoxWrapper = null;AjaxControlToolkit.TextBoxWrapper.callBaseMethod(this, 'dispose');},
get_Current : function() {
this._current = this.get_element().value;return this._current;},
set_Current : function(value) {
this._current = value;this._updateElement();},
get_Value : function() {
if (this.get_IsWatermarked()) {
return "";} else {
return this.get_Current();}
},
set_Value : function(text) {
this.set_Current(text);if (!text || (0 == text.length)) {
if (null != this._watermark) {
this.set_IsWatermarked(true);}
} else {
this.set_IsWatermarked(false);}
},
get_Watermark : function() {
return this._watermark;},
set_Watermark : function(value) {
this._watermark = value;this._updateElement();},
get_IsWatermarked : function() {
return this._isWatermarked;},
set_IsWatermarked : function(isWatermarked) {
if (this._isWatermarked != isWatermarked) {
this._isWatermarked = isWatermarked;this._updateElement();this._raiseWatermarkChanged();}
},
_updateElement : function() {
var element = this.get_element();if (this._isWatermarked) {
if (element.value != this._watermark) {
element.value = this._watermark;}
} else {
if (element.value != this._current) {
element.value = this._current;}
}
},
add_WatermarkChanged : function(handler) {
this.get_events().addHandler("WatermarkChanged", handler);},
remove_WatermarkChanged : function(handler) {
this.get_events().removeHandler("WatermarkChanged", handler);},
_raiseWatermarkChanged : function() {
var onWatermarkChangedHandler = this.get_events().getHandler("WatermarkChanged");if (onWatermarkChangedHandler) {
onWatermarkChangedHandler(this, Sys.EventArgs.Empty);}
}
}
AjaxControlToolkit.TextBoxWrapper.get_Wrapper = function(element) {
if (null == element.AjaxControlToolkitTextBoxWrapper) {
element.AjaxControlToolkitTextBoxWrapper = new AjaxControlToolkit.TextBoxWrapper(element);}
return element.AjaxControlToolkitTextBoxWrapper;}
AjaxControlToolkit.TextBoxWrapper.registerClass('AjaxControlToolkit.TextBoxWrapper', Sys.UI.Behavior);AjaxControlToolkit.TextBoxWrapper.validatorGetValue = function(id) {
var control = $get(id);if (control && control.AjaxControlToolkitTextBoxWrapper) {
return control.AjaxControlToolkitTextBoxWrapper.get_Value();}
return AjaxControlToolkit.TextBoxWrapper._originalValidatorGetValue(id);}
if (typeof(ValidatorGetValue) == 'function') {
AjaxControlToolkit.TextBoxWrapper._originalValidatorGetValue = ValidatorGetValue;ValidatorGetValue = AjaxControlToolkit.TextBoxWrapper.validatorGetValue;}
if (Sys.CultureInfo.prototype._getAbbrMonthIndex) {
try {
Sys.CultureInfo.prototype._getAbbrMonthIndex('');} catch(ex) {
Sys.CultureInfo.prototype._getAbbrMonthIndex = function(value) {
if (!this._upperAbbrMonths) {
this._upperAbbrMonths = this._toUpperArray(this.dateTimeFormat.AbbreviatedMonthNames);}
return Array.indexOf(this._upperAbbrMonths, this._toUpper(value));}
Sys.CultureInfo.CurrentCulture._getAbbrMonthIndex = Sys.CultureInfo.prototype._getAbbrMonthIndex;Sys.CultureInfo.InvariantCulture._getAbbrMonthIndex = Sys.CultureInfo.prototype._getAbbrMonthIndex;}
}

//END AjaxControlToolkit.Common.Common.js
//START AjaxControlToolkit.ExtenderBase.BaseScripts.js
Type.registerNamespace('AjaxControlToolkit');AjaxControlToolkit.BehaviorBase = function(element) {
AjaxControlToolkit.BehaviorBase.initializeBase(this,[element]);this._clientStateFieldID = null;this._pageRequestManager = null;this._partialUpdateBeginRequestHandler = null;this._partialUpdateEndRequestHandler = null;}
AjaxControlToolkit.BehaviorBase.prototype = {
initialize : function() {
AjaxControlToolkit.BehaviorBase.callBaseMethod(this, 'initialize');},
dispose : function() {
AjaxControlToolkit.BehaviorBase.callBaseMethod(this, 'dispose');if (this._pageRequestManager) {
if (this._partialUpdateBeginRequestHandler) {
this._pageRequestManager.remove_beginRequest(this._partialUpdateBeginRequestHandler);this._partialUpdateBeginRequestHandler = null;}
if (this._partialUpdateEndRequestHandler) {
this._pageRequestManager.remove_endRequest(this._partialUpdateEndRequestHandler);this._partialUpdateEndRequestHandler = null;}
this._pageRequestManager = null;}
},
get_ClientStateFieldID : function() {
return this._clientStateFieldID;},
set_ClientStateFieldID : function(value) {
if (this._clientStateFieldID != value) {
this._clientStateFieldID = value;this.raisePropertyChanged('ClientStateFieldID');}
},
get_ClientState : function() {
if (this._clientStateFieldID) {
var input = document.getElementById(this._clientStateFieldID);if (input) {
return input.value;}
}
return null;},
set_ClientState : function(value) {
if (this._clientStateFieldID) {
var input = document.getElementById(this._clientStateFieldID);if (input) {
input.value = value;}
}
},
registerPartialUpdateEvents : function() {
if (Sys && Sys.WebForms && Sys.WebForms.PageRequestManager){
this._pageRequestManager = Sys.WebForms.PageRequestManager.getInstance();if (this._pageRequestManager) {
this._partialUpdateBeginRequestHandler = Function.createDelegate(this, this._partialUpdateBeginRequest);this._pageRequestManager.add_beginRequest(this._partialUpdateBeginRequestHandler);this._partialUpdateEndRequestHandler = Function.createDelegate(this, this._partialUpdateEndRequest);this._pageRequestManager.add_endRequest(this._partialUpdateEndRequestHandler);}
}
},
_partialUpdateBeginRequest : function(sender, beginRequestEventArgs) {
},
_partialUpdateEndRequest : function(sender, endRequestEventArgs) {
}
}
AjaxControlToolkit.BehaviorBase.registerClass('AjaxControlToolkit.BehaviorBase', Sys.UI.Behavior);AjaxControlToolkit.DynamicPopulateBehaviorBase = function(element) {
AjaxControlToolkit.DynamicPopulateBehaviorBase.initializeBase(this, [element]);this._DynamicControlID = null;this._DynamicContextKey = null;this._DynamicServicePath = null;this._DynamicServiceMethod = null;this._cacheDynamicResults = false;this._dynamicPopulateBehavior = null;this._populatingHandler = null;this._populatedHandler = null;}
AjaxControlToolkit.DynamicPopulateBehaviorBase.prototype = {
initialize : function() {
AjaxControlToolkit.DynamicPopulateBehaviorBase.callBaseMethod(this, 'initialize');this._populatingHandler = Function.createDelegate(this, this._onPopulating);this._populatedHandler = Function.createDelegate(this, this._onPopulated);},
dispose : function() {
if (this._populatedHandler) {
if (this._dynamicPopulateBehavior) {
this._dynamicPopulateBehavior.remove_populated(this._populatedHandler);}
this._populatedHandler = null;}
if (this._populatingHandler) {
if (this._dynamicPopulateBehavior) {
this._dynamicPopulateBehavior.remove_populating(this._populatingHandler);}
this._populatingHandler = null;}
if (this._dynamicPopulateBehavior) {
this._dynamicPopulateBehavior.dispose();this._dynamicPopulateBehavior = null;}
AjaxControlToolkit.DynamicPopulateBehaviorBase.callBaseMethod(this, 'dispose');},
populate : function(contextKeyOverride) {
if (this._dynamicPopulateBehavior && (this._dynamicPopulateBehavior.get_element() != $get(this._DynamicControlID))) {
this._dynamicPopulateBehavior.dispose();this._dynamicPopulateBehavior = null;}
if (!this._dynamicPopulateBehavior && this._DynamicControlID && this._DynamicServiceMethod) {
this._dynamicPopulateBehavior = $create(AjaxControlToolkit.DynamicPopulateBehavior,
{
"id" : this.get_id() + "_DynamicPopulateBehavior",
"ContextKey" : this._DynamicContextKey,
"ServicePath" : this._DynamicServicePath,
"ServiceMethod" : this._DynamicServiceMethod,
"cacheDynamicResults" : this._cacheDynamicResults
}, null, null, $get(this._DynamicControlID));this._dynamicPopulateBehavior.add_populating(this._populatingHandler);this._dynamicPopulateBehavior.add_populated(this._populatedHandler);}
if (this._dynamicPopulateBehavior) {
this._dynamicPopulateBehavior.populate(contextKeyOverride ? contextKeyOverride : this._DynamicContextKey);}
},
_onPopulating : function(sender, eventArgs) {
this.raisePopulating(eventArgs);},
_onPopulated : function(sender, eventArgs) {
this.raisePopulated(eventArgs);},
get_dynamicControlID : function() {
return this._DynamicControlID;},
get_DynamicControlID : this.get_dynamicControlID,
set_dynamicControlID : function(value) {
if (this._DynamicControlID != value) {
this._DynamicControlID = value;this.raisePropertyChanged('dynamicControlID');this.raisePropertyChanged('DynamicControlID');}
},
set_DynamicControlID : this.set_dynamicControlID,
get_dynamicContextKey : function() {
return this._DynamicContextKey;},
get_DynamicContextKey : this.get_dynamicContextKey,
set_dynamicContextKey : function(value) {
if (this._DynamicContextKey != value) {
this._DynamicContextKey = value;this.raisePropertyChanged('dynamicContextKey');this.raisePropertyChanged('DynamicContextKey');}
},
set_DynamicContextKey : this.set_dynamicContextKey,
get_dynamicServicePath : function() {
return this._DynamicServicePath;},
get_DynamicServicePath : this.get_dynamicServicePath,
set_dynamicServicePath : function(value) {
if (this._DynamicServicePath != value) {
this._DynamicServicePath = value;this.raisePropertyChanged('dynamicServicePath');this.raisePropertyChanged('DynamicServicePath');}
},
set_DynamicServicePath : this.set_dynamicServicePath,
get_dynamicServiceMethod : function() {
return this._DynamicServiceMethod;},
get_DynamicServiceMethod : this.get_dynamicServiceMethod,
set_dynamicServiceMethod : function(value) {
if (this._DynamicServiceMethod != value) {
this._DynamicServiceMethod = value;this.raisePropertyChanged('dynamicServiceMethod');this.raisePropertyChanged('DynamicServiceMethod');}
},
set_DynamicServiceMethod : this.set_dynamicServiceMethod,
get_cacheDynamicResults : function() {
return this._cacheDynamicResults;},
set_cacheDynamicResults : function(value) {
if (this._cacheDynamicResults != value) {
this._cacheDynamicResults = value;this.raisePropertyChanged('cacheDynamicResults');}
},
add_populated : function(handler) {
this.get_events().addHandler("populated", handler);},
remove_populated : function(handler) {
this.get_events().removeHandler("populated", handler);},
raisePopulated : function(arg) {
var handler = this.get_events().getHandler("populated");if (handler) handler(this, arg);},
add_populating : function(handler) {
this.get_events().addHandler('populating', handler);},
remove_populating : function(handler) {
this.get_events().removeHandler('populating', handler);},
raisePopulating : function(eventArgs) {
var handler = this.get_events().getHandler('populating');if (handler) {
handler(this, eventArgs);}
}
}
AjaxControlToolkit.DynamicPopulateBehaviorBase.registerClass('AjaxControlToolkit.DynamicPopulateBehaviorBase', AjaxControlToolkit.BehaviorBase);AjaxControlToolkit.ControlBase = function(element) {
AjaxControlToolkit.ControlBase.initializeBase(this, [element]);this._clientStateField = null;this._callbackTarget = null;this._onsubmit$delegate = Function.createDelegate(this, this._onsubmit);this._oncomplete$delegate = Function.createDelegate(this, this._oncomplete);this._onerror$delegate = Function.createDelegate(this, this._onerror);}
AjaxControlToolkit.ControlBase.prototype = {
initialize : function() {
AjaxControlToolkit.ControlBase.callBaseMethod(this, "initialize");if (this._clientStateField) {
this.loadClientState(this._clientStateField.value);}
if (typeof(Sys.WebForms)!=="undefined" && typeof(Sys.WebForms.PageRequestManager)!=="undefined") {
Array.add(Sys.WebForms.PageRequestManager.getInstance()._onSubmitStatements, this._onsubmit$delegate);} else {
$addHandler(document.forms[0], "submit", this._onsubmit$delegate);}
},
dispose : function() {
if (typeof(Sys.WebForms)!=="undefined" && typeof(Sys.WebForms.PageRequestManager)!=="undefined") {
Array.remove(Sys.WebForms.PageRequestManager.getInstance()._onSubmitStatements, this._onsubmit$delegate);} else {
$removeHandler(document.forms[0], "submit", this._onsubmit$delegate);}
AjaxControlToolkit.ControlBase.callBaseMethod(this, "dispose");},
findElement : function(id) {
return $get(this.get_id() + '_' + id.split(':').join('_'));},
get_clientStateField : function() {
return this._clientStateField;},
set_clientStateField : function(value) {
if (this.get_isInitialized()) throw Error.invalidOperation(AjaxControlToolkit.Resources.ExtenderBase_CannotSetClientStateField);if (this._clientStateField != value) {
this._clientStateField = value;this.raisePropertyChanged('clientStateField');}
},
loadClientState : function(value) {
},
saveClientState : function() {
return null;},
_invoke : function(name, args, cb) {
if (!this._callbackTarget) {
throw Error.invalidOperation(AjaxControlToolkit.Resources.ExtenderBase_ControlNotRegisteredForCallbacks);}
if (typeof(WebForm_DoCallback)==="undefined") {
throw Error.invalidOperation(AjaxControlToolkit.Resources.ExtenderBase_PageNotRegisteredForCallbacks);}
var ar = [];for (var i = 0;i < args.length;i++) 
ar[i] = args[i];var clientState = this.saveClientState();if (clientState != null && !String.isInstanceOfType(clientState)) {
throw Error.invalidOperation(AjaxControlToolkit.Resources.ExtenderBase_InvalidClientStateType);}
var payload = Sys.Serialization.JavaScriptSerializer.serialize({name:name,args:ar,state:this.saveClientState()});WebForm_DoCallback(this._callbackTarget, payload, this._oncomplete$delegate, cb, this._onerror$delegate, true);},
_oncomplete : function(result, context) {
result = Sys.Serialization.JavaScriptSerializer.deserialize(result);if (result.error) {
throw Error.create(result.error);}
this.loadClientState(result.state);context(result.result);},
_onerror : function(message, context) {
throw Error.create(message);},
_onsubmit : function() {
if (this._clientStateField) {
this._clientStateField.value = this.saveClientState();}
return true;} 
}
AjaxControlToolkit.ControlBase.registerClass("AjaxControlToolkit.ControlBase", Sys.UI.Control);
AjaxControlToolkit.Resources={
"PasswordStrength_InvalidWeightingRatios":"Strength Weighting ratios must have 4 elements","Animation_ChildrenNotAllowed":"AjaxControlToolkit.Animation.createAnimation cannot add child animations to type \"{0}\" that does not derive from AjaxControlToolkit.Animation.ParentAnimation","PasswordStrength_RemainingSymbols":"{0} symbol characters","ExtenderBase_CannotSetClientStateField":"clientStateField can only be set before initialization","RTE_PreviewHTML":"Preview HTML","RTE_JustifyCenter":"Justify Center","PasswordStrength_RemainingUpperCase":"{0} more upper case characters","Animation_TargetNotFound":"AjaxControlToolkit.Animation.Animation.set_animationTarget requires the ID of a Sys.UI.DomElement or Sys.UI.Control.  No element or control could be found corresponding to \"{0}\"","RTE_FontColor":"Font Color","RTE_LabelColor":"Label Color","Common_InvalidBorderWidthUnit":"A unit type of \"{0}\"\u0027 is invalid for parseBorderWidth","RTE_Heading":"Heading","Tabs_PropertySetBeforeInitialization":"{0} cannot be changed before initialization","RTE_OrderedList":"Ordered List","ReorderList_DropWatcherBehavior_NoChild":"Could not find child of list with id \"{0}\"","CascadingDropDown_MethodTimeout":"[Method timeout]","RTE_Columns":"Columns","RTE_InsertImage":"Insert Image","RTE_InsertTable":"Insert Table","RTE_Values":"Values","RTE_OK":"OK","ExtenderBase_PageNotRegisteredForCallbacks":"This Page has not been registered for callbacks","Animation_NoDynamicPropertyFound":"AjaxControlToolkit.Animation.createAnimation found no property corresponding to \"{0}\" or \"{1}\"","Animation_InvalidBaseType":"AjaxControlToolkit.Animation.registerAnimation can only register types that inherit from AjaxControlToolkit.Animation.Animation","RTE_UnorderedList":"Unordered List","ResizableControlBehavior_InvalidHandler":"{0} handler not a function, function name, or function text","Animation_InvalidColor":"Color must be a 7-character hex representation (e.g. #246ACF), not \"{0}\"","RTE_CellColor":"Cell Color","PasswordStrength_RemainingMixedCase":"Mixed case characters","RTE_Italic":"Italic","CascadingDropDown_NoParentElement":"Failed to find parent element \"{0}\"","ValidatorCallout_DefaultErrorMessage":"This control is invalid","RTE_Indent":"Indent","ReorderList_DropWatcherBehavior_CallbackError":"Reorder failed, see details below.\\r\\n\\r\\n{0}","PopupControl_NoDefaultProperty":"No default property supported for control \"{0}\" of type \"{1}\"","RTE_Normal":"Normal","PopupExtender_NoParentElement":"Couldn\u0027t find parent element \"{0}\"","RTE_ViewValues":"View Values","RTE_Legend":"Legend","RTE_Labels":"Labels","RTE_CellSpacing":"Cell Spacing","PasswordStrength_RemainingNumbers":"{0} more numbers","RTE_Border":"Border","RTE_Create":"Create","RTE_BackgroundColor":"Background Color","RTE_Cancel":"Cancel","RTE_JustifyFull":"Justify Full","RTE_JustifyLeft":"Justify Left","RTE_Cut":"Cut","ResizableControlBehavior_CannotChangeProperty":"Changes to {0} not supported","RTE_ViewSource":"View Source","Common_InvalidPaddingUnit":"A unit type of \"{0}\" is invalid for parsePadding","RTE_Paste":"Paste","ExtenderBase_ControlNotRegisteredForCallbacks":"This Control has not been registered for callbacks","Calendar_Today":"Today: {0}","Common_DateTime_InvalidFormat":"Invalid format","ListSearch_DefaultPrompt":"Type to search","CollapsiblePanel_NoControlID":"Failed to find element \"{0}\"","RTE_ViewEditor":"View Editor","RTE_BarColor":"Bar Color","PasswordStrength_DefaultStrengthDescriptions":"NonExistent;Very Weak;Weak;Poor;Almost OK;Barely Acceptable;Average;Good;Strong;Excellent;Unbreakable!","RTE_Inserttexthere":"Insert text here","Animation_UknownAnimationName":"AjaxControlToolkit.Animation.createAnimation could not find an Animation corresponding to the name \"{0}\"","ExtenderBase_InvalidClientStateType":"saveClientState must return a value of type String","Rating_CallbackError":"An unhandled exception has occurred:\\r\\n{0}","Tabs_OwnerExpected":"owner must be set before initialize","DynamicPopulate_WebServiceTimeout":"Web service call timed out","PasswordStrength_RemainingLowerCase":"{0} more lower case characters","Animation_MissingAnimationName":"AjaxControlToolkit.Animation.createAnimation requires an object with an AnimationName property","RTE_JustifyRight":"Justify Right","Tabs_ActiveTabArgumentOutOfRange":"Argument is not a member of the tabs collection","RTE_CellPadding":"Cell Padding","RTE_ClearFormatting":"Clear Formatting","AlwaysVisible_ElementRequired":"AjaxControlToolkit.AlwaysVisibleControlBehavior must have an element","Slider_NoSizeProvided":"Please set valid values for the height and width attributes in the slider\u0027s CSS classes","DynamicPopulate_WebServiceError":"Web Service call failed: {0}","PasswordStrength_StrengthPrompt":"Strength: ","PasswordStrength_RemainingCharacters":"{0} more characters","PasswordStrength_Satisfied":"Nothing more required","RTE_Hyperlink":"Hyperlink","Animation_NoPropertyFound":"AjaxControlToolkit.Animation.createAnimation found no property corresponding to \"{0}\"","PasswordStrength_InvalidStrengthDescriptionStyles":"Text Strength description style classes must match the number of text descriptions.","PasswordStrength_GetHelpRequirements":"Get help on password requirements","PasswordStrength_InvalidStrengthDescriptions":"Invalid number of text strength descriptions specified","RTE_Underline":"Underline","Tabs_PropertySetAfterInitialization":"{0} cannot be changed after initialization","RTE_Rows":"Rows","RTE_Redo":"Redo","RTE_Size":"Size","RTE_Undo":"Undo","RTE_Bold":"Bold","RTE_Copy":"Copy","RTE_Font":"Font","CascadingDropDown_MethodError":"[Method error {0}]","RTE_BorderColor":"Border Color","RTE_Paragraph":"Paragraph","RTE_InsertHorizontalRule":"Insert Horizontal Rule","Common_UnitHasNoDigits":"No digits","RTE_Outdent":"Outdent","Common_DateTime_InvalidTimeSpan":"\"{0}\" is not a valid TimeSpan format","Animation_CannotNestSequence":"AjaxControlToolkit.Animation.SequenceAnimation cannot be nested inside AjaxControlToolkit.Animation.ParallelAnimation","Shared_BrowserSecurityPreventsPaste":"Your browser security settings don\u0027t permit the automatic execution of paste operations. Please use the keyboard shortcut Ctrl+V instead."};
//END AjaxControlToolkit.ExtenderBase.BaseScripts.js
//START AjaxControlToolkit.TextboxWatermark.TextboxWatermark.js
Type.registerNamespace('AjaxControlToolkit');AjaxControlToolkit.TextBoxWatermarkBehavior = function(element) {
AjaxControlToolkit.TextBoxWatermarkBehavior.initializeBase(this, [element]);this._watermarkText = null;this._watermarkCssClass = null;this._focusHandler = null;this._blurHandler = null;this._keyPressHandler = null;this._propertyChangedHandler = null;this._watermarkChangedHandler = null;this._oldClassName = null;this._clearedForSubmit = null;this._maxLength = null;if ((typeof(WebForm_OnSubmit) == 'function') && !AjaxControlToolkit.TextBoxWatermarkBehavior._originalWebForm_OnSubmit) {
AjaxControlToolkit.TextBoxWatermarkBehavior._originalWebForm_OnSubmit = WebForm_OnSubmit;WebForm_OnSubmit = AjaxControlToolkit.TextBoxWatermarkBehavior.WebForm_OnSubmit;}
}
AjaxControlToolkit.TextBoxWatermarkBehavior.prototype = {
initialize : function() {
AjaxControlToolkit.TextBoxWatermarkBehavior.callBaseMethod(this, 'initialize');var e = this.get_element();var hasInitialFocus = false;var clientState = AjaxControlToolkit.TextBoxWatermarkBehavior.callBaseMethod(this, 'get_ClientState');if (clientState != null && clientState != "") {
hasInitialFocus = (clientState == "Focused");AjaxControlToolkit.TextBoxWatermarkBehavior.callBaseMethod(this, 'set_ClientState', null);}
this._oldClassName = e.className;this._focusHandler = Function.createDelegate(this, this._onFocus);this._blurHandler = Function.createDelegate(this, this._onBlur);this._keyPressHandler = Function.createDelegate(this, this._onKeyPress);$addHandler(e, 'focus', this._focusHandler);$addHandler(e, 'blur', this._blurHandler);$addHandler(e, 'keypress', this._keyPressHandler);this.registerPropertyChanged();var currentValue = AjaxControlToolkit.TextBoxWrapper.get_Wrapper(this.get_element()).get_Current();var wrapper = AjaxControlToolkit.TextBoxWrapper.get_Wrapper(this.get_element());if (("" == currentValue) || (this._watermarkText == currentValue)) {
wrapper.set_Watermark(this._watermarkText)
wrapper.set_IsWatermarked(true);}
if (hasInitialFocus) {
this._onFocus();} else {
e.blur();this._onBlur();}
this._clearedForSubmit = false;this.registerPartialUpdateEvents();this._watermarkChangedHandler = Function.createDelegate(this, this._onWatermarkChanged);wrapper.add_WatermarkChanged(this._watermarkChangedHandler);},
dispose : function() {
var e = this.get_element();if (this._watermarkChangedHandler) {
AjaxControlToolkit.TextBoxWrapper.get_Wrapper(this.get_element()).remove_WatermarkChanged(this._watermarkChangedHandler);this._watermarkChangedHandler = null;}
if(e.control && this._propertyChangedHandler) {
e.control.remove_propertyChanged(this._propertyChangedHandler);this._propertyChangedHandler = null;}
if (this._focusHandler) {
$removeHandler(e, 'focus', this._focusHandler);this._focusHandler = null;}
if (this._blurHandler) {
$removeHandler(e, 'blur', this._blurHandler);this._blurHandler = null;}
if (this._keyPressHandler) {
$removeHandler(e, 'keypress', this._keyPressHandler);this._keyPressHandler = null;}
if(AjaxControlToolkit.TextBoxWrapper.get_Wrapper(this.get_element()).get_IsWatermarked()) {
this.clearText(false);}
AjaxControlToolkit.TextBoxWatermarkBehavior.callBaseMethod(this, 'dispose');},
_onWatermarkChanged : function(sender, eventArgs) {
if (AjaxControlToolkit.TextBoxWrapper.get_Wrapper(this.get_element()).get_IsWatermarked()) {
this._onBlur();} else {
this._onFocus();}
},
clearText : function(focusing) {
var element = this.get_element();var wrapper = AjaxControlToolkit.TextBoxWrapper.get_Wrapper(element);wrapper.set_Value("");wrapper.set_IsWatermarked(false);if(focusing) {
element.setAttribute("autocomplete","off");element.select();}
},
_onFocus : function(evt) {
var e = this.get_element();if(AjaxControlToolkit.TextBoxWrapper.get_Wrapper(e).get_IsWatermarked()) {
this.clearText(evt ? true : false);}
e.className = this._oldClassName;if (this._maxLength > 0) {
this.get_element().maxLength = this._maxLength;this._maxLength = null;}
},
_onBlur : function() {
var wrapper = AjaxControlToolkit.TextBoxWrapper.get_Wrapper(this.get_element());if(("" == wrapper.get_Current()) || wrapper.get_IsWatermarked()) {
if (this.get_element().maxLength > 0 && this._watermarkText.length > this.get_element().maxLength) {
this._maxLength = this.get_element().maxLength;this.get_element().maxLength = this._watermarkText.length;}
this._applyWatermark();}
},
_applyWatermark : function() {
var wrapper = AjaxControlToolkit.TextBoxWrapper.get_Wrapper(this.get_element());wrapper.set_Watermark(this._watermarkText);wrapper.set_IsWatermarked(true);if(this._watermarkCssClass) {
this.get_element().className = this._watermarkCssClass;}
},
_onKeyPress : function() {
AjaxControlToolkit.TextBoxWrapper.get_Wrapper(this.get_element()).set_IsWatermarked(false);},
registerPropertyChanged : function() {
var e = this.get_element();if(e.control && !this._propertyChangedHandler) {
this._propertyChangedHandler = Function.createDelegate(this, this._onPropertyChanged);e.control.add_propertyChanged(this._propertyChangedHandler);}
},
_onPropertyChanged : function(sender, propertyChangedEventArgs) {
if("text" == propertyChangedEventArgs.get_propertyName()) {
this.set_Value(AjaxControlToolkit.TextBoxWrapper.get_Wrapper(this.get_element()).get_Current());}
},
_onSubmit : function() {
if(AjaxControlToolkit.TextBoxWrapper.get_Wrapper(this.get_element()).get_IsWatermarked()) {
this.clearText(false);this._clearedForSubmit = true;}
},
_partialUpdateEndRequest : function(sender, endRequestEventArgs) {
AjaxControlToolkit.TextBoxWatermarkBehavior.callBaseMethod(this, '_partialUpdateEndRequest', [sender, endRequestEventArgs]);if (this.get_element() && this._clearedForSubmit) {
this.get_element().blur();this._onBlur();this._clearedForSubmit = false;}
},
get_WatermarkText : function() {
return this._watermarkText;},
set_WatermarkText : function(value) {
if (this._watermarkText != value) {
this._watermarkText = value;if (AjaxControlToolkit.TextBoxWrapper.get_Wrapper(this.get_element()).get_IsWatermarked()) {
this._applyWatermark();}
this.raisePropertyChanged('WatermarkText');}
},
get_WatermarkCssClass : function() {
return this._watermarkCssClass;},
set_WatermarkCssClass : function(value) {
if (this._watermarkCssClass != value) {
this._watermarkCssClass = value;if (AjaxControlToolkit.TextBoxWrapper.get_Wrapper(this.get_element()).get_IsWatermarked()) {
this._applyWatermark();}
this.raisePropertyChanged('WatermarkCssClass');}
},
get_Text : function() {
return AjaxControlToolkit.TextBoxWrapper.get_Wrapper(this.get_element()).get_Value();},
set_Text : function(value) {
if ("" == value) {
AjaxControlToolkit.TextBoxWrapper.get_Wrapper(this.get_element()).set_Current("");this.get_element().blur();this._onBlur();} else {
this._onFocus();AjaxControlToolkit.TextBoxWrapper.get_Wrapper(this.get_element()).set_Current(value);}
}
}
AjaxControlToolkit.TextBoxWatermarkBehavior.registerClass('AjaxControlToolkit.TextBoxWatermarkBehavior', AjaxControlToolkit.BehaviorBase);AjaxControlToolkit.TextBoxWatermarkBehavior.WebForm_OnSubmit = function() {
var result = AjaxControlToolkit.TextBoxWatermarkBehavior._originalWebForm_OnSubmit();if (result) {
var components = Sys.Application.getComponents();for(var i = 0 ;i < components.length ;i++) {
var component = components[i];if (AjaxControlToolkit.TextBoxWatermarkBehavior.isInstanceOfType(component)) {
component._onSubmit();}
}
}
return result;}

//END AjaxControlToolkit.TextboxWatermark.TextboxWatermark.js
//START AjaxControlToolkit.Compat.Timer.Timer.js
/////////////////////////////////////////////////////////////////////////////
Sys.Timer = function() {
Sys.Timer.initializeBase(this);this._interval = 1000;this._enabled = false;this._timer = null;}
Sys.Timer.prototype = {
get_interval: function() {
return this._interval;},
set_interval: function(value) {
if (this._interval !== value) {
this._interval = value;this.raisePropertyChanged('interval');if (!this.get_isUpdating() && (this._timer !== null)) {
this._stopTimer();this._startTimer();}
}
},
get_enabled: function() {
return this._enabled;},
set_enabled: function(value) {
if (value !== this.get_enabled()) {
this._enabled = value;this.raisePropertyChanged('enabled');if (!this.get_isUpdating()) {
if (value) {
this._startTimer();}
else {
this._stopTimer();}
}
}
},
add_tick: function(handler) {
this.get_events().addHandler("tick", handler);},
remove_tick: function(handler) {
this.get_events().removeHandler("tick", handler);},
dispose: function() {
this.set_enabled(false);this._stopTimer();Sys.Timer.callBaseMethod(this, 'dispose');},
updated: function() {
Sys.Timer.callBaseMethod(this, 'updated');if (this._enabled) {
this._stopTimer();this._startTimer();}
},
_timerCallback: function() {
var handler = this.get_events().getHandler("tick");if (handler) {
handler(this, Sys.EventArgs.Empty);}
},
_startTimer: function() {
this._timer = window.setInterval(Function.createDelegate(this, this._timerCallback), this._interval);},
_stopTimer: function() {
window.clearInterval(this._timer);this._timer = null;}
}
Sys.Timer.descriptor = {
properties: [ {name: 'interval', type: Number},
{name: 'enabled', type: Boolean} ],
events: [ {name: 'tick'} ]
}
Sys.Timer.registerClass('Sys.Timer', Sys.Component);
//END AjaxControlToolkit.Compat.Timer.Timer.js
//START AjaxControlToolkit.Animation.Animations.js
Type.registerNamespace('AjaxControlToolkit.Animation');var $AA = AjaxControlToolkit.Animation;$AA.registerAnimation = function(name, type) {
if (type && ((type === $AA.Animation) || (type.inheritsFrom && type.inheritsFrom($AA.Animation)))) {
if (!$AA.__animations) {
$AA.__animations = { };}
$AA.__animations[name.toLowerCase()] = type;type.play = function() {
var animation = new type();type.apply(animation, arguments);animation.initialize();var handler = Function.createDelegate(animation,
function() {
animation.remove_ended(handler);handler = null;animation.dispose();});animation.add_ended(handler);animation.play();}
} else {
throw Error.argumentType('type', type, $AA.Animation, AjaxControlToolkit.Resources.Animation_InvalidBaseType);}
}
$AA.buildAnimation = function(json, defaultTarget) {
if (!json || json === '') {
return null;}
var obj;json = '(' + json + ')';if (! Sys.Debug.isDebug) {
try { obj = Sys.Serialization.JavaScriptSerializer.deserialize(json);} catch (ex) { } 
} else {
obj = Sys.Serialization.JavaScriptSerializer.deserialize(json);}
return $AA.createAnimation(obj, defaultTarget);}
$AA.createAnimation = function(obj, defaultTarget) {
if (!obj || !obj.AnimationName) {
throw Error.argument('obj', AjaxControlToolkit.Resources.Animation_MissingAnimationName);}
var type = $AA.__animations[obj.AnimationName.toLowerCase()];if (!type) {
throw Error.argument('type', String.format(AjaxControlToolkit.Resources.Animation_UknownAnimationName, obj.AnimationName));}
var animation = new type();if (defaultTarget) {
animation.set_target(defaultTarget);}
if (obj.AnimationChildren && obj.AnimationChildren.length) {
if ($AA.ParentAnimation.isInstanceOfType(animation)) {
for (var i = 0;i < obj.AnimationChildren.length;i++) {
var child = $AA.createAnimation(obj.AnimationChildren[i]);if (child) {
animation.add(child);}
}
} else {
throw Error.argument('obj', String.format(AjaxControlToolkit.Resources.Animation_ChildrenNotAllowed, type.getName()));}
}
var properties = type.__animationProperties;if (!properties) {
type.__animationProperties = { };type.resolveInheritance();for (var name in type.prototype) {
if (name.startsWith('set_')) {
type.__animationProperties[name.substr(4).toLowerCase()] = name;}
}
delete type.__animationProperties['id'];properties = type.__animationProperties;}
for (var property in obj) {
var prop = property.toLowerCase();if (prop == 'animationname' || prop == 'animationchildren') {
continue;}
var value = obj[property];var setter = properties[prop];if (setter && String.isInstanceOfType(setter) && animation[setter]) {
if (! Sys.Debug.isDebug) {
try { animation[setter](value);} catch (ex) { }
} else {
animation[setter](value);}
} else {
if (prop.endsWith('script')) {
setter = properties[prop.substr(0, property.length - 6)];if (setter && String.isInstanceOfType(setter) && animation[setter]) {
animation.DynamicProperties[setter] = value;} else if ( Sys.Debug.isDebug) {
throw Error.argument('obj', String.format(AjaxControlToolkit.Resources.Animation_NoDynamicPropertyFound, property, property.substr(0, property.length - 5)));}
} else if ( Sys.Debug.isDebug) {
throw Error.argument('obj', String.format(AjaxControlToolkit.Resources.Animation_NoPropertyFound, property));}
}
}
return animation;}
$AA.Animation = function(target, duration, fps) {
$AA.Animation.initializeBase(this);this._duration = 1;this._fps = 25;this._target = null;this._tickHandler = null;this._timer = null;this._percentComplete = 0;this._percentDelta = null;this._owner = null;this._parentAnimation = null;this.DynamicProperties = { };if (target) {
this.set_target(target);}
if (duration) {
this.set_duration(duration);}
if (fps) { 
this.set_fps(fps);}
}
$AA.Animation.prototype = {
dispose : function() {
if (this._timer) {
this._timer.dispose();this._timer = null;}
this._tickHandler = null;this._target = null;$AA.Animation.callBaseMethod(this, 'dispose');},
play : function() {
if (!this._owner) {
var resume = true;if (!this._timer) {
resume = false;if (!this._tickHandler) {
this._tickHandler = Function.createDelegate(this, this._onTimerTick);}
this._timer = new Sys.Timer();this._timer.add_tick(this._tickHandler);this.onStart();this._timer.set_interval(1000 / this._fps);this._percentDelta = 100 / (this._duration * this._fps);this._updatePercentComplete(0, true);}
this._timer.set_enabled(true);this.raisePropertyChanged('isPlaying');if (!resume) {
this.raisePropertyChanged('isActive');}
}
},
pause : function() {
if (!this._owner) {
if (this._timer) {
this._timer.set_enabled(false);this.raisePropertyChanged('isPlaying');}
}
},
stop : function(finish) {
if (!this._owner) {
var t = this._timer;this._timer = null;if (t) {
t.dispose();if (this._percentComplete !== 100) {
this._percentComplete = 100;this.raisePropertyChanged('percentComplete');if (finish || finish === undefined) {
this.onStep(100);}
}
this.onEnd();this.raisePropertyChanged('isPlaying');this.raisePropertyChanged('isActive');}
}
},
onStart : function() {
this.raiseStarted();for (var property in this.DynamicProperties) {
try {
this[property](eval(this.DynamicProperties[property]));} catch(ex) {
if ( Sys.Debug.isDebug) {
throw ex;}
}
}
},
onStep : function(percentage) {
this.setValue(this.getAnimatedValue(percentage));},
onEnd : function() {
this.raiseEnded();},
getAnimatedValue : function(percentage) {
throw Error.notImplemented();},
setValue : function(value) {
throw Error.notImplemented();},
interpolate : function(start, end, percentage) {
return start + (end - start) * (percentage / 100);},
_onTimerTick : function() {
this._updatePercentComplete(this._percentComplete + this._percentDelta, true);},
_updatePercentComplete : function(percentComplete, animate) {
if (percentComplete > 100) {
percentComplete = 100;}
this._percentComplete = percentComplete;this.raisePropertyChanged('percentComplete');if (animate) {
this.onStep(percentComplete);}
if (percentComplete === 100) {
this.stop(false);}
},
setOwner : function(owner) {
this._owner = owner;},
raiseStarted : function() {
var handlers = this.get_events().getHandler('started');if (handlers) {
handlers(this, Sys.EventArgs.Empty);}
},
add_started : function(handler) {
this.get_events().addHandler("started", handler);},
remove_started : function(handler) {
this.get_events().removeHandler("started", handler);},
raiseEnded : function() {
var handlers = this.get_events().getHandler('ended');if (handlers) {
handlers(this, Sys.EventArgs.Empty);}
},
add_ended : function(handler) {
this.get_events().addHandler("ended", handler);},
remove_ended : function(handler) {
this.get_events().removeHandler("ended", handler);},
get_target : function() {
if (!this._target && this._parentAnimation) {
return this._parentAnimation.get_target();}
return this._target;},
set_target : function(value) {
if (this._target != value) {
this._target = value;this.raisePropertyChanged('target');}
},
set_animationTarget : function(id) {
var target = null;var element = $get(id);if (element) {
target = element;} else {
var ctrl = $find(id);if (ctrl) {
element = ctrl.get_element();if (element) {
target = element;}
}
}
if (target) { 
this.set_target(target);} else {
throw Error.argument('id', String.format(AjaxControlToolkit.Resources.Animation_TargetNotFound, id));}
},
get_duration : function() {
return this._duration;},
set_duration : function(value) {
value = this._getFloat(value);if (this._duration != value) {
this._duration = value;this.raisePropertyChanged('duration');}
},
get_fps : function() {
return this._fps;},
set_fps : function(value) {
value = this._getInteger(value);if (this.fps != value) {
this._fps = value;this.raisePropertyChanged('fps');}
},
get_isActive : function() {
return (this._timer !== null);},
get_isPlaying : function() {
return (this._timer !== null) && this._timer.get_enabled();},
get_percentComplete : function() {
return this._percentComplete;},
_getBoolean : function(value) {
if (String.isInstanceOfType(value)) {
return Boolean.parse(value);}
return value;},
_getInteger : function(value) {
if (String.isInstanceOfType(value)) {
return parseInt(value);}
return value;},
_getFloat : function(value) {
if (String.isInstanceOfType(value)) {
return parseFloat(value);}
return value;},
_getEnum : function(value, type) {
if (String.isInstanceOfType(value) && type && type.parse) {
return type.parse(value);}
return value;}
}
$AA.Animation.registerClass('AjaxControlToolkit.Animation.Animation', Sys.Component);$AA.registerAnimation('animation', $AA.Animation);$AA.ParentAnimation = function(target, duration, fps, animations) {
$AA.ParentAnimation.initializeBase(this, [target, duration, fps]);this._animations = [];if (animations && animations.length) {
for (var i = 0;i < animations.length;i++) {
this.add(animations[i]);}
}
}
$AA.ParentAnimation.prototype = {
initialize : function() {
$AA.ParentAnimation.callBaseMethod(this, 'initialize');if (this._animations) {
for (var i = 0;i < this._animations.length;i++) {
var animation = this._animations[i];if (animation && !animation.get_isInitialized) {
animation.initialize();}
}
}
},
dispose : function() {
this.clear();this._animations = null;$AA.ParentAnimation.callBaseMethod(this, 'dispose');},
get_animations : function() {
return this._animations;},
add : function(animation) {
if (this._animations) {
if (animation) {
animation._parentAnimation = this;}
Array.add(this._animations, animation);this.raisePropertyChanged('animations');}
},
remove : function(animation) {
if (this._animations) {
if (animation) {
animation.dispose();}
Array.remove(this._animations, animation);this.raisePropertyChanged('animations');}
},
removeAt : function(index) {
if (this._animations) {
var animation = this._animations[index];if (animation) {
animation.dispose();}
Array.removeAt(this._animations, index);this.raisePropertyChanged('animations');}
},
clear : function() {
if (this._animations) {
for (var i = this._animations.length - 1;i >= 0;i--) {
this._animations[i].dispose();this._animations[i] = null;}
Array.clear(this._animations);this._animations = [];this.raisePropertyChanged('animations');}
}
}
$AA.ParentAnimation.registerClass('AjaxControlToolkit.Animation.ParentAnimation', $AA.Animation);$AA.registerAnimation('parent', $AA.ParentAnimation);$AA.ParallelAnimation = function(target, duration, fps, animations) {
$AA.ParallelAnimation.initializeBase(this, [target, duration, fps, animations]);}
$AA.ParallelAnimation.prototype = {
add : function(animation) {
$AA.ParallelAnimation.callBaseMethod(this, 'add', [animation]);animation.setOwner(this);},
onStart : function() {
$AA.ParallelAnimation.callBaseMethod(this, 'onStart');var animations = this.get_animations();for (var i = 0;i < animations.length;i++) {
animations[i].onStart();}
},
onStep : function(percentage) {
var animations = this.get_animations();for (var i = 0;i < animations.length;i++) {
animations[i].onStep(percentage);}
},
onEnd : function() {
var animations = this.get_animations();for (var i = 0;i < animations.length;i++) {
animations[i].onEnd();}
$AA.ParallelAnimation.callBaseMethod(this, 'onEnd');}
}
$AA.ParallelAnimation.registerClass('AjaxControlToolkit.Animation.ParallelAnimation', $AA.ParentAnimation);$AA.registerAnimation('parallel', $AA.ParallelAnimation);$AA.SequenceAnimation = function(target, duration, fps, animations, iterations) {
$AA.SequenceAnimation.initializeBase(this, [target, duration, fps, animations]);this._handler = null;this._paused = false;this._playing = false;this._index = 0;this._remainingIterations = 0;this._iterations = (iterations !== undefined) ? iterations : 1;}
$AA.SequenceAnimation.prototype = {
dispose : function() {
this._handler = null;$AA.SequenceAnimation.callBaseMethod(this, 'dispose');},
stop : function() {
if (this._playing) {
var animations = this.get_animations();if (this._index < animations.length) {
animations[this._index].remove_ended(this._handler);for (var i = this._index;i < animations.length;i++) {
animations[i].stop();}
}
this._playing = false;this._paused = false;this.raisePropertyChanged('isPlaying');this.onEnd();}
},
pause : function() {
if (this.get_isPlaying()) {
var current = this.get_animations()[this._index];if (current != null) {
current.pause();}
this._paused = true;this.raisePropertyChanged('isPlaying');}
},
play : function() {
var animations = this.get_animations();if (!this._playing) {
this._playing = true;if (this._paused) {
this._paused = false;var current = animations[this._index];if (current != null) {
current.play();this.raisePropertyChanged('isPlaying');}
} else {
this.onStart();this._index = 0;var first = animations[this._index];if (first) {
first.add_ended(this._handler);first.play();this.raisePropertyChanged('isPlaying');} else {
this.stop();}
}
}
},
onStart : function() {
$AA.SequenceAnimation.callBaseMethod(this, 'onStart');this._remainingIterations = this._iterations - 1;if (!this._handler) {
this._handler = Function.createDelegate(this, this._onEndAnimation);}
},
_onEndAnimation : function() {
var animations = this.get_animations();var current = animations[this._index++];if (current) {
current.remove_ended(this._handler);}
if (this._index < animations.length) {
var next = animations[this._index];next.add_ended(this._handler);next.play();} else if (this._remainingIterations >= 1 || this._iterations <= 0) {
this._remainingIterations--;this._index = 0;var first = animations[0];first.add_ended(this._handler);first.play();} else {
this.stop();}
},
onStep : function(percentage) {
throw Error.invalidOperation(AjaxControlToolkit.Resources.Animation_CannotNestSequence);},
onEnd : function() {
this._remainingIterations = 0;$AA.SequenceAnimation.callBaseMethod(this, 'onEnd');},
get_isActive : function() {
return true;},
get_isPlaying : function() {
return this._playing && !this._paused;},
get_iterations : function() {
return this._iterations;},
set_iterations : function(value) {
value = this._getInteger(value);if (this._iterations != value) {
this._iterations = value;this.raisePropertyChanged('iterations');}
},
get_isInfinite : function() {
return this._iterations <= 0;}
}
$AA.SequenceAnimation.registerClass('AjaxControlToolkit.Animation.SequenceAnimation', $AA.ParentAnimation);$AA.registerAnimation('sequence', $AA.SequenceAnimation);$AA.SelectionAnimation = function(target, duration, fps, animations) {
$AA.SelectionAnimation.initializeBase(this, [target, duration, fps, animations]);this._selectedIndex = -1;this._selected = null;}
$AA.SelectionAnimation.prototype = { 
getSelectedIndex : function() {
throw Error.notImplemented();},
onStart : function() {
$AA.SelectionAnimation.callBaseMethod(this, 'onStart');var animations = this.get_animations();this._selectedIndex = this.getSelectedIndex();if (this._selectedIndex >= 0 && this._selectedIndex < animations.length) {
this._selected = animations[this._selectedIndex];if (this._selected) {
this._selected.setOwner(this);this._selected.onStart();}
}
},
onStep : function(percentage) {
if (this._selected) {
this._selected.onStep(percentage);}
},
onEnd : function() {
if (this._selected) {
this._selected.onEnd();this._selected.setOwner(null);}
this._selected = null;this._selectedIndex = null;$AA.SelectionAnimation.callBaseMethod(this, 'onEnd');}
}
$AA.SelectionAnimation.registerClass('AjaxControlToolkit.Animation.SelectionAnimation', $AA.ParentAnimation);$AA.registerAnimation('selection', $AA.SelectionAnimation);$AA.ConditionAnimation = function(target, duration, fps, animations, conditionScript) {
$AA.ConditionAnimation.initializeBase(this, [target, duration, fps, animations]);this._conditionScript = conditionScript;}
$AA.ConditionAnimation.prototype = { 
getSelectedIndex : function() {
var selected = -1;if (this._conditionScript && this._conditionScript.length > 0) {
try {
selected = eval(this._conditionScript) ? 0 : 1;} catch(ex) {
}
}
return selected;},
get_conditionScript : function() {
return this._conditionScript;},
set_conditionScript : function(value) {
if (this._conditionScript != value) {
this._conditionScript = value;this.raisePropertyChanged('conditionScript');}
}
}
$AA.ConditionAnimation.registerClass('AjaxControlToolkit.Animation.ConditionAnimation', $AA.SelectionAnimation);$AA.registerAnimation('condition', $AA.ConditionAnimation);$AA.CaseAnimation = function(target, duration, fps, animations, selectScript) {
$AA.CaseAnimation.initializeBase(this, [target, duration, fps, animations]);this._selectScript = selectScript;}
$AA.CaseAnimation.prototype = {
getSelectedIndex : function() {
var selected = -1;if (this._selectScript && this._selectScript.length > 0) {
try {
var result = eval(this._selectScript)
if (result !== undefined)
selected = result;} catch (ex) {
}
}
return selected;},
get_selectScript : function() {
return this._selectScript;},
set_selectScript : function(value) {
if (this._selectScript != value) {
this._selectScript = value;this.raisePropertyChanged('selectScript');}
}
}
$AA.CaseAnimation.registerClass('AjaxControlToolkit.Animation.CaseAnimation', $AA.SelectionAnimation);$AA.registerAnimation('case', $AA.CaseAnimation);$AA.FadeEffect = function() {
throw Error.invalidOperation();}
$AA.FadeEffect.prototype = {
FadeIn : 0,
FadeOut : 1
}
$AA.FadeEffect.registerEnum("AjaxControlToolkit.Animation.FadeEffect", false);$AA.FadeAnimation = function(target, duration, fps, effect, minimumOpacity, maximumOpacity, forceLayoutInIE) {
$AA.FadeAnimation.initializeBase(this, [target, duration, fps]);this._effect = (effect !== undefined) ? effect : $AA.FadeEffect.FadeIn;this._max = (maximumOpacity !== undefined) ? maximumOpacity : 1;this._min = (minimumOpacity !== undefined) ? minimumOpacity : 0;this._start = this._min;this._end = this._max;this._layoutCreated = false;this._forceLayoutInIE = (forceLayoutInIE === undefined || forceLayoutInIE === null) ? true : forceLayoutInIE;this._currentTarget = null;this._resetOpacities();}
$AA.FadeAnimation.prototype = {
_resetOpacities : function() {
if (this._effect == $AA.FadeEffect.FadeIn) {
this._start = this._min;this._end = this._max;} else {
this._start = this._max;this._end = this._min;}
},
_createLayout : function() {
var element = this._currentTarget;if (element) {
var originalWidth = $common.getCurrentStyle(element, 'width');var originalHeight = $common.getCurrentStyle(element, 'height');var originalBackColor = $common.getCurrentStyle(element, 'backgroundColor');if ((!originalWidth || originalWidth == '' || originalWidth == 'auto') &&
(!originalHeight || originalHeight == '' || originalHeight == 'auto')) {
element.style.width = element.offsetWidth + 'px';}
if (!originalBackColor || originalBackColor == '' || originalBackColor == 'transparent' || originalBackColor == 'rgba(0, 0, 0, 0)') {
element.style.backgroundColor = $common.getInheritedBackgroundColor(element);}
this._layoutCreated = true;}
},
onStart : function() {
$AA.FadeAnimation.callBaseMethod(this, 'onStart');this._currentTarget = this.get_target();this.setValue(this._start);if (this._forceLayoutInIE && !this._layoutCreated && Sys.Browser.agent == Sys.Browser.InternetExplorer) {
this._createLayout();}
},
getAnimatedValue : function(percentage) {
return this.interpolate(this._start, this._end, percentage);},
setValue : function(value) {
if (this._currentTarget) {
$common.setElementOpacity(this._currentTarget, value);}
},
get_effect : function() {
return this._effect;},
set_effect : function(value) {
value = this._getEnum(value, $AA.FadeEffect);if (this._effect != value) {
this._effect = value;this._resetOpacities();this.raisePropertyChanged('effect');}
},
get_minimumOpacity : function() {
return this._min;},
set_minimumOpacity : function(value) {
value = this._getFloat(value);if (this._min != value) {
this._min = value;this._resetOpacities();this.raisePropertyChanged('minimumOpacity');}
},
get_maximumOpacity : function() {
return this._max;},
set_maximumOpacity : function(value) {
value = this._getFloat(value);if (this._max != value) {
this._max = value;this._resetOpacities();this.raisePropertyChanged('maximumOpacity');}
},
get_forceLayoutInIE : function() {
return this._forceLayoutInIE;},
set_forceLayoutInIE : function(value) {
value = this._getBoolean(value);if (this._forceLayoutInIE != value) {
this._forceLayoutInIE = value;this.raisePropertyChanged('forceLayoutInIE');}
},
set_startValue : function(value) {
value = this._getFloat(value);this._start = value;}
}
$AA.FadeAnimation.registerClass('AjaxControlToolkit.Animation.FadeAnimation', $AA.Animation);$AA.registerAnimation('fade', $AA.FadeAnimation);$AA.FadeInAnimation = function(target, duration, fps, minimumOpacity, maximumOpacity, forceLayoutInIE) {
$AA.FadeInAnimation.initializeBase(this, [target, duration, fps, $AA.FadeEffect.FadeIn, minimumOpacity, maximumOpacity, forceLayoutInIE]);}
$AA.FadeInAnimation.prototype = {
onStart : function() {
$AA.FadeInAnimation.callBaseMethod(this, 'onStart');if (this._currentTarget) {
this.set_startValue($common.getElementOpacity(this._currentTarget));}
}
}
$AA.FadeInAnimation.registerClass('AjaxControlToolkit.Animation.FadeInAnimation', $AA.FadeAnimation);$AA.registerAnimation('fadeIn', $AA.FadeInAnimation);$AA.FadeOutAnimation = function(target, duration, fps, minimumOpacity, maximumOpacity, forceLayoutInIE) {
$AA.FadeOutAnimation.initializeBase(this, [target, duration, fps, $AA.FadeEffect.FadeOut, minimumOpacity, maximumOpacity, forceLayoutInIE]);}
$AA.FadeOutAnimation.prototype = {
onStart : function() {
$AA.FadeOutAnimation.callBaseMethod(this, 'onStart');if (this._currentTarget) {
this.set_startValue($common.getElementOpacity(this._currentTarget));}
}
}
$AA.FadeOutAnimation.registerClass('AjaxControlToolkit.Animation.FadeOutAnimation', $AA.FadeAnimation);$AA.registerAnimation('fadeOut', $AA.FadeOutAnimation);$AA.PulseAnimation = function(target, duration, fps, iterations, minimumOpacity, maximumOpacity, forceLayoutInIE) {
$AA.PulseAnimation.initializeBase(this, [target, duration, fps, null, ((iterations !== undefined) ? iterations : 3)]);this._out = new $AA.FadeOutAnimation(target, duration, fps, minimumOpacity, maximumOpacity, forceLayoutInIE);this.add(this._out);this._in = new $AA.FadeInAnimation(target, duration, fps, minimumOpacity, maximumOpacity, forceLayoutInIE);this.add(this._in);}
$AA.PulseAnimation.prototype = {
get_minimumOpacity : function() {
return this._out.get_minimumOpacity();},
set_minimumOpacity : function(value) {
value = this._getFloat(value);this._out.set_minimumOpacity(value);this._in.set_minimumOpacity(value);this.raisePropertyChanged('minimumOpacity');},
get_maximumOpacity : function() {
return this._out.get_maximumOpacity();},
set_maximumOpacity : function(value) {
value = this._getFloat(value);this._out.set_maximumOpacity(value);this._in.set_maximumOpacity(value);this.raisePropertyChanged('maximumOpacity');},
get_forceLayoutInIE : function() {
return this._out.get_forceLayoutInIE();},
set_forceLayoutInIE : function(value) {
value = this._getBoolean(value);this._out.set_forceLayoutInIE(value);this._in.set_forceLayoutInIE(value);this.raisePropertyChanged('forceLayoutInIE');},
set_duration : function(value) {
value = this._getFloat(value);$AA.PulseAnimation.callBaseMethod(this, 'set_duration', [value]);this._in.set_duration(value);this._out.set_duration(value);},
set_fps : function(value) {
value = this._getInteger(value);$AA.PulseAnimation.callBaseMethod(this, 'set_fps', [value]);this._in.set_fps(value);this._out.set_fps(value);}
}
$AA.PulseAnimation.registerClass('AjaxControlToolkit.Animation.PulseAnimation', $AA.SequenceAnimation);$AA.registerAnimation('pulse', $AA.PulseAnimation);$AA.PropertyAnimation = function(target, duration, fps, property, propertyKey) {
$AA.PropertyAnimation.initializeBase(this, [target, duration, fps]);this._property = property;this._propertyKey = propertyKey;this._currentTarget = null;}
$AA.PropertyAnimation.prototype = {
onStart : function() {
$AA.PropertyAnimation.callBaseMethod(this, 'onStart');this._currentTarget = this.get_target();},
setValue : function(value) {
var element = this._currentTarget;if (element && this._property && this._property.length > 0) { 
if (this._propertyKey && this._propertyKey.length > 0 && element[this._property]) {
element[this._property][this._propertyKey] = value;} else {
element[this._property] = value;}
}
},
getValue : function() {
var element = this.get_target();if (element && this._property && this._property.length > 0) { 
var property = element[this._property];if (property) {
if (this._propertyKey && this._propertyKey.length > 0) {
return property[this._propertyKey];}
return property;}
}
return null;},
get_property : function() {
return this._property;},
set_property : function(value) {
if (this._property != value) {
this._property = value;this.raisePropertyChanged('property');}
},
get_propertyKey : function() {
return this._propertyKey;},
set_propertyKey : function(value) {
if (this._propertyKey != value) {
this._propertyKey = value;this.raisePropertyChanged('propertyKey');}
}
}
$AA.PropertyAnimation.registerClass('AjaxControlToolkit.Animation.PropertyAnimation', $AA.Animation);$AA.registerAnimation('property', $AA.PropertyAnimation);$AA.DiscreteAnimation = function(target, duration, fps, property, propertyKey, values) {
$AA.DiscreteAnimation.initializeBase(this, [target, duration, fps, property, propertyKey]);this._values = (values && values.length) ? values : [];}
$AA.DiscreteAnimation.prototype = {
getAnimatedValue : function(percentage) {
var index = Math.floor(this.interpolate(0, this._values.length - 1, percentage));return this._values[index];},
get_values : function() {
return this._values;},
set_values : function(value) {
if (this._values != value) {
this._values = value;this.raisePropertyChanged('values');}
}
}
$AA.DiscreteAnimation.registerClass('AjaxControlToolkit.Animation.DiscreteAnimation', $AA.PropertyAnimation);$AA.registerAnimation('discrete', $AA.DiscreteAnimation);$AA.InterpolatedAnimation = function(target, duration, fps, property, propertyKey, startValue, endValue) {
$AA.InterpolatedAnimation.initializeBase(this, [target, duration, fps, ((property !== undefined) ? property : 'style'), propertyKey]);this._startValue = startValue;this._endValue = endValue;}
$AA.InterpolatedAnimation.prototype = {
get_startValue : function() {
return this._startValue;},
set_startValue : function(value) {
value = this._getFloat(value);if (this._startValue != value) {
this._startValue = value;this.raisePropertyChanged('startValue');}
},
get_endValue : function() {
return this._endValue;},
set_endValue : function(value) {
value = this._getFloat(value);if (this._endValue != value) {
this._endValue = value;this.raisePropertyChanged('endValue');}
} 
}
$AA.InterpolatedAnimation.registerClass('AjaxControlToolkit.Animation.InterpolatedAnimation', $AA.PropertyAnimation);$AA.registerAnimation('interpolated', $AA.InterpolatedAnimation);$AA.ColorAnimation = function(target, duration, fps, property, propertyKey, startValue, endValue) {
$AA.ColorAnimation.initializeBase(this, [target, duration, fps, property, propertyKey, startValue, endValue]);this._start = null;this._end = null;this._interpolateRed = false;this._interpolateGreen = false;this._interpolateBlue = false;}
$AA.ColorAnimation.prototype = {
onStart : function() {
$AA.ColorAnimation.callBaseMethod(this, 'onStart');this._start = $AA.ColorAnimation.getRGB(this.get_startValue());this._end = $AA.ColorAnimation.getRGB(this.get_endValue());this._interpolateRed = (this._start.Red != this._end.Red);this._interpolateGreen = (this._start.Green != this._end.Green);this._interpolateBlue = (this._start.Blue != this._end.Blue);},
getAnimatedValue : function(percentage) {
var r = this._start.Red;var g = this._start.Green;var b = this._start.Blue;if (this._interpolateRed)
r = Math.round(this.interpolate(r, this._end.Red, percentage));if (this._interpolateGreen)
g = Math.round(this.interpolate(g, this._end.Green, percentage));if (this._interpolateBlue)
b = Math.round(this.interpolate(b, this._end.Blue, percentage));return $AA.ColorAnimation.toColor(r, g, b);},
set_startValue : function(value) {
if (this._startValue != value) {
this._startValue = value;this.raisePropertyChanged('startValue');}
},
set_endValue : function(value) {
if (this._endValue != value) {
this._endValue = value;this.raisePropertyChanged('endValue');}
} 
}
$AA.ColorAnimation.getRGB = function(color) {
if (!color || color.length != 7) {
throw String.format(AjaxControlToolkit.Resources.Animation_InvalidColor, color);}
return { 'Red': parseInt(color.substr(1,2), 16),
'Green': parseInt(color.substr(3,2), 16),
'Blue': parseInt(color.substr(5,2), 16) };}
$AA.ColorAnimation.toColor = function(red, green, blue) {
var r = red.toString(16);var g = green.toString(16);var b = blue.toString(16);if (r.length == 1) r = '0' + r;if (g.length == 1) g = '0' + g;if (b.length == 1) b = '0' + b;return '#' + r + g + b;}
$AA.ColorAnimation.registerClass('AjaxControlToolkit.Animation.ColorAnimation', $AA.InterpolatedAnimation);$AA.registerAnimation('color', $AA.ColorAnimation);$AA.LengthAnimation = function(target, duration, fps, property, propertyKey, startValue, endValue, unit) {
$AA.LengthAnimation.initializeBase(this, [target, duration, fps, property, propertyKey, startValue, endValue]);this._unit = (unit != null) ? unit : 'px';}
$AA.LengthAnimation.prototype = {
getAnimatedValue : function(percentage) {
var value = this.interpolate(this.get_startValue(), this.get_endValue(), percentage);return Math.round(value) + this._unit;},
get_unit : function() {
return this._unit;},
set_unit : function(value) {
if (this._unit != value) {
this._unit = value;this.raisePropertyChanged('unit');}
}
}
$AA.LengthAnimation.registerClass('AjaxControlToolkit.Animation.LengthAnimation', $AA.InterpolatedAnimation);$AA.registerAnimation('length', $AA.LengthAnimation);$AA.MoveAnimation = function(target, duration, fps, horizontal, vertical, relative, unit) {
$AA.MoveAnimation.initializeBase(this, [target, duration, fps, null]);this._horizontal = horizontal ? horizontal : 0;this._vertical = vertical ? vertical : 0;this._relative = (relative === undefined) ? true : relative;this._horizontalAnimation = new $AA.LengthAnimation(target, duration, fps, 'style', 'left', null, null, unit);this._verticalAnimation = new $AA.LengthAnimation(target, duration, fps, 'style', 'top', null, null, unit);this.add(this._verticalAnimation);this.add(this._horizontalAnimation);}
$AA.MoveAnimation.prototype = {
onStart : function() {
$AA.MoveAnimation.callBaseMethod(this, 'onStart');var element = this.get_target();this._horizontalAnimation.set_startValue(element.offsetLeft);this._horizontalAnimation.set_endValue(this._relative ? element.offsetLeft + this._horizontal : this._horizontal);this._verticalAnimation.set_startValue(element.offsetTop);this._verticalAnimation.set_endValue(this._relative ? element.offsetTop + this._vertical : this._vertical);},
get_horizontal : function() {
return this._horizontal;},
set_horizontal : function(value) {
value = this._getFloat(value);if (this._horizontal != value) {
this._horizontal = value;this.raisePropertyChanged('horizontal');}
},
get_vertical : function() {
return this._vertical;},
set_vertical : function(value) {
value = this._getFloat(value);if (this._vertical != value) {
this._vertical = value;this.raisePropertyChanged('vertical');}
},
get_relative : function() {
return this._relative;},
set_relative : function(value) {
value = this._getBoolean(value);if (this._relative != value) {
this._relative = value;this.raisePropertyChanged('relative');}
},
get_unit : function() {
this._horizontalAnimation.get_unit();},
set_unit : function(value) {
var unit = this._horizontalAnimation.get_unit();if (unit != value) {
this._horizontalAnimation.set_unit(value);this._verticalAnimation.set_unit(value);this.raisePropertyChanged('unit');}
}
}
$AA.MoveAnimation.registerClass('AjaxControlToolkit.Animation.MoveAnimation', $AA.ParallelAnimation);$AA.registerAnimation('move', $AA.MoveAnimation);$AA.ResizeAnimation = function(target, duration, fps, width, height, unit) {
$AA.ResizeAnimation.initializeBase(this, [target, duration, fps, null]);this._width = width;this._height = height;this._horizontalAnimation = new $AA.LengthAnimation(target, duration, fps, 'style', 'width', null, null, unit);this._verticalAnimation = new $AA.LengthAnimation(target, duration, fps, 'style', 'height', null, null, unit);this.add(this._horizontalAnimation);this.add(this._verticalAnimation);}
$AA.ResizeAnimation.prototype = {
onStart : function() {
$AA.ResizeAnimation.callBaseMethod(this, 'onStart');var element = this.get_target();this._horizontalAnimation.set_startValue(element.offsetWidth);this._verticalAnimation.set_startValue(element.offsetHeight);this._horizontalAnimation.set_endValue((this._width !== null && this._width !== undefined) ?
this._width : element.offsetWidth);this._verticalAnimation.set_endValue((this._height !== null && this._height !== undefined) ?
this._height : element.offsetHeight);},
get_width : function() {
return this._width;},
set_width : function(value) {
value = this._getFloat(value);if (this._width != value) {
this._width = value;this.raisePropertyChanged('width');}
},
get_height : function() {
return this._height;},
set_height : function(value) {
value = this._getFloat(value);if (this._height != value) {
this._height = value;this.raisePropertyChanged('height');}
},
get_unit : function() {
this._horizontalAnimation.get_unit();},
set_unit : function(value) {
var unit = this._horizontalAnimation.get_unit();if (unit != value) {
this._horizontalAnimation.set_unit(value);this._verticalAnimation.set_unit(value);this.raisePropertyChanged('unit');}
}
}
$AA.ResizeAnimation.registerClass('AjaxControlToolkit.Animation.ResizeAnimation', $AA.ParallelAnimation);$AA.registerAnimation('resize', $AA.ResizeAnimation);$AA.ScaleAnimation = function(target, duration, fps, scaleFactor, unit, center, scaleFont, fontUnit) {
$AA.ScaleAnimation.initializeBase(this, [target, duration, fps]);this._scaleFactor = (scaleFactor !== undefined) ? scaleFactor : 1;this._unit = (unit !== undefined) ? unit : 'px';this._center = center;this._scaleFont = scaleFont;this._fontUnit = (fontUnit !== undefined) ? fontUnit : 'pt';this._element = null;this._initialHeight = null;this._initialWidth = null;this._initialTop = null;this._initialLeft = null;this._initialFontSize = null;}
$AA.ScaleAnimation.prototype = { 
getAnimatedValue : function(percentage) {
return this.interpolate(1.0, this._scaleFactor, percentage);},
onStart : function() {
$AA.ScaleAnimation.callBaseMethod(this, 'onStart');this._element = this.get_target();if (this._element) {
this._initialHeight = this._element.offsetHeight;this._initialWidth = this._element.offsetWidth;if (this._center) {
this._initialTop = this._element.offsetTop;this._initialLeft = this._element.offsetLeft;}
if (this._scaleFont) {
this._initialFontSize = parseFloat(
$common.getCurrentStyle(this._element, 'fontSize'));}
}
},
setValue : function(scale) {
if (this._element) {
var width = Math.round(this._initialWidth * scale);var height = Math.round(this._initialHeight * scale);this._element.style.width = width + this._unit;this._element.style.height = height + this._unit;if (this._center) {
this._element.style.top = (this._initialTop +
Math.round((this._initialHeight - height) / 2)) + this._unit;this._element.style.left = (this._initialLeft +
Math.round((this._initialWidth - width) / 2)) + this._unit;}
if (this._scaleFont) {
var size = this._initialFontSize * scale;if (this._fontUnit == 'px' || this._fontUnit == 'pt') {
size = Math.round(size);}
this._element.style.fontSize = size + this._fontUnit;}
}
},
onEnd : function() {
this._element = null;this._initialHeight = null;this._initialWidth = null;this._initialTop = null;this._initialLeft = null;this._initialFontSize = null;$AA.ScaleAnimation.callBaseMethod(this, 'onEnd');},
get_scaleFactor : function() {
return this._scaleFactor;},
set_scaleFactor : function(value) {
value = this._getFloat(value);if (this._scaleFactor != value) {
this._scaleFactor = value;this.raisePropertyChanged('scaleFactor');}
},
get_unit : function() {
return this._unit;},
set_unit : function(value) {
if (this._unit != value) {
this._unit = value;this.raisePropertyChanged('unit');}
},
get_center : function() {
return this._center;},
set_center : function(value) {
value = this._getBoolean(value);if (this._center != value) {
this._center = value;this.raisePropertyChanged('center');}
},
get_scaleFont : function() {
return this._scaleFont;},
set_scaleFont : function(value) {
value = this._getBoolean(value);if (this._scaleFont != value) {
this._scaleFont = value;this.raisePropertyChanged('scaleFont');}
},
get_fontUnit : function() {
return this._fontUnit;},
set_fontUnit : function(value) {
if (this._fontUnit != value) { 
this._fontUnit = value;this.raisePropertyChanged('fontUnit');}
}
}
$AA.ScaleAnimation.registerClass('AjaxControlToolkit.Animation.ScaleAnimation', $AA.Animation);$AA.registerAnimation('scale', $AA.ScaleAnimation);$AA.Action = function(target, duration, fps) {
$AA.Action.initializeBase(this, [target, duration, fps]);if (duration === undefined) {
this.set_duration(0);}
}
$AA.Action.prototype = {
onEnd : function() {
this.doAction();$AA.Action.callBaseMethod(this, 'onEnd');},
doAction : function() {
throw Error.notImplemented();},
getAnimatedValue : function() {
},
setValue : function() {
}
}
$AA.Action.registerClass('AjaxControlToolkit.Animation.Action', $AA.Animation);$AA.registerAnimation('action', $AA.Action);$AA.EnableAction = function(target, duration, fps, enabled) {
$AA.EnableAction.initializeBase(this, [target, duration, fps]);this._enabled = (enabled !== undefined) ? enabled : true;}
$AA.EnableAction.prototype = {
doAction : function() {
var element = this.get_target();if (element) {
element.disabled = !this._enabled;}
},
get_enabled : function() {
return this._enabled;},
set_enabled : function(value) {
value = this._getBoolean(value);if (this._enabled != value) {
this._enabled = value;this.raisePropertyChanged('enabled');}
}
}
$AA.EnableAction.registerClass('AjaxControlToolkit.Animation.EnableAction', $AA.Action);$AA.registerAnimation('enableAction', $AA.EnableAction);$AA.HideAction = function(target, duration, fps, visible) {
$AA.HideAction.initializeBase(this, [target, duration, fps]);this._visible = visible;}
$AA.HideAction.prototype = {
doAction : function() {
var element = this.get_target();if (element) {
$common.setVisible(element, this._visible);}
},
get_visible : function() {
return this._visible;},
set_visible : function(value) {
if (this._visible != value) {
this._visible = value;this.raisePropertyChanged('visible');}
}
}
$AA.HideAction.registerClass('AjaxControlToolkit.Animation.HideAction', $AA.Action);$AA.registerAnimation('hideAction', $AA.HideAction);$AA.StyleAction = function(target, duration, fps, attribute, value) {
$AA.StyleAction.initializeBase(this, [target, duration, fps]);this._attribute = attribute;this._value = value;}
$AA.StyleAction.prototype = {
doAction : function() {
var element = this.get_target();if (element) {
element.style[this._attribute] = this._value;}
},
get_attribute : function() {
return this._attribute;},
set_attribute : function(value) {
if (this._attribute != value) {
this._attribute = value;this.raisePropertyChanged('attribute');}
},
get_value : function() {
return this._value;},
set_value : function(value) {
if (this._value != value) {
this._value = value;this.raisePropertyChanged('value');}
}
}
$AA.StyleAction.registerClass('AjaxControlToolkit.Animation.StyleAction', $AA.Action);$AA.registerAnimation('styleAction', $AA.StyleAction);$AA.OpacityAction = function(target, duration, fps, opacity) {
$AA.OpacityAction.initializeBase(this, [target, duration, fps]);this._opacity = opacity;}
$AA.OpacityAction.prototype = {
doAction : function() {
var element = this.get_target();if (element) {
$common.setElementOpacity(element, this._opacity);}
},
get_opacity : function() {
return this._opacity;},
set_opacity : function(value) {
value = this._getFloat(value);if (this._opacity != value) {
this._opacity = value;this.raisePropertyChanged('opacity');}
}
}
$AA.OpacityAction.registerClass('AjaxControlToolkit.Animation.OpacityAction', $AA.Action);$AA.registerAnimation('opacityAction', $AA.OpacityAction);$AA.ScriptAction = function(target, duration, fps, script) {
$AA.ScriptAction.initializeBase(this, [target, duration, fps]);this._script = script;}
$AA.ScriptAction.prototype = {
doAction : function() {
try {
eval(this._script);} catch (ex) {
}
},
get_script : function() {
return this._script;},
set_script : function(value) {
if (this._script != value) {
this._script = value;this.raisePropertyChanged('script');}
}
}
$AA.ScriptAction.registerClass('AjaxControlToolkit.Animation.ScriptAction', $AA.Action);$AA.registerAnimation('scriptAction', $AA.ScriptAction);
//END AjaxControlToolkit.Animation.Animations.js
//START AjaxControlToolkit.Animation.AnimationBehavior.js
Type.registerNamespace('AjaxControlToolkit.Animation');AjaxControlToolkit.Animation.AnimationBehavior = function(element) {
AjaxControlToolkit.Animation.AnimationBehavior.initializeBase(this, [element]);this._onLoad = null;this._onClick = null;this._onMouseOver = null;this._onMouseOut = null;this._onHoverOver = null;this._onHoverOut = null;this._onClickHandler = null;this._onMouseOverHandler = null;this._onMouseOutHandler = null;}
AjaxControlToolkit.Animation.AnimationBehavior.prototype = {
initialize : function() {
AjaxControlToolkit.Animation.AnimationBehavior.callBaseMethod(this, 'initialize');var element = this.get_element();if (element) {
this._onClickHandler = Function.createDelegate(this, this.OnClick);$addHandler(element, 'click', this._onClickHandler);this._onMouseOverHandler = Function.createDelegate(this, this.OnMouseOver);$addHandler(element, 'mouseover', this._onMouseOverHandler);this._onMouseOutHandler = Function.createDelegate(this, this.OnMouseOut);$addHandler(element, 'mouseout', this._onMouseOutHandler);}
},
dispose : function() {
var element = this.get_element();if (element) {
if (this._onClickHandler) {
$removeHandler(element, 'click', this._onClickHandler);this._onClickHandler = null;}
if (this._onMouseOverHandler) {
$removeHandler(element, 'mouseover', this._onMouseOverHandler);this._onMouseOverHandler = null;}
if (this._onMouseOutHandler) {
$removeHandler(element, 'mouseout', this._onMouseOutHandler);this._onMouseOutHandler = null;}
}
this._onLoad = null;this._onClick = null;this._onMouseOver = null;this._onMouseOut = null;this._onHoverOver = null;this._onHoverOut = null;AjaxControlToolkit.Animation.AnimationBehavior.callBaseMethod(this, 'dispose');},
get_OnLoad : function() {
return this._onLoad ? this._onLoad.get_json() : null;},
set_OnLoad : function(value) {
if (!this._onLoad) {
this._onLoad = new AjaxControlToolkit.Animation.GenericAnimationBehavior(this.get_element());this._onLoad.initialize();}
this._onLoad.set_json(value);this.raisePropertyChanged('OnLoad');this._onLoad.play();},
get_OnLoadBehavior : function() {
return this._onLoad;},
get_OnClick : function() {
return this._onClick ? this._onClick.get_json() : null;},
set_OnClick : function(value) {
if (!this._onClick) {
this._onClick = new AjaxControlToolkit.Animation.GenericAnimationBehavior(this.get_element());this._onClick.initialize();}
this._onClick.set_json(value);this.raisePropertyChanged('OnClick');},
get_OnClickBehavior : function() {
return this._onClick;},
OnClick : function() {
if (this._onClick) {
this._onClick.play();}
},
get_OnMouseOver : function() {
return this._onMouseOver ? this._onMouseOver.get_json() : null;},
set_OnMouseOver : function(value) {
if (!this._onMouseOver) {
this._onMouseOver = new AjaxControlToolkit.Animation.GenericAnimationBehavior(this.get_element());this._onMouseOver.initialize();}
this._onMouseOver.set_json(value);this.raisePropertyChanged('OnMouseOver');},
get_OnMouseOverBehavior : function() {
return this._onMouseOver;},
OnMouseOver : function() {
if (this._onMouseOver) {
this._onMouseOver.play();}
if (this._onHoverOver) {
if (this._onHoverOut) {
this._onHoverOut.quit();}
this._onHoverOver.play();}
},
get_OnMouseOut : function() {
return this._onMouseOut ? this._onMouseOut.get_json() : null;},
set_OnMouseOut : function(value) {
if (!this._onMouseOut) {
this._onMouseOut = new AjaxControlToolkit.Animation.GenericAnimationBehavior(this.get_element());this._onMouseOut.initialize();}
this._onMouseOut.set_json(value);this.raisePropertyChanged('OnMouseOut');},
get_OnMouseOutBehavior : function() {
return this._onMouseOut;},
OnMouseOut : function() {
if (this._onMouseOut) {
this._onMouseOut.play();}
if (this._onHoverOut) {
if (this._onHoverOver) {
this._onHoverOver.quit();}
this._onHoverOut.play();}
},
get_OnHoverOver : function() {
return this._onHoverOver ? this._onHoverOver.get_json() : null;},
set_OnHoverOver : function(value) {
if (!this._onHoverOver) {
this._onHoverOver = new AjaxControlToolkit.Animation.GenericAnimationBehavior(this.get_element());this._onHoverOver.initialize();}
this._onHoverOver.set_json(value);this.raisePropertyChanged('OnHoverOver');},
get_OnHoverOverBehavior : function() {
return this._onHoverOver;},
get_OnHoverOut : function() {
return this._onHoverOut ? this._onHoverOut.get_json() : null;},
set_OnHoverOut : function(value) {
if (!this._onHoverOut) {
this._onHoverOut = new AjaxControlToolkit.Animation.GenericAnimationBehavior(this.get_element());this._onHoverOut.initialize();}
this._onHoverOut.set_json(value);this.raisePropertyChanged('OnHoverOut');},
get_OnHoverOutBehavior : function() {
return this._onHoverOut;}
}
AjaxControlToolkit.Animation.AnimationBehavior.registerClass('AjaxControlToolkit.Animation.AnimationBehavior', AjaxControlToolkit.BehaviorBase);AjaxControlToolkit.Animation.GenericAnimationBehavior = function(element) {
AjaxControlToolkit.Animation.GenericAnimationBehavior.initializeBase(this, [element]);this._json = null;this._animation = null;}
AjaxControlToolkit.Animation.GenericAnimationBehavior.prototype = {
dispose : function() {
this.disposeAnimation();AjaxControlToolkit.Animation.GenericAnimationBehavior.callBaseMethod(this, 'dispose');},
disposeAnimation : function() {
if (this._animation) {
this._animation.dispose();}
this._animation = null;},
play : function() {
if (this._animation && !this._animation.get_isPlaying()) {
this.stop();this._animation.play();}
},
stop : function() {
if (this._animation) {
if (this._animation.get_isPlaying()) {
this._animation.stop(true);}
}
},
quit : function() {
if (this._animation) {
if (this._animation.get_isPlaying()) {
this._animation.stop(false);}
}
},
get_json : function() {
return this._json;},
set_json : function(value) {
if (this._json != value) {
this._json = value;this.raisePropertyChanged('json');this.disposeAnimation();var element = this.get_element();if (element) {
this._animation = AjaxControlToolkit.Animation.buildAnimation(this._json, element);if (this._animation) {
this._animation.initialize();}
this.raisePropertyChanged('animation');}
}
},
get_animation : function() {
return this._animation;}
}
AjaxControlToolkit.Animation.GenericAnimationBehavior.registerClass('AjaxControlToolkit.Animation.GenericAnimationBehavior', AjaxControlToolkit.BehaviorBase);
//END AjaxControlToolkit.Animation.AnimationBehavior.js
//START AjaxControlToolkit.PopupExtender.PopupBehavior.js
Type.registerNamespace('AjaxControlToolkit');AjaxControlToolkit.PopupBehavior = function(element) {
AjaxControlToolkit.PopupBehavior.initializeBase(this, [element]);this._x = 0;this._y = 0;this._positioningMode = AjaxControlToolkit.PositioningMode.Absolute;this._parentElement = null;this._parentElementID = null;this._moveHandler = null;this._firstPopup = true;this._originalParent = null;this._visible = false;this._onShow = null;this._onShowEndedHandler = null;this._onHide = null;this._onHideEndedHandler = null;}
AjaxControlToolkit.PopupBehavior.prototype = {
initialize : function() {
AjaxControlToolkit.PopupBehavior.callBaseMethod(this, 'initialize');this._hidePopup();this.get_element().style.position = "absolute";this._onShowEndedHandler = Function.createDelegate(this, this._onShowEnded);this._onHideEndedHandler = Function.createDelegate(this, this._onHideEnded);},
dispose : function() {
var element = this.get_element();if (element) {
if (this._visible) {
this.hide();}
if (this._originalParent) {
element.parentNode.removeChild(element);this._originalParent.appendChild(element);this._originalParent = null;}
element._hideWindowedElementsIFrame = null;}
this._parentElement = null;if (this._onShow && this._onShow.get_animation() && this._onShowEndedHandler) {
this._onShow.get_animation().remove_ended(this._onShowEndedHandler);}
this._onShowEndedHandler = null;this._onShow = null;if (this._onHide && this._onHide.get_animation() && this._onHideEndedHandler) {
this._onHide.get_animation().remove_ended(this._onHideEndedHandler);}
this._onHideEndedHandler = null;this._onHide = null;AjaxControlToolkit.PopupBehavior.callBaseMethod(this, 'dispose');},
show : function() {
if (this._visible) {
return;}
var eventArgs = new Sys.CancelEventArgs();this.raiseShowing(eventArgs);if (eventArgs.get_cancel()) {
return;}
this._visible = true;var element = this.get_element();$common.setVisible(element, true);this.setupPopup();if (this._onShow) {
$common.setVisible(element, false);this.onShow();} else {
this.raiseShown(Sys.EventArgs.Empty);}
},
hide : function() {
if (!this._visible) {
return;}
var eventArgs = new Sys.CancelEventArgs();this.raiseHiding(eventArgs);if (eventArgs.get_cancel()) {
return;}
this._visible = false;if (this._onHide) {
this.onHide();} else {
this._hidePopup();this._hideCleanup();}
},
getBounds : function() {
var element = this.get_element();var offsetParent = element.offsetParent || document.documentElement;var diff;var parentBounds;if (this._parentElement) {
parentBounds = $common.getBounds(this._parentElement);var offsetParentLocation = $common.getLocation(offsetParent);diff = {x: parentBounds.x - offsetParentLocation.x, y:parentBounds.y - offsetParentLocation.y};} else {
parentBounds = $common.getBounds(offsetParent);diff = {x:0, y:0};}
var width = element.offsetWidth - (element.clientLeft ? element.clientLeft * 2 : 0);var height = element.offsetHeight - (element.clientTop ? element.clientTop * 2 : 0);var position;switch (this._positioningMode) {
case AjaxControlToolkit.PositioningMode.Center:
position = {
x: Math.round(parentBounds.width / 2 - width / 2),
y: Math.round(parentBounds.height / 2 - height / 2)
};break;case AjaxControlToolkit.PositioningMode.BottomLeft:
position = {
x: 0,
y: parentBounds.height
};break;case AjaxControlToolkit.PositioningMode.BottomRight:
position = {
x: parentBounds.width - width,
y: parentBounds.height
};break;case AjaxControlToolkit.PositioningMode.TopLeft:
position = {
x: 0,
y: -element.offsetHeight
};break;case AjaxControlToolkit.PositioningMode.TopRight:
position = {
x: parentBounds.width - width,
y: -element.offsetHeight
};break;default:
position = {x: 0, y: 0};}
position.x += this._x + diff.x;position.y += this._y + diff.y;return new Sys.UI.Bounds(position.x, position.y, width, height);},
adjustPopupPosition : function(bounds) {
var element = this.get_element();if (!bounds) {
bounds = this.getBounds();}
if (this._firstPopup) {
element.style.width = bounds.width + "px";this._firstPopup = false;}
var newPosition = $common.getBounds(element);var updateNeeded = false;if (newPosition.x < 0) {
bounds.x -= newPosition.x;updateNeeded = true;}
if (newPosition.y < 0) {
bounds.y -= newPosition.y;updateNeeded = true;}
if (updateNeeded) {
$common.setLocation(element, bounds);}
},
addBackgroundIFrame : function() {
var element = this.get_element();if ((Sys.Browser.agent === Sys.Browser.InternetExplorer) && (Sys.Browser.version < 7)) {
var childFrame = element._hideWindowedElementsIFrame;if (!childFrame) {
childFrame = document.createElement("iframe");childFrame.src = "javascript:'<html></html>';";childFrame.style.position = "absolute";childFrame.style.display = "none";childFrame.scrolling = "no";childFrame.frameBorder = "0";childFrame.tabIndex = "-1";childFrame.style.filter = "progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)";element.parentNode.insertBefore(childFrame, element);element._hideWindowedElementsIFrame = childFrame;this._moveHandler = Function.createDelegate(this, this._onMove);Sys.UI.DomEvent.addHandler(element, "move", this._moveHandler);}
$common.setBounds(childFrame, $common.getBounds(element));childFrame.style.display = element.style.display;if (element.currentStyle && element.currentStyle.zIndex) {
childFrame.style.zIndex = element.currentStyle.zIndex;} else if (element.style.zIndex) {
childFrame.style.zIndex = element.style.zIndex;}
}
},
setupPopup : function() {
var element = this.get_element();var bounds = this.getBounds();$common.setLocation(element, bounds);this.adjustPopupPosition(bounds);element.zIndex = 1000;this.addBackgroundIFrame();},
_hidePopup : function() {
var element = this.get_element();$common.setVisible(element, false);if (element.originalWidth) {
element.style.width = element.originalWidth + "px";element.originalWidth = null;}
},
_hideCleanup : function() {
var element = this.get_element();if (this._moveHandler) {
Sys.UI.DomEvent.removeHandler(element, "move", this._moveHandler);this._moveHandler = null;}
if (Sys.Browser.agent === Sys.Browser.InternetExplorer) {
var childFrame = element._hideWindowedElementsIFrame;if (childFrame) {
childFrame.style.display = "none";}
}
this.raiseHidden(Sys.EventArgs.Empty);},
_onMove : function() {
var element = this.get_element();if (element._hideWindowedElementsIFrame) {
element.parentNode.insertBefore(element._hideWindowedElementsIFrame, element);element._hideWindowedElementsIFrame.style.top = element.style.top;element._hideWindowedElementsIFrame.style.left = element.style.left;}
},
get_onShow : function() {
return this._onShow ? this._onShow.get_json() : null;},
set_onShow : function(value) {
if (!this._onShow) {
this._onShow = new AjaxControlToolkit.Animation.GenericAnimationBehavior(this.get_element());this._onShow.initialize();}
this._onShow.set_json(value);var animation = this._onShow.get_animation();if (animation) {
animation.add_ended(this._onShowEndedHandler);}
this.raisePropertyChanged('onShow');},
get_onShowBehavior : function() {
return this._onShow;},
onShow : function() {
if (this._onShow) {
if (this._onHide) {
this._onHide.quit();}
this._onShow.play();}
},
_onShowEnded : function() {
this.adjustPopupPosition();this.addBackgroundIFrame();this.raiseShown(Sys.EventArgs.Empty);},
get_onHide : function() {
return this._onHide ? this._onHide.get_json() : null;},
set_onHide : function(value) {
if (!this._onHide) {
this._onHide = new AjaxControlToolkit.Animation.GenericAnimationBehavior(this.get_element());this._onHide.initialize();}
this._onHide.set_json(value);var animation = this._onHide.get_animation();if (animation) {
animation.add_ended(this._onHideEndedHandler);}
this.raisePropertyChanged('onHide');},
get_onHideBehavior : function() {
return this._onHide;},
onHide : function() {
if (this._onHide) {
if (this._onShow) {
this._onShow.quit();}
this._onHide.play();}
},
_onHideEnded : function() {
this._hideCleanup();},
get_parentElement : function() {
if (!this._parentElement && this._parentElementID) {
this.set_parentElement($get(this._parentElementID));Sys.Debug.assert(this._parentElement != null, String.format(AjaxControlToolkit.Resources.PopupExtender_NoParentElement, this._parentElementID));} 
return this._parentElement;},
set_parentElement : function(element) {
this._parentElement = element;this.raisePropertyChanged('parentElement');},
get_parentElementID : function() {
if (this._parentElement) {
return this._parentElement.id
}
return this._parentElementID;},
set_parentElementID : function(elementID) {
this._parentElementID = elementID;if (this.get_isInitialized()) {
this.set_parentElement($get(elementID));}
},
get_positioningMode : function() {
return this._positioningMode;},
set_positioningMode : function(mode) {
this._positioningMode = mode;this.raisePropertyChanged('positioningMode');},
get_x : function() {
return this._x;},
set_x : function(value) {
if (value != this._x) {
this._x = value;if (this._visible) {
this.setupPopup();}
this.raisePropertyChanged('x');}
},
get_y : function() {
return this._y;},
set_y : function(value) {
if (value != this._y) {
this._y = value;if (this._visible) {
this.setupPopup();}
this.raisePropertyChanged('y');}
},
get_visible : function() {
return this._visible;},
add_showing : function(handler) {
this.get_events().addHandler('showing', handler);},
remove_showing : function(handler) {
this.get_events().removeHandler('showing', handler);},
raiseShowing : function(eventArgs) {
var handler = this.get_events().getHandler('showing');if (handler) {
handler(this, eventArgs);}
},
add_shown : function(handler) {
this.get_events().addHandler('shown', handler);},
remove_shown : function(handler) {
this.get_events().removeHandler('shown', handler);},
raiseShown : function(eventArgs) {
var handler = this.get_events().getHandler('shown');if (handler) {
handler(this, eventArgs);}
}, 
add_hiding : function(handler) {
this.get_events().addHandler('hiding', handler);},
remove_hiding : function(handler) {
this.get_events().removeHandler('hiding', handler);},
raiseHiding : function(eventArgs) {
var handler = this.get_events().getHandler('hiding');if (handler) {
handler(this, eventArgs);}
},
add_hidden : function(handler) {
this.get_events().addHandler('hidden', handler);},
remove_hidden : function(handler) {
this.get_events().removeHandler('hidden', handler);},
raiseHidden : function(eventArgs) {
var handler = this.get_events().getHandler('hidden');if (handler) {
handler(this, eventArgs);}
}
}
AjaxControlToolkit.PopupBehavior.registerClass('AjaxControlToolkit.PopupBehavior', AjaxControlToolkit.BehaviorBase);AjaxControlToolkit.PositioningMode = function() {
throw Error.invalidOperation();}
AjaxControlToolkit.PositioningMode.prototype = {
Absolute: 0,
Center: 1,
BottomLeft: 2,
BottomRight: 3,
TopLeft: 4,
TopRight: 5
}
AjaxControlToolkit.PositioningMode.registerEnum('AjaxControlToolkit.PositioningMode');
//END AjaxControlToolkit.PopupExtender.PopupBehavior.js
//START AjaxControlToolkit.AutoComplete.AutoCompleteBehavior.js
Type.registerNamespace('AjaxControlToolkit');AjaxControlToolkit.AutoCompleteBehavior = function(element) {
AjaxControlToolkit.AutoCompleteBehavior.initializeBase(this, [element]);this._servicePath = null;this._serviceMethod = null;this._contextKey = null;this._useContextKey = false;this._minimumPrefixLength = 3;this._completionSetCount = 10;this._completionInterval = 1000;this._completionListElementID = null;this._completionListElement = null;this._textColor = 'windowtext';this._textBackground = 'window';this._popupBehavior = null;this._popupBehaviorHiddenHandler = null;this._onShowJson = null;this._onHideJson = null;this._timer = null;this._cache = null;this._currentPrefix = null;this._selectIndex = -1;this._focusHandler = null;this._blurHandler = null;this._bodyClickHandler = null;this._completionListBlurHandler = null;this._keyDownHandler = null;this._mouseDownHandler = null;this._mouseUpHandler = null;this._mouseOverHandler = null;this._tickHandler = null;this._enableCaching = true;this._flyoutHasFocus = false;this._textBoxHasFocus = false;this._completionListCssClass = null;this._completionListItemCssClass = null;this._highlightedItemCssClass = null;this._delimiterCharacters = null;this._firstRowSelected = false;}
AjaxControlToolkit.AutoCompleteBehavior.prototype = {
initialize: function() {
AjaxControlToolkit.AutoCompleteBehavior.callBaseMethod(this, 'initialize');$common.prepareHiddenElementForATDeviceUpdate();this._popupBehaviorHiddenHandler = Function.createDelegate(this, this._popupHidden);this._tickHandler = Function.createDelegate(this, this._onTimerTick);this._focusHandler = Function.createDelegate(this, this._onGotFocus);this._blurHandler = Function.createDelegate(this, this._onLostFocus);this._keyDownHandler = Function.createDelegate(this, this._onKeyDown);this._mouseDownHandler = Function.createDelegate(this, this._onListMouseDown);this._mouseUpHandler = Function.createDelegate(this, this._onListMouseUp);this._mouseOverHandler = Function.createDelegate(this, this._onListMouseOver);this._completionListBlurHandler = Function.createDelegate(this, this._onCompletionListBlur);this._bodyClickHandler = Function.createDelegate(this, this._onCompletionListBlur);this._timer = new Sys.Timer();this.initializeTimer(this._timer);var element = this.get_element();this.initializeTextBox(element);if(this._completionListElementID !== null)
this._completionListElement = $get(this._completionListElementID);if (this._completionListElement == null ) {
this._completionListElement = document.createElement('ul');this._completionListElement.id = this.get_id() + '_completionListElem';if (Sys.Browser.agent === Sys.Browser.Safari) {
document.body.appendChild(this._completionListElement);} else {
element.parentNode.insertBefore(this._completionListElement, element.nextSibling);}
}
this.initializeCompletionList(this._completionListElement);this._popupBehavior = $create(AjaxControlToolkit.PopupBehavior, 
{ 'id':this.get_id()+'PopupBehavior', 'parentElement':element, "positioningMode": AjaxControlToolkit.PositioningMode.BottomLeft }, null, null, this._completionListElement);this._popupBehavior.add_hidden(this._popupBehaviorHiddenHandler);if (this._onShowJson) {
this._popupBehavior.set_onShow(this._onShowJson);}
if (this._onHideJson) {
this._popupBehavior.set_onHide(this._onHideJson);}
},
dispose: function() {
this._onShowJson = null;this._onHideJson = null;if (this._popupBehavior) {
if (this._popupBehaviorHiddenHandler) {
this._popupBehavior.remove_hidden(this._popupBehaviorHiddenHandler);}
this._popupBehavior.dispose();this._popupBehavior = null;}
if (this._timer) { 
this._timer.dispose();this._timer = null;}
var element = this.get_element();if (element) {
$removeHandler(element, "focus", this._focusHandler);$removeHandler(element, "blur", this._blurHandler);$removeHandler(element, "keydown", this._keyDownHandler);$removeHandler(this._completionListElement, 'blur', this._completionListBlurHandler);$removeHandler(this._completionListElement, 'mousedown', this._mouseDownHandler);$removeHandler(this._completionListElement, 'mouseup', this._mouseUpHandler);$removeHandler(this._completionListElement, 'mouseover', this._mouseOverHandler);}
if (this._bodyClickHandler) {
$removeHandler(document.body, 'click', this._bodyClickHandler);this._bodyClickHandler = null;}
this._popupBehaviorHiddenHandler = null;this._tickHandler = null;this._focusHandler = null;this._blurHandler = null;this._keyDownHandler = null;this._completionListBlurHandler = null;this._mouseDownHandler = null;this._mouseUpHandler = null;this._mouseOverHandler = null;AjaxControlToolkit.AutoCompleteBehavior.callBaseMethod(this, 'dispose');},
initializeTimer: function(timer) {
timer.set_interval(this._completionInterval);timer.add_tick(this._tickHandler);},
initializeTextBox: function(element) {
element.autocomplete = "off";$addHandler(element, "focus", this._focusHandler);$addHandler(element, "blur", this._blurHandler);$addHandler(element, "keydown", this._keyDownHandler);},
initializeCompletionList: function(element) {
if(this._completionListCssClass) {
Sys.UI.DomElement.addCssClass(element, this._completionListCssClass);} else {
var completionListStyle = element.style;completionListStyle.textAlign = 'left';completionListStyle.visibility = 'hidden';completionListStyle.cursor = 'default';completionListStyle.listStyle = 'none';completionListStyle.padding = '0px';completionListStyle.margin = '0px! important';if (Sys.Browser.agent === Sys.Browser.Safari) {
completionListStyle.border = 'solid 1px gray';completionListStyle.backgroundColor = 'white';completionListStyle.color = 'black';} else {
completionListStyle.border = 'solid 1px buttonshadow';completionListStyle.backgroundColor = this._textBackground;completionListStyle.color = this._textColor;}
}
$addHandler(element, "mousedown", this._mouseDownHandler);$addHandler(element, "mouseup", this._mouseUpHandler);$addHandler(element, "mouseover", this._mouseOverHandler);$addHandler(element, "blur", this._completionListBlurHandler);$addHandler(document.body, 'click', this._bodyClickHandler);},
_currentCompletionWord: function() {
var element = this.get_element();var elementValue = element.value;var word = elementValue;if (this.get_isMultiWord()) {
var startIndex = this._getCurrentWordStartIndex();var endIndex = this._getCurrentWordEndIndex(startIndex);if (endIndex <= startIndex) {
word = elementValue.substring(startIndex);} else {
word = elementValue.substring(startIndex, endIndex);}
}
return word;},
_getCursorIndex: function() {
return this.get_element().selectionStart;},
_getCurrentWordStartIndex: function() {
var element = this.get_element();var elementText = element.value.substring(0,this._getCursorIndex());var index = 0;var lastIndex = -1;for (var i = 0;i < this._delimiterCharacters.length;++i) {
var curIndex = elementText.lastIndexOf(this._delimiterCharacters.charAt(i));if (curIndex > lastIndex) {
lastIndex = curIndex;}
} 
index = lastIndex;if (index >= this._getCursorIndex()) {
index = 0;}
return index < 0 ? 0 : index + 1;},
_getCurrentWordEndIndex: function(wordStartIndex) {
var element = this.get_element();var elementText = element.value.substring(wordStartIndex);var index = 0;for (var i = 0;i < this._delimiterCharacters.length;++i) {
var curIndex = elementText.indexOf(this._delimiterCharacters.charAt(i));if (curIndex > 0 && (curIndex < index || index == 0)) {
index = curIndex;}
}
return index <= 0 ? element.value.length : index + wordStartIndex;},
get_isMultiWord : function() {
return (this._delimiterCharacters != null) && (this._delimiterCharacters != '');},
_getTextWithInsertedWord: function(wordToInsert) {
var text = wordToInsert;var replaceIndex = 0;var element = this.get_element();var originalText = element.value;if (this.get_isMultiWord()) {
var startIndex = this._getCurrentWordStartIndex();var endIndex = this._getCurrentWordEndIndex(startIndex);var prefix = '';var suffix = '';if (startIndex > 0) {
prefix = originalText.substring(0, startIndex);}
if (endIndex > startIndex) {
suffix = originalText.substring(endIndex);}
text = prefix + wordToInsert + suffix;}
return text;},
_hideCompletionList: function() {
var eventArgs = new Sys.CancelEventArgs();this.raiseHiding(eventArgs);if (eventArgs.get_cancel()) {
return;}
this.hidePopup();},
showPopup : function() {
this._popupBehavior.show();this.raiseShown(Sys.EventArgs.Empty);},
hidePopup : function() {
if (this._popupBehavior) {
this._popupBehavior.hide();} else {
this._popupHidden();}
},
_popupHidden : function() {
this._completionListElement.innerHTML = '';this._selectIndex = -1;this._flyoutHasFocus = false;this.raiseHidden(Sys.EventArgs.Empty);},
_highlightItem: function(item) {
var children = this._completionListElement.childNodes;for (var i = 0;i < children.length;i++) {
var child = children[i];if (child._highlighted) {
if (this._completionListItemCssClass) {
Sys.UI.DomElement.removeCssClass(child, this._highlightedItemCssClass);Sys.UI.DomElement.addCssClass(child, this._completionListItemCssClass);} else {
if (Sys.Browser.agent === Sys.Browser.Safari) {
child.style.backgroundColor = 'white';child.style.color = 'black';} else {
child.style.backgroundColor = this._textBackground;child.style.color = this._textColor;}
}
this.raiseItemOut(new AjaxControlToolkit.AutoCompleteItemEventArgs(child, child.firstChild.nodeValue, child._value));}
}
if(this._highlightedItemCssClass) {
Sys.UI.DomElement.removeCssClass(item, this._completionListItemCssClass);Sys.UI.DomElement.addCssClass(item, this._highlightedItemCssClass);} else {
if (Sys.Browser.agent === Sys.Browser.Safari) {
item.style.backgroundColor = 'lemonchiffon';} else {
item.style.backgroundColor = 'highlight';item.style.color = 'highlighttext';}
}
item._highlighted = true;this.raiseItemOver(new AjaxControlToolkit.AutoCompleteItemEventArgs(item, item.firstChild.nodeValue, item._value));},
_onCompletionListBlur: function(ev) {
this._hideCompletionList();},
_onListMouseDown: function(ev) {
if (ev.target !== this._completionListElement) {
this._setText(ev.target);this._flyoutHasFocus = false;} else { 
this._flyoutHasFocus = true;}
},
_onListMouseUp: function(ev) {
this.get_element().focus();},
_onListMouseOver: function(ev) {
var item = ev.target;if(item !== this._completionListElement) {
var children = this._completionListElement.childNodes;for (var i = 0;i < children.length;++i) {
if (item === children[i]) {
this._highlightItem(item);this._selectIndex = i;break;} 
}
}
},
_onGotFocus: function(ev) {
this._textBoxHasFocus = true;if (this._flyoutHasFocus) {
this._hideCompletionList();}
this._timer.set_enabled(true);},
_onKeyDown: function(ev) {
var k = ev.keyCode ? ev.keyCode : ev.rawEvent.keyCode;if (k === Sys.UI.Key.esc) {
this._hideCompletionList();ev.preventDefault();}
else if (k === Sys.UI.Key.up) {
if (this._selectIndex > 0) {
this._selectIndex--;this._handleScroll(this._completionListElement.childNodes[this._selectIndex], this._selectIndex);this._highlightItem(this._completionListElement.childNodes[this._selectIndex]);ev.stopPropagation();ev.preventDefault();}
}
else if (k === Sys.UI.Key.down) {
if (this._selectIndex < (this._completionListElement.childNodes.length - 1)) {
this._selectIndex++;this._handleScroll(this._completionListElement.childNodes[this._selectIndex], this._selectIndex);this._highlightItem(this._completionListElement.childNodes[this._selectIndex]);ev.stopPropagation();ev.preventDefault();}
}
else if (k === Sys.UI.Key.enter) {
if (this._selectIndex !== -1) {
this._setText(this._completionListElement.childNodes[this._selectIndex]);ev.preventDefault();} else {
this.hidePopup();}
}
else if (k === Sys.UI.Key.tab) {
if (this._selectIndex !== -1) {
this._setText(this._completionListElement.childNodes[this._selectIndex]);}
}
else {
this._timer.set_enabled(true);}
},
_handleScroll : function(element, index) {
var flyout = this._completionListElement;var elemBounds = $common.getBounds(element);var numItems = this._completionListElement.childNodes.length;if (((elemBounds.height * index) - (flyout.clientHeight + flyout.scrollTop)) >= 0) {
flyout.scrollTop += (((elemBounds.height * index) - (flyout.clientHeight + flyout.scrollTop)) + elemBounds.height);}
if (((elemBounds.height * (numItems - (index + 1))) - (flyout.scrollHeight - flyout.scrollTop)) >= 0) {
flyout.scrollTop -= (((elemBounds.height * (numItems - (index + 1))) - (flyout.scrollHeight - flyout.scrollTop)) + elemBounds.height);} 
if (flyout.scrollTop % elemBounds.height !== 0) { 
if (((elemBounds.height * (index + 1)) - (flyout.clientHeight + flyout.scrollTop)) >= 0) { 
flyout.scrollTop -= (flyout.scrollTop % elemBounds.height);} else { 
flyout.scrollTop += (elemBounds.height - (flyout.scrollTop % elemBounds.height));}
} 
},
_handleFlyoutFocus : function() {
if(!this._textBoxHasFocus) { 
if (!this._flyoutHasFocus) { 
this._hideCompletionList();} else {
}
}
}, 
_onLostFocus: function() {
this._textBoxHasFocus = false;this._timer.set_enabled(false);window.setTimeout(Function.createDelegate(this, this._handleFlyoutFocus), 500);}, 
_onMethodComplete: function(result, context) {
this._update(context, result,  true);},
_onMethodFailed: function(err, response, context) {
},
_onTimerTick: function(sender, eventArgs) {
if (this._servicePath && this._serviceMethod) {
var text = this._currentCompletionWord();if (text.trim().length < this._minimumPrefixLength) {
this._currentPrefix = null;this._update('', null,  false);return;}
if ((this._currentPrefix !== text) || ((text == "") && (this._minimumPrefixLength == 0))) {
this._currentPrefix = text;if ((text != "") && this._cache && this._cache[text]) {
this._update(text, this._cache[text],  false);return;}
var eventArgs = new Sys.CancelEventArgs();this.raisePopulating(eventArgs);if (eventArgs.get_cancel()) {
return;}
var params = { prefixText : this._currentPrefix, count: this._completionSetCount };if (this._useContextKey) {
params.contextKey = this._contextKey;}
Sys.Net.WebServiceProxy.invoke(this.get_servicePath(), this.get_serviceMethod(), false, params,
Function.createDelegate(this, this._onMethodComplete),
Function.createDelegate(this, this._onMethodFailed),
text);$common.updateFormToRefreshATDeviceBuffer();}
}
},
_setText: function(item) {
var text = (item && item.firstChild) ? item.firstChild.nodeValue : null;this._timer.set_enabled(false);var element = this.get_element();var control = element.control;if (control && control.set_text) {
control.set_text(text);$common.tryFireEvent(control, "change");}
else {
element.value = text;$common.tryFireEvent(element, "change");}
this.raiseItemSelected(new AjaxControlToolkit.AutoCompleteItemEventArgs(item, text, item ? item._value : null));this._currentPrefix = this._currentCompletionWord();this._hideCompletionList();},
_update: function(prefixText, completionItems, cacheResults) {
if (cacheResults && this.get_enableCaching()) {
if (!this._cache) {
this._cache = {};}
this._cache[prefixText] = completionItems;}
if ((!this._textBoxHasFocus) || (prefixText != this._currentCompletionWord())) {
this._hideCompletionList();return;} 
if (completionItems && completionItems.length) {
this._completionListElement.innerHTML = '';this._selectIndex = -1;var _firstChild = null;var text = null;var value = null;for (var i = 0;i < completionItems.length;i++) {
var itemElement = null;if (this._completionListElementID) { 
itemElement = document.createElement('div');} else {
itemElement = document.createElement('li');}
if( _firstChild == null ){
_firstChild = itemElement;}
try {
var pair = Sys.Serialization.JavaScriptSerializer.deserialize('(' + completionItems[i] + ')');if (pair && pair.First) {
text = pair.First;value = pair.Second;} else {
text = pair;value = pair;} 
} catch (ex) {
text = completionItems[i];value = completionItems[i];}
itemElement.appendChild(document.createTextNode(this._getTextWithInsertedWord(text)));itemElement._value = value;itemElement.__item = '';if (this._completionListItemCssClass) {
Sys.UI.DomElement.addCssClass(itemElement, this._completionListItemCssClass);} else {
var itemElementStyle = itemElement.style;itemElementStyle.padding = '0px';itemElementStyle.textAlign = 'left';itemElementStyle.textOverflow = 'ellipsis';if (Sys.Browser.agent === Sys.Browser.Safari) {
itemElementStyle.backgroundColor = 'white';itemElementStyle.color = 'black';} else {
itemElementStyle.backgroundColor = this._textBackground;itemElementStyle.color = this._textColor;}
}
this._completionListElement.appendChild(itemElement);}
var elementBounds = $common.getBounds(this.get_element());this._completionListElement.style.width = Math.max(1, elementBounds.width - 2) + 'px';this._completionListElement.scrollTop = 0;this.raisePopulated(Sys.EventArgs.Empty);var eventArgs = new Sys.CancelEventArgs();this.raiseShowing(eventArgs);if (!eventArgs.get_cancel()) {
this.showPopup();if (this._firstRowSelected && (_firstChild != null)) {
this._highlightItem( _firstChild );this._selectIndex = 0;}
} 
} else {
this._hideCompletionList();}
},
get_onShow : function() {
return this._popupBehavior ? this._popupBehavior.get_onShow() : this._onShowJson;},
set_onShow : function(value) {
if (this._popupBehavior) {
this._popupBehavior.set_onShow(value)
} else {
this._onShowJson = value;}
this.raisePropertyChanged('onShow');},
get_onShowBehavior : function() {
return this._popupBehavior ? this._popupBehavior.get_onShowBehavior() : null;},
onShow : function() {
if (this._popupBehavior) {
this._popupBehavior.onShow();}
},
get_onHide : function() {
return this._popupBehavior ? this._popupBehavior.get_onHide() : this._onHideJson;},
set_onHide : function(value) {
if (this._popupBehavior) {
this._popupBehavior.set_onHide(value)
} else {
this._onHideJson = value;}
this.raisePropertyChanged('onHide');},
get_onHideBehavior : function() {
return this._popupBehavior ? this._popupBehavior.get_onHideBehavior() : null;},
onHide : function() {
if (this._popupBehavior) {
this._popupBehavior.onHide();}
},
get_completionInterval: function() {
return this._completionInterval;},
set_completionInterval: function(value) {
if (this._completionInterval != value) {
this._completionInterval = value;this.raisePropertyChanged('completionInterval');}
},
get_completionList: function() {
return this._completionListElement;},
set_completionList: function(value) {
if (this._completionListElement != value) {
this._completionListElement = value;this.raisePropertyChanged('completionList');}
},
get_completionSetCount: function() {
return this._completionSetCount;},
set_completionSetCount: function(value) {
if (this._completionSetCount != value) {
this._completionSetCount = value;this.raisePropertyChanged('completionSetCount');}
},
get_minimumPrefixLength: function() {
return this._minimumPrefixLength;},
set_minimumPrefixLength: function(value) {
if (this._minimumPrefixLength != value) {
this._minimumPrefixLength = value;this.raisePropertyChanged('minimumPrefixLength');}
},
get_serviceMethod: function() {
return this._serviceMethod;},
set_serviceMethod: function(value) {
if (this._serviceMethod != value) {
this._serviceMethod = value;this.raisePropertyChanged('serviceMethod');}
},
get_servicePath: function() {
return this._servicePath;},
set_servicePath: function(value) {
if (this._servicePath != value) {
this._servicePath = value;this.raisePropertyChanged('servicePath');}
},
get_contextKey : function() {
return this._contextKey;},
set_contextKey : function(value) {
if (this._contextKey != value) {
this._contextKey = value;this.set_useContextKey(true);this.raisePropertyChanged('contextKey');}
},
get_useContextKey : function() {
return this._useContextKey;},
set_useContextKey : function(value) {
if (this._useContextKey != value) {
this._useContextKey = value;this.raisePropertyChanged('useContextKey');}
},
get_enableCaching: function() {
return this._enableCaching;},
set_enableCaching: function(value) {
if (this._enableCaching != value) {
this._enableCaching = value;this.raisePropertyChanged('enableCaching');}
},
get_completionListElementID: function() {
return this._completionListElementID;},
set_completionListElementID: function(value) {
if (this._completionListElementID != value) {
this._completionListElementID = value;this.raisePropertyChanged('completionListElementID');}
}, 
get_completionListCssClass : function() {
return this._completionListCssClass;},
set_completionListCssClass : function(value) {
if (this._completionListCssClass != value) {
this._completionListCssClass = value;this.raisePropertyChanged('completionListCssClass');}
}, 
get_completionListItemCssClass : function() {
return this._completionListItemCssClass;},
set_completionListItemCssClass : function(value) {
if (this._completionListItemCssClass != value) {
this._completionListItemCssClass = value;this.raisePropertyChanged('completionListItemCssClass');}
},
get_highlightedItemCssClass : function() {
return this._highlightedItemCssClass;},
set_highlightedItemCssClass : function(value) {
if(this._highlightedItemCssClass != value) {
this._highlightedItemCssClass = value;this.raisePropertyChanged('highlightedItemCssClass');}
},
get_delimiterCharacters: function() {
return this._delimiterCharacters;},
set_delimiterCharacters: function(value) {
if (this._delimiterCharacters != value) {
this._delimiterCharacters = value;this.raisePropertyChanged('delimiterCharacters');}
},
get_firstRowSelected:function() {
return this._firstRowSelected;},
set_firstRowSelected:function(value) {
if(this._firstRowSelected != value) {
this._firstRowSelected = value;this.raisePropertyChanged('firstRowSelected');}
},
add_populating : function(handler) {
this.get_events().addHandler('populating', handler);},
remove_populating : function(handler) {
this.get_events().removeHandler('populating', handler);},
raisePopulating : function(eventArgs) {
var handler = this.get_events().getHandler('populating');if (handler) {
handler(this, eventArgs);}
},
add_populated : function(handler) {
this.get_events().addHandler('populated', handler);},
remove_populated : function(handler) {
this.get_events().removeHandler('populated', handler);},
raisePopulated : function(eventArgs) {
var handler = this.get_events().getHandler('populated');if (handler) {
handler(this, eventArgs);}
},
add_showing : function(handler) {
this.get_events().addHandler('showing', handler);},
remove_showing : function(handler) {
this.get_events().removeHandler('showing', handler);},
raiseShowing : function(eventArgs) {
var handler = this.get_events().getHandler('showing');if (handler) {
handler(this, eventArgs);}
},
add_shown : function(handler) {
this.get_events().addHandler('shown', handler);},
remove_shown : function(handler) {
this.get_events().removeHandler('shown', handler);},
raiseShown : function(eventArgs) {
var handler = this.get_events().getHandler('shown');if (handler) {
handler(this, eventArgs);}
},
add_hiding : function(handler) {
this.get_events().addHandler('hiding', handler);},
remove_hiding : function(handler) {
this.get_events().removeHandler('hiding', handler);},
raiseHiding : function(eventArgs) {
var handler = this.get_events().getHandler('hiding');if (handler) {
handler(this, eventArgs);}
},
add_hidden : function(handler) {
this.get_events().addHandler('hidden', handler);},
remove_hidden : function(handler) {
this.get_events().removeHandler('hidden', handler);},
raiseHidden : function(eventArgs) {
var handler = this.get_events().getHandler('hidden');if (handler) {
handler(this, eventArgs);}
},
add_itemSelected : function(handler) {
this.get_events().addHandler('itemSelected', handler);},
remove_itemSelected : function(handler) {
this.get_events().removeHandler('itemSelected', handler);},
raiseItemSelected : function(eventArgs) {
var handler = this.get_events().getHandler('itemSelected');if (handler) {
handler(this, eventArgs);}
},
add_itemOver : function(handler) {
this.get_events().addHandler('itemOver', handler);},
remove_itemOver : function(handler) {
this.get_events().removeHandler('itemOver', handler);},
raiseItemOver : function(eventArgs) {
var handler = this.get_events().getHandler('itemOver');if (handler) {
handler(this, eventArgs);}
},
add_itemOut : function(handler) {
this.get_events().addHandler('itemOut', handler);},
remove_itemOut : function(handler) {
this.get_events().removeHandler('itemOut', handler);},
raiseItemOut : function(eventArgs) {
var handler = this.get_events().getHandler('itemOut');if (handler) {
handler(this, eventArgs);}
}
}
AjaxControlToolkit.AutoCompleteBehavior.registerClass('AjaxControlToolkit.AutoCompleteBehavior', AjaxControlToolkit.BehaviorBase);AjaxControlToolkit.AutoCompleteBehavior.descriptor = {
properties: [ {name: 'completionInterval', type: Number},
{name: 'completionList', isDomElement: true},
{name: 'completionListElementID', type: String},
{name: 'completionSetCount', type: Number},
{name: 'minimumPrefixLength', type: Number},
{name: 'serviceMethod', type: String},
{name: 'servicePath', type: String},
{name: 'enableCaching', type: Boolean} ]
}
AjaxControlToolkit.AutoCompleteItemEventArgs = function(item, text, value) {
AjaxControlToolkit.AutoCompleteItemEventArgs.initializeBase(this);this._item = item;this._text = text;this._value = (value !== undefined) ? value : null;}
AjaxControlToolkit.AutoCompleteItemEventArgs.prototype = {
get_item : function() {
return this._item;},
set_item : function(value) {
this._item = value;},
get_text : function() {
return this._text;},
set_text : function(value) {
this._text = value;},
get_value : function() {
return this._value;},
set_value : function(value) {
this._value = value;}
}
AjaxControlToolkit.AutoCompleteItemEventArgs.registerClass('AjaxControlToolkit.AutoCompleteItemEventArgs', Sys.EventArgs);
//END AjaxControlToolkit.AutoComplete.AutoCompleteBehavior.js
if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();
(function() {var fn = function() {$get('ctl00_ScriptManager1_HiddenField').value += ';;RealtyTrac.Common.Web.Scripts:en-US:ea7fdbdf-06a9-48e3-b692-51af4f227e3d:ff206037:89320994:adb12799:73373c4b:cd8fc28d;AjaxControlToolkit, Version=1.0.11119.27737, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e:en-US:eafbf4f4-d0b5-45a6-abe1-6f27cdbec783:865923e8:91bd373d:ff62b0be:411fea1c:e7c87f07:bbfda34c:30a78ec5:3510d9fc';Sys.Application.remove_load(fn);};Sys.Application.add_load(fn);})();
