//START RealtyTrac.Common.Web.Scripts.MapSearch.sniffer.js
//browser identity strings
var FIREFOX_IDENTITY = "firefox";
var IE_IDENTITY = "msie";
var OPERA_IDENTITY = "opera";
var SAFARI_IDENTITY = "safari";

//check whether browser is supported
function isSupportedBrowser()
{
    // convert all characters to lowercase to simplify testing
    var agt = navigator.userAgent.toLowerCase();
            
    //is internet explorer, and not opera
    var isIe = agt.indexOf(IE_IDENTITY) != -1 && agt.indexOf(OPERA_IDENTITY) == -1;
    var ieVersion = getBrowserVersion(agt, IE_IDENTITY);
    
    //is firefox
    var isFirefox = agt.indexOf(FIREFOX_IDENTITY) != -1;
    var firefoxVersion = getBrowserVersion(agt, FIREFOX_IDENTITY);

    var isOpera = agt.indexOf(OPERA_IDENTITY) != -1;
    var operaVersion = getBrowserVersion(agt, OPERA_IDENTITY);
        
    var isSafari = agt.indexOf(SAFARI_IDENTITY) != -1;
    var safariVersion = getBrowserVersion(agt, SAFARI_IDENTITY);
        
    if(isIe)
    {
        gBrowserType = G_IE;
    }
    else
    {
        if(isFirefox)
        {
            gBrowserType = G_FIRE_FOX;
        }
        else
        {
            if(isSafari)
            {
                gBrowserType = G_SAFARI;
            }
            else
            {
                if(isOpera)
                {
                    gBrowserType = G_OPERA;    
                }
                else
                {
                    gBrowserType = G_OTHER_BROWSER;
                }
            }
        }
    }
    
    
    /*****************************************
    Firefox 2.0 Error Fix
    ******************************************/
    var ffv = 0;
		var ffn = "Firefox/"
		var ffp = navigator.userAgent.indexOf(ffn);
		if (ffp != -1) ffv = parseFloat(navigator.userAgent.substring(ffp + ffn.length));
		// If we're using Firefox 1.5 or above override the Virtual Earth drawing functions to use SVG
		if (ffv >= 1.5) 
		{
			try
			{
				Msn.Drawing.Graphic.CreateGraphic=function(f,b) { return new Msn.Drawing.SVGGraphic(f,b) }
			}
			catch(ex){}
		}
    /*****************************************
    Firefox 2.0  End Error Fix
    ******************************************/
    
    
    //we support ie 6+, firefox 1.5+, safari 2.0 (build 412+) and opera 9.0+
    return (isIe && ieVersion >= 6 ) || (isFirefox && firefoxVersion >= 1.5) || (isSafari && safariVersion >= 412) || (isOpera && operaVersion >= 9);
}

//gets browser version, searches for the first valid number after identity string
function getBrowserVersion(dataString, identity)
{
    var index = dataString.indexOf(identity);
    var length = identity.length;

    if(index == -1)
        return 0;
    else
        return parseFloat(dataString.substring(index + length + 1));
}



//END RealtyTrac.Common.Web.Scripts.MapSearch.sniffer.js
//START RealtyTrac.Common.Web.Scripts.MapSearch.globalvars.js
//VEMap
var gMap = null;
var geoMap;
var gViewComps;

var gObjPOIs;
var gLockZoomStrata = true;
var gMousePosition;
var gDragMouse = true;
var VEZoomLevel4 = 17;
var VEZoomLevel3 = 16;
var VEZoomLevel2 = 15;
var VEZoomLevel1 = 14;
var gDataExists=true;
var MAP_OFFSET_X = 25;
var MAP_OFFSET_Y = 119;

var gRegionalWhiteSiteFreeMember;

var gSearchResultList;
var gShowPOIPopup = true;
var gMapInitialized = false;

var gCleansedSearchTerm = null;
var gInvalidSearchTerm = false;
var gNeedToRefreshBanners = false;

var RETRY_FAILURE_COUNT = 100;

var G_SORT_BY_AUCTION_DATE = 0;
var G_SORT_BY_ENTERED_DATE = 1;
var G_SORT_BY_RECORD_DATE = 2;
var G_SORT_BY_CITY = 3;
var G_SORT_BY_BEDS = 4;
var G_SORT_BY_BATHS = 5;
var G_SORT_BY_AMOUNT = 6;
var G_SORT_BY_LIST_DATE = 7;
var G_SORT_BY_GARAGES = 8;
var G_SORT_DEFAULT = 9;
var G_SORT_BY_PROXIMITY = 11;
var G_SORT_BY_SQUARE_FEET = 12;
var G_SORT_BY_OPENING_BID = 13;
var G_SORT_BY_AUCTION_END_DATE = 14;
var G_SORT_BY_LIST_PRICE = 15;
var G_SORT_BY_DEFAULT_DATE = 18;
var G_SORT_BY_DEFAULT_PRICE = 20;

var G_SORT_ASC = 0;
var G_SORT_DESC = 1;

var G_SEARCH_RESPONSE_EMPTY = 2;
var G_SEARCH_RESPONSE_VALID = 0;
var G_SEARCH_RESPONSE_INVALID_PASSPORT = 1;
var G_SEARCH_RESPONSE_SCREEN_SCRAPER = 3;


var G_SEARCH_TYPE_CITY = 0;
var G_SEARCH_TYPE_COUNTY = 1;
var G_SEARCH_TYPE_ADDRESS = 2;
var G_SEARCH_TYPE_ZIP = 3;
var G_SEARCH_TYPE_PROPERTY_ID = 4;

var G_SORT_BY_PROXIMITY_TEXT = 'Proximity';
var G_SORT_BY_DEFAULT_DATE_TEXT = 'DefaultDate';

var G_IE = 0;
var G_FIRE_FOX = 1;
var G_SAFARI = 2;
var G_OPERA = 3;
var G_OTHER_BROWSER = 4;

var gBrowserType = G_IE;

var G_ZOOM_LEVEL_PROPERTY_VIEW = 15;

var gNumberOfRetries = 3;

var gSelectedProperties = new Array();

var MAP_IT_SCROLL_TO = 300;

                                
var PROPERTY_LIST_DELIMITER_ID = "propListDelimiter";
var PROPERTY_LIST_DELIMITER_CLASS = "propListDelimiterClass";

var gDma = "";

var g_DDLSortByOptions = null;
var messageAlert;

var gSavedSearchName = '';

var gSelectingValue = false;
var gGenerateRep = true;
var gModSearchOrdBy = null;

var PIN_TYPE_PROPERTY_PIN = 'propPin';

//// -- Do we really need to have function in global variables js?
function MapPosition()
{
    var m_long1 = 0;
    var m_long2 = 0;
    var m_lat1 = 0;
    var m_lat2 = 0;
    
    this.SetMapPosition = SetMapPosition;
    this.Long1 = Long1;
    this.Long2 = Long2;
    this.Lat1 = Lat1;
    this.Lat2 = Lat2;
    
    function Long1()
    {
        return m_long1;
    }
    
    function Long2()
    {
        return m_long2;
    }
    
    function Lat1()
    {
        return m_lat1;
    }
    
    function Lat2()
    {
        return m_lat2;
    }
    
    function SetMapPosition(lat1, long1, lat2, long2) 
    {
        m_long1 = long1;
        m_long2 = long2;
        m_lat1 = lat1;
        m_lat2 = lat2;
    }
}


var LISTED_COLUMN_ITEM_IMAGE_NAME = "/images/ResaleTieIn/ms_forsale_star_";
var LISTED_COLUMN_MASKED_ITEM_IMAGE_NAME = "/images/MapSearch/forsale_sign_42x38.gif";
var LISTED_COLUMN_NO_STAR_IMAGE_NAME = "/images/ResaleTieIn/ms_forsale_nostar_50x42.gif";

var RATING_COLUMN_ITEMIMAGE_NAME = "/images/ResaleTieIn/ms_star_";
var STATUS_COLUMN_ITEM_IMAGE_NAME = "/images/ResaleTieIn/ms_status_";
//END RealtyTrac.Common.Web.Scripts.MapSearch.globalvars.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 += "g_SEONavigationEngine.PropertyDetailsPage.RedirectWithDynamicBackParameter('" + url + "'); return false;"; //"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)
        {
            if (typeof(backParameter) != "undefined" && backParameter != "")
            {
                _backParameter = backParameter;
            }
            
            if (typeof(propertyIDsParameter) != "undefined" && propertyIDsParameter != "")
            {
                _propertyIDsParameter = propertyIDsParameter;
            }
        }
        
        this.RedirectWithDynamicBackParameter = function(url)
        {
            if (_backParameter != null && _backParameter != "")
            {
                url = SafeAddUrlParameterInternal(url, "back=" + _backParameter);
            }
            
            if (_propertyIDsParameter != null && _propertyIDsParameter != "")
            {
                url = SafeAddUrlParameterInternal(url, "propids=" + _propertyIDsParameter);
            }
            
            window.location = url;
            
        }
    }
    
    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.searchresults.js
var COST_TO_RESTORE_TAB_INDEX = 4;
var gIsMapRestored = false;

//Function run on page load.
function OnSearchLoad() 
{
    try 
    {       
        // check for Ajax not being supported
        if (typeof (SearchService) === "undefined") 
        {
            return;
        }

        HideSelectAllCheckbox();
        var searchRequestHash = GetSearchRequestHash();

        ShowSearchOverlay();
        
        var request = GetSearchRequest(gSearchRequest);

        if (searchRequestHash != null && searchRequestHash.length > 0)
        {
            RestoreMap(GetSearchRequest(searchRequestHash));
        }

        if (typeof (request) != "undefined"
            && null != request
            && typeof(gSuggestionList) != "undefined"
            && null != gSuggestionList
            && null != request.BasicRequest
            && request.BasicRequest.SearchType == 6) 
            {
                var suggestionList = null;
                suggestionList = Base64.decode(gSuggestionList);
                suggestionList = Sys.Serialization.JavaScriptSerializer.deserialize(suggestionList);
                
                OpenInvalidAddressPopup(suggestionList);
            }

            else 
        {
            if (typeof (SearchService) !== "undefined" && typeof (SearchService.GetSearchListWithTabs) === "function") 
            {
                ShowSearchInProcess();
                
                SetRecordsPerPageDdl();                
                
                SearchService.GetSearchListWithTabs(
                                                gPassportKey,
                                                gSearchRequest,
                                                searchRequestHash,
                                                CheckHistoryMark(),
                                                PropTypeToPropCode(availablePropTypes),
                                                GetSearchList_Callback
                                           );

            }

        }        
    }
    catch (er) 
    {
        LogErrorMessage("OnSearchLoad: ", er);
        HideSearchOverlay();
    }
}

function SetRecordsPerPageDdl(recordCount)
{
    if(!recordCount)
    {
        recordCount = 0;
        
        var request = GetSearchRequest(gSearchRequest);
        
        if(request != null && request.AdvancedRequest != null && request.AdvancedRequest.RecordsPerPage != null)
        {
            recordCount = request.AdvancedRequest.RecordsPerPage;
        }
   }
   
    var ddlRecordsPerPage = document.getElementById('ddlRecordsPerPage');
    
    if(ddlRecordsPerPage != null && recordCount > 0)
    {            
        ddlRecordsPerPage.options.selectedIndex = parseInt( recordCount / 25, 10);
    }
   
}

function ddlRecordsPerPageChange()
{   
    ShowSearchOverlay();
    setTimeout(SetRequestForRecordsPerPage, 0);
}

function SetRequestForRecordsPerPage()
{
    
    
    var request = GetSearchRequest(gSearchRequest);
    
    if(request != null && request.AdvancedRequest != null)
    {
        var ddlRecordsPerPage = document.getElementById('ddlRecordsPerPage');
        
        if(ddlRecordsPerPage != null)
        {
            
            request.AdvancedRequest.RecordsPerPage = parseInt(ddlRecordsPerPage.value, 10);
            SetSearchRequest(request);
            var advanced = request.AdvancedRequest;            
            RequerySearchService(advanced.SortField, advanced.SortOperation, advanced.PropertySubTabName, request.CurrentPage, advanced.RecordsPerPage, false);
        }
        else
        {
            HideSearchOverlay();
        }
    }
    else
    {
        HideSearchOverlay();
    }
}

function SearchListForm(address) 
{

    try 
    {
        // check for Ajax not being supported
        if (typeof (SearchService) === "undefined") 
        {
            return;
        }

        var isMapVisible = false;
        if (TheMap && TheMap.isMapVisible) 
        {
            isMapVisible = true;
        }

        HideSelectAllCheckbox();
        HideMLSTab();
        ShowSearchOverlay();

        if (typeof (SearchService) !== "undefined" && typeof (SearchService.GetSearchListForm) === "function") 
        {
            ShowSearchInProcess();

            SearchService.GetSearchListForm(
                                                gPassportKey,
                                                gSearchRequest,
                                                address,
                                                isMapVisible,
                                                PropTypeToPropCode(availablePropTypes),
                                                SearchListForm_Callback
                                           );
        }

    }
    catch (er) 
    {
        LogErrorMessage("SearchListForm: ", er);
    }
}

function PropTypeToPropCode(propTypes) 
{
    var propCodes = '';

    for (i = 0; i < propTypes.length; i++) 
    {
        switch (propTypes.substr(i, 1)) 
        {
            case 'P': propCodes += 'D';
                break;
            case 'A': propCodes += 'T';
                break;
            case 'B': propCodes += 'R';
                break;
            case 'G': propCodes += 'G';
                break;
            case 'F': propCodes += 'F';
                break;
            case 'R': propCodes += 'M';
                break;
        }
    }

    return propCodes;
}

function RequerySearchService(sortField, sortCriteria, tabType, pageNumber, pageSize, getBannersInfo) 
{
    try 
    {
        var isMapVisible = false;
        if (TheMap && TheMap.isMapVisible) 
        {
            isMapVisible = true;
        }
        ShowSearchInProcess();

        SearchService.GetSearchListAdvanced(
                                                gPassportKey,
                                                gSearchRequest,
                                                sortField,
                                                sortCriteria,
                                                tabType,
                                                pageNumber,
                                                pageSize,
                                                isMapVisible,
                                                getBannersInfo,
                                                GetSearchListAdvanced_Callback
                                           );
    }
    catch (er) 
    {
        HideSearchOverlay();
        LogErrorMessage("RequerySearchService: ", er);
    }
}

function ShowSearchInProcess() 
{
    ShowHideSearchInProcess(true);
}

function HideSearchInProcess() 
{
    ShowHideSearchInProcess(false);
}

function ShowHideReportSection(isVisible) 
{
    var divReportSection = document.getElementById('divReportSection');

    if (divReportSection != null) 
    {
        if (!isVisible) 
        {
            divReportSection.style.display = 'none';
        }
        else 
        {
            divReportSection.style.display = '';
            $('#sendReportQMark').bt({width: '400px', ajaxPath: '/mapsearch/TooltipCopy.xml div#sendPostCards'});
        }
    }   
}

function ShowHideSearchInProcess(show) 
{
    var divResultCount = document.getElementById('divSearchResultsCount');
    var divLoadingResults = document.getElementById('divLoadingResults');


    if (divResultCount != null && divLoadingResults != null && show != null) 
    {
        if (show) 
        {
            divResultCount.style.display = 'none';
            divLoadingResults.style.display = 'block';
        }
        else 
        {
            divResultCount.style.display = 'block';
            divLoadingResults.style.display = 'none';
        }
    }
}

function ShowSearchOverlay() 
{
    if(typeof(IsDivVisible) === 'function' && IsDivVisible('list_Overlay_Container'))
    {
        return;
    }
    
    if (!g_NavigationEngine._isMember && typeof(CreateAdInContainer) === 'function') 
    {
        CreateAdInContainer('overlayAdContainerDiv');
    }

    if (typeof (showDiv) === 'function') 
    {
        showDiv('list_Overlay_Container');
    }
    var divSearchList = document.getElementById('SR-list');
    if (divSearchList) 
    {
        divSearchList.style.padding = "0";
        var overlayContainer = document.getElementById('list_Overlay');
        if (overlayContainer) 
        {
            overlayContainer.style.height = divSearchList.offsetHeight + 'px';
        }
    }
    document.getElementById('SR-list').style.padding = "0";
}

function HideReportSectionForBHD()
{
    if(isBHDDomain)
    {
        $('#divReportSection').hide();
    }
}

function HideSearchOverlay() 
{
    if(typeof(ClearAdInContainer) === 'function')
    {
        ClearAdInContainer('overlayAdContainerDiv');
    }
    
    if (typeof (hideDiv) === 'function') 
    {
        hideDiv('list_Overlay_Container');
    }
    gIsMapLoaded = true;
}

function HideMLSTab() 
{
    var mlsTab = document.getElementById('propTabMLS');

    if (mlsTab) 
    {
        mlsTab.style.display = 'none';
    }
}

function GetSearchRequestHash() 
{
    var currentHash = null;

    if (CheckHistoryMark()) 
    {
        var r = window.location.href;
        var i = r.indexOf("#");
        return r.substr(i + 1);
    }

    return currentHash;
}

function GetSearchRequest(searchRequestEncoded) 
{
    if (!searchRequestEncoded)
    {
        searchRequestEncoded = GetSearchRequestHash();
    }

    if (searchRequestEncoded) 
    {
        try 
        {
            var searchRequestDecoded = Base64.decode(searchRequestEncoded);

            var request = Sys.Serialization.JavaScriptSerializer.deserialize(searchRequestDecoded);
            
            return request;
        }
        catch (er) 
        {
            alert(er.message);
        }
    }

    return null;
}


function SetSearchRequest(searchRequestObject) 
{
    if (searchRequestObject) 
    {
        var serialized = Sys.Serialization.JavaScriptSerializer.serialize(searchRequestObject);
        SetSearchRequestHash(Base64.encode(serialized));
        
        if (typeof(g_SEONavigationEngine) != "undefined" && g_SEONavigationEngine != null)
        {
            g_SEONavigationEngine.PropertyDetailsPage.UpdateAdditionalParameters(Base64.encode(serialized));
        }
    }
}

function SetUnmatchedSearchLink(link) 
{
    var unmatchedSearchLink = document.getElementById("lnkUnmatchedSearch");

    if (unmatchedSearchLink != null) 
    {
        unmatchedSearchLink.href = link;
    }
}

function GetSearchList_Callback(results)
{
    gNeedToRefreshBanners = true;
    ProcessSearchResults(results, false, true);
    ShowPropertyCountDdl();
}

function SearchListForm_Callback(results)
{
    gNeedToRefreshBanners = true;
    ProcessSearchResults(results, false, true);
    ShowPropertyCountDdl();
}

function GetSearchListAdvanced_Callback(results)
{
    gNeedToRefreshBanners = true;
    ProcessSearchResults(results, true, true);
    ShowPropertyCountDdl();
}

function ShowPropertyCountDdl()
{
    var divRecordsPerPage = document.getElementById('divRecordsPerPage');
        
    if(divRecordsPerPage != null)
    {  
        divRecordsPerPage.style.display = 'block';
    }
}

function GetSearchResultType(type) 
{
    var searchType = undefined;

    switch (type) 
    {
        case 0:
            searchType = "city";
            break;
        case 1:
            searchType = "county";
            break;
        case 2:
            searchType = "address";
            break;
        case 7:
            searchType = "zip";
            break;
        case 3:
            searchType = "propertyid";
            break;
        case 4:
            searchType = "parcelnumber";
            break;
        case 5:
            searchType = "invalid";
            break;
        case 6:
            searchType = "multipleZzp";
            break;
    }
    return searchType;
}

function UpdateQuery(results) 
{
    gSearchRequest = results.SearchRequestEncoded;
    SetSearchRequestHash(gSearchRequest);
    SetupMapSearchModifyControls();
}

function ProcessSearchResults(results, isInteractiveQuery, updateAgentLenderBanners) 
{
    try
    {
        if (results != null) 
        {
            SetUnmatchedSearchLink(results.UnmatchedRecordsLink);
            
            SetRecordsPerPageDdl(results.PageSize);

            gSubjectProperty = false;
            if (results.ResponseState == G_SEARCH_RESPONSE_INVALID_PASSPORT) 
            {
                if (TheMap && TheMap.isMapVisible) 
                {
                    TheMap.InvalidPassportReloadPage();
                }
                return;
            }

            gCriteriaType = GetSearchResultType(results.SearchType);
            gCriteriaValue = results.SearchLocationDisplay;

            if (results.SearchType == 2) 
            {
                if (results.HasExactProperty && gMember  && !gIsGuestMember && !gIsCancelledMember)
                {
                    if (IsMapOnPage())
                    {
                        TheMap.PinsOnMap.mainPropertyShown = true;
                        gSubjectPropertyID = null;
                        gSubjectPropertyLat = null;
                        gSubjectPropertyLon = null;
                        gSubjPropDecodedLatLong._reserved = '';
                        TheMap.AddMainProperty(results.AddressPropertyID, AddMainProperty_Continue);
                    }
                    else
                    {
                        gMainPropertyID = results.AddressPropertyID;
                    }
                }
                else
                {
                    gSubjectProperty = true;
                    gSubjectPropertyID = results.AddressPropertyID;
                    gMainPropertyID = null;

                    if (IsMapOnPage() && TheMap.isMapVisible && !TheMap.PinsOnMap.subjectPropPinOnMap && TheMap.PinsOnMap.pinsDrawn)
                    {

                        gSubjectPropertyLat = null;
                        gSubjectPropertyLon = null;
                        gSubjPropDecodedLatLong._reserved = '';
                        TheMap.PinsOnMap.PopUpClass.isSubjectPopUp = true;
                        TheMap.PinsOnMap.MapSubjectPropPin();
                    }
                }
            }
            if (results.ResponseState == G_SEARCH_RESPONSE_SCREEN_SCRAPER) 
            {
                ScreenScraperRedirect(results.LogoutFlag);
                return;
            }

            if (updateAgentLenderBanners) 
            {
                if (null == results.LenderBanner && null != results.LowMortageRatesBanner) 
                {
                    DisplayLenderBanner(false);
                    DisplayLowMortageRatesBanner(true);
                    SetLowMortageRatesBanner(results.LowMortageRatesBanner);
                }
                else if (null != results.LenderBanner) 
                {
                    DisplayLenderBanner(true);
                    DisplayLowMortageRatesBanner(false);
                    if (typeof (SetLenderBanner) !== 'undefined' && results.LenderBanner) 
                    {
                        SetLenderBanner(results.LenderBanner);
                    }

                }



                if (typeof (SetAgentBanner) !== 'undefined' && results.AgentBanner) 
                {
                    SetAgentBanner(results.AgentBanner.AgentName, results.AgentBanner.AgentPicture,
                        results.AgentBanner.AgentSpeciality, results.AgentBanner.NavigationUrl);
                }
            }

            // if search type is parcel number
            // we get zip code from request and new coordinates for map
            if (results.SearchType == 5 && results.Tabs != null && results.Tabs.PropertyCount > 0) 
            {
                UpdateMapPosition();
            }

            if (results.MlsUrl && results.MlsUrl.length > 0) 
            {
                gMLSUrl = results.MlsUrl;
            }

            PopulateBreadcrumbsAndTitle(results);

            g_NavigationEngine._propertyIDs = results.PropertyIDsEncoded;
            
            g_SEONavigationEngine.PropertyDetailsPage.UpdateAdditionalParameters(results.SearchRequestEncoded, results.PropertyIDsEncoded);
            
            if (results.SearchRequestEncoded && results.SearchRequestEncoded.length > 0) 
            {
                UpdateQuery(results);
            }
            
            gSearchResultList = new SearchResultList(results);
            gSearchResultList.UpdatePropertyCount();
            gSearchResultList.PopulateList(isInteractiveQuery);

            if (!isInteractiveQuery) 
            {
                GetMLSCount();

                LoadHitboxScript();
            }

            if (results.Dma && results.Dma != 0) 
            {
                gDma = results.Dma;
            }

            if (gNeedToRefreshBanners) 
            {
                gNeedToRefreshBanners = false;

                if (typeof (RefreshDoubleClickBannerUtil) !== "undefined") 
                {
                    RefreshDoubleClickBannerUtil();
                }
            }
        }

        HideSearchInProcess();

    }
    catch (er) 
    {
        LogErrorMessage("ProcessSearchResults: ", er);
    }
    finally 
    {
        HideSearchOverlay();
        HideSearchInProcess();
    }
}

function RestoreMap(request)
{
    try
    {
        if (request != null && request.IsMapVisible)
        {
            if (!TheMap || !TheMap.IsVisible)
            {
                CreateMap();
            }
            
            if (request.MapPosition == null 
                && request.Latitude != null && request.Latitude > 0 && request.Longitude != null && request.Longitude > 0)
            {
                request.MapPosition = request.Latitude + ',' + request.Longitude;
            }
                        
            gIsMapRestored = TheMap.RestoreZoomAndPosition(request);
        }
    }
    catch (er)
    {
        LogErrorMessage("RestoreMap: ", er);
    }
}

function DisplayLenderBanner(display) 
{
    var banner = document.getElementById("lenderBannerDiv");
    ShowHideElement(banner, display);
}

function DisplayLowMortageRatesBanner(display) 
{
    var banner = document.getElementById("LiveMortgageBanner");
    ShowHideElement(banner, display);
}

function ShowHideElement(element, show) 
{
    if (null != element) 
    {
        if (show) 
        {
            element.style.display = "block";
        }
        else 
        {
            element.style.display = "none";
        }
    }
}

function SetLowMortageRatesBanner(source) 
{
    if (null != source) 
    {
        var currentRateElement = document.getElementById("lowMortageBannerCurrentRate");
        if (null != currentRateElement) 
        {
            currentRateElement.innerHTML = source.CurrentRates + "%";
        }
    }
}

function UpdateMapPosition() 
{
    var request = GetSearchRequest();

    if (request && request.BasicRequest) 
    {
        var zip = request.BasicRequest.Zip;
        if (zip != null) 
        {
            gCriteriaType = "zip";
            gCriteriaValue = zip;
        }
        if (TheMap && TheMap.isMapVisible) 
        {
            AddPinsBySearchValues();
        }
    }
}

function GetMLSCount() 
{
    try 
    {
        if (gMember && gMLSUrl && gMLSUrl.length > 0 && !g_NavigationEngine._isWhiteSite && !g_NavigationEngine._isDataLink) 
        {
            if (gCallMLSWebService) 
            {
                if (typeof (MLSService) !== "undefined" && typeof (MLSService.GetMLSResultCount) === "function") 
                {
                    MLSService.GetMLSResultCount(gPassportKey, gSearchRequest, GetMLSCount_Callback);
                }
            }
            else 
            {
                // don't call the web service, just show the tab
                var mlsTab = document.getElementById('propTabMLS');
                var propCountSpan = document.getElementById('propTabMLS_Count');
                if (mlsTab) 
                {
                    mlsTab.style.display = 'block';
                    propCountSpan.innerHTML = '&nbsp;'
                }
            }
        }
    }
    catch (er) 
    {
        LogErrorMessage("GetMLSCount: ", er);
    }
}

function GetMLSCount_Callback(propertyCount) 
{
    try 
    {
        if (propertyCount && propertyCount.IsSucceeded == true && propertyCount.PropertyCount > 0) 
        {
            var mlsTab = document.getElementById('propTabMLS');
            var propCountSpan = document.getElementById('propTabMLS_Count');

            if (propCountSpan && mlsTab) 
            {
                mlsTab.style.display = 'block';
                propCountSpan.innerHTML = propertyCount.PropertyCount == 1 ? propertyCount.PropertyCount + ' Property' : propertyCount.PropertyCount + ' Properties';
            }
        }
        else 
        {
            HideMLSTab();
        }
    }
    catch (er) 
    {
        LogErrorMessage("GetMLSCount_Callback: ", er);
    }
}

function ShowMLS() 
{
    if (gMember && gMLSUrl && gMLSUrl.length > 0) 
    {
        window.open(gMLSUrl, '_blank', 'toolbar=yes, location=yes, directories=yes, status=yes, menubar=yes, scrollbars=yes, resizable=yes, copyhistory=no, width=1000, height=825');
    }
}

function PopulateBreadcrumbsAndTitle(results) 
{
    if (results) 
    {
        var searchArea = document.getElementById('spanSearchArea');

        if (results.SearchLocationDisplay && searchArea) 
        {
            searchArea.innerHTML = results.SearchLocationDisplay;
            gSearchTerm = results.SearchLocationDisplay;
        }

        if (results.PageTitle) 
        {
            document.title = results.PageTitle;
        }

        if (results.Breadcrumbs && results.Breadcrumbs.length > 0) 
        {
            ChangeBreadcrumb(results.Breadcrumbs)
        }

        if (results.SeoLinks && results.SeoLinks.length > 0 && typeof (PopulateSEOFooter) !== "undefined") 
        {
            PopulateSEOFooter(results.SeoLinks);
        }
    }
}

function ChangeBreadcrumb(breadcumbs) 
{
    var breacumbsControl = document.getElementById('divBreadcrumbs');

    if (breacumbsControl) 
    {
        var breadcrumbArray = new Array();

        for (i in breadcumbs) 
        {
            var breadcrumb = breadcumbs[i];
            if (breadcrumb && breadcrumb.Url && breadcrumb.Url.length > 0 
                && (breadcrumb.WhiteSiteCompatible || !g_NavigationEngine._isWhiteSite || (typeof(gIsCustomFreeSite) != 'undefined' && gIsCustomFreeSite))) 
            {
                if(gIsCustomFreeSite && breadcrumb.Title.toLowerCase() == 'home')
                {
                    breadcrumb.Url = '/mapsearch/';
                }
                
                breadcrumbArray.push("<a href='" + breadcrumb.Url + "'>" + breadcrumb.Title + "</a>");                
            }
            else 
            {
                breadcrumbArray.push(breadcumbs[i].Title);
            }
        }

        breacumbsControl.innerHTML = breadcrumbArray.join(" > ");
    }
}

function Tab(tabs) 
{
    this._name = tabs.Name;
    this._visible = tabs.Visible;
    this._selected = tabs.Selected;
    this._propertyCount = tabs.PropertyCount;
    this._showAlways = tabs.ShowAlways;
    this._title = tabs.Title;

    if (tabs.SubTabs != null) 
    {
        this._subTabs = new Array();

        for (var i = 0; i < tabs.SubTabs.length; i++) 
        {
            this._subTabs[i] = new Tab(tabs.SubTabs[i]);
        }
    }
    else 
    {
        this._subTabs = null;
    }

    this.SetupTabs = function(selectedTabName) 
    {
        try 
        {
            var selectedTabCodeName = this.GetTabCodeName(selectedTabName);

            if (selectedTabCodeName != null) 
            {
                var codeName = selectedTabCodeName.split(';');
                if (codeName.length = 2) 
                {
                    this.SetVisibility(codeName[0]);
                }
            }

            SetupSearchBySection(selectedTabName);

            return selectedTabCodeName;
        }
        catch (er) 
        {
            LogErrorMessage("Tab.SetupTabs: ", er, true);
        }
    }

    this.GetTabCodeName = function(tabName) 
    {
        try 
        {
            var code = this.GetCodeByTabName(tabName);

            if (code != 0) 
            {
                code += ';' + tabName;
            }

            return code;
        }
        catch (er) 
        {
            LogErrorMessage("Tab.GetTabCodeName: ", er, true);
        }
    }

    this.GetTabNameByCode = function(tabCode)
    {
        try 
        {
            var name = '';

            if (this._selected == tabCode) 
            {
                name = this._name;
            }

            if (name == '' && this._subTabs != null) 
            {
                for (var i = 0; i < this._subTabs.length; i++) 
                {
                    name = this._subTabs[i].GetTabNameByCode(tabCode);
                    if (name != '') 
                    {
                        break;
                    }
                }
            }

            return name;
        }
        catch (er) 
        {
            LogErrorMessage("Tab.GetTabNameByCode: ", er, true);
        }
    }

    this.GetCodeByTabName = function(tabName) 
    {
        try 
        {
            var code = 0;

            if (this._name == tabName) 
            {
                code = this._selected;
            }

            if (code == 0 && this._subTabs != null) 
            {
                for (var i = 0; i < this._subTabs.length; i++) 
                {
                    code = this._subTabs[i].GetCodeByTabName(tabName);
                    if (code != 0) 
                    {
                        break;
                    }
                }
            }

            return code;
        }
        catch (er) 
        {
            LogErrorMessage("Tab.GetCodeByTabName: ", er, true);
        }
    }

    this.SetVisibility = function(selectedTabCode) 
    {
        try 
        {
            if (this._showAlways || ((this._visible & selectedTabCode) > 0 && this._propertyCount > 0)) 
            {
                this.ShowTab(true);
            }
            else 
            {
                this.ShowTab(false);
            }

            if ((this._selected & selectedTabCode) > 0) 
            {
                this.SelectTab(true);
            }
            else 
            {
                this.SelectTab(false);
            }

            if (this._subTabs != null) 
            {
                for (var i = 0; i < this._subTabs.length; i++) 
                {
                    this._subTabs[i].SetVisibility(selectedTabCode);
                }
            }
        }
        catch (er) 
        {
            LogErrorMessage("Tab.SetVisibility: ", er, true);
        }
    }

    this.ShowTab = function(isVisible) 
    {
        try 
        {
            var tabControl = document.getElementById('propTab' + this._name);
            if (tabControl != null) 
            {
                tabControl.style.display = (isVisible ? 'block' : 'none');
                if (this._title != "") 
                {
                    var propSubTabTitle = document.getElementById('propTab' + this._name + '_Title');
                    var propCountControl = document.getElementById('propTab' + this._name + '_Count');

                    if (propCountControl != null && propSubTabTitle != null) 
                    {
                        propSubTabTitle.innerHTML = this._title;
                        propCountControl.innerHTML = this._propertyCount + ((this._propertyCount > 1) ? ' Properties' : ' Property');
                    }
                    else 
                    {
                        this.CreateSubTab(tabControl);
                    }
                }
            }
        }
        catch (er) 
        {
            LogErrorMessage("Tab.ShowTab: ", er, true);
        }
    }

    this.CreateSubTab = function(parentNode) 
    {
        try 
        {
            var dt = document.createElement('dt');
            dt.setAttribute('id', 'propTab' + this._name + '_Title');
            dt.innerHTML = this._title;
            parentNode.appendChild(dt);

            var dd = document.createElement('dd');
            dd.setAttribute('id', 'propTab' + this._name + '_Count');
            dd.innerHTML = this._propertyCount + ((this._propertyCount > 1) ? ' Properties' : ' Property');
            parentNode.appendChild(dd);
        }
        catch (er) 
        {
            LogErrorMessage("Tab.CreateSubTab: ", er, true);
        }
    }

    this.SelectTab = function(isSelected) 
    {
        try 
        {
            var tabControl = document.getElementById('propTab' + this._name);
            if (tabControl != null) 
            {
                if (isSelected) 
                {
                    if (tabControl.className.indexOf('SR_tab') > -1 || tabControl.className == '') 
                    {
                        tabControl.className = 'SR_tab' + this._name + ' on';
                    }
                    else 
                    {
                        tabControl.className = this._name + 'On';
                    }
                }
                else 
                {
                    if (tabControl.className.indexOf('SR_tab') > -1 || tabControl.className == '') 
                    {
                        tabControl.className = 'SR_tab' + this._name;
                    }
                    else 
                    {
                        tabControl.className = this._name;
                    }
                }
            }
        }
        catch (er) 
        {
            LogErrorMessage("Tab.SelectTab: ", er, true);
        }
    }
}

function AddTableCellNew(trElement, index, id, tdClass, innerHTML, tdColspan) 
{
    var oCell = document.createElement("th");

    if (trElement != null && oCell != null && id != null && tdColspan == parseInt(tdColspan)) 
    {
        oCell.innerHTML = innerHTML;        
        oCell.id = id;
        oCell.colSpan = tdColspan;
        trElement.appendChild(oCell);
    }
}

function SearchResultList(searchResult) 
{
    this._searchResults = searchResult;
    this._button;
    this._buttonAction;
    this._showCheckboxes = false;

    // reset "Select All" checkbox
    ResetSelectAllCheckbox();

    //reset the selected properties
    gSelectedProperties = new Array();
    
    this.CreateButton = function(property) 
    {
        // Buttoms removed according to requirement 4.3.1.1 ("Resale Tie In Ver. 1.1") 
        this._button = null;
        this._buttonAction = null;
        var needToShowButtonColumn = false;

        switch (this._searchResults.SelectedSubTab) 
        {
            case "PreForeclosuresDefaults":
                //this.CreateGetLoanButton(property);
                break;

            case "AuctionTrusteeSale":
            case "AuctionSheriffSale":
                //this.CreateGetLoanButton(property);
                break;

            case "AuctionOnlineAuction":
                this.CreateBidNowButton(property);
                needToShowButtonColumn = true;
                break;

            case "AuctionLiveAuction":

                hideShowSendProstcardsButton(false);

                break;

            case "BankOwnedBankOwned":
                this.CreateMakeOfferButton(property);
                needToShowButtonColumn = true;
                break;

            case "BankOwnedReoListings":
                this.CreateMakeOfferButton(property);
                needToShowButtonColumn = true;
                break;

            case "BankOwnedOnlineAuction":
                this.CreateBidNowButton(property);
                needToShowButtonColumn = true;
                break;

            case "BankOwnedLiveAuction":

                hideShowSendProstcardsButton(false);

                break;

            case "BankOwnedGovernmentOwned":
                //this.CreateGetLoanButton(property);
                break;

            case "HomesForSaleResaleMLS":
                //this.CreateGetLoanButton(property);
                break;

            case "HomesForSaleReoListing":
                this.CreateMakeOfferButton(property);
                needToShowButtonColumn = true;
                break;

            case "HomesForSaleFSBO":
                //this.CreateGetLoanButton(property);
                break;

            default:
                this._button = null;
                this._buttonAction = null;
        }
        
        return needToShowButtonColumn;
    }

    this.CreateGetLoanButton = function(property) 
    {
        if (property.IsFusionEligible) 
        {
            this._button = '<img src="../../PropertyDetails/Images/onlineMortgageApp/get_loan_button_72x19.gif" onmouseover="this.src=\'../../PropertyDetails/Images/onlineMortgageApp/get_loan_button_72x19.gif\'" onmouseout="this.src=\'../../PropertyDetails/Images/onlineMortgageApp/get_loan_button_72x19.gif\'" alt="Get Loan" />';
            this._buttonAction = g_NavigationEngine.NewPropDetailsPath + 'RateQuote.aspx?propId=' + property.CombineKeyID + '&state=' + property.State + '&county=' + property.CountyCode + '&isPurchase=true' + g_NavigationEngine.PropertyDetailsExtra();
        }
    }

    this.CreateBidNowButton = function(property)
     {
        if (property.IsOnlineAuction) 
        {
            this._button = '<img src="../images/buttons/bidNow_72x19_a.png" onmouseover="this.src=\'../images/buttons/bidNow_72x19_h.png\'" onmouseout="this.src=\'../images/buttons/bidNow_72x19_a.png\'" alt="Bid Now" />';
            
            if (!gIsInternationalUser)
            {
                this._buttonAction = g_NavigationEngine.PropertyBidPage(property.CombineKeyID);
            }
            else
            {
                this._buttonAction = "javascript:void(OpenBidNowInternationalPopup());";
            }
        }
    }

    this.CreateMakeOfferButton = function(property) 
    {      
        if (property.IsMakeOffer && !property.IsSold) 
        {
            this._button = '<img src="../images/buttons/make_offer_button.gif" onmouseover="this.src=\'../images/buttons/make_offer_button_rollover.gif\'" onmouseout="this.src=\'../images/buttons/make_offer_button.gif\'" alt="Make Offer" />';
            this._buttonAction = '/' + gMakeOfferSiteName + '/GoToaspx.aspx?destpage=OfferForm.aspx%3FpropId%3D' + property.CombineKeyID;
        }
    }

    this.PopulateList = function(isInteractiveQuery) 
    {
        try 
        {
            if (this._searchResults != null) 
            {
                this.CleanupSearchList();

                if (this._searchResults.Tabs.PropertyCount > 0) 
                {
                    this.SetTabs();
                    this.CreateColumnTitles();
                    this.ShowColumnTitles();
                    if (!isDatalinkOrWhitesiteMode) 
                    {
                        this.DisplayFeaturedProperties();
                    }
                    this.DisplayList();
                    this.DisplayPageNavigation();
                    this.UpdateSortArrows();
                }
                else 
                {
                    this.HideTabs(this._searchResults.Tabs);

                    ShowTableRow('propFeaturedProperties', false);

                    ShowTableRow('propHeader', false);
                    ShowTableCell('pageNavList', false);
                    ShowTableCell('pageNavJump', false);

                    ShowTableRow('noPropertiesFound', true);
                }
            }
        }
        catch (er) 
        {
            LogErrorMessage("SearchResultList.PopulateList: ", er, true);
        }
    }

    this.HideTabs = function(tab) 
    {
        try 
        {
            if (tab.SubTabs != null) 
            {
                for (var i = 0; i < tab.SubTabs.length; i++) 
                {
                    this.HideTabs(tab.SubTabs[i]);
                }
            }
            var tabControl = document.getElementById('propTab' + tab.Name);

            if (tabControl != null) 
            {
                tabControl.style.display = 'none';
            }
        }
        catch (Error) 
        {
            LogErrorMessage("SearchResultList.HideTabs: ", er, true);
        }
    }

    this.GetTitle = function(name, title) 
    {
        if (name == "DefaultDate" || name == "DefaultPrice") 
        {
            return title;
        }

        return name;
    }

    this.GetColumnTitleHTML = function(searchResult) 
    {
        var result = "";
        result += "<a href=\"javascript:gSearchResultList.SortByField('" + searchResult.Name + "');\"><img src=\"../images/arrow_u.gif\" class=\"off\" id=\"imgArrow" +
                searchResult.Name + "\" alt=\"\" /><span id=\"span" + searchResult.Name + "Title\" title=\"" + this.GetTitle(searchResult.Name, searchResult.Title) + "\">" + searchResult.Title + "</span></a>";

        if (typeof (searchResult.TitleImages) != 'undefined'
            && searchResult.TitleImages != null
            && searchResult.TitleImages.length > 0) 
            {
            for (var i = 0; i < searchResult.TitleImages.length; i++) 
            {
                var onclick = (searchResult.TitleImages[i].OnClickEvent != null && searchResult.TitleImages[i].OnClickEvent.length > 0) ? "onclick='" + searchResult.TitleImages[i].OnClickEvent + "();'" : '';
                var onmouseover = (searchResult.TitleImages[i].OnMouseOver != null && searchResult.TitleImages[i].OnMouseOver.length > 0) ? "onmouseover='" + searchResult.TitleImages[i].OnMouseOver + "();'" : '';
                var onmouseout = (searchResult.TitleImages[i].OnMouseOver != null && searchResult.TitleImages[i].OnMouseOver.length > 0) ? "onmouseout='" + searchResult.TitleImages[i].OnMouseOver + "();'" : '';
                var idAttr = (searchResult.TitleImages[i].Id != null && searchResult.TitleImages[i].Id.length > 0) ? "id='" + searchResult.TitleImages[i].Id + "'" : '';
                var classAttr = (searchResult.TitleImages[i].Class != null && searchResult.TitleImages[i].Class.length > 0) ? "class='" + searchResult.TitleImages[i].Class + "'" : "class='question'";
                result += "<img src='"
                    + searchResult.TitleImages[i].Url
                    + "' alt='"
                    + searchResult.TitleImages[i].AltText
                    + "' " + onclick + " "
                    + idAttr + " "
                    + classAttr + " "
                    + "/>";
            }
        }
        
        return result;
    }

    this.CreateColumnTitles = function() 
    {
		var table = document.getElementById("propertyListTable");
		
		table.deleteRow( 0 );
		
        var titleRow = table.insertRow(0);
        
        titleRow.id = "propHeader";
        
        titleRow.style.display = "block";
        
        var searchResult;
        
        var cellIndex = 0;

        if (titleRow != null && this._searchResults.TabColumns != null) 
        {
            AddTableCellNew(titleRow, cellIndex++, 'thSelectToPrint', 'propPrint first',  (g_NavigationEngine._isWhiteSite) ? '' : 'Select to Print', 2);
            AddTableCellNew(titleRow, cellIndex++, 'thEmpty', '', '', 2);

            for (var i = 0; i < this._searchResults.TabColumns.length; i++) 
            {
                if(i == 1)
                {
                    AddTableCellNew(titleRow, cellIndex++, 'propMap', '', '', 1);            
                }
                searchResult = this._searchResults.TabColumns[i];
                AddTableCellNew(titleRow, cellIndex++, 'th' + searchResult.Name, 'prop' + searchResult.Name, this.GetColumnTitleHTML(searchResult), 1);
            }

            AddTableCellNew(titleRow, cellIndex++, 'thAction', 'propMap', '', 1);
        }
        //tool tip for colum headers
        $('#RepairCost').bt({width: '400px', ajaxPath: '/MapSearch/TooltipCopy.xml div#costToRepairColumn'});
        $('#Rating').bt({width: '400px', ajaxPath: '/MapSearch/TooltipCopy.xml div#ratingColumn'});
        $('#Listed').bt({width: '300px', ajaxPath: '/MapSearch/TooltipCopy.xml div#listedColumn'});
        $('#Status').bt({width: '300px', ajaxPath: '/MapSearch/TooltipCopy.xml div#statusColumn'});
    }
    
    this.SetTabs = function() 
    {
        var tab = new Tab(this._searchResults.Tabs);
        if (tab != null) 
        {
            tab.SetupTabs(this._searchResults.SelectedSubTab);
            this._searchResults.Tabs = tab;
        }
    }

    this.ShowColumnTitles = function()
    {
        try
        {
            switch (this._searchResults.SelectedSubTab)
            {
                case "PreForeclosures":
                case "PreForeclosuresDefaults":
                    this.PreforeclosureTabSetColumns();
                    break;

                case "Auction":
                case "AuctionTrusteeSale":
                case "AuctionOnlineAuction":
                case "AuctionLiveAuction":
                case "AuctionSheriffSale":
                    this.AuctionTabSetColumns();
                    break;

                case "BankOwned":
                case "BankOwnedBankOwned":
                case "BankOwnedReoListings":
                case "BankOwnedGovernmentOwned":
                case "BankOwnedOnlineAuction":
                case "BankOwnedLiveAuction":
                    this.BankownedTabSetColumn();
                    break;

                case "HomesForSale":
                case "HomesForSaleResaleMLS":
                case "HomesForSaleReoListing":
                case "HomesForSaleFSBO":
                    this.ForsaleTabSetColumn();
                    break;

                case "FeaturedProperties":
                    this.FeaturedTabSetColumn();
                    break;

                case "Listings":
                    this.MlslistingTabSetColumn();
                    break;
            }

            var thAddressControl = document.getElementById('thAddress');
            if (thAddressControl != null)
            {
                if (gMember && !g_NavigationEngine._isWhiteSite)
                {
                    thAddressControl.className = 'propAddress';
                }
                else
                {
                    thAddressControl.className = 'propAddress first';
                }
            }
            
            var searchReq = GetSearchRequest();
            if (searchReq != null && searchReq.BasicRequest != null)
            {
                if (searchReq.BasicRequest.SearchType == SEARCH_TYPE_ADDRESS || (isPremiumMember && searchReq.BasicRequest.SearchType == G_SEARCH_TYPE_PROPERTY_ID))
                {
                    ShowTableCell('thProximity', true);
                }
                else
                {
                    ShowTableCell('thProximity', false);
                }
            }
            else
            {
                ShowTableCell('thProximity', false);
            }

            ShowTableRow('propHeader', true);
            ShowTableCell('pageNavList', true);
            ShowTableCell('pageNavJump', true);

            ShowTableCell('tdSelectAll', isPremiumMember && !isBHDDomain && !g_NavigationEngine._isWhiteSite);

            ShowTableCell('thAction', (gPostcardMultiplePropertiesActive && (this._searchResults.IsPreForeclosureTab || this._searchResults.IsAuctionTab)));

            hideShowSendProstcardsButton(this._searchResults.IsPreForeclosureTab || this._searchResults.IsAuctionTab);

            HideReportSectionForBHD();
            
            HideSearchOverlay();
        }
        catch (er)
        {
            LogErrorMessage("SearchResultList.ShowColumnTitles: ", er, true);
        }
    }


    this.PreforeclosureTabSetColumns = function() 
    {
        try 
        {
            if (isPremiumMember && !isBHDDomain) 
            {
                this._showCheckboxes = true;
                ShowTableCell('thSelectToPrint', true);
                ShowTableCell('thEmpty', false);
                ToggleGenerateReportsWidget(true);
            }
            else 
            {
                this._showCheckboxes = false;
                ShowTableCell('thSelectToPrint', false);
                ShowTableCell('thEmpty', true);
            }

        }
        catch (er) 
        {
            LogErrorMessage("SearchResultList.PreforeclosureTabSetColumns: ", er, true);
        }
    }

    this.AuctionTabSetColumns = function() 
    {
        try 
        {
            switch (this._searchResults.SelectedSubTab) 
            {
                case "AuctionTrusteeSale":
                case "AuctionSheriffSale":

                    if (isPremiumMember && !isBHDDomain) 
                    {
                        this._showCheckboxes = true;
                        ShowTableCell('thSelectToPrint', true);
                        ShowTableCell('thEmpty', false);
                        ToggleGenerateReportsWidget(true);
                    }
                    else 
                    {
                        this._showCheckboxes = false;
                        ShowTableCell('thSelectToPrint', false);
                        ShowTableCell('thEmpty', true);
                    }

                    break;

                case "AuctionOnlineAuction":

                    if (isPremiumMember && !isBHDDomain) 
                    {
                        this._showCheckboxes = true;
                        ShowTableCell('thSelectToPrint', true);
                        ShowTableCell('thEmpty', false);
                        ToggleGenerateReportsWidget(true);
                    }
                    else 
                    {
                        this._showCheckboxes = false;
                        ShowTableCell('thSelectToPrint', false);
                        ShowTableCell('thEmpty', true);
                    }

                    break;

                case "AuctionLiveAuction":
                    if (isPremiumMember && !isBHDDomain) 
                    {
                        this._showCheckboxes = true;
                        ShowTableCell('thSelectToPrint', true);
                        ShowTableCell('thEmpty', false);
                        ToggleGenerateReportsWidget(true);
                    }
                    else 
                    {
                        this._showCheckboxes = false;
                        ShowTableCell('thSelectToPrint', false);
                        ShowTableCell('thEmpty', true);
                    }

                    break;
            }
        }
        catch (er) 
        {
            LogErrorMessage("SearchResultList.AuctionTabSetColumns: ", er, true);
        }
    }

    this.BankownedTabSetColumn = function() 
    {
        try 
        {
            switch (this._searchResults.SelectedSubTab) 
            {
                case "BankOwnedBankOwned":

                    if (isPremiumMember && !isBHDDomain) 
                    {
                        this._showCheckboxes = true;
                        ShowTableCell('thSelectToPrint', true);
                        ShowTableCell('thEmpty', false);
                        ToggleGenerateReportsWidget(true);
                    }
                    else 
                    {
                        this._showCheckboxes = false;
                        ShowTableCell('thSelectToPrint', false);
                        ShowTableCell('thEmpty', true);
                    }

                    break;

                case "BankOwnedReoListings":
                    if (isPremiumMember && !isBHDDomain) 
                    {
                        this._showCheckboxes = true;
                        ShowTableCell('thSelectToPrint', true);
                        ShowTableCell('thEmpty', false);
                        ToggleGenerateReportsWidget(true);
                    }
                    else 
                    {
                        this._showCheckboxes = false;
                        ShowTableCell('thSelectToPrint', false);
                        ShowTableCell('thEmpty', true);
                    }

                    break;

                case "BankOwnedOnlineAuction":
                    if (isPremiumMember && !isBHDDomain) 
                    {
                        this._showCheckboxes = true;
                        ShowTableCell('thSelectToPrint', true);
                        ShowTableCell('thEmpty', false);
                        ToggleGenerateReportsWidget(true);
                    }
                    else 
                    {
                        this._showCheckboxes = false;
                        ShowTableCell('thSelectToPrint', false);
                        ShowTableCell('thEmpty', true);
                    }

                    break;

                case "BankOwnedLiveAuction":
                    if (isPremiumMember && !isBHDDomain) 
                    {
                        this._showCheckboxes = true;
                        ShowTableCell('thSelectToPrint', true);
                        ShowTableCell('thEmpty', false);
                        ToggleGenerateReportsWidget(true);
                    }
                    else 
                    {
                        this._showCheckboxes = false;
                        ShowTableCell('thSelectToPrint', false);
                        ShowTableCell('thEmpty', true);
                    }


                    break;

                case "BankOwnedGovernmentOwned":
                    if (isPremiumMember && !isBHDDomain) 
                    {
                        this._showCheckboxes = true;
                        ShowTableCell('thSelectToPrint', true);
                        ShowTableCell('thEmpty', false);
                        ToggleGenerateReportsWidget(true);
                    }
                    else 
                    {
                        this._showCheckboxes = false;
                        ShowTableCell('thSelectToPrint', false);
                        ShowTableCell('thEmpty', true);
                        ToggleGenerateReportsWidget(false);
                    }


                    break;
            }
        }
        catch (er) 
        {
            LogErrorMessage("SearchResultList.BankownedTabSetColumn: ", er, true);
        }
    }

    this.ForsaleTabSetColumn = function() 
    {
        try 
        {
            switch (this._searchResults.SelectedSubTab) 
            {
                case "HomesForSaleResaleMLS":
                case "HomesForSaleReoListing":
                case "HomesForSaleFSBO":

                    if (isPremiumMember && !isBHDDomain) 
                    {
                        this._showCheckboxes = true;
                        ShowTableCell('thSelectToPrint', true);
                        ShowTableCell('thEmpty', false);
                        ToggleGenerateReportsWidget(true);
                    }
                    else 
                    {
                        this._showCheckboxes = false;
                        ShowTableCell('thSelectToPrint', false);
                        ShowTableCell('thEmpty', true);
                    }

                    break;
            }
        }
        catch (er) 
        {
            LogErrorMessage("SearchResultList.ForsaleTabSetColumn: ", er, true);
        }
    }

    this.FeaturedTabSetColumn = function() 
    {
        try 
        {
            if (isPremiumMember && !isBHDDomain) 
            {
                this._showCheckboxes = true;
                ShowTableCell('thSelectToPrint', true);
                ShowTableCell('thEmpty', false);
            }
            else 
            {
                this._showCheckboxes = false;
                ShowTableCell('thSelectToPrint', false);
                ShowTableCell('thEmpty', true);
            }

            ToggleGenerateReportsWidget(false);

        }
        catch (er) 
        {
            LogErrorMessage("SearchResultList.FeaturedTabSetColumn: ", er, true);
        }
    }

    this.RemoveHeadingFromTable = function(tableElement) 
    {
        try 
        {
            for (var i = 0; i < tableElement.rows.length; i++) 
            {
                if (tableElement.rows[i].id == PROPERTY_LIST_DELIMITER_ID) 
                {
                    tableElement.deleteRow(i);
                    i--;
                    if (i < 0) 
                    {
                        i = 0;
                    }
                }
            }
        }
        catch (er) 
        {
            LogErrorMessage("SearchResultList.RemoveHeadingFromTable: ", er, true);
        }
    }

    this.CreateExternalLink = function(property) 
    {
        var externalLink = "";

        if (typeof (property) != "undefined" && property != null
            && typeof (property.LinkToSupplier) != "undefined" && property.LinkToSupplier != null
            && property.LinkToSupplier == "HomeSeekers") 
        {
            externalLink = externalLink = g_NavigationEngine.CreateMLSDetailsLink(property.CombineKeyID, property.Address, property.Zip, property.City, property.State);
        }
        else if (typeof (property) != "undefined" && property != null 
            && typeof (property.LinkToSupplier) != "undefined" && property.LinkToSupplier != null
            && (property.LinkToSupplier != "RTInternal" && property.LinkToSupplier != "" ))       
        {
            //Phu Tran: If it's an external 
            externalLink =  g_NavigationEngine.PropertyDetailsPageForPropertyType(property.ForeclosureStatusLinkID, property.ForeclosureStatus)
        }
        
        return externalLink;
    }

    this.GetListedHtml = function(property) 
    {
        var listedHtml = "";
        var listingsCode = new Object();
        listingsCode.ID = "gcpLockIcon" + ((property != null) ? property.CombineKeyID : 0);
         
        if (property != null
            && property.CalculatedRank != null
            && property.CalculatedRank > -1) 
            {
            var starsCount = property.CalculatedRank;
            var externalLink = this.CreateExternalLink(property);

            if (0 <= starsCount && starsCount <= 3) 
            {
                var imageRef = "<img src='" + LISTED_COLUMN_MASKED_ITEM_IMAGE_NAME + "' alt='listed for sale'/>";
                var imageHref = "#";
                var imageOnClick = null;
                if (isPremiumMember && !gIsPreferredMember)
                {
                    imageRef = "<img src='" + LISTED_COLUMN_ITEM_IMAGE_NAME + starsCount + ".gif' alt='listed for sale'/>";
                    
                    if (externalLink != null && externalLink != "") 
                    {
                        imageOnClick = "javascript:return OpenExternalUrl('" + externalLink + "');";
                    }
                    else 
                    {
                        imageHref = g_NavigationEngine.PropertyDetailsPageForPropertyType(property.ForeclosureStatusLinkID, property.ForeclosureStatus);
                    }    
                }
                else 
                {
                    if (gIsGuestMember)
                    {
                        imageHref = g_NavigationEngine.GuestMemberUpgrade(property.CombineKeyID);
                    }
                    else if (gIsCancelledMember)
                    {
                        imageHref = g_NavigationEngine.ModifyAccount(property.CombineKeyID);
                    }
                    else if (gIsPreferredMember)
                    {
                        imageHref = g_NavigationEngine.UpgradeLanding(property.CombineKeyID)
                    }
                    else
                    {
                        imageHref = g_NavigationEngine.RegistrationPage(property.CombineKeyID);
                    }                    
                }
                
                listedHtml += "<a href=\"" + imageHref + "\" class=\"target\" id=\"" + listingsCode.ID + "\"" + ((imageOnClick != null) ? " onclick=\"" + imageOnClick + "\"" : "") + " >";
                listedHtml += imageRef;                
                listedHtml += "</a>";
            }
        }
                
        listingsCode.HTML = listedHtml;
        return listingsCode;
    }

    this.GetRatingsHtml = function(property) 
    {
        var ratingsHtml = "";

        if (!isPremiumMember || gIsPreferredMember) 
        {
            if (gIsPreferredMember)
            {
                ratingsHtml += "<a href=\"" + g_NavigationEngine.UpgradeLanding(property.CombineKeyID) + "\" class=\"target\" id=\"RatingsLockIcon" + property.CombineKeyID + "\" >" 
            }
            else
            {
                ratingsHtml += "<a href=\"" + g_NavigationEngine.RegistrationPage(property.CombineKeyID) + "\" class=\"target\" id=\"RatingsLockIcon" + property.CombineKeyID + "\" >"
            }
            ratingsHtml += "<img src='/images/ResaleTieIn/ms_lockgrey_15x19.gif' alt='lock' onmouseover=\"this.src='/images/ResaleTieIn/ms_lockblue_15x19.gif';\" onmouseout=\"this.src='/images/ResaleTieIn/ms_lockgrey_15x19.gif';\" />"
            ratingsHtml += "</a>";
        }
        else if (property != null
            && property.CalculatedRank != null
            && property.CalculatedRank > -1) 
            {
            var starsCount = property.CalculatedRank;
            if (0 <= starsCount && starsCount <= 3) 
            {
                ratingsHtml += "<img src='" + RATING_COLUMN_ITEMIMAGE_NAME + starsCount + ".gif' alt='rating'/>";
            }
        }

        var ratingsCode = new Object();
        ratingsCode.ID = "RatingsLockIcon" + property.CombineKeyID;
        ratingsCode.HTML = ratingsHtml;
        return ratingsCode;

    }

    this.GetStatusHtml = function(property) 
    {
        var statusHtml = "";
        var statusCode = new Object();
        statusCode.toolTipID = '';
        statusCode.ID = '';

        if (!isPremiumMember) 
        {
            statusHtml += "<a href=\"" + g_NavigationEngine.RegistrationPage(property.CombineKeyID) + "\" class=\"target\" id=\"StatusLockIcon" + property.CombineKeyID + "\" >"
            statusHtml += "<img src='/images/ResaleTieIn/ms_lockgrey_15x19.gif' alt='lock' onmouseover=\"this.src='/images/ResaleTieIn/ms_lockblue_15x19.gif';\" onmouseout=\"this.src='/images/ResaleTieIn/ms_lockgrey_15x19.gif';\" />"
            statusHtml += "</a>";
            statusCode.toolTipID = 'foreclosureStatusIconLock';
            statusCode.ID = "StatusLockIcon" + property.CombineKeyID;  
        }
        else if (property != null
            && property.ForeclosureStatus != null
            && property.ForeclosureStatus.length != ""
            && property.ForeclosureStatus.length == 1) 
            {
            var link = "";
            var externalLink = this.CreateExternalLink(property);

            if (externalLink != null && externalLink != "") 
            {
                link = "<a href=\"#\" onclick=\"javascript:return OpenExternalUrl('" + externalLink + "');\" class=\"target\" id=\"ForeclosureStatus"+ property.CombineKeyID + "\" >";
            }
            else 
            {
                link = "<a href=\"" + g_NavigationEngine.PropertyDetailsPageForPropertyType(property.ForeclosureStatusLinkID, property.ForeclosureStatus) + "\" class=\"target\" id=\"ForeclosureStatus" + property.CombineKeyID + "\" >";
            }

            statusHtml += link;
            statusHtml += "<img src='" + STATUS_COLUMN_ITEM_IMAGE_NAME + property.ForeclosureStatus.toUpperCase() + ".jpg' alt='status'/>";
            statusHtml += "</a>";
            statusCode.toolTipID = 'foreclosureStatusIcon' + property.ForeclosureStatus.toUpperCase();
            statusCode.ID = "ForeclosureStatus" + property.CombineKeyID;  
        }

        statusCode.HTML = statusHtml;
        
        return statusCode;
    }

    this.DisplayProperties = function() 
    {
        try 
        {
            var propertyTable = document.getElementById('propertyListTable');
            var tableElement = propertyTable.tBodies[0];
            propertyTable.className = gMember ? 'propertyList memberList' : 'propertyList nonMemberList';

            if (this._searchResults.PropertySearchResults) 
            {
                var rowCounter = 1;
                var offsetForPropNearRow = 0;
                var currentPropSearchResult;
                var searchLocation = this._searchResults.SearchLocationDisplay;
                var tr;
                var selectedSubTab = this._searchResults.SelectedSubTab;
                var date = "";
                var price = "";
                var showLnkGetEmailAlerts = false;
                var needToShowTheButtonColumn = false;

                this.RemoveHeadingFromTable(tableElement);
                if (this._searchResults.PropertySearchResults.length > 0) 
                {
                    ShowTableRow('noPropertiesFound', false);
                    for (var i = 0; i < this._searchResults.PropertySearchResults.length; i++) 
                    {
                        currentPropSearchResult = this._searchResults.PropertySearchResults[i];

                        if (this.FeaturedPropertiesLength() > 0 && rowCounter >= (4 + 1 + offsetForPropNearRow)) 
                        {
                            rowCounter = propertyTable.rows.length - 1;
                        }
                        tr = tableElement.insertRow(rowCounter);

                        if (currentPropSearchResult.GroupDelimiterMark > 1) 
                        {
                            tr.id = PROPERTY_LIST_DELIMITER_ID;
                            if (currentPropSearchResult.GroupDelimiterMark == 2) 
                            {
                                AddTableCell(tr, 0, PROPERTY_LIST_DELIMITER_CLASS, '<span>Properties that may interest you</span><a href="#" onclick="return OpenPropertiesMayInterestPopUp();">what\'s this?</a>', 12);
                            }
                            else if (currentPropSearchResult.GroupDelimiterMark == 3) 
                            {
                                AddTableCell(tr, 0, PROPERTY_LIST_DELIMITER_CLASS, '<span>Properties Near ' + searchLocation + '</span>', 12);
                            }
                            else 
                            {
                                AddTableCell(tr, 0, PROPERTY_LIST_DELIMITER_CLASS, '<span>Properties Near ' + searchLocation + ' that may interest you</span><a href="#" onclick="return OpenPropertiesMayInterestPopUp();">what\'s this?</a>', 12);
                            }
                            offsetForPropNearRow = 1;
                            //Insert next row
                            rowCounter++;
                            tr = tableElement.insertRow(rowCounter);
                        }

                        tr.className = 'propertyRow';
                        tr.onmouseover = function() { this.className = 'propHover'; };
                        tr.onmouseout = function() { this.className = 'propertyRow'; };

                        var property = currentPropSearchResult;
                        var cellId = 0;


                        if (property.DateDisplay != null && property.DateDisplay != "") 
                        {
                            date = property.DateDisplay;
                        }
                        else {
                            date = "NA";
                        }

                        if (property.DefaultPrice != null && property.DefaultPrice != "" && property.DefaultPrice > 0) 
                        {
                            price = "$" + AddCommas(property.DefaultPrice);
                        }
                        else if (property.DefaultPrice == "" || property.DefaultPrice == 0) 
                        {
                            price = "NA";
                        }

                        if (this._showCheckboxes && !g_NavigationEngine._isWhiteSite) 
                        {
                            AddTableCell(tr, cellId++, 'propPrint first', '<input name="" class="propertySelectCheckbox" type="checkbox" value="" onclick="SelectPropertyID(this, ' + property.CombineKeyID + ')"/>');
                        }
                        else {

                            AddTableCell(tr, cellId++, '', '');
                        }

                        var propertyDetailsPageUrl = g_SEONavigationEngine.PropertyDetailsPage.GetUrl(
                            property.CombineKeyID, 
                            property.StreetName, 
                            property.City, 
                            (property.StateCode != null) ? property.StateCode : property.State,
                            property.Zip, 
                            'details');
                        
                        var propertyDetailsPageLink = g_SEONavigationEngine.CreateLink(propertyDetailsPageUrl, property.AddressDisplay, property.AddressDisplay, false, true);                        
                        
                        if (property.Supplier.toLowerCase() == "oodle") 
                        {
                            propertyDetailsPageLink = g_NavigationEngine.CreatePropertyDetailsLinkForPropertyType(property, property.AddressDisplay, 'details')
                            propertyDetailsPageLink += '<br/><span style="color:#939393;font-size:9px;" >powered by Oodle</span>';
                        }

                        var propertyDetailsPageLinkSOLD = g_NavigationEngine.CreatePropertyDetailsLinkForPropertyType(property, 'SOLD');

                        var mappingUrl = 'javascript:gSearchResultList.ShowPropertyOnMap(' + property.CombineKeyID + ', \'' + (property.IsOnlineAuction ? 'E' : property.RecordTypeRaw) + '\')';

                        var loadingImageId = 'loadingImage' + property.CombineKeyID + '_' + i;
                        var hiddenImageTag = '<img height="0" onerror="PropertyImageError(\''
                            + loadingImageId + '\');" onload="PropertyImageLoaded(\''
                            + loadingImageId + '\', this);" style="visibility:hidden;" visible="false" width="0" height="0" src="' + this.GetPropertyImageSrc(property, 'srt') + '" />';

                        var imageClass = 'propPhoto' + ((gMember) ? '' : ' first');
                        AddTableCell(tr, cellId++, imageClass, '<a href="' + propertyDetailsPageUrl + '"><img id="' + loadingImageId + '" src="../images/loading_small.gif" alt="Photo Icon" class="propertyPhoto" /></a>');
                        AddTableCell(tr, cellId++, 'propAddress', propertyDetailsPageLink);
                        AddTableCell(tr, cellId++, 'propMap', '<div class="button"> <a href="' + mappingUrl + '" class="buttonSystemSmall" title="Map"><span>Map</span></a></div>');
                        AddTableCell(tr, cellId++, 'propEntered', date + hiddenImageTag);
                        AddTableCell(tr, cellId++, 'propBeds', property.BedroomDisplay);
                        AddTableCell(tr, cellId++, 'propBaths', property.BathroomDisplay);
                        AddTableCell(tr, cellId++, 'propSqFt', property.SquareFeetDisplay);

                        if (!property.IsSold) 
                        {
                            var priceDisplayValue = price;
                            if (property.IsHudsonAndMarshall && priceDisplayValue == 'NA') 
                            {
                                priceDisplayValue = 'No Minimum';
                            }
                            AddTableCell(tr, cellId++, 'propAmount', priceDisplayValue);
                        }
                        else 
                        {
                            AddTableCell(tr, cellId++, 'propAmountSold', propertyDetailsPageLinkSOLD);
                        }

                        if (!g_NavigationEngine._isWhiteSite && !g_NavigationEngine._isDataLink &&
                            gShowBlueBookData && !isBHDDomain) 
                        {
                            if (property.RepairCost != null && property.RepairCost != "" && property.RepairCost > 0) 
                            {
                                price = g_NavigationEngine.CreatePropertyDetailsLinkForPropertyType(property, '$' + AddCommas(property.RepairCost), 'repairCostDetails', COST_TO_RESTORE_TAB_INDEX);
                            }
                            else if (property.RepairCost == "" || property.RepairCost == 0) 
                            {
                                price = "NA";
                            }
                            AddTableCell(tr, cellId++, 'propRepairCost', price);
                        }

                        if (!g_NavigationEngine._isWhiteSite && !g_NavigationEngine._isDataLink &&
				            (typeof (hideListedColumn) == "undefined" || !hideListedColumn)) 
				            {
                            // If selected subtab is Resale/MLS or FSBO than we display "Rating" and "status" columns
                            // for "Pre-Foreclosure â€“ Defaults", "Auction - Trustee Sales / Sheriff's Sales", 
                            // "Bank Owned - Bank Owned" we display "Listed column".
                            // Otherwise we don't display anything
                            if (this._searchResults.SelectedSubTab == "HomesForSaleResaleMLS"
                                || this._searchResults.SelectedSubTab == "HomesForSaleFSBO") 
                                {
                                var statusCode = this.GetStatusHtml(property);
                                var ratingsCode = this.GetRatingsHtml(property);

                                AddTableCell(tr, cellId++, 'propRating', ratingsCode.HTML);
                                AddTableCell(tr, cellId++, 'propStatus', statusCode.HTML)

                                $('#' + ratingsCode.ID).bt({ width: '300px', ajaxPath: '/MapSearch/TooltipCopy.xml div#foreclosureRatingIconLock' });

                                if (statusCode.toolTipID && statusCode.toolTipID.length > 0) 
                                {
                                    $('#' + statusCode.ID).bt({ width: '300px', ajaxPath: '/MapSearch/TooltipCopy.xml div#' + statusCode.toolTipID });
                                }
                            }
                            else if (this._searchResults.SelectedSubTab == "PreForeclosuresDefaults"
                                || this._searchResults.SelectedSubTab == "AuctionTrusteeSale"
                                || this._searchResults.SelectedSubTab == "AuctionSheriffSale"
                                || this._searchResults.SelectedSubTab == "BankOwnedBankOwned"
                                || this._searchResults.SelectedSubTab == "BankOwnedGovernmentOwned") 
                                {

                                var listingsCode = this.GetListedHtml(property);

                                AddTableCell(tr, cellId++, 'propListed', listingsCode.HTML);

                                if (isPremiumMember) 
                                {
                                    $('#' + listingsCode.ID).bt({ width: '100px', ajaxPath: '/MapSearch/TooltipCopy.xml div#resaleFlagPremium' });
                                }
                                else 
                                {
                                    $('#' + listingsCode.ID).bt({ width: '200px', ajaxPath: '/MapSearch/TooltipCopy.xml div#resaleFlagNonPremium' });
                                }
                            }
                        }


                        if (this._searchResults.SearchType == SEARCH_TYPE_ADDRESS || (isPremiumMember && this._searchResults.SearchType == SEARCH_TYPE_PROPERTY_ID)) 
                        {
                            if (isPremiumMember) 
                            {
                                AddTableCell(tr, cellId++, 'propDistance', property.DistanceDisplay);
                            }
                            else 
                            {
                                AddTableCell(tr, cellId++, 'propDistanceLock', this.ShowProxPopUp(tr.rowIndex, property.CombineKeyID));
                                $('#lockIcon' + tr.rowIndex).bt({ width: '225px', ajaxPath: '/MapSearch/TooltipCopy.xml div#proxLockPopUp' });
                            }
                        }

                        needToShowTheButtonColumn = this.CreateButton(property) || needToShowTheButtonColumn;

                        if (this._button != null) 
                        {
                            AddTableCell(tr, cellId++, 'propAction', g_NavigationEngine.CreateLink(this._buttonAction, this._button));
                        }
                        else 
                        {
                            AddTableCell(tr, cellId++, '', '');
                        }
                        
                        showLnkGetEmailAlerts = showLnkGetEmailAlerts || this.ShowEmailAlertsButtonForProperty(property);

                        rowCounter++;
                    }
                    
                    if(isBHDDomain || g_NavigationEngine._isWhiteSite || g_NavigationEngine._isDataLink)
                    {
                        showLnkGetEmailAlerts = false;
                    }

                    this.ShowHideEmailAlertsButton(showLnkGetEmailAlerts);
                    
                    if(needToShowTheButtonColumn)
                    {
                        ShowTableCell('thAction', true);
                    }
                }
                else 
                {
                    ShowTableRow('propFeaturedProperties', false);
                    ShowTableRow('noPropertiesFound', true);
                }
            }
        }
        catch (er) {
            LogErrorMessage("SearchResultList.DisplayProperties: ", er, true);
        }
    }
    
    this.ShowEmailAlertsButtonForProperty = function(property)
    {
        return property && property.IsMakeOffer;
    }

    this.ShowHideEmailAlertsButton = function(showButton) 
    {        
        var lnkEmails = document.getElementById(g_ModifySearchHelper.LnkGetEmailAlerts);
        var alertEmailContainer = document.getElementById('BuyerArmyEmailAlert');
        if (null != lnkEmails)
        {
            lnkEmails.style.display = showButton ? 'inline' : 'none';
        }
        if(alertEmailContainer != null)
        {
            alertEmailContainer.style.display = showButton ? 'block' : 'none';
        }
    }

    this.ShowProxPopUp = function(index, propID) {
        try {
            var divColumn = document.createElement('div');
            var lckLink = document.createElement('a');

            $(lckLink).attr('href', g_NavigationEngine.RegistrationPage(propID)).attr('onmouseover', "$('#lockIcon" + index + "').attr('src', '../images/propertyList/lockProximity_RO.gif');").attr('onmouseout', "$('#lockIcon" + index + "').attr('src', '../images/propertyList/lockProximity.gif');").html('<img id="lockIcon' + index + '" src="../images/propertyList/lockProximity.gif" alt="locked" />');
            divColumn.appendChild(lckLink);

            return divColumn.innerHTML;
        }
        catch (ex) {
            LogErrorMessage("SearchResultList.ShowProxPopUp: ", er, true);
        }
    }

    this.ContactOwnerUpdate = function(propertyID) 
    {
        try 
        {
            var hdn = document.getElementById("hdnContactOwnerProps");
            if (hdn) 
            {
                var values = hdn.value;
                var propSelected = new Array();
                var result = '';
                propSelected = hdn.value.split(",");
                var f = false;
                for (i = 0; i < propSelected.length; i++) 
                {
                    if (propertyID == propSelected[i]) 
                    { // unselect
                        f = true;
                        propSelected[i] = '';
                        break;
                    }
                }
                for (i = 0; i < propSelected.length; i++) 
                {
                    if (propSelected[i] != '') 
                    {
                        if (result != '') 
                        {
                            result = result + ',';
                        }
                        result = result + propSelected[i];
                    }
                }
                if (!f) 
                {
                    if (result != '') 
                    {
                        result = result + ',';
                    }
                    result = result + propertyID;
                }
                hdn.value = result;
            }
        }
        catch (er) 
        {
            LogErrorMessage("SearchResultList.ContactOwnerUpdate: ", er, true);
        }
    }

    this.ShowContactOwnerProperties = function() 
    {
        try 
        {
            var hdn = document.getElementById("hdnContactOwnerProps");
            if (hdn && hdn.value != '') 
            {
                var searchCriteria = GetSearchRequestHash();
                var propList = hdn.value;

                __doPostBack('ContactOwner', propList);
            }
            else 
            {
                alert('Please select properties first if you want to contact their owners!');
            }
        }
        catch (er) 
        {
            LogErrorMessage("SearchResultList.ShowContactOwnerProperties: ", er, true);
        }
    }

    this.GetPropertyImageSrc = function(property, source) 
    {
        if (property != null && property.PropertyPictureExists) 
        {
            return property.PictureURL;
        }

        return '/BirdsEyeImage/propertyimage.ashx?propid=' + property.CombineKeyID + ' &z=30&tn=true&src=' + source;
    }


    this.DisplayList = function() 
    {
        this.DisplayProperties();
    }

    this.DisplayFeaturedProperties = function() 
    {
        try 
        {
            if (this._searchResults == null || this._searchResults.FeaturedProperties == null) 
            {
                return;
            }

            if (this.FeaturedPropertiesLength() > 0 && !this._searchResults.IsNewHomesTab) 
            {
                this.DisplayFeaturedProperty(1);
                this.DisplayFeaturedProperty(2);
                this.DisplayFeaturedProperty(3);
                this.DisplayFeaturedProperty(4);

                ShowTableRow('propFeaturedProperties', true);
            }
            else 
            {
                ShowTableRow('propFeaturedProperties', false);
            }
        }
        catch (er) 
        {
            LogErrorMessage("SearchResultList.DisplayFeaturedProperties: ", er, true);
        }
    }

    this.UpdateFeaturedPropertyTitle = function(isMakeOffer, propertyIndex)
    {
        var header = document.getElementById("featuredPropertyHeader" + propertyIndex);
        var cssClass = "featurePropHeader boldtext";
        var innerHTML = 'Featured Property <a href="/database/fp_program.asp"><img id="FeaturedProp' + propertyIndex + '" class="target" alt="?" src="/images/ResaleTieIn/ms_questionmark_12x12.gif" bt-xtitle="" title=""/></a>';
        
        if (header != null)
        {
            if (isMakeOffer)
            {
                cssClass = "featurePropHeader whitetext boldtext emphasized";
                innerHTML = 'Taking Offers Now!';
            }
           
            header.className = cssClass;
            header.innerHTML = innerHTML;
            
            if (!isMakeOffer)
            {
                $('#FeaturedProp' + propertyIndex).bt({width: '400px', ajaxPath: '/MapSearch/TooltipCopy.xml div#featuredProperty'});
            }
        }
    }

    this.DisplayFeaturedProperty = function(propertyIndex) {
        try {
            var featuredPropertyTable = document.getElementById('featuredProperty' + propertyIndex);
            var featuredPropertyFSBOTable = document.getElementById('featuredPropertyFSBO' + propertyIndex);

            if (featuredPropertyTable == null || featuredPropertyFSBOTable == null) {
                return;
            }

            if (propertyIndex <= this.FeaturedPropertiesLength()) {
                var property = this._searchResults.FeaturedProperties[propertyIndex - 1];

                if (property == null) {
                    return;
                }

                var featuredPropertyHiddenImage = document.getElementById('featuredPropertyHiddenImage' + propertyIndex);
                var featuredPropertyAddress = document.getElementById('featuredPropertyAddress' + propertyIndex);
                var featuredPropertyTypeImage = document.getElementById('featuredPropertyTypeImage' + propertyIndex);
                var featuredPropertyTypeName = document.getElementById('featuredPropertyTypeName' + propertyIndex);
                var featuredPropertyAmount = document.getElementById('featuredPropertyAmount' + propertyIndex);
                var featuredPropertyBedBath = document.getElementById('featuredPropertyBedBath' + propertyIndex);
                var featuredPropertyMapLink = document.getElementById('featuredPropertyMapLink' + propertyIndex);
                var featuredPropertyImgHref = document.getElementById('hrefOodle' + propertyIndex);
                var ancFPMakeOffer = document.getElementById('ancFPMakeOffer' + propertyIndex);

                this.UpdateFeaturedPropertyTitle(property.IsMakeOffer, propertyIndex);

                if (!featuredPropertyHiddenImage
                    || !featuredPropertyAddress
                    || !featuredPropertyTypeImage
                    || !featuredPropertyTypeName
                    || !featuredPropertyAmount
                    || !featuredPropertyBedBath
                    || !featuredPropertyMapLink
                    || !featuredPropertyImgHref
                    || !ancFPMakeOffer) {
                    return;
                }

                featuredPropertyAddress.innerHTML = property.Address;
                try { featuredPropertyHiddenImage.src = this.GetPropertyImageSrc(property, 'mp'); } catch(ex) {}                
                featuredPropertyTypeImage.src = '../images/propertyType/' + property.PropertyIcon;

                featuredPropertyTypeName.innerHTML = property.PropertyTypeDescription;
                featuredPropertyBedBath.innerHTML = ' ' + property.BedroomDisplay + ' Bd, ' + property.BathroomDisplay + ' Ba';

                var propertyDetailsPageUrl = g_NavigationEngine.PropertyDetailsPageURL(property);

                if (property.Supplier.toLowerCase() == "oodle") {
                    featuredPropertyBedBath.innerHTML += '<br/><span style="color:#939393;font-size:8px;" >powered by Oodle</span> ';
                    featuredPropertyImgHref.setAttribute('href', propertyDetailsPageUrl);

                    Event.add(featuredPropertyAmount, 'click',
                               function(e) {
                                   _hbLink('Oodledetails_FeaturedProperty', 'right', '0,0,30,30');
                               });

                    Event.add(featuredPropertyAddress, 'click',
                               function(e) {
                                   _hbLink('Oodledetails_FeaturedProperty', 'right', '0,0,30,30');
                               });
                }

                var mappingUrl = 'javascript:gSearchResultList.ShowPropertyOnMap(' + property.CombineKeyID + ', \'' + (property.IsOnlineAuction ? 'E' : property.RecordTypeRaw) + '\')';


                if (property.IsREDC) {
                    propertyDetailsPageUrl = g_NavigationEngine.REDCPropertyDetailsPage(property.CombineKeyID);
                }

                var priceDisplayNDValue = property.PriceDisplayNoDecimals;
                if (property.IsHudsonAndMarshall && priceDisplayNDValue == 'NA') {
                    priceDisplayNDValue = 'No Minimum';
                }

                featuredPropertyAmount.innerHTML = priceDisplayNDValue;
                featuredPropertyAmount.href = propertyDetailsPageUrl;

                featuredPropertyMapLink.href = mappingUrl;
                featuredPropertyAddress.href = propertyDetailsPageUrl;

                if (property.Supplier.toLowerCase() == "oodle") {
                    featuredPropertyAmount.target = '_blank';
                    featuredPropertyAddress.target = '_blank';
                }

                featuredPropertyTable.className = 'featuredProperty' + (propertyIndex == this.FeaturedPropertiesLength() ? ' last' : '');
                featuredPropertyTable.style.display = 'block';

                featuredPropertyFSBOTable.style.display = 'none';

                ShowTableRow('trFPMakeOffer' + propertyIndex, property.IsMakeOffer);
                ancFPMakeOffer.href = '/' + gMakeOfferSiteName + '/GoToaspx.aspx?destpage=OfferForm.aspx%3FpropId%3D' + property.CombineKeyID;
            }
            else {
                featuredPropertyTable.className = 'featuredProperty FSBO' + (propertyIndex == this.FeaturedPropertiesLength() ? ' last' : '');

                /* New code to fix IE6 Bug */
                featuredPropertyFSBOTable.style.margin = '0px';
                featuredPropertyFSBOTable.style.padding = '0px';
                featuredPropertyFSBOTable.style.border = '0px none';
                featuredPropertyFSBOTable.style.border = '168px';
                featuredPropertyFSBOTable.style.float = 'left';
                featuredPropertyFSBOTable.style.clear = 'right';
                /* end */

                featuredPropertyFSBOTable.style.display = 'block';

                featuredPropertyTable.style.display = 'none';
            }
        }
        catch (er) {
            LogErrorMessage("SearchResultList.DisplayFeaturedProperty: ", er, false);
        }
    }



    this.DisplayPageNavigation = function() 
    {
        try 
        {
            document.getElementById('pageNavList_previousPage').style.display = this._searchResults.CurrentPage > 0 ? 'block' : 'none';
            document.getElementById('pageNavList_nextPage').style.display = this._searchResults.CurrentPage < this._searchResults.NumberOfPages - 1 ? 'block' : 'none';
            document.getElementById('pageNavList_previousPage').href = 'javascript:gSearchResultList.NavigateToPage(' + (this._searchResults.CurrentPage) + ')';
            document.getElementById('pageNavList_nextPage').href = 'javascript:gSearchResultList.NavigateToPage(' + (this._searchResults.CurrentPage + 2) + ')';

            var firstPageInRange = this._searchResults.CurrentPage - 9;
            if (firstPageInRange < 0) 
            {
                firstPageInRange = 0;
            }

            var pageHTML = '';
            for (var i = firstPageInRange; i < this._searchResults.NumberOfPages && i <= firstPageInRange + 9; i++) 
            {
                var liClass = '';
                if (i == firstPageInRange) 
                {
                    liClass = 'first';
                }
                if (i == this._searchResults.NumberOfPages - 1 || i == firstPageInRange + 9) 
                {
                    liClass = 'last';
                }
                if (i == this._searchResults.CurrentPage) 
                {
                    pageHTML += '<li class="' + liClass + ' on">' + (i + 1) + '</li>';
                }
                else 
                {
                    pageHTML += '<li class="' + liClass + '"><a href="javascript:gSearchResultList.NavigateToPage(' + (i + 1) + ')">' + (i + 1) + '</a></li>';
                }
            }

            document.getElementById('pagecount').innerHTML = pageHTML;
            var pagesText = this._searchResults.NumberOfPages < 2 ? 'Page' : 'Pages';
            document.getElementById('pageNav_PageCount').innerHTML = this._searchResults.NumberOfPages + ' ' + pagesText + ' &gt; ';
        }
        catch (er) 
        {
            LogErrorMessage("SearchResultList.DisplayPageNavigation: ", er, true);
        }
    }

    this.UpdateSortArrows = function() 
    {
        try 
        {
            var isZipOrAddressSearch = false;

            if (this._searchResults != null &&
                (this._searchResults.SearchType == G_SEARCH_TYPE_ZIP || this._searchResults.SearchType == G_SEARCH_TYPE_ADDRESS)) 
                {
                isZipOrAddressSearch = true;
            }

            var sortByDefaultDate = false;
            if (this._searchResults.SortBy == 'DefaultDate' ||
                this._searchResults.SortBy == 'RecordDate' ||
                this._searchResults.SortBy == 'EnteredDate' ||
                this._searchResults.SortBy == 'AuctionDate' ||
                this._searchResults.SortBy == 'ListDate') 
                {
                sortByDefaultDate = true;
            }

            // New functionality            
            this.UpdateSortArrow('imgArrowAddress', this._searchResults.SortBy == 'Address');
            this.UpdateSortArrow('imgArrowDefaultDate', sortByDefaultDate || (this._searchResults.SortBy == G_SORT_DEFAULT && !isZipOrAddressSearch));
            this.UpdateSortArrow('imgArrowBeds', this._searchResults.SortBy == 'Beds');
            this.UpdateSortArrow('imgArrowBaths', this._searchResults.SortBy == 'Baths');
            this.UpdateSortArrow('imgArrowDefaultPrice', this._searchResults.SortBy == 'DefaultPrice');
            this.UpdateSortArrow('imgArrowProximity', this._searchResults.SortBy == 'Proximity' || this._searchResults.SortBy == 'Distance' || (this._searchResults.SortBy == G_SORT_DEFAULT && isZipOrAddressSearch));
            this.UpdateSortArrow('imgArrowSquareFeet', this._searchResults.SortBy == 'SquareFeet');
            this.UpdateSortArrow('imgArrowListed', this._searchResults.SortBy == 'Listed');
            this.UpdateSortArrow('imgArrowRating', this._searchResults.SortBy == 'Rating');
            this.UpdateSortArrow('imgArrowStatus', this._searchResults.SortBy == 'Status');
            this.UpdateSortArrow('imgArrowRepairCost', this._searchResults.SortBy == 'RepairCost');
        }
        catch (er) 
        {
            LogErrorMessage("SearchResultList.UpdateSortArrows: ", er, true);
        }
    }

    this.UpdateSortArrow = function(arrow, sortByThisField) 
    {
        try 
        {
            var arrowElement = document.getElementById(arrow);
            if (arrowElement) 
            {
                if (!sortByThisField) 
                {
                    arrowElement.className = 'off';
                }
                else 
                {
                    arrowElement.className = 'on';

                    if (this._searchResults.SortDirection == G_SORT_ASC) 
                    {
                        arrowElement.src = '../images/arrow_u.gif';
                    }
                    else 
                    {
                        arrowElement.src = '../images/arrow_d.gif';
                    }
                }
            }
        }
        catch (er) 
        {
            LogErrorMessage("SearchResultList.UpdateSortArrow: ", er, true);
        }
    }

    this.SortByField = function(sortField)
    {
        try
        {
            // Do not sort by "Rating", "Status" for non-members
            if (isPremiumMember || (sortField != "Status" && sortField != "Rating"))
            {
                if (this._searchResults.SortBy == sortField)
                {
                    if (this._searchResults.SortDirection == G_SORT_ASC)
                    {
                        this._searchResults.SortDirection = G_SORT_DESC;
                    }
                    else
                    {
                        this._searchResults.SortDirection = G_SORT_ASC;
                    }
                }
                else
                {
                    this._searchResults.SortBy = sortField;
                    this._searchResults.SortDirection = G_SORT_DESC;
                }
                gModSearchOrdBy = sortField;
                this.UpdateSortArrows();
                this.RequerySearch(false);
            }
        }
        catch (er)
        {
            LogErrorMessage("SearchResultList.SortByField: ", er, true);
        }
    }

    this.ReSort = function() 
    {
        try 
        {
            this._searchResults.SortBy = document.getElementById('columnTitle').value;
            this._searchResults.SortDirection = document.getElementById('columnOrder').value;
            this._searchResults.PageSize = document.getElementById('displayCount').value;

            this.RequerySearch(false);
        }
        catch (er) 
        {
            LogErrorMessage("SearchResultList.ReSort: ", er, true);
        }
    }

    this.NavigateToPage = function(pageNumber) 
    {
        try 
        {
            if (IsNumericValue(pageNumber)) 
            {
                if (pageNumber > 0 && pageNumber <= this._searchResults.NumberOfPages) 
                {
                    this._searchResults.CurrentPage = pageNumber - 1;
                    gNeedToRefreshBanners = true;

                    this.RequerySearch(false);

                    return;
                }
            }

            alert('You have entered an invalid page number. Please try again.');
        }
        catch (er) 
        {
            LogErrorMessage("SearchResultList.NavigateToPage: ", er, true);
        }
    }

    this.ShowPropertyOnMap = function(propertyID, propertyRecordType) 
    {
        try 
        {
            if (CreateMap()) 
            {
                if (TheMap.IsBirdEyeView() && !TheMap.isMember) 
                {
                    TheMap.PinsOnMap.PopUpClass.JoinNowPopUp();
                    return;
                }

                mainPropertyId = propertyID;
                TheMap.ShowMap();
                BtnImageToShow(true);
                TheMap.ShowOverLay();
                TheMap.PinsOnMap.mainPropertyShown = true;
                gSubjectPropertyID = null;
                gSubjectPropertyLat = null;
                gSubjectPropertyLon = null;
                gSubjPropDecodedLatLong._reserved = '';
                TheMap.AddMainProperty(mainPropertyId, AddMainProperty_Continue);

            }
        }
        catch (er) 
        {
            if (TheMap && TheMap.isMapVisible) 
            {
                TheMap.HideOverLay();
            }
            LogErrorMessage("SearchResultList.ShowPropertyOnMap: ", er, true);
        }
    }

    this.RequerySearch = function(getBannersInfo) 
    {
        try 
        {
            RequerySearchService(this._searchResults.SortBy, this._searchResults.SortDirection, this._searchResults.SelectedSubTab, this._searchResults.CurrentPage, this._searchResults.PageSize, getBannersInfo);
        }
        catch (er) 
        {
            LogErrorMessage("SearchResultList.RequerySearch: ", er, true);
        }
    }

    this.RequeryList = function(subTabName, getBannersInfo) 
    {
        try 
        {
            if (subTabName != '') 
            {
                this._searchResults.SelectedSubTab = subTabName;
            }

            this._searchResults.CurrentPage = 0;
            gNeedToRefreshBanners = true;

            this.RequerySearch(getBannersInfo);
        }
        catch (er) 
        {
            LogErrorMessage("SearchResultList.SetTab: ", er, true);
        }
    }

    this.CleanupSearchList = function() 
    {
        try 
        {
            // delete all property rows
            var tableElement = document.getElementById('propertyListTable').tBodies[0];
            var rowsToDelete = new Array();
            var rowCount = 0;

            for (i = 0; i < tableElement.rows.length; i++) 
            {
                var row = tableElement.rows[i];
                if (row.className == 'propertyRow' || row.className == 'propHover' || row.id == PROPERTY_LIST_DELIMITER_ID) 
                {
                    rowsToDelete[rowCount++] = row;
                }
            }

            for (var iRow = 0; iRow < rowsToDelete.length; iRow++) 
            {
                var rIndex = rowsToDelete[iRow].sectionRowIndex;
                rowsToDelete[iRow].parentNode.deleteRow(rIndex);
            }

            // and all sort bar options
            ClearDropDown('columnTitle');
            ClearDropDown('columnOrder');
            ClearDropDown('displayCount');
        }
        catch (er) 
        {
            LogErrorMessage("SearchResultList.CleanupSearchList: ", er, true);
        }
    }

    this.FeaturedPropertiesLength = function() 
    {
        try 
        {
            if (this._searchResults != null) 
            {
                if (this._searchResults.FeaturedProperties != null) 
                {
                    if (this._searchResults.FeaturedProperties.length != null) 
                    {
                        return this._searchResults.FeaturedProperties.length;
                    }
                }
            }

            return 0;
        }
        catch (ex) 
        {
            return 0;
        }
    }

    this.GetStreetName = function(address) 
    {
        var streetName = "";
        addressSplt = address.split(",");

        if (addressSplt.length > 0) 
        {
            var streetArr = addressSplt[0].split(" ");
            if (streetArr.length > 0) 
            {
                streetArr[0] = streetArr[0].replace(/^[\d\s]+/g, "");
                streetName = streetArr.join(" ");
            }
        }

        return streetName;
    }

    this.GetZipCode = function(address) 
    {
        var zip = "";
        var regex = /\d{5}/;
        var addressArr = address.split(",");

        if (addressArr.length > 0 && addressArr[addressArr.length - 1].match(regex) != null) 
        {
            zip = addressArr[addressArr.length - 1].match(regex).join("");
        }

        return zip;
    }

    this.UpdatePropertyCount = function() 
    {
        try 
        {
            var searchCriteriaElement = document.getElementById("txtSearchRequestAddress");
            var addressSearchElement = document.getElementById("spanAddressSearch");
            var propertyCountElement = document.getElementById("spanPropertyCount");
            var areaPropertyCountElement = document.getElementById("spanAreaPropertCount");
            var addressAreaNameElement = document.getElementById("txtSearchArea");
            var searchResultsDescriprionElement = document.getElementById("txtSearchResultsDescription");

            var noPropFoundText = document.getElementById("spanNoLocationFound");

            if (this._searchResults != null && this._searchResults.SearchLocationDisplay != null && this._searchResults.SearchLocationDisplay != "") 
            {
                searchResultsDescriprionElement.innerHTML = "properties match your search";
                propertyCountElement.innerHTML = this._searchResults.PropertyCount;

                searchCriteriaElement.innerHTML = this._searchResults.SearchLocationDisplay;
                noPropFoundText.innerHTML = this._searchResults.SearchLocationDisplay;
            }

            HideSearchInProcess();

        }
        catch (ex) 
        {
            LogErrorMessage("SearchResultList.UpdatePropertyCount: ", ex, true);
        }
    }

}

function UpdatePropertyCountWithEnteredValue(enteredAddress) 
{
    var searchCriteriaElement = document.getElementById("txtSearchRequestAddress");
    var noPropFoundText = document.getElementById("spanNoLocationFound");
    var addressSearchElement = document.getElementById("spanAddressSearch");
    var propertyCountElement = document.getElementById("spanPropertyCount");

    propertyCountElement.innerHTML = "0";
    addressSearchElement.style.display = "none";
    searchCriteriaElement.innerHTML = enteredAddress;
    noPropFoundText.innerHTML = enteredAddress; ;
}

function ScrollWindow() 
{
    var map = document.getElementById('mapAll');
    var pos = getPos(map);
    window.scrollTo(0, pos);
}

function getPos(element) 
{
    var offsetY = -10;
    while (element != null) 
    {
        offsetY += element.offsetTop;
        element = element.offsetParent;
    }
    return offsetY;
}


function AddDropdownOption(dropdownId, optionText, optionValue, isSelected) 
{
    var elementDopDown = document.getElementById(dropdownId);
    if (elementDopDown) 
    {
        var elementNewOption = document.createElement('option');
        elementNewOption.text = optionText;
        elementNewOption.value = optionValue;
        try 
        {
            elementDopDown.add(elementNewOption, null); // DOM standard
        }
        catch (ex) 
        {
            elementDopDown.add(elementNewOption); // IE specific
        }

        if (isSelected) 
        {
            elementDopDown.selectedIndex = elementDopDown.options.length - 1;
        }
    }
}

function AddTableCell(trElement, id, tdClass, innerHTML, tdColspan) 
{
    var td = trElement.insertCell(id);

    if (tdClass) 
    {
        td.className = tdClass;
    }

    if (tdColspan) 
    {
        td.colSpan = tdColspan;
    }

    td.innerHTML = innerHTML;
}

function ClearDropDown(dropDownId) 
{
    var dropDownElement = document.getElementById(dropDownId);

    if (dropDownElement) 
    {
        while (dropDownElement.hasChildNodes()) 
        {
            dropDownElement.removeChild(dropDownElement.childNodes[0]);
        }
    }
}

function PropertyImageError(loadingImageId) 
{
    var element = document.getElementById(loadingImageId);
    if (element) 
    {
        element.src = '/images/image_na.gif';
    }
}

function PropertyImageLoaded(loadingImageId, propertyImage) 
{
    try
    {
        var element = document.getElementById(loadingImageId);
        if (element) 
        {
            element.src = propertyImage.src;
        }
    }
    catch(ex)
    {
    }
}

function IsNumericValue(value) 
{
    return value != null && value.toString().match(/^[-]?\d*\.?\d*$/);
}

function ShowTableRow(trId, show) 
{
    var tr = document.getElementById(trId);

    try 
    {
        if (tr) 
        {
            if (gBrowserType != G_IE) 
            {
                tr.style.display = show ? 'table-row' : 'none';
            }
            else 
            {
                tr.style.display = show ? 'block' : 'none';
            }
        }
    }
    catch (ex) 
    {
    }
}

function ShowTableCell(tdId, show) 
{
    var td = document.getElementById(tdId);

    try 
    {
        if (td) 
        {	
            if (gBrowserType != G_IE) 
            {
                td.style.display = show ? 'table-cell' : 'none';
            }
            else 
            {
                td.style.display = show ? 'block' : 'none';
            }
        }
    }
    catch (ex) 
    {		
    }
}

function ShowTab(subTabName) 
{
    ShowSearchOverlay();
    if (gSearchResultList) 
    {
        gSearchResultList._searchResults.SortBy = G_SORT_BY_DEFAULT_DATE_TEXT;

        // Set sort order for Auction tabs
        if(subTabName.toLowerCase().indexOf('auction') > -1)
        {
            gSearchResultList._searchResults.SortDirection = G_SORT_ASC;
        }
        else
        {
            gSearchResultList._searchResults.SortDirection = G_SORT_DESC;
        }
        
        if (gSearchResultList._searchResults.SearchType == SEARCH_TYPE_ADDRESS || (isPremiumMember && gSearchResultList._searchResults.SearchType == SEARCH_TYPE_PROPERTY_ID)) 
        {
            gSearchResultList._searchResults.SortBy = G_SORT_BY_PROXIMITY_TEXT;
            gSearchResultList._searchResults.SortDirection = G_SORT_ASC;
        }

        if (gModSearchOrdBy != null) 
        {
            gSearchResultList._searchResults.SortBy = gModSearchOrdBy;
        }

        gSearchResultList.RequeryList(subTabName, false);

    }
}

gIsAuctionSubTabSelected = '';

function RepopulateDdlSortBy(curentSelItem) 
{
    if (gIsAuctionSubTabSelected != undefined || gIsAuctionSubTabSelected != '')
    {
        var ddlSortBy = document.getElementById("ddlSortBy");
        
        if (!g_DDLSortByOptions)
        {
            g_DDLSortByOptions = new Array();
            for (i = 0; i < ddlSortBy.options.length; i++)
            {
                g_DDLSortByOptions[i] = ddlSortBy.options[i];
            }
        }

        while (ddlSortBy.childNodes[0])
        {
            ddlSortBy.removeChild(ddlSortBy.childNodes[0]);
        }
        
        for (i = 0; i < g_DDLSortByOptions.length; i++)
        {            
            var sortType = '';
            var itemValue = '';
            
            if (g_DDLSortByOptions[i].value == 17) //Auction Date
            {
                if (gIsAuctionSubTabSelected == "Auction"
                    || gIsAuctionSubTabSelected == "AuctionTrusteeSale"
                    || gIsAuctionSubTabSelected == "AuctionOnlineAuction"
                    || gIsAuctionSubTabSelected == "AuctionLiveAuction"
                    || gIsAuctionSubTabSelected == "AuctionSheriffSale")
                {
                    ddlSortBy.appendChild(g_DDLSortByOptions[i]);
                }
            }
            else
            {
                ddlSortBy.appendChild(g_DDLSortByOptions[i]);
            }
        }
        if (curentSelItem != null) //select Item
        {
            ddlSortBy.value = curentSelItem;
        }
    }
}


function SetupSearchBySection(subTabName)
{
    gIsAuctionSubTabSelected = subTabName;
    var ddlSortBy = document.getElementById('ddlSortBy');
    
    if (IsAdvancedSearchVisible() && ddlSortBy)
    {
        RepopulateDdlSortBy(ddlSortBy.value);
    }
}

function IsAdvancedSearchVisible()
{
    var divBottom = document.getElementById('divBottom');    
    return divBottom != null && divBottom.style.display != 'none';
}

function ShowFAQ(faqNo) 
{
    if (typeof (show_faq) != "undefined") 
    {
        show_faq(faqNo);
    }
}

function CheckForCleansedLocation() 
{
    if (gInvalidSearchTerm) 
    {
        document.getElementById('spanBadLocation').innerHTML = gOriginalSearchTerm;

        showDiv('divInvalidLocation');
        hideDiv('divCleansedLocation');
        showDiv('noLocationFound');

        setTimeout('hideDiv(\'noLocationFound\')', 10000);
    }
    else 
    {
        if (gCleansedSearchTerm) 
        {
            document.getElementById('spanBadLocation').innerHTML = gOriginalSearchTerm;
            document.getElementById('spanBadLocation2').innerHTML = gOriginalSearchTerm;
            document.getElementById('cleansedLocation').innerHTML = gCleansedSearchTerm;

            showDiv('divCleansedLocation');
            hideDiv('divInvalidLocation');
            showDiv('noLocationFound');

            setTimeout('hideDiv(\'noLocationFound\')', 10000);
        }
    }
}


function SelectPropertyID(chkSelect, propertyID) 
{
    if (chkSelect.checked) 
    {
        gSelectedProperties.push(propertyID);
    }
    else 
    {
        var tempArray = new Array();
        for (var i = 0; i < gSelectedProperties.length; i++) 
        {
            if (gSelectedProperties[i] != propertyID) 
            {
                tempArray.push(gSelectedProperties[i]);
            }
        }

        gSelectedProperties = tempArray;
    }
}

function SelectAllProperties() 
{
    var allInputs = document.getElementsByTagName('input');
    var selectAll = document.getElementById('chkSelectAll');

    for (var i = 0; i < allInputs.length; i++) 
    {
        var element = allInputs[i];
        if (element.className == 'propertySelectCheckbox') 
        {
            element.checked = selectAll.checked;
        }
    }

    gSelectedProperties = new Array();

    if (selectAll.checked) 
    {
        for (var iProp = 0; iProp < gSearchResultList._searchResults.PropertySearchResults.length; iProp++) 
        {
            var prop = gSearchResultList._searchResults.PropertySearchResults[iProp];
            gSelectedProperties.push(prop.CombineKeyID);
        }
    }
}

function ScreenScraperRedirect(logoutFlag) 
{
    window.location.href = "/UserProfile/ScreenScrapeNotification.aspx?actionFlag=" + logoutFlag;
}

function HideSelectAllCheckbox() 
{
    var selectAllElement = document.getElementById('chkSelectAll');

    ShowTableCell('tdSelectAll', false);

    if (selectAllElement != null) 
    {
        selectAllElement.checked = false;
    }
}

function fnGetCookie(psName) 
{
    var liStart = document.cookie.indexOf(psName + "=");
    var liLen = liStart + psName.length + 1;

    if ((!liStart) && (psName != document.cookie.substring(0, psName.length))) 
    { 
        return null; 
    }
    if (liStart == -1) 
    { 
        return null; 
    }
    var liEnd = document.cookie.indexOf(";", liLen);
    if (liEnd == -1) 
    {
        liEnd = document.cookie.length;
    }
    return unescape(document.cookie.substring(liLen, liEnd));
}

function fnSetCookie(psName, psValue, piExpires, psPath, psDomain, psSecure) 
{
    var ldToday = new Date();
    ldToday.setTime(ldToday.getTime());

    //piExpires = Days
    if (piExpires) { piExpires = piExpires * 1000 * 60 * 60 * 24; }
    var ldExpiresDate = new Date(ldToday.getTime() + (piExpires));

    document.cookie = psName + "=" + escape(psValue) +
					((piExpires) ? ";expires=" + ldExpiresDate.toGMTString() : "") +
					((psPath) ? ";path=" + psPath : "") +
					((psDomain) ? ";domain=" + psDomain : "") +
					((psSecure) ? ";secure" : "");

}

function CheckHistoryMark() 
{
    try 
    {
        var r = window.location.href;
        var i = r.indexOf("#");
        return i >= 0;
    }
    catch (ex) 
    {
        return false;
    }
}

function SetSearchRequestHash(searchRequest)
{

    
    window.location.hash = searchRequest;
    gSearchRequest = searchRequest;
}

function gotoSearchCriteria() 
{
    var link = "/database/searchCriteria.asp";
    var hash = GetSearchRequestHash();

    if (hash != null && hash != "") 
    {
        window.document.location.href = link + "#" + hash;
    }
}

function ToggleGenerateReportsWidget(show) 
{
    var widgetElement = document.getElementById("SR-reports");
    if (widgetElement != null) 
    {
        if (show) 
        {
            widgetElement.style.display = "block";
        }
        else 
        {
            widgetElement.style.display = "none";
        }
    }
}

//----------------------------- functions moved from map SearchResults.js --------------------------

//------- these functions are being used in:
//--C:\Inetpub\wwwroot\RealtyTrac.Web\RealtyTrac.MapSearch\RealtyTrac.MapSearch.Web\MapSearch\WebUI\ctlGenerateReportsWidget.ascx


function fnReportMethod(psMethod, containerId) 
{
    loDownloadType = document.getElementById('downloadTypeID');
    loDownloadGeneration = document.getElementById(containerId);

    if (psMethod.id == "reportDownload") 
    {
        loDownloadType.style.display = "block"
    }
    else 
    {
        loDownloadType.style.display = "none"
    }
}

function submitRepp() 
{
    if (typeof ("CheckHeaderEventOnSubmit") != "undefined") 
    {
        if (CheckHeaderEventOnSubmit()) 
        {
            return false;
        }
    }

    if (gGenerateRep) 
    {
        loReportOneLine = document.getElementById('reportOneLine');
        loReportPropDetail = document.getElementById('reportPropDetail');
        loReportPrint = document.getElementById('reportPrint');
        loReportDownload = document.getElementById('reportDownload');
        loDownloadTab = document.getElementById('downloadTab');
        loDownloadCSV = document.getElementById('downloadCSV');

        if (!loReportOneLine.checked && !loReportPropDetail.checked) 
        {
            alert('Please select report type.');
            return false;
        }

        if (!loReportPrint.checked && !loReportDownload.checked) 
        {
            alert('Please select report method.');
            return false;
        }

        if (loReportDownload.checked && !loDownloadTab.checked && !loDownloadCSV.checked) 
        {
            alert('Please select download type.');
            return false;
        }

        if (loReportPrint.checked) 
        {
            document.forms.frm.printReport.value = "true";
        }
        else 
        {
            document.forms.frm.printReport.value = "false";
            if (loDownloadTab.checked) 
            {
                document.forms.frm.downloadType.value = "tab";
            } else 
            {
                document.forms.frm.downloadType.value = "comma";
            }
        }

        document.forms.frm.fullDetails.value = loReportPropDetail.checked;

        document.forms.frm.propId.value = gSelectedProperties.join(',');
        document.forms.frm.submit();
    }
}

//------- these functions are being used in:
//--C:\Documents and Settings\socratesm\My Documents\Skype Received Files\VladimirGavrilov\MapSearch_20080930\ctlMapSearchModify.ascx

function fnShowHideHover(psEvent) 
{
}

//----------------------------- End functions moved from map SearchResults.js --------------------------


//----- Modify Search Control functions ---//

var MSG_END_DATE_MUST_BE_GREATER_THAN_BEGIN_DATE = 'End Date must be greater than begin date';
var AUCTION_DATE = "0";
var ENTERED_DATE = "1";
var RECORD_DATE = "2";
var LIST_DATE = "12";
var AUCTION_DATE_DEFAULT = "17";
var ENTERED_DATE_DEFAULT = "18";
var LIST_DATE_DEFAULT = "19";
var PRICE_DEFAULT = "20";
var SITUS_CITY = "3";
var BEDS = "4";
var BATHS = "5";
var AMOUNT = "9";

var MSG_PLEASE_SELECT_STATE_AND_COUNTY = 'Please Select State and County \n';
var MSG_PLEASE_SELECT_COUNTY = 'Please Select a County \n';
var MSG_PLEASE_SELECT_CITY_AND_COUNTY = 'Please Enter City, State \n';
var MSG_PLEASE_ENTER_ZIP_CODE = 'Please Enter Zip Code \n';
var MSG_PLEASE_ENTER_ADDRESS = 'Please Enter Address, City, State or Zip \n';
var MSG_PLEASE_ENTER_CITY_STATE_OR_ZIP = 'Please Enter City, State or Zip \n';
var MSG_PLEASE_ENTER_PROPERTY_ID = 'Please Enter Property ID or APN Number \n';
var MSG_WRONG_BEGIN_DATE = 'Begin Date is not valid \n';
var MSG_WRONG_END_DATE = 'End Date is not valid \n';
var MSG_PLEASE_ENTER_ = '';
var MSG_WRONG_PRICE_INTERVAL = "\"To\" Price should be greater than \"from\" price \n";

var setCountyByCode;

var IMAGE_MODIFY_SEARCH_MINUS = '../images/mapSearch/arrowUp.gif';
var IMAGE_MODIFY_SEARCH_PLUS = '../images/mapSearch/arrowDown.gif';

var SEARCH_TYPE_CITY = 0;
var SEARCH_TYPE_COUNTY = 1;
var SEARCH_TYPE_ADDRESS = 2;
var SEARCH_TYPE_ZIP = 3;
var SEARCH_TYPE_PROPERTY_ID = 4;
var SEARCH_TYPE_PARCEL_NUMBER = 5;
var SEARCH_TYPE_INVALID = 6;

var BEDS_VALUE_FIVE_OR_MORE = 5;
var BATHS_VALUE_FIVE_OR_MORE = 5;

//-- We register this class from .NET with all server elements IDs
function ModifySearchControlHelper(panelSaveToMyRealtyTracID,
    txtNameSearchID,
    ddlStateID,
    tbxCityID,
    tbxZipID,
    tbxAddressID,
    tbxAddressCityID,
    tbxPropertyID,
    chbxSetDefaultSearchID,
    chbxReceive3EmailAlertsID,
    tbxPropertyAPNID,
    tbxPriceMinID,
    tbxPriceMaxID,
    txtSearchFor,
    btnSave,
    btnSearch,
    btnSaveAndSearch,
    tbxSearchName,
    divSearchForContainer,
    divSaveSearchButtons,
    btnSaveEditedsavedSearch,
    lnkGetEmailAlerts
    ) 
    {
    this.PanelSaveToMyRealtyTracID = panelSaveToMyRealtyTracID;
    this.TxtNameSearchID = txtNameSearchID;
    this.DdlStateID = ddlStateID;
    this.TbxCityID = tbxCityID;
    this.TbxZipID = tbxZipID;
    this.TbxAddressID = tbxAddressID;
    this.TbxAddressCityID = tbxAddressCityID;
    this.TbxPropertyID = tbxPropertyID;
    this.ChbxSetDefaultSearchID = chbxSetDefaultSearchID;
    this.ChbxReceive3EmailAlertsID = chbxReceive3EmailAlertsID;
    this.TbxPropertyAPNID = tbxPropertyAPNID;
    this.TbxPriceMinID = tbxPriceMinID;
    this.TbxPriceMaxID = tbxPriceMaxID;
    this.TxtSearchFor = txtSearchFor;
    this.BtnSave = btnSave;
    this.BtnSearch = btnSearch;
    this.BtnSaveAndSearch = btnSaveAndSearch;
    this.TbxSearchName = tbxSearchName;
    this.DivSearchForContainer = divSearchForContainer;
    this.DivSaveSearchButtons = divSaveSearchButtons;
    this.BtnSaveEditedsavedSearch = btnSaveEditedsavedSearch;
    this.LnkGetEmailAlerts = lnkGetEmailAlerts;
}


function EnableDisableDateRange(me) 
{
    var ddlRangeMonthBegin = document.getElementById('ddlRangeMonthBegin');
    var tbxRangeDateBegin = document.getElementById('tbxRangeDateBegin');
    var ddlRangeYearBegin = document.getElementById('ddlRangeYearBegin');
    var ddlRangeMonthEnd = document.getElementById('ddlRangeMonthEnd');
    var tbxRangeDateEnd = document.getElementById('tbxRangeDateEnd');
    var ddlRangeYearEnd = document.getElementById('ddlRangeYearEnd');


    EnableDisableDateRange_Continue(me, false);
}

function EnableDisableDateRange_Continue(me, isFreeSearch)
{
    var isDateRangeEnabled = 'false';
    
    if (null != me)
    {
        isDateRangeEnabled = me[me.selectedIndex].getAttribute('enableDateRange');
    }

    if (isDateRangeEnabled == 'true')
    {
        SetDataRangeVisibility(true);
    }
    else
    {
        SetDataRangeVisibility(false);
    }

    if (me.value == ENTERED_DATE_DEFAULT || me.value == AUCTION_DATE_DEFAULT || me.value == RECORD_DATE || me.value == LIST_DATE_DEFAULT)
    {
        if (isFreeSearch)
        {
            SetFormDates();
        }
        else
        {
            SetEnteredAuctionStartDate();
        }
    }
}


function SetDataRangeVisibility(isEnabled) 
{
    var ddlRangeMonthBegin = document.getElementById('ddlRangeMonthBegin');
    var tbxRangeDateBegin = document.getElementById('tbxRangeDateBegin');
    var ddlRangeYearBegin = document.getElementById('ddlRangeYearBegin');
    var ddlRangeMonthEnd = document.getElementById('ddlRangeMonthEnd');
    var tbxRangeDateEnd = document.getElementById('tbxRangeDateEnd');
    var ddlRangeYearEnd = document.getElementById('ddlRangeYearEnd');

    if (ddlRangeMonthBegin != null && tbxRangeDateBegin != null && ddlRangeYearBegin != null &&
       ddlRangeMonthEnd != null && tbxRangeDateEnd != null && ddlRangeYearEnd != null) 
       {
        if (isEnabled) 
        {
            ddlRangeMonthBegin.disabled = tbxRangeDateBegin.disabled = ddlRangeYearBegin.disabled = false;
            ddlRangeMonthEnd.disabled = tbxRangeDateEnd.disabled = ddlRangeYearEnd.disabled = false;
        }
        else 
        {
            ddlRangeMonthBegin.disabled = tbxRangeDateBegin.disabled = ddlRangeYearBegin.disabled = true;
            ddlRangeMonthEnd.disabled = tbxRangeDateEnd.disabled = ddlRangeYearEnd.disabled = true;
        }
    }
}

function CheckDayDateEntered(event, e, typeDate) 
{
    var isNumber = false;
    var year;
    var month;
    var day;
    var keynum;
    var keychar;

    keynum = keyNumPressed(event);

    if (keyNumPressed(event) == 13) 
    { 
    ValidateForm(); 
    }
    //if we have "." "," enter, back space, delete or an arrow we return true
    if (keynum == 44 || keynum == 46) 
    {
        return false;
    }

    keychar = String.fromCharCode(keynum);

    isNumber = OnlyNumbers(event, e);

    return isNumber;
}

function CheckDateRange() 
{
    var ddlRangeMonthBegin = document.getElementById('ddlRangeMonthBegin');
    var tbxRangeDateBegin = document.getElementById('tbxRangeDateBegin');
    var ddlRangeYearBegin = document.getElementById('ddlRangeYearBegin');
    var ddlRangeMonthEnd = document.getElementById('ddlRangeMonthEnd');
    var tbxRangeDateEnd = document.getElementById('tbxRangeDateEnd');
    var ddlRangeYearEnd = document.getElementById('ddlRangeYearEnd');

    var beginDate = Date.UTC(ddlRangeYearBegin.value, ddlRangeMonthBegin.value, tbxRangeDateBegin.value, 0, 0, 0, 0);
    var endDate = Date.UTC(ddlRangeYearEnd.value, ddlRangeMonthEnd.value, tbxRangeDateEnd.value, 0, 0, 0, 0);

    if (endDate < beginDate) 
    {
        messageAlert = MSG_END_DATE_MUST_BE_GREATER_THAN_BEGIN_DATE;
    }
}

function SetEnteredAuctionStartDate() 
{
    var pnlSaveToMyRealtyTrac = document.getElementById(g_ModifySearchHelper.PanelSaveToMyRealtyTracID);

    if (pnlSaveToMyRealtyTrac) 
    {
        SetFormDates();
    }
}

function SetFormDates()
{
    var ddlRangeMonthBegin = document.getElementById('ddlRangeMonthBegin');
    var tbxRangeDateBegin = document.getElementById('tbxRangeDateBegin');
    var ddlRangeYearBegin = document.getElementById('ddlRangeYearBegin');
    var ddlRangeMonthEnd = document.getElementById('ddlRangeMonthEnd');
    var tbxRangeDateEnd = document.getElementById('tbxRangeDateEnd');
    var ddlRangeYearEnd = document.getElementById('ddlRangeYearEnd');
    var ddlSortBy = document.getElementById('ddlSortBy');

    var dateToday = new Date();

    if (null != ddlSortBy && ddlSortBy.value == AUCTION_DATE_DEFAULT)
    {
        dateToday.setDate(dateToday.getDate() + 120);
    }

    if (null != ddlRangeYearEnd && null != ddlRangeMonthEnd && null != tbxRangeDateEnd)
    {
        ddlRangeYearEnd.selectedIndex = LookForIndex(ddlRangeYearEnd, dateToday.getFullYear());
        ddlRangeMonthEnd.selectedIndex = dateToday.getMonth();
        tbxRangeDateEnd.value = dateToday.getDate();
    }

    if (null != ddlSortBy && (ddlSortBy.value == ENTERED_DATE_DEFAULT || ddlSortBy.value == RECORD_DATE || ddlSortBy.value == LIST_DATE_DEFAULT))
    {
        dateToday.setDate(dateToday.getDate() - 450);
    }

    if (null != ddlSortBy && ddlSortBy.value == AUCTION_DATE_DEFAULT)
    {
        dateToday.setDate(dateToday.getDate() - 240);
    }

    if (null != ddlRangeMonthBegin && null != tbxRangeDateBegin && null != ddlRangeYearBegin)
    {
        ddlRangeMonthBegin.selectedIndex = dateToday.getMonth();
        tbxRangeDateBegin.value = dateToday.getDate();
        ddlRangeYearBegin.selectedIndex = LookForIndex(ddlRangeYearBegin, dateToday.getFullYear());
    }
}

function LookForIndex(me, valueToSearch) 
{
    var index = '';
    if (null != me) 
    {
        for (var i = 0; i < me.length; i++) 
        {
            if (me[i].value == valueToSearch) 
            {
                index = i;
                break;
            }
        }
    }
    return index;
}

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 OnlyNumbers(e, element) 
{
    var keynum;
    var keychar;
    var numcheck;
    var isNumberOrSpecialChar = true;

    keynum = keyNumPressed(e);
    keychar = String.fromCharCode(keynum);

    //if we have "," enter, back space, delete or an arrow we return true
    //8 = ','
    //9 = 'tab'
    //13 = 'enter'
    if (keychar == '' || keynum == undefined || keynum == 8 || keynum == 44 || keynum == 9 || keynum == 13) 
    {
        return isNumberOrSpecialChar;
    }

    numcheck = /\d/;
    isNumberOrSpecialChar = numcheck.test(keychar);
    return isNumberOrSpecialChar;

}

function checkClickedKeys(event, isOnlyNumbers, element) 
{
    if (keyNumPressed(event) == 40) 
    {
        gSelectingValue = true;
    }
    if (keyNumPressed(event) == 13 && !gSelectingValue) 
    {
        ValidateForm();
    }
    else if (keyNumPressed(event) == 13 && gSelectingValue) 
    {
        gSelectingValue = false;
        return false;
    }
    if (isOnlyNumbers) 
    {
        var isNumber = OnlyNumbers(event, element);

        if (isNumber && (element.id == g_ModifySearchHelper.TbxPriceMinID || g_ModifySearchHelper.TbxPriceMaxID)) 
        {
            var maxVal = 100000000;
            var comp = element.value + String.fromCharCode(keyNumPressed(event));
            comp = comp.replace(/[\,]/g, '');

            if (eval(comp) >= maxVal) 
            {
                return false;
            }
        }

        return isNumber;
    }
    return true;
}

function ValidateForm() 
{
    gGenerateRep = false;
    messageAlert = '';
    ValidateSearchBySection();
    CheckDateRange();

    if (messageAlert != '') 
    {
        alert(messageAlert);
    }
    else 
    {
        UpdateRequest();
        InitSaveSearchFormElements();
    }

    return false;
}

function ValidateEditForm(searchID) 
{
    gGenerateRep = false;
    messageAlert = '';
    ValidateSearchBySection();
    CheckDateRange();

    if (messageAlert != '') 
    {
        alert(messageAlert);
    }
    else 
    {
        UpdateRequest();
        SavedSearchEdit(searchID);
    }

    return false;
}

function InitSaveSearchFormElements() 
{
    var divCheckboxesPopUpSaveToMyRealtytrac = document.getElementById('divCheckboxesPopUpSaveToMyRealtytrac');
    var divSearchHasBeenSavedMessage = document.getElementById('divSearchHasBeenSavedMessage');
    var txtNameSearch = document.getElementById(g_ModifySearchHelper.TxtNameSearchID);
    var alertMessage = document.getElementById('spanPopUpErrorMessages');

    if (divCheckboxesPopUpSaveToMyRealtytrac && divSearchHasBeenSavedMessage) 
    {
        divSearchHasBeenSavedMessage.style.display = 'none';
        if (alertMessage) 
        {
            alertMessage.innerHTML = '';
        }
        divCheckboxesPopUpSaveToMyRealtytrac.style.display = 'block';
        if (txtNameSearch) 
        {
            txtNameSearch.value = 'Name Search';
        }
    }
}

function GetCountyName() 
{
    var ddlState = document.getElementById(g_ModifySearchHelper.DdlStateID);
    var ddlCounty = document.getElementById('ddlCounty');
    if (ddlCounty && ddlState) 
    {
        return ddlCounty.options[ddlCounty.selectedIndex].text + " County," + ddlState.value;
    }
}

function UpdateRequest() 
{
    var address = "";
    var thisSearch = new currentSearchToSave();
    var propIDSearch = false;


    SetPropertyType(thisSearch);
    SetSearchBy(thisSearch);
    SetPropertyProfile(thisSearch);
    SetSortBy(thisSearch);

    switch (thisSearch.searchBy) 
    {
        case "state":
            address = GetCountyName();
            break;

        case "city":
            address = thisSearch.city;
            break;

        case "zip":
            address = thisSearch.zipCode;
            break;

        case "address":
            address = thisSearch.address + ", " + thisSearch.cityStateCode;
            break;

        case "id":
            if (thisSearch.propID != 'Enter Property ID' && thisSearch.propID > 0) 
            {
                propIDSearch = true;
                address = thisSearch.propID;
                if (g_NavigationEngine != "undefined") 
                {
                    var propertyDetailsUrl = g_NavigationEngine.PropertyDetailsPageForPropertyType(address, "");
                    window.location = propertyDetailsUrl;
                }
            }
            else 
            {
                address = thisSearch.propAPN;
            }



            break;
    }

    gCriteriaType = thisSearch.searchBy;
    gCriteriaValue = address;

    ShowOverlays();
    ShowHideBottomPart();

    gThisSearch = thisSearch;
    if (thisSearch.searchBy != "id") 
    {
        if (typeof (Autocomplete.IsAddressValid) != "undefined") 
        {

            Autocomplete.IsAddressValid(address, "MapSearch", g_PassportKey, SearchByAddress);
        }
    }
    else if (!propIDSearch) 
    {
        SearchByAPN(address);
    }

}

function SearchByAPN(apn) 
{
    UpdatePropertyCountWithEnteredValue(apn);
    var searchRequest = GetSearchRequest();
    searchRequest.BasicRequest.Address = null;
    searchRequest.BasicRequest.City = null;
    searchRequest.BasicRequest.CountyCode = null;
    searchRequest.BasicRequest.ExactZip = false;
    searchRequest.BasicRequest.PropertyID = null;
    searchRequest.BasicRequest.Zip = null;

    searchRequest.BasicRequest.ParcelNumber = apn;
    searchRequest.BasicRequest.SearchType = 5; //Search type parcel number

    UpdateRequest_Continue(searchRequest);
}

function SearchByAddress(addressValidationResponse) 
{
    if (addressValidationResponse != null && typeof (gThisSearch) != "undefined" && gThisSearch != null) 
    {
        if (!addressValidationResponse.IsValid) 
        {
            OpenInvalidAddressPopup(addressValidationResponse.Suggestions, UpdateRequest_Continue);
        }
        else 
        {
            var request = addressValidationResponse.SearchRequest;
            UpdatePropertyCountWithEnteredValue(addressValidationResponse.Address);

            if (typeof (UpdateHeaderSearchField) != "undefined") 
            {
                UpdateHeaderSearchField(addressValidationResponse.Address);
            }

            UpdateRequest_Continue(request);
        }
    }
}

function UpdateRequest_Continue(request) 
{
    if (request != null) 
    {
        request.IsMf = true;

        if (request.AdvancedRequest != null) 
        {
            if (gThisSearch.priceFrom != null) 
            {
                request.AdvancedRequest.PriceFrom = gThisSearch.priceFrom.replace(/,/g, '');
            }
            if (gThisSearch.priceTo != null) 
            {
                request.AdvancedRequest.PriceTo = gThisSearch.priceTo.replace(/,/g, '');
            }
            request.AdvancedRequest.BedroomCountFrom = gThisSearch.bedsNo;
            request.AdvancedRequest.BathroomCountFrom = gThisSearch.bathsNo;
            request.AdvancedRequest.SquareFeetFrom = gThisSearch.homeSize;
            request.AdvancedRequest.PropertyType = gThisSearch.propType;
            request.AdvancedRequest.SortField = gThisSearch.sortBy;
            if (gSearchResultList != null) 
            {
                gSearchResultList._searchResults.SortBy = gThisSearch.sortBy;
            }
            request.AdvancedRequest.FromDate = gThisSearch.beginDate;
            request.AdvancedRequest.ToDate = gThisSearch.endDate;
            if (gThisSearch.databaseType != null) 
            {
                request.AdvancedRequest.DatabaseType = gThisSearch.databaseType;
            }
        }

        SetSearchRequest(request);
    }


    if (TheMap && TheMap.isMapVisible) 
    {
        AddPinsBySearchValues();
    }

    if (gSearchResultList) 
    {
        gSearchResultList.RequeryList('', true);
    }
    else 
    {
        OnSearchLoad();
    }
}

function ValidateSearchBySection() 
{
    var searchState = document.getElementById('searchState');
    var searchCity = document.getElementById('searchCity');
    var searchZip = document.getElementById('searchZip');
    var searchAddress = document.getElementById('searchAddress');
    var searchProperty = document.getElementById('searchProperty');

    if (searchState.checked) 
    {
        var ddlState = document.getElementById(g_ModifySearchHelper.DdlStateID);
        if (ddlState.value == '') 
        {
            messageAlert = messageAlert + MSG_PLEASE_SELECT_STATE_AND_COUNTY;
        }
        if (ddlState.value != '') 
        {
            var ddlCounty = document.getElementById('ddlCounty');
            if (ddlCounty.value == '') 
            {
                messageAlert = messageAlert + MSG_PLEASE_SELECT_COUNTY;
            }
        }
    }
    if (searchCity.checked) 
    {
        var tbxCity = document.getElementById(g_ModifySearchHelper.TbxCityID);
        if (tbxCity.value == '' || tbxCity.value == 'Enter City, State') 
        {
            messageAlert = messageAlert + MSG_PLEASE_SELECT_CITY_AND_COUNTY;
        }
    }
    if (searchZip.checked) 
    {
        var tbxZip = document.getElementById(g_ModifySearchHelper.TbxZipID);
        if (tbxZip.value == '' || tbxZip.value == 'Enter ZIP') 
        {
            messageAlert = messageAlert + MSG_PLEASE_ENTER_ZIP_CODE;
        }
    }
    if (searchAddress.checked) 
    {
        var tbxAddress = document.getElementById(g_ModifySearchHelper.TbxAddressID);
        var tbxAddressCity = document.getElementById(g_ModifySearchHelper.TbxAddressCityID);
        if ((tbxAddress.value == '' || tbxAddress.value == 'Enter Address') && (tbxAddressCity.value == '' || tbxAddressCity.value == 'Enter City, State or ZIP')) 
        {
            messageAlert = messageAlert + MSG_PLEASE_ENTER_ADDRESS;
        }
    }

    if (searchProperty != null)
    {
        if (searchProperty.checked)
        {
            var tbxPropertyID = document.getElementById(g_ModifySearchHelper.TbxPropertyID);
            var tbxPropertyAPNID = document.getElementById(g_ModifySearchHelper.TbxPropertyAPNID);

            if ((tbxPropertyAPNID.value == '' || tbxPropertyAPNID.value == 'Enter Property APN') && (tbxPropertyID.value == '' || tbxPropertyID.value == 'Enter Property ID'))
            {
                messageAlert = messageAlert + MSG_PLEASE_ENTER_PROPERTY_ID;
            }
        }
    }
    
        ValidateBeginDate();
        ValidateEndDate();    
        ValidatePriceFromTo();
    
}

function ValidatePriceFromTo(beginPrice, endPrice)
{
    ValidatePriceFromTo();
}
function ValidatePriceFromTo()
{
    var beginPrice = document.getElementById(g_ModifySearchHelper.TbxPriceMinID);
    var endPrice = document.getElementById(g_ModifySearchHelper.TbxPriceMaxID);
    if (beginPrice.value != "No Min" && endPrice.value != "No Max")
    {
        if (parseInt(beginPrice.value.replace(/,/g, "")) > parseInt(endPrice.value.replace(/,/g, "")))
        {
            messageAlert += MSG_WRONG_PRICE_INTERVAL;
        }
    }
}

function ValidateBeginDate(beginDateDay, beginDateMonth, beginDateYear)
{
    ValidateBeginDate();
}
function ValidateBeginDate()
{
    var beginDateDay = document.getElementById('tbxRangeDateBegin');
    var beginDateMonth = document.getElementById('ddlRangeMonthBegin');
    var beginDateYear = document.getElementById('ddlRangeYearBegin');

    if (!beginDateDay.disabled && !beginDateMonth.disabled && !beginDateYear.disabled)
    {
        var dateTest = new Date();
        try
        {
            dateTest.setFullYear(parseInt(beginDateYear.value.substr(2, 2), 10), parseInt(beginDateMonth.value, 10) - 1, parseInt(beginDateDay.value, 10));
            if (parseInt(beginDateYear.value.substr(2, 2), 10) != dateTest.getFullYear() ||
               parseInt(beginDateMonth.value, 10) - 1 != dateTest.getMonth() ||
               parseInt(beginDateDay.value, 10) != dateTest.getDate())
            {
                messageAlert = messageAlert + MSG_WRONG_BEGIN_DATE;
            }
        }
        catch (ex)
        {
            messageAlert = messageAlert + MSG_WRONG_BEGIN_DATE;
        }
    }
}

function ValidateEndDate(endDateDay, endDateMonth, endDateYear)
{
ValidateEndDate();
}
function ValidateEndDate()
{
    var endDateDay = document.getElementById('tbxRangeDateEnd');
    var endDateMonth = document.getElementById('ddlRangeMonthEnd');
    var endDateYear = document.getElementById('ddlRangeYearEnd');
    if (!endDateDay.disabled && !endDateMonth.disabled && !endDateYear.disabled)
    {

        var dateTest = new Date();
        try
        {
            dateTest.setFullYear(parseInt(endDateYear.value.substr(2, 2), 10), parseInt(endDateMonth.value, 10) - 1, parseInt(endDateDay.value, 10));
            if (parseInt(endDateYear.value.substr(2, 2), 10) != dateTest.getFullYear() ||
               parseInt(endDateMonth.value, 10) - 1 != dateTest.getMonth() ||
               parseInt(endDateDay.value, 10) != dateTest.getDate())
            {
                messageAlert = messageAlert + MSG_WRONG_END_DATE;
            }
        }
        catch (ex)
        {
            messageAlert = messageAlert + MSG_WRONG_END_DATE;
        }
    }
}

function SaveToMyRealtyTracPopUpValidation() 
{
    gGenerateRep = false;
    var isValidated = false;
    var errorMessage = '';
    var txtNameSearch = document.getElementById(g_ModifySearchHelper.TxtNameSearchID);
    var spanPopUpErrorMessages = document.getElementById('spanPopUpErrorMessages');

    if (txtNameSearch) 
    {
        if (txtNameSearch.value == '' || txtNameSearch.value == 'Name Search') 
        {
            errorMessage = 'You must name the search in order to save it.';
            spanPopUpErrorMessages.innerHTML = errorMessage;
            return false;
        }
    }

    spanPopUpErrorMessages.innerHTML = '';
    SaveThisSearch(txtNameSearch.value);
    return isValidated;
}

function SaveThisSearch(searchName) 
{
    var divCheckboxesPopUpSaveToMyRealtytrac = document.getElementById('divCheckboxesPopUpSaveToMyRealtytrac');
    var divSearchHasBeenSavedMessage = document.getElementById('divSearchHasBeenSavedMessage');

    var thisSearch = new currentSearchToSave();
    SetPropertyType(thisSearch);
    SetSearchBy(thisSearch);
    SetPropertyProfile(thisSearch);
    SetSortBy(thisSearch);
    SetDefaultSearch(thisSearch);
    SetReceiveMailAlerts(thisSearch);

    SaveUpdateSearches(thisSearch, editSearchID, searchName, false, UpdateDDLSearches);

    divSearchHasBeenSavedMessage.style.display = '';
    divCheckboxesPopUpSaveToMyRealtytrac.style.display = 'none';
    closeSaveSearchPopup();
}


function SaveUpdateSearches(thisSearch, searchID, searchName, isUpdate, ReceiveFunction)
{
    if (typeof (SearchService) !== "undefined" && typeof (SearchService.SaveThisSearch) === "function")
    {
        SearchService.SaveThisSearch(searchName, thisSearch.searchBy, thisSearch.propCharacteristics, thisSearch.propType, thisSearch.databaseType,
                                        thisSearch.sortBy, thisSearch.city, thisSearch.stateCode, thisSearch.countyCode, thisSearch.zipCode,
                                        thisSearch.address, thisSearch.cityStateCode, thisSearch.propID, thisSearch.propAPN,
                                        thisSearch.priceFrom, thisSearch.priceTo, thisSearch.bedsNo, thisSearch.bathsNo,
                                        thisSearch.homeSize, thisSearch.beginDate, thisSearch.endDate, thisSearch.isDefaultSearch,
                                        thisSearch.receiveMailAlerts, searchID, isUpdate, ReceiveFunction);
        gSavedSearchName = searchName;
    }
}

function SetSearchByAndFor(Search)
{
    var ddlSearchIn = document.getElementById('ddlSearchIn');
    var txtSearchFor = document.getElementById(g_ModifySearchHelper.TxtSearchFor);
    
    if (txtSearchFor != null && ddlSearchIn != null)
    {
        switch (ddlSearchIn.value)
        {
            case 'address':
                Search.address = txtSearchFor.value;
                Search.searchBy = ddlSearchIn.value;
                break;
            case 'propid':
                Search.propID = txtSearchFor.value;
                Search.searchBy = 'id';
                break;
            case 'apn':
                Search.propAPN = txtSearchFor.value;
                Search.searchBy = 'id';
                break;
        }        
    }            
    
}

function UpdateDDLSearches(searchSavedList) 
{
    var ddlSavedSearches = document.getElementById(g_HeaderControlHelper.DdlSavedSearches);
    if (null != ddlSavedSearches) 
    {
        for (var removeID = ddlSavedSearches.options.length - 1; removeID >= 0; removeID--) 
        {
            ddlSavedSearches.remove(removeID);
        }

        var opt = document.createElement("option");
        opt.text = 'View Saved Searches';
        opt.value = '0';
        ddlSavedSearches.options.add(opt);

        for (var i = 0; i < searchSavedList.length; i++) 
        {
            var opt = document.createElement("option");
            opt.text = searchSavedList[i].Name;
            opt.value = searchSavedList[i].SearchID;


            if (gSavedSearchName == searchSavedList[i].Name) 
            {
                opt.selected = 'selected';
            }

            ddlSavedSearches.options.add(opt);
        }
    }
    gSavedSearchName = '';
}

function SetDefaultSearch(Search) 
{
    var chbxSetDefaultSearch = document.getElementById(g_ModifySearchHelper.ChbxSetDefaultSearchID);

    if (chbxSetDefaultSearch) 
    {
        Search.isDefaultSearch = chbxSetDefaultSearch.checked;
    }
}

function SetReceiveMailAlerts(Search) 
{
    var chbxReceive3EmailAlerts = document.getElementById(g_ModifySearchHelper.ChbxReceive3EmailAlertsID);

    if (chbxReceive3EmailAlerts) 
    {
        Search.receiveMailAlerts = chbxReceive3EmailAlerts.checked;
    }
}

function SetSearchBy(Search) 
{
    var state = document.getElementById('searchState');
    var city = document.getElementById('searchCity');
    var zip = document.getElementById('searchZip');
    var address = document.getElementById('searchAddress');
    var idApn = document.getElementById('searchProperty');

    if (state.checked) 
    {
        var ddlState = document.getElementById(g_ModifySearchHelper.DdlStateID);
        if (ddlState) 
        {
            Search.searchBy = state.value;
            Search.stateCode = ddlState.value;
        }

        var ddlCounty = document.getElementById('ddlCounty');
        if (ddlCounty) 
        {
            Search.countyCode = ddlCounty.value;
        }
    }
    if (city.checked) 
    {
        var tbxCity = document.getElementById(g_ModifySearchHelper.TbxCityID);
        if (tbxCity) 
        {
            Search.searchBy = city.value;
            Search.city = tbxCity.value;
        }
    }
    if (zip.checked) 
    {
        var tbxZip = document.getElementById(g_ModifySearchHelper.TbxZipID);
        if (tbxZip) 
        {
            Search.searchBy = zip.value;
            Search.zipCode = tbxZip.value;
        }
    }
    if (address.checked) 
    {
        var tbxAddress = document.getElementById(g_ModifySearchHelper.TbxAddressID);
        var tbxAddressCity = document.getElementById(g_ModifySearchHelper.TbxAddressCityID);

        Search.searchBy = address.value;
        if (tbxAddress) 
        {
            Search.address = tbxAddress.value;
        }
        if (tbxAddressCity) 
        {
            Search.cityStateCode = tbxAddressCity.value;
        }
    }

    if (idApn != null) 
    {
        if (idApn.checked) 
        {
            var tbxPropertyID = document.getElementById(g_ModifySearchHelper.TbxPropertyID);
            var tbxPropertyAPN = document.getElementById(g_ModifySearchHelper.TbxPropertyAPNID);

            Search.searchBy = 'id';
            if (tbxPropertyAPN) 
            {
                Search.propAPN = tbxPropertyAPN.value;
            }

            if (tbxPropertyID) 
            {
                Search.propID = tbxPropertyID.value;
            }
        }
    }

    return Search;
}

function SetPropertyProfile(Search) 
{
    var tbxPriceMin = document.getElementById(g_ModifySearchHelper.TbxPriceMinID);
    var tbxPriceMax = document.getElementById(g_ModifySearchHelper.TbxPriceMaxID);
    var ddlBeds = document.getElementById('ddlBeds');
    var ddlBaths = document.getElementById('ddlBaths');
    var ddlSqFt = document.getElementById('ddlSqFt');

    if (tbxPriceMin != null && tbxPriceMin.value != 'No Min') 
    {
        Search.priceFrom = tbxPriceMin.value;
    }
    if (tbxPriceMax != null && tbxPriceMax.value != 'No Max') 
    {
        Search.priceTo = tbxPriceMax.value;
    }
    if (ddlBeds) 
    {
        Search.bedsNo = ddlBeds.value;
    }
    if (ddlBaths) 
    {
        Search.bathsNo = ddlBaths.value;
    }
    if (ddlSqFt) 
    {
        Search.homeSize = ddlSqFt.value;
    }
}

function SetPropertyType(Search) 
{
    var cbxPropAll = document.getElementById('cbxPropAll');
    var cbxPropRSFR = document.getElementById('cbxPropRSFR');
    var cbxPropRCON = document.getElementById('cbxPropRCON');
    var cbxPropRAPT = document.getElementById('cbxPropRAPT');
    var cbxPropRVAC = document.getElementById('cbxPropRVAC');
    var cbxPropCOM = document.getElementById('cbxPropCOM');
    var cbxPropOther = document.getElementById('cbxPropOther');
    var tbxPropOther = document.getElementById('tbxPropOther');

    Search.propType = '';

    if (null != cbxPropAll && cbxPropAll.checked) 
    {

    }
    if (null != cbxPropRSFR && cbxPropRSFR.checked) 
    {
        Search.propType += "RSFR" + ',';
    }
    if (null != cbxPropRCON && cbxPropRCON.checked) 
    {
        Search.propType += "RCON" + ',';
    }
    if (null != cbxPropRAPT && cbxPropRAPT.checked) 
    {
        Search.propType += "RAPT" + ',';
    }
    if (null != cbxPropRVAC && cbxPropRVAC.checked) 
    {
        Search.propType += "RVAC" + ',';
    }
    if (null != cbxPropCOM && cbxPropCOM.checked) 
    {
        Search.databaseType = 1;
    }
    if (null != cbxPropOther && cbxPropOther.checked && null != tbxPropOther) 
    {
        Search.propType += tbxPropOther.value;
    }
}

function SetSortBy(Search) 
{
    var ddlSortBy = document.getElementById('ddlSortBy');
    
    if (ddlSortBy) 
    {
        //we match the numbers to pass in our object according to the enum list SearchSortFieldType        
        switch (ddlSortBy.value) 
        {
            case ENTERED_DATE:
                Search.sortBy = 'EnteredDate';
                Search.endDate = GetEnteredEndDate();
                Search.beginDate = GetEnteredBeginDate();
                break;
            case AUCTION_DATE:
                Search.sortBy = 'AuctionDate';
                Search.endDate = GetEnteredEndDate();
                Search.beginDate = GetEnteredBeginDate();
                break;
            case LIST_DATE:
                Search.sortBy = 'ListDate';
                Search.endDate = GetEnteredEndDate();
                Search.beginDate = GetEnteredBeginDate();
                break;
            case RECORD_DATE:
                Search.sortBy = 'RecordDate';
                Search.endDate = GetEnteredEndDate();
                Search.beginDate = GetEnteredBeginDate();
                break;
            case SITUS_CITY:
                Search.sortBy = 'Address';
                break;
            case BEDS:
                Search.sortBy = "Beds";
                break;
            case BATHS:
                Search.sortBy = "Baths";
                break;
            case AMOUNT:
                Search.sortBy = "DefaultPrice";
                break;
            case ENTERED_DATE_DEFAULT:
                Search.sortBy = 'EnteredDate';
                Search.endDate = GetEnteredEndDate();
                Search.beginDate = GetEnteredBeginDate();
                break;
            case AUCTION_DATE_DEFAULT:
                Search.sortBy = 'AuctionDate';
                Search.endDate = GetEnteredEndDate();
                Search.beginDate = GetEnteredBeginDate();
                break;
            case LIST_DATE_DEFAULT:
                Search.sortBy = 'ListDate';
                Search.endDate = GetEnteredEndDate();
                Search.beginDate = GetEnteredBeginDate();
                break;
            case PRICE_DEFAULT:
                Search.sortBy = "DefaultPrice";
                break;
        }
        gModSearchOrdBy = Search.sortBy;
    }
}

function GetEnteredEndDate() 
{
    var ddlRangeMonthEnd = document.getElementById('ddlRangeMonthEnd');
    var tbxRangeDateEnd = document.getElementById('tbxRangeDateEnd');
    var ddlRangeYearEnd = document.getElementById('ddlRangeYearEnd');

    var formatedDate = ddlRangeMonthEnd.value + '/' + tbxRangeDateEnd.value + '/' + ddlRangeYearEnd.value;
    return formatedDate;

}

function GetEnteredBeginDate() 
{
    var ddlRangeMonthBegin = document.getElementById('ddlRangeMonthBegin');
    var tbxRangeDateBegin = document.getElementById('tbxRangeDateBegin');
    var ddlRangeYearBegin = document.getElementById('ddlRangeYearBegin');

    var formatedDate = ddlRangeMonthBegin.value + '/' + tbxRangeDateBegin.value + '/' + ddlRangeYearBegin.value;

    return formatedDate;
}

//Class currentSearchToSave
function currentSearchToSave(searchBy, propCharacteristics, propType, databaseType, sortBy, city, stateCode, countyCode, zipCode,
                                address, cityStateCode, propID, propAPN, priceFrom, priceTo, bedsNo, bathsNo, homeSize,
                                beginDate, endDate, isDefaultSearch, receiveMailAlerts) 
                                {
    this.searchBy = searchBy != undefined ? searchBy : null;
    this.propCharacteristics = propCharacteristics != undefined ? propCharacteristics : null;
    this.propType = propType != undefined ? propType : null;
    this.databaseType = databaseType != undefined ? databaseType : null;
    this.sortBy = sortBy != undefined ? sortBy : null;
    this.city = city != undefined ? city : null;
    this.stateCode = stateCode != undefined ? stateCode : null;
    this.countyCode = countyCode != undefined ? countyCode : null;
    this.zipCode = zipCode != undefined ? zipCode : null;
    this.address = address != undefined ? address : null;
    this.cityStateCode = cityStateCode != undefined ? cityStateCode : null;
    this.propID = propID != undefined ? propID : null;
    this.propAPN = propAPN != undefined ? propAPN : null;
    this.priceFrom = priceFrom != undefined ? priceFrom : null;
    this.priceTo = priceTo != undefined ? priceTo : null;
    this.bedsNo = bedsNo != undefined ? bedsNo : null;
    this.bathsNo = bathsNo != undefined ? bathsNo : null;
    this.homeSize = homeSize != undefined ? homeSize : null;
    this.beginDate = beginDate != undefined ? beginDate : null;
    this.endDate = endDate != undefined ? endDate : null;
    this.isDefaultSearch = isDefaultSearch != undefined ? isDefaultSearch : null;
    this.receiveMailAlerts = receiveMailAlerts != undefined ? receiveMailAlerts : null;
}

function closeSaveSearchPopup() 
{
    var divPopcontainer = document.getElementById('divPopcontainer');
    InitSaveSearchFormElements();
    $find('ModalBehaviorSaveToMyRealtyTrac').hide();
    divPopcontainer.style.display = 'none';
    return false;
}

function OpenPopUp() 
{
    var divPopcontainer = document.getElementById('divPopcontainer');
    if(divPopcontainer != null && typeof($find) != "undefined")
    {
        divPopcontainer.style.display = '';
        $find('ModalBehaviorSaveToMyRealtyTrac').show();
    }
    return false;
}

function ShowHideMapModifiedSearch() 
{
    try 
    {
        var imgBtnMap = document.getElementById('hideMapModifiedSearch');
        var closeMap = false;
        if (!isPreCondition('ToggleMapDisplay')) 
        {
            return;
        }

        if (TheMap == undefined) 
        {
            //fi teh Map is not initialized at all then we show it and initialize it
            ShowMap();
            closeMap = true;
            SwapSearchFunctions(true);
        }
        else 
        {
            if ((TheMap && !TheMap.isMapVisible)) 
            {
                //This will only show the Map not doing any search
                TheMap.ShowMap();
                closeMap = true;
                SwapSearchFunctions(true);
            }
            else 
            {
                if (TheMap) 
                {
                    TheMap.HideMap();
                }
                SwapSearchFunctions(false);
            }
        }
        if (TheMap && TheMap.isMapVisible)
        {

            TheMap.ShowOverLay();

            if (gMainPropertyID == null && gSubjectProperty && gSubjectPropertyID != null && gSubjectPropertyID > 0 && gSubjectPropertyLat != null && gSubjectPropertyLon != null)
             {
                if (!TheMap.IsBirdEyeView() && TheMap.isMapVisible) 
                {
                    TheMap.SetCenterAndZoom(gSubjectPropertyLat, gSubjectPropertyLon);
                    TheMap.GetPinsByMapLatLon(GetPinsByLatLong_Continue);
                }
            }
            else 
            {
                AddPinsBySearchValues();
                if (gMainPropertyID != null)
                {
                    TheMap.AddMainProperty(gMainPropertyID, AddMainProperty_Continue);
                }
            }
        }

        BtnImageToShow(closeMap);
    }
    catch (ex) 
    {
        LogErrorMessage("ToggleMapDisplay: ", ex);
    }
}

function BtnImageToShow(closeMap) 
{
    try 
    {
        if (closeMap) 
        {
            document.getElementById('hideMapModifiedSearch').src = '../images/buttons/buttonHideMapOrange.gif';
        }
        else 
        {
            document.getElementById('hideMapModifiedSearch').src = '../images/buttons/buttonShowMapOrange.gif';
        }
    }
    catch (ex) 
    {
        LogErrorMessage("ToggleMapDisplay: ", ex);
    }
}

function ResetModifySearch() 
{
    var rbtState = document.getElementById('searchState');
    if (rbtState != null) 
    {
        rbtState.checked = true;
        SetSearchTypeControls();
    }

    resetTextbox(g_ModifySearchHelper.TbxCityID, 'Enter City, State');
    resetTextbox(g_ModifySearchHelper.TbxZipID, 'Enter ZIP');
    resetTextbox(g_ModifySearchHelper.TbxAddressID, 'Enter Address');
    resetTextbox(g_ModifySearchHelper.TbxAddressCityID, 'Enter City, State or ZIP');
    resetTextbox(g_ModifySearchHelper.TbxPropertyID, 'Enter Property ID');
    resetTextbox(g_ModifySearchHelper.TbxPropertyAPNID, 'Enter Property APN');
    resetTextbox(g_ModifySearchHelper.TbxPriceMinID, 'No Min');
    resetTextbox(g_ModifySearchHelper.TbxPriceMaxID, 'No Max');
    resetTextbox('tbxPropOther', '');

    resetDropdown(g_ModifySearchHelper.DdlStateID);
    resetDropdown('ddlCounty');
    resetDropdown('ddlBeds');
    resetDropdown('ddlBaths');
    resetDropdown('ddlSqFt');
    resetDropdown('ddlSortBy');

    var propAll = document.getElementById('cbxPropAll');
    if (propAll != null) 
    {
        propAll.checked = true;
    }
    UncheckPropType(true);
    var ddlSort = document.getElementById('ddlSortBy');
    if (ddlSort != null) 
    {
        EnableDisableDateRange(ddlSort);
    }
}

function ResetFreeSearchAdvanced()
{
    resetTextbox(g_ModifySearchHelper.TxtSearchFor, 'Address, city/state, cnty/state, or ZIP');
    resetTextbox(g_ModifySearchHelper.TbxSearchName, 'Name your search to save it');
    resetTextbox(g_ModifySearchHelper.TbxPriceMinID, 'No Min');
    resetTextbox(g_ModifySearchHelper.TbxPriceMaxID, 'No Max');
    resetTextbox('tbxPropOther', '');
    
    resetDropdown('ddlSearchIn');
    resetDropdown('ddlBeds');
    resetDropdown('ddlBaths');
    resetDropdown('ddlSqFt');
    resetDropdown('ddlSortBy');

    var propAll = document.getElementById('cbxPropAll');
    if (propAll != null)
    {
        propAll.checked = true;
    }
    UncheckPropType(true);
    var ddlSort = document.getElementById('ddlSortBy');
    if (ddlSort != null)
    {
        EnableDisableDateRange(ddlSort);
    }
}

function resetTextbox(name, value) 
{
    var textboxControl = document.getElementById(name);
    if (textboxControl != null) 
    {
        textboxControl.value = value;
    }
}

function resetDropdown(name) 
{
    var dropdownControl = document.getElementById(name);
    if (dropdownControl != null) 
    {
        dropdownControl.selectedIndex = 0;
    }
}

function ShowHideBottomPart(showSection) 
{
    var divBottom = document.getElementById('divBottom');
    var modifyBtn = document.getElementById("divSMModifyTab");
    var ddlSortBy = document.getElementById('ddlSortBy');
    
   
    if (divBottom) 
    {
        if ((typeof(showSection) != "undefined" && showSection) || !IsAdvancedSearchVisible()) 
        {
            divBottom.style.display = 'block';
            SetModifySearchImage(IMAGE_MODIFY_SEARCH_MINUS);
            modifyBtn.className = "modifySearchOn";
            if (ddlSortBy)
            {
                ddlSortBy.style.display = 'block';
            }
            RepopulateDdlSortBy(ddlSortBy.value);
        }
        else 
        {
            divBottom.style.display = 'none';
            SetModifySearchImage(IMAGE_MODIFY_SEARCH_PLUS);
            modifyBtn.className = "modifySearch";
            if (ddlSortBy)
            {
                ddlSortBy.style.display = 'none';
            }
        }
        if (TheMap) 
        {
            TheMap.PinsOnMap.PopUpClass.RePosGroupedPopUp()
        }
    }
}

function SetModifySearchImage(imgSrc) 
{
    var imgSearch = document.getElementById('imgModifySearch');

    if (imgSearch) 
    {
        imgSearch.src = imgSrc;
    }
}

function SetSearchTypeControls() 
{
    var cicleContinue = true;
    var radioButtons = document.getElementsByName('searchType');

    if (radioButtons) 
    {
        var divModifySearch;

        for (var i = 0; i < radioButtons.length && cicleContinue; i++) 
        {
            if (radioButtons[i].checked) 
            {
                divModifySearch = document.getElementById(radioButtons[i].getAttribute('divIdToShow'));
                if (radioButtons[i].getAttribute('divIdToShow') == 'divSearchState') 
                {
                    var ddlCounty = document.getElementById('ddlCounty');

                    if (ddlCounty && ddlCounty.options.length > 0) 
                    {
                        var divCounty = document.getElementById('divSearchCounty');

                        if (divCounty) 
                        {
                            divCounty.style.display = 'block';
                        }
                    }
                }
                cicleContinue = false;
            }
        }

        if (divModifySearch) 
        {
            HideSearchControls();
            divModifySearch.style.display = 'block';
        }
    }
}

function HideSearchControls() 
{
    var controlsName = new Array('divSearchState', 'divSearchCity', 'divSearchZip', 'divSearchAddress', 'divSearchProperty');
    var divControl;

    for (var i = 0; i < controlsName.length; i++) 
    {
        divControl = document.getElementById(controlsName[i]);
        if (divControl) 
        {
            divControl.style.display = 'none';
        }
    }
}

function State_OnChange(stateCode) 
{
    if (stateCode == '') 
    {
        HideCountyDropDown();
    }
    else 
    {
        SearchService.GetCountyByStateCode(stateCode, FillCountyDropDown);
    }
}

function FillCountyDropDown(counties) 
{
    if (counties) 
    {
        var ddlControl = document.getElementById('ddlCounty');

        if (ddlControl) 
        {
            var option;

            for (var i = ddlControl.options.length - 1; i >= 0; i--) 
            {
                ddlControl.remove(i);
            }

            option = document.createElement('option');
            ddlControl.options.add(option);
            option.value = '';
            option.innerText = 'Please Select';

            for (var i = 0; i < counties.length; i++) 
            {
                option = document.createElement('option');
                ddlControl.options.add(option);
                option.value = counties[i].CountyID;
                option.innerText = counties[i].CountyName;

            }

            if (setCountyByCode != null) 
            {
                ddlControl.value = setCountyByCode;
                setCountyByCode = null;
            }
        }
    }
    ShowCountyDropDown();
}

function ShowCountyDropDown() 
{
    SetCountyDropDownVisibility(true);
}

function HideCountyDropDown() 
{
    SetCountyDropDownVisibility(false);
}

function SetCountyDropDownVisibility(isVisible) 
{
    var ddlControl = document.getElementById('divSearchCounty');

    if (ddlControl) 
    {
        if (isVisible) 
        {
            ddlControl.style.display = 'block';
        }
        else 
        {
            ddlControl.style.display = 'none';
        }
    }
}

function preparePrice(el) 
{
    if (el) 
    {
        el.value = AddCommas(el.value.replace(/\$/g, '').replace(/,/g, ''));
    }
}

function SetContextForMaxPrice(minPrice) 
{
    var autoComplete = $find('autoPriceMax');

    if (minPrice && autoComplete) 
    {
        autoComplete.set_contextKey(minPrice.replace(/,/g, ''));
    }
}

function SetupMapSearchModifyControls() 
{
    var searchRequest = GetSearchRequest();
    
    SetupSearchPanel(searchRequest);
    SetupPropCharacterPanel(searchRequest);
    SetupPropertyTypePanel(searchRequest);
    SetupSortPanel(searchRequest);
}


function SetupSortPanel(searchRequest) 
{
    try 
    {
        var ddlSort = document.getElementById('ddlSortBy');
        var ddlSortValues = '';
        
        if (searchRequest != null && searchRequest.AdvancedRequest != null &&
            searchRequest.AdvancedRequest.SortField != null && ddlSort != null) 
            {
                var sortField;
                if (searchRequest.AdvancedRequest.SortField == "CreationDate")
                {
                    sortField = "EnteredDate";
                }
                else if (searchRequest.AdvancedRequest.SortField == "DefaultDate")
                {
                    sortField = "EnteredDate";
                }
                else if (searchRequest.AdvancedRequest.SortField == "DefaultPrice")
                {
                    sortField = "Amount";
                }
                else if (searchRequest.AdvancedRequest.SortField == "CityState")
                {
                    sortField = "City";
                }
                else if (searchRequest.AdvancedRequest.SortField == "BedroomCount")
                {
                    sortField = "Beds";
                }
                else if (searchRequest.AdvancedRequest.SortField == "BathroomCount")
                {
                    sortField = "Baths";
                }
                else if (searchRequest.AdvancedRequest.SortField == "NtdsAuctionDate")
                {
                    sortField = "Auction Date";
                }
                else if (searchRequest.AdvancedRequest.SortField == "RecordingDate")
                {
                    sortField = "Record Date";
                }
                else
                {
                    sortField = searchRequest.AdvancedRequest.SortField;
                }
                
            for (var i = 0; i < ddlSort.options.length; i++) 
            {

                if (ddlSort.options[i].innerHTML.replace(' ', '') == sortField) 
                {
                    ddlSort.options[i].selected = true;
                    break;
                }
            }

            if (ddlSort.value <= '2') 
            {
                if (searchRequest.AdvancedRequest.FromDate != null) 
                {
                    var ddlMonth = document.getElementById('ddlRangeMonthBegin');
                    var ddlDay = document.getElementById('tbxRangeDateBegin');
                    var ddlYear = document.getElementById('ddlRangeYearBegin');
                    if (ddlMonth != null && ddlDay != null && ddlYear != null) 
                    {
                        var date = new Date(searchRequest.AdvancedRequest.FromDate);
                        ddlDay.value = date.getDate().toString();
                        ddlMonth.value = (date.getMonth() + 1).toString();
                        ddlYear.value = date.getFullYear().toString();
                    }
                }
                if (searchRequest.AdvancedRequest.ToDate != null) 
                {
                    var ddlMonth = document.getElementById('ddlRangeMonthEnd');
                    var ddlDay = document.getElementById('tbxRangeDateEnd');
                    var ddlYear = document.getElementById('ddlRangeYearEnd');
                    if (ddlMonth != null && ddlDay != null && ddlYear != null) 
                    {
                        var date = new Date(searchRequest.AdvancedRequest.ToDate);
                        ddlDay.value = date.getDate().toString();
                        ddlMonth.value = (date.getMonth() + 1).toString();
                        ddlYear.value = date.getFullYear().toString();
                    }
                }
                SetDataRangeVisibility(true);
            }
            else 
            {
                SetDataRangeVisibility(false);
            }
        }
    }
    catch (er) 
    {
        LogErrorMessage("SetupSortPanel: ", er);
    }
}

function SetupPropertyTypePanel(searchRequest) 
{
    try 
    {
        if (searchRequest != null && searchRequest.AdvancedRequest != null) 
        {
            if (searchRequest.AdvancedRequest.PropertyType != null) 
            {
                var doUncheckCbxAll = false;
                var cbx;
                var propertiesTypes = searchRequest.AdvancedRequest.PropertyType.split(',');

                for (var i = 0; i < propertiesTypes.length; i++) 
                {
                    switch (propertiesTypes[i].toUpperCase()) 
                    {
                        case '':

                            break;

                        case 'RSFR':
                            cbx = document.getElementById('cbxPropRSFR');
                            if (cbx != null) 
                            {
                                cbx.checked = true;
                                doUncheckCbxAll = true;
                            }
                            break;

                        case 'RCON':
                            cbx = document.getElementById('cbxPropRCON');
                            if (cbx != null) 
                            {
                                cbx.checked = true;
                                doUncheckCbxAll = true;
                            }
                            break;

                        case 'RAPT':
                            cbx = document.getElementById('cbxPropRAPT');
                            if (cbx != null) 
                            {
                                cbx.checked = true;
                                doUncheckCbxAll = true;
                            }
                            break;

                        case 'RVAC':
                            cbx = document.getElementById('cbxPropRVAC');
                            if (cbx != null) 
                            {
                                cbx.checked = true;
                                doUncheckCbxAll = true;
                            }
                            break;

                        default:
                            cbx = document.getElementById('cbxPropOther');
                            if (cbx != null) 
                            {
                                cbx.checked = true;
                                doUncheckCbxAll = true;
                                var tbx = document.getElementById('tbxPropOther');
                                if (tbx != null) 
                                {
                                    tbx.disabled = false;
                                    if (tbx.value.length > 0) 
                                    {
                                        tbx.value += ',';
                                    }
                                    tbx.value = propertiesTypes[i].toUpperCase();
                                }
                            }

                    }
                }

                if (searchRequest.AdvancedRequest.DatabaseType == 1) 
                {
                    cbx = document.getElementById('cbxPropCom');
                    if (cbx != null) 
                    {
                        cbx.checked = true;
                        doUncheckCbxAll = true;
                    }
                }

                if (doUncheckCbxAll) 
                {
                    UncheckPropAll(true);
                }
            }
        }
    }
    catch (er) 
    {
        LogErrorMessage("SetupPropertyTypePanel: ", er);
    }
}

function SetupPropCharacterPanel(searchRequest) 
{
    try 
    {
        if (searchRequest != null && searchRequest.AdvancedRequest != null) 
        {
            var tbxPriceFrom = document.getElementById(g_ModifySearchHelper.TbxPriceMinID);
            if (tbxPriceFrom != null) 
            {
                if (searchRequest.AdvancedRequest.PriceFrom != null && searchRequest.AdvancedRequest.PriceFrom != '0') 
                {
                    tbxPriceFrom.value = AddCommas(searchRequest.AdvancedRequest.PriceFrom);
                }
                else 
                {
                    tbxPriceFrom.value = 'No Min';
                }
            }

            var tbxPriceTo = document.getElementById(g_ModifySearchHelper.TbxPriceMaxID);
            if (tbxPriceTo != null) 
            {
                if (searchRequest.AdvancedRequest.PriceTo != null && searchRequest.AdvancedRequest.PriceTo != '99999999') 
                {
                    tbxPriceTo.value = AddCommas(searchRequest.AdvancedRequest.PriceTo);
                }
                else 
                {
                    tbxPriceTo.value = 'No Max';
                }
            }

            var ddlBeds = document.getElementById('ddlBeds');
            if (ddlBeds != null) 
            {
                if (0 < searchRequest.AdvancedRequest.BedroomCountFrom && searchRequest.AdvancedRequest.BedroomCountFrom <= 4)
                {                    
                    ddlBeds.value = searchRequest.AdvancedRequest.BedroomCountFrom;
                }
                else if (searchRequest.AdvancedRequest.BedroomCountFrom > 4) 
                {
                    ddlBeds.value = BEDS_VALUE_FIVE_OR_MORE;
                }
                if (searchRequest.AdvancedRequest.BedroomCountFrom == null || searchRequest.AdvancedRequest.BedroomCountFrom == 0) 
                {
                    ddlBeds.value = 0;
                }
            }

            var ddlBaths = document.getElementById('ddlBaths');
            if (ddlBaths != null) 
            {
                if (0 < searchRequest.AdvancedRequest.BathroomCountFrom && searchRequest.AdvancedRequest.BathroomCountFrom <= 4) 
                {                    
                    var tempVal = searchRequest.AdvancedRequest.BathroomCountFrom;
                    if (tempVal < 1 && tempVal > 0)
                    {
                        tempVal = tempVal * 10;
                    }
                    ddlBaths.value = tempVal;
                }
                else if (searchRequest.AdvancedRequest.BathroomCountFrom > 4) 
                {
                    ddlBaths.value = BATHS_VALUE_FIVE_OR_MORE;
                }
                if (searchRequest.AdvancedRequest.BathroomCountFrom == null || searchRequest.AdvancedRequest.BathroomCountFrom == 0) 
                {
                    ddlBaths.value = 0;
                }
            }

            var ddlSqFt = document.getElementById('ddlSqFt');
            if (ddlSqFt != null) 
            {
                if (searchRequest.AdvancedRequest.SquareFeetFrom >= 10000) 
                {
                    ddlSqFt.value = 10000;
                }
                else if (searchRequest.AdvancedRequest.SquareFeetFrom >= 7500) 
                {
                    ddlSqFt.value = 7500;
                }
                else if (searchRequest.AdvancedRequest.SquareFeetFrom >= 5000) 
                {
                    ddlSqFt.value = 5000;
                }
                else if (searchRequest.AdvancedRequest.SquareFeetFrom >= 4000) 
                {
                    ddlSqFt.value = 4000;
                }
                else if (searchRequest.AdvancedRequest.SquareFeetFrom >= 3500) 
                {
                    ddlSqFt.value = 3500;
                }
                else if (searchRequest.AdvancedRequest.SquareFeetFrom >= 3000) 
                {
                    ddlSqFt.value = 3000;
                }
                else if (searchRequest.AdvancedRequest.SquareFeetFrom >= 2500) 
                {
                    ddlSqFt.value = 2500;
                }
                else if (searchRequest.AdvancedRequest.SquareFeetFrom >= 2000) 
                {
                    ddlSqFt.value = 2000;
                }
                else if (searchRequest.AdvancedRequest.SquareFeetFrom >= 1500) 
                {
                    ddlSqFt.value = 1500;
                }
                else if (searchRequest.AdvancedRequest.SquareFeetFrom >= 1000) 
                {
                    ddlSqFt.value = 1000;
                }
                else if (searchRequest.AdvancedRequest.SquareFeetFrom >= 500) 
                {
                    ddlSqFt.value = 500;
                }
                else if (searchRequest.AdvancedRequest.SquareFeetFrom == null || searchRequest.AdvancedRequest.SquareFeetFrom == 0)
                {
                    ddlSqFt.value = 0;
                }
            }
        }
    }
    catch (er) 
    {
        LogErrorMessage("SetupPropCharacterPanel: ", er);
    }
}

function SetupSearchFor(searchResponse)
{
    try
    {
        if(searchResponse != null && searchResponse.FreetextCriteria != null)    
        {
            var txtSearchFor = document.getElementById(g_ModifySearchHelper.TxtSearchFor);                        
            var ddlSearchIn = document.getElementById('ddlSearchIn');
            
            switch(searchResponse.Search.BasicRequest.SearchType)
            {
                case SEARCH_TYPE_PROPERTY_ID:
                    ddlSearchIn.value = 'propid';
                    txtSearchFor.value = searchResponse.Search.BasicRequest.PropertyID;
                    break;
                
                case SEARCH_TYPE_PARCEL_NUMBER:
                    ddlSearchIn.value = 'apn';
                    txtSearchFor.value = searchResponse.Search.BasicRequest.ParcelNumber;
                    break;
                    
                default:
                    ddlSearchIn.value = 'address';
                    txtSearchFor.value = searchResponse.FreetextCriteria;
                    break;
            }
            
        }
    }
    catch (er)
    {
        LogErrorMessage("SetupSearchFor: ", er);
    }
}

function SetupSearchPanel(searchRequest) 
{
    try 
    {
        if (searchRequest != null && searchRequest.BasicRequest != null && searchRequest.BasicRequest.SearchType != null) 
        {
            switch (searchRequest.BasicRequest.SearchType) 
            {
                case SEARCH_TYPE_CITY:
                    var btnCity = document.getElementById('searchCity');
                    if (btnCity != null) 
                    {
                        btnCity.checked = true;
                        var tbxCity = document.getElementById(g_ModifySearchHelper.TbxCityID);
                        if (tbxCity != null) 
                        {
                            tbxCity.value = searchRequest.BasicRequest.City;
                        }
                    }
                    break;

                case SEARCH_TYPE_COUNTY:
                    var btnState = document.getElementById('searchState');
                    if (btnState != null) 
                    {
                        btnState.checked = true;
                        var ddlState = document.getElementById(g_ModifySearchHelper.DdlStateID);
                        var countyCode = searchRequest.BasicRequest.CountyCode.toUpperCase();
                        if (ddlState != null && countyCode != null && countyCode.length == 4) 
                        {
                            ddlState.value = countyCode.substr(0, 2);
                            State_OnChange(countyCode.substr(0, 2));
                            var ddlCounty = document.getElementById('ddlCounty');
                            if (ddlCounty != null) 
                            {
                                setCountyByCode = countyCode;
                            }
                        }
                    }
                    break;

                case SEARCH_TYPE_ADDRESS:
                    var btnAddress = document.getElementById('searchAddress');
                    if (btnAddress != null) 
                    {
                        btnAddress.checked = true;
                        var tbxAddress = document.getElementById(g_ModifySearchHelper.TbxAddressID);
                        var tbxAddressCity = document.getElementById(g_ModifySearchHelper.TbxAddressCityID);
                        if (tbxAddress != null && tbxAddressCity != null) 
                        {
                            tbxAddress.value = searchRequest.BasicRequest.Address;
                            if (searchRequest.BasicRequest.City != null) 
                            {
                                tbxAddressCity.value = searchRequest.BasicRequest.City;
                            }
                            else if (searchRequest.BasicRequest.Zip != null) 
                            {
                                tbxAddressCity.value = searchRequest.BasicRequest.Zip;
                            }
                        }
                    }
                    break;

                case SEARCH_TYPE_ZIP:
                    var btnZip = document.getElementById('searchZip');
                    if (btnZip != null) 
                    {
                        btnZip.checked = true;
                        var tbxZip = document.getElementById(g_ModifySearchHelper.TbxZipID);
                        if (tbxZip != null) 
                        {
                            tbxZip.value = searchRequest.BasicRequest.Zip;
                        }
                    }
                    break;

                case SEARCH_TYPE_PROPERTY_ID:
                    var btnProperty = document.getElementById('searchProperty');
                    if (btnProperty != null) 
                    {
                        btnProperty.checked = true;
                        var tbxID = document.getElementById(g_ModifySearchHelper.TbxPropertyID);
                        if (tbxID != null) 
                        {
                            tbxID.value = searchRequest.BasicRequest.PropertyID;
                        }
                    }
                    break;

                case SEARCH_TYPE_PARCEL_NUMBER:
                    var btnProperty = document.getElementById('searchProperty');
                    if (btnProperty != null) 
                    {
                        btnProperty.checked = true;
                        var tbxAPN = document.getElementById(g_ModifySearchHelper.TbxPropertyAPNID);
                        if (tbxAPN != null) 
                        {
                            tbxAPN.value = searchRequest.BasicRequest.ParcelNumber;
                        }
                    }
                    break;

                default:
                    break;
            }
        }

        SetSearchTypeControls();
    }
    catch (er) 
    {
        LogErrorMessage("SetupSearchPanel: ", er);
    }
}

function UncheckPropAll(doUncheck) 
{
    if (doUncheck) 
    {
        var cbxAll = document.getElementById('cbxPropAll');

        if (cbxAll != null) 
        {
            cbxAll.checked = false;
        }
    }
}

function UncheckPropType(doUncheck) 
{
    if (doUncheck) 
    {
        var cbxRSFR = document.getElementById('cbxPropRSFR');
        if (cbxRSFR != null) 
        {
            cbxRSFR.checked = false;
        }
        var cbxRCON = document.getElementById('cbxPropRCON');
        if (cbxRCON != null) 
        {
            cbxRCON.checked = false;
        }
        var cbxRAPT = document.getElementById('cbxPropRAPT');
        if (cbxRAPT != null) 
        {
            cbxRAPT.checked = false;
        }
        var cbxRVAC = document.getElementById('cbxPropRVAC');
        if (cbxRVAC != null) 
        {
            cbxRVAC.checked = false;
        }
        var cbxCOM = document.getElementById('cbxPropCOM');
        if (cbxCOM != null) 
        {
            cbxCOM.checked = false;
        }
        var cbxOther = document.getElementById('cbxPropOther');
        if (cbxOther != null) 
        {
            cbxOther.checked = false;
        }
    }
}

function SetTbxOtherEnable(setEnabled) 
{
    try 
    {
        var tbxOther = document.getElementById('tbxPropOther');

        if (tbxOther != null) 
        {
            tbxOther.disabled = !setEnabled;
        }
    }
    catch (er) 
    {
        LogErrorMessage("SetTbxOtherEnable: ", er);
    }
}
//----- END Modify Search Control functions ---//

//--- Function for lender and Low Moratage Rates banner ---//
function SubmitLenderBanner(txtZipID, ddlStID) 
{

    var txtZip = document.getElementById(txtZipID);
    var ddlSt = document.getElementById(ddlStID);
    var ddlItem = "";

    var isValid = true;
    var errorMsg = "";
    var params = "";

    var regex = "^[0-9]{5}";

    if (txtZip != null) 
    {
        var zip = txtZip.value;
        if (zip.match(regex)) 
        {
            params = "?zip=" + zip;
        }
        else 
        {
            isValid = false;
            errorMsg = "Zip code is invalid.";
            txtZip.value = "";
        }
    }
    else 
    {
        isValid = false;
    }

    if (null != ddlSt && ddlSt.options.length > 0) 
    {
        if (ddlSt.selectedIndex < 0) 
        {
            ddlItem = ddlSt.options[0].value;
        }
        else 
        {
            ddlItem = ddlSt.options[ddlSt.selectedIndex].value;
        }

        if (params != "") 
        {
            params += "&loan=" + ddlItem;
        }
        else 
        {
            params = "";
        }
    }
    else 
    {
        isValid = false;
    }

    if (isValid) 
    {
        window.location.href = "/finance/landing.aspx" + params;
    }
    else 
    {
        if (errorMsg != "") 
        {
            alert(errorMsg);
        }
    }
}

function sendPostcards() 
{
    var postcardSelection = '';


    if (gSelectedProperties) 
    {
        for (var i = 0; i < gSelectedProperties.length; i++) 
        {
            postcardSelection += gSelectedProperties[i] + ',';
        }

        if (postcardSelection != '') 
        {
            var request = GetSearchRequest(gSearchRequest);

            var searchCriteria = '';

            if (request && request.BasicRequest) 
            {
                if (request.BasicRequest.Address && request.BasicRequest.Address != '') 
                {
                    searchCriteria = request.BasicRequest.Address;
                }
                else if (request.BasicRequest.City && request.BasicRequest.City != '') 
                {
                    searchCriteria = request.BasicRequest.City;
                }
                else if (request.BasicRequest.CountyCode && request.BasicRequest.CountyCode != '') 
                {
                    searchCriteria = request.BasicRequest.CountyCode;
                }
                else if (request.BasicRequest.Zip && request.BasicRequest.Zip != '') 
                {
                    searchCriteria = request.BasicRequest.Zip;
                }
            }

            window.location = "/Postcards/postcards_intermediatepage.aspx?postcardSelection=" + postcardSelection + "&searchCriteria=" + searchCriteria;
        }
        else 
        {
            alert('Please select properties first if you want to contact their owners!');
        }
    }
}

function hideShowSendProstcardsButton(isShow) 
{
    var sendProstcardsButton = document.getElementById('sendPostcard');
    if (gPostcardMultiplePropertiesActive) 
    {
        ShowHideReportSection(true);
    }
    else 
    {
        ShowHideReportSection(false);
    }
    if (sendProstcardsButton) 
    {
        if (isShow) 
        {
            sendProstcardsButton.style.display = "";
        }
        else 
        {
            sendProstcardsButton.style.display = "none";
        }

    }
}


function ToggleReportTypePopup(display) 
{
    if (typeof ($find) != "undefined") 
    {
        if (display) 
        {
            $find('ModalBehaviorGenerateReport').show();
        }
        else 
        {
            $find('ModalBehaviorGenerateReport').hide();
        }
    }
}

function ToogleReportHelpPopup(display) 
{
    if (typeof ($find) != "undefined") 
    {
        if (display) 
        {
            $find('mpeHelp').show();
        }
        else 
        {
            $find('mpeHelp').hide();
        }
    }
}

/*----------- AJAX modal popups open/close ----------*/
///Properties may interest popup functions
function ClosePropertiesPopUp() 
{
    var divPopcontainer = document.getElementById('divPropertiesMayInterest');
    $find('ModalBehaviorPropertiesMayInterest').hide();
    divPopcontainer.style.display = 'none';
    return false;
}

function OpenPropertiesMayInterestPopUp() 
{
    var divPopcontainer = document.getElementById('divPropertiesMayInterest');
    divPopcontainer.style.display = 'block';
    $find('ModalBehaviorPropertiesMayInterest').show();
    return false;
}

function OpenReportHelpPopup() 
{
    var divPopcontainer = document.getElementById('divReportHelp');
    divPopcontainer.style.display = 'block';
    $find('ModalBehaviorReportHelp').show();
    return false;
}

function CloseReportHelpPopup() 
{
    var divPopcontainer = document.getElementById('divReportHelp');
    divPopcontainer.style.display = 'none';
    $find('ModalBehaviorReportHelp').hide();
    return false;
}

function OpenReportTypePopup() 
{
    var divPopcontainer = document.getElementById('divGenerateReport');
    divPopcontainer.style.display = 'block';
    $find('ModalBehaviorReportType').show();
    return false;
}

function ResetSelectAllCheckbox() 
{
    var selectAll = document.getElementById('chkSelectAll');
    if (selectAll) 
    {
        selectAll.checked = false;
    }
}

function CloseReportTypePopup() 
{
    var divPopcontainer = document.getElementById('divGenerateReport');
    divPopcontainer.style.display = 'none';
    $find('ModalBehaviorReportType').hide();
    return false;
}

function OpenBidNowInternationalPopup() 
{
    var divPopcontainer = document.getElementById('divBidNowInternational');
    divPopcontainer.style.display = 'block';
    $find('ModalBehaviorBidNowInternational').show();
    return false;
}

function CloseBidNowInternationalPopup() 
{
    var divPopcontainer = document.getElementById('divBidNowInternational');
    divPopcontainer.style.display = 'none';
    $find('ModalBehaviorBidNowInternational').hide();
    return false;
}


function OpenExternalUrl(url) 
{
    window.open(url, '_blank', 'toolbar=yes, location=yes, directories=yes, status=yes, menubar=yes, scrollbars=yes, resizable=yes, copyhistory=no, width=1000, height=825');
    return false;
}

function PositionObjects(objToMove, staticObj, dx, dy) 
{
    if (typeof (dx) == "undefined" || dx == null) 
    {
        dx = 0;
    }

    if (typeof (dy) == "undefined" || dy == null) 
    {
        dy = 0;
    }

    if (typeof (objToMove) != "undefined" && objToMove != null && typeof (staticObj) != "undefined" && staticObj != null) 
    {
        objToMove.style.left = 0;
        objToMove.style.top = 0;
        var objToMoveX = GetOffsetLeft(objToMove);
        var objToMoveY = GetOffsetTop(objToMove);
        var staticObjX = GetOffsetLeft(staticObj);
        var staticObjY = GetOffsetTop(staticObj);

        objToMove.style.left = staticObjX - objToMoveX + dx;
        objToMove.style.top = staticObjY - objToMoveY + dy;
    }
}


function GetOffsetLeft(el) 
{
    var left = 0;

    if (el.offsetParent) 
    {
        do 
        {
            left += el.offsetLeft;
        }
        while (el = el.offsetParent);
    }

    return left;
}

function GetOffsetTop(el) 
{
    var top = 0;

    if (el.offsetParent) 
    {
        do 
        {
            top += el.offsetTop;
        }
        while (el = el.offsetParent);
    }

    return top;
}

function getOuterContainer(element)  // move to global
{
    containerObj = $(element).parent().get(0);
    count = 9;  // die after 10 failed tries
    do 
    {
        containerObj = $(containerObj).parent().get(0);
        count--;
    }
    while ($(containerObj).css("position") != "relative" && count > 0);
    return containerObj;
}

/******************************************************************************************/
/* *********************** Saved Searches Links actions ***********************************/
/******************************************************************************************/
var curDivConatiner = null;
//Edit

var editSearchID = 0;

function FillModifySearchFormWithSavedSearch(searchID, divContainerID)
{
    if (typeof (SearchService) != "undefined")
    {
        curDivConatiner = divContainerID;
        ChangeButon(true, searchID, divContainerID);
        SearchService.SavedSearchbyIDGet(searchID, FillModifySearchFormWithSavedSearch_Continue);
       editSearchID =  searchID;
    }
    curDivConatiner = null;
}

function FillModifySearchFormWithSavedSearch_Continue(searchResponse)
{
    var searchRequest = searchResponse.Search;
    
    SetSavedSearchName(searchRequest);
    SetupSearchFor(searchResponse);
    SetupPropCharacterPanel(searchRequest);
    SetupPropertyTypePanel(searchRequest);
    SetupSortPanel(searchRequest);
    
    if (!IsAdvancedSearchVisible())
    {
        $("div#divBottom").slideToggle("slow");
    }

}

function SetSavedSearchName(searchRequest)
{
    var tbxSearchName = document.getElementById(g_ModifySearchHelper.TbxSearchName);

    if (tbxSearchName != null)
    {
        tbxSearchName.value = searchRequest.Name;
    }
}

function ChangeButon(isEdit, searchID, divContainerID)
{
    var btnSaveAndSearch = document.getElementById(g_ModifySearchHelper.BtnSave);
    var btnSearch = document.getElementById(g_ModifySearchHelper.BtnSearch);
    var divSearchForContainer = document.getElementById(g_ModifySearchHelper.DivSearchForContainer);
    var divSaveSearchButtons = document.getElementById(g_ModifySearchHelper.DivSaveSearchButtons);
    var tbxSearchName = document.getElementById(g_ModifySearchHelper.TbxSearchName);
    var btnSaveEdit = document.getElementById(g_ModifySearchHelper.BtnSaveEditedsavedSearch);
    var divEditBtns = document.getElementById('divSMSearchButton');
    var errorMsg = document.getElementById('spanPopUpErrorMessages');
    var txtSearchFor = document.getElementById(g_ModifySearchHelper.TxtSearchFor);
    var optionalLabel = document.getElementById('lblOptional');
    var divClearForm = document.getElementById('divClearForm');

    if (errorMsg != null)
    {
        errorMsg.innerHTML = '';
    }
   
    if (btnSaveAndSearch != null)
    {
        if (isEdit)
        {            
            divEditBtns.style.display = 'block';
            btnSaveAndSearch.style.display = 'block';
            divClearForm.style.display = 'none';

            divSaveSearchButtons.setAttribute('class', 'divSaveSearchEditButtonsLoggedIn');
            divSaveSearchButtons.setAttribute('className', 'divSaveSearchEditButtonsLoggedIn');
            
            if (btnSaveEdit != null)
            {
                btnSaveEdit.setAttribute('href', 'javascript:SavedSearchEdit(' + searchID + ', "' + divContainerID + '");');
                btnSaveEdit.removeAttribute('onclick');
            }

            btnSaveAndSearch.setAttribute('href', 'javascript:FreeSearchPageSaveSearchValidation(true);');
            btnSaveAndSearch.removeAttribute('onclick'); 
            txtSearchFor.setAttribute('onkeypress', 'javascript:if(keyNumPressed(event) == 13){FreeSearchPageSaveSearchValidation(true);}');
            //tbxSearchName.style.width = '405px';            
            optionalLabel.style.display = "none";
        }
        else
        {
            //Set Search Mode
            ResetModifySearch();
            divClearForm.style.display = 'block';
            if(tbxSearchName != null)
            {
                tbxSearchName.value = NAME_YOUR_SEARCH_TO_SAVE_IT;
                txtSearchFor.value = ADDRESS_CITY_STATE_CNTY_STATE_OR_ZIP;
            }
            
            divEditBtns.style.display = 'none';
            btnSaveAndSearch.style.display = 'none';
            divSaveSearchButtons.setAttribute('class', 'divSaveSearchButtonsLoggedIn');
            divSaveSearchButtons.setAttribute('className', 'divSaveSearchButtonsLoggedIn');
            btnSaveAndSearch.removeAttribute('onclick');
            btnSaveAndSearch.setAttribute('href', 'javascript:FreeSearchPageSaveSearchValidation(false);');
            txtSearchFor.setAttribute('onkeypress', 'javascript:if(keyNumPressed(event) == 13){FreeSearchPageSaveSearchValidation(false);}');
            
            //tbxSearchName.style.width = '455px';
            optionalLabel.style.display = "block";  
        }
    }
    
    if(btnSearch != null)
    {
        if (isEdit)
        {
            btnSearch.style.display = 'none';
        }
        else
        {
            btnSearch.style.display = 'block';
        }
    }
}

var gSavedSearchID = null;
var gDivRowContainer = null;

//saved modified search
function SavedSearchEdit(searchID, divContainerID)
{
    var tbxSearchName = document.getElementById(g_ModifySearchHelper.TbxSearchName);
    var errorMsg = document.getElementById('spanPopUpErrorMessages');
   
    
    if (tbxSearchName != null && tbxSearchName.value != '' && tbxSearchName.value != NAME_YOUR_SEARCH_TO_SAVE_IT)
    {
        var thisSearch = new currentSearchToSave();
        SetPropertyType(thisSearch);

        //if is update the we are in FreeSearchPage and we have a ddl insetad of check boxes
        SetSearchByAndFor(thisSearch);

        SetPropertyProfile(thisSearch);
        SetSortBy(thisSearch);
        ChangeButon(true);

        thisSearch.name = tbxSearchName.value;
        UpdateRowInformation(thisSearch, searchID, divContainerID);
        gSavedSearchID = searchID;
        gDivRowContainer = divContainerID;
        
        if(thisSearch.searchBy == 'address')
        {
            gThisSearch = thisSearch;
            gSearchName = thisSearch.name;
            if (Autocomplete != null)
            {
                Autocomplete.IsAddressValid(thisSearch.address, "MapSearch", g_PassportKey, SavedSearchEdit_Continue);
            }
        }
        else
        {
            SaveUpdateSearches(thisSearch, searchID, thisSearch.name, true, RepopulateList);
        }
    }
    else
    {        
        if (errorMsg != null)
        {
            errorMsg.innerHTML = "Saved Search Name is required";
        }
    }
}

function SavedSearchEdit_Continue(addressValidationResponse)
{     
    if (addressValidationResponse != null && typeof (gThisSearch) != "undefined" && gThisSearch != null)
    {
        if (!addressValidationResponse.IsValid)
        {
            FreeSearchOpenInvalidAddressPopup(addressValidationResponse.Suggestions);
        }
        else
        {
            var request = addressValidationResponse.SearchRequest;
            request = SetsavedsearchForRequest(request);

            if (gSearchName != null && gSearchName != '' && gSearchName != NAME_YOUR_SEARCH_TO_SAVE_IT)
            {
                SetSavedSearchFromSearchRequest(gThisSearch, request);
                SaveUpdateSearches(gThisSearch, gSavedSearchID, gThisSearch.name, true, RepopulateList);
            }            
        }
    }
}


function RepopulateList(Result)
{
    
    var btnSaveEdit = document.getElementById(g_ModifySearchHelper.BtnSaveEditedsavedSearch);
    if (btnSaveEdit != null)
    {
        btnSaveEdit.setAttribute('href', 'javascript:SavedSearchEdit(' + gSavedSearchID + ', "' + gDivRowContainer + '");');
        btnSaveEdit.setAttribute('onclick', 'SavedSearchEdit(' + gSavedSearchID + ', "' + gDivRowContainer + '"); return false;');
    }
    return false;
}

//Delete
function SavedSearchbyIDDelete(searchID, divContainerID)
{
    if (typeof (SearchService) != "undefined" && searchID != null)
    {
        curDivConatiner = divContainerID;
        SearchService.SavedSearchbyIDDelete(searchID, SavedSearchbyIDDelete_Continue);
    }
}

function SavedSearchbyIDDelete_Continue()
{
    
    var div = document.getElementById(curDivConatiner);
    if (div != null)
    {
        div.style.display = 'none';
    }    
    curDivConatiner = null;
}

function UpdateRowInformation(Search, SearchID, divContainerID)
{

    var min = document.getElementById('min_' + SearchID);
    var max = document.getElementById('max_' + SearchID);
    var beds = document.getElementById('beds_' + SearchID);
    var baths = document.getElementById('baths_' + SearchID);
    var sqft = document.getElementById('sqft_' + SearchID);
    var propType = document.getElementById('propType_' + SearchID);
    var dateFrom = document.getElementById('dateFrom_' + SearchID);
    var dateTo = document.getElementById('dateTo_' + SearchID);
    var sortBy = document.getElementById('sortBy_' + SearchID);
    var divContainerID = document.getElementById(divContainerID);
    var searchName = document.getElementById('spanSearchName_' + SearchID);
    var defaultValue = '';

  
    if (searchName != null)
    {
        searchName.innerHTML = Search.name;
    }
    if (min != null && Search.priceFrom != null)
    {
        min.innerHTML = '$' + Search.priceFrom + ' min,';                
    }
    else
    {
        min.innerHTML = defaultValue;
    }

    if (max != null && Search.priceTo != null)
    {
        max.innerHTML = '$' + Search.priceTo + ' max,';
    }
    else
    {
        max.innerHTML = defaultValue;
    }

    if (beds != null && Search.bedsNo != null)
    {
        beds.innerHTML = (Search.bedsNo == '0') ? defaultValue : Search.bedsNo + '+ beds,';
    }
    else
    {
        beds.innerHTML = defaultValue;
    }

    if (baths != null && Search.bathsNo != null)
    {
        baths.innerHTML = (Search.bathsNo == '0') ? defaultValue : Search.bathsNo + '+ baths,';
    }
    else
    {
        baths.innerHTML = defaultValue;
    }

    if (sqft != null && Search.homeSize != null)
    {
        sqft.innerHTML = (Search.homeSize == '0') ? defaultValue : Search.homeSize + '+ sq. ft.,';
    }
    else
    {
        sqft.innerHTML = defaultValue;
    }

    if (dateFrom != null && Search.beginDate != null)
    {
        dateFrom.innerHTML = Search.beginDate;
    }
    else
    {

    }

    if (dateTo != null && Search.endDate != null)
    {
        dateTo.innerHTML = Search.endDate;
    }
    else
    {

    }

    if (sortBy != null && Search.AdvancedRequest != null && null != Search.AdvancedRequest.SortField)
    {
        sortBy.innerHTML = 'Sort By ' + Search.AdvancedRequest.SortField;
    }
    else
    {

    }

    if (propType != null && Search.homeSize != null)
    {
        var text = Search.propType;

        text = text.replace(/RSFR/, 'Single Family');
        text = text.replace(/RCON/, 'Condo / Townhome');
        text = text.replace(/RAPT/, 'Multi Family Home');
        text = text.replace(/RVAC/, 'Vacant Residential');

        propType.innerHTML = text;
    }
    else
    {

    }

}

/************************ Saving Functionality ****************************/

function FreeSearchPageSaveSearchValidation(isSaveSearch)
{
    if(SearchValidation(isSaveSearch))
    {
        var txtNameSearch = '';
        if (g_ModifySearchHelper != null && g_ModifySearchHelper.TbxSearchName != null && document.getElementById(g_ModifySearchHelper.TbxSearchName) != null)
        {
            txtNameSearch = document.getElementById(g_ModifySearchHelper.TbxSearchName).value;
        }

        var hasSearchName = (txtNameSearch != '' && txtNameSearch != NAME_YOUR_SEARCH_TO_SAVE_IT);

        if(hasSearchName)
        {
            isSaveSearch = true;
        }
        
        SaveSearchAndstartSearch(txtNameSearch, isSaveSearch);
    }
}

function SearchValidation(isSaveSearch)
{
    var isValid = true;
    var errorMsg = document.getElementById('spanPopUpErrorMessages');
    
    if (isSaveSearch && g_ModifySearchHelper != null && g_ModifySearchHelper.TbxSearchName != null && 
        document.getElementById(g_ModifySearchHelper.TbxSearchName) != null &&
        document.getElementById(g_ModifySearchHelper.TbxSearchName).value == NAME_YOUR_SEARCH_TO_SAVE_IT)
    {
        if (errorMsg != null)
        {
            errorMsg.innerHTML = "Saved Search Name is required";
        }
        isValid = false;
    }
    
    if(g_ModifySearchHelper != null && g_ModifySearchHelper.TxtSearchFor != null && 
        document.getElementById(g_ModifySearchHelper.TxtSearchFor) != null &&
        document.getElementById(g_ModifySearchHelper.TxtSearchFor).value == ADDRESS_CITY_STATE_CNTY_STATE_OR_ZIP)
    {
        if (errorMsg != null)
        {
            errorMsg.innerHTML = "Search For criteria is required";
        }
        isValid = false;
    }   
    return isValid;
}

var g_isSaveSearch = false;
var gSearchName = null;
var gThisSearch = null;

function SaveSearchAndstartSearch(searchName, isSaveSearch)
{
    var thisSearch = new currentSearchToSave();
    SetSearchByAndFor(thisSearch);
    
    if (IsAdvancedSearchVisible())
    {
        SetPropertyProfile(thisSearch);
        SetPropertyType(thisSearch);
        SetSortBy(thisSearch);
    }
        
    if (thisSearch.searchBy == "address")
    {
        if (typeof (Autocomplete.IsAddressValid) != "undefined")
        {
            gThisSearch = thisSearch;
            gSearchName = searchName;
            g_isSaveSearch = isSaveSearch;
            Autocomplete.IsAddressValid(thisSearch.address, "MapSearch", g_PassportKey, ExecuteSearch_Continue);
        }
    }
    else
    {
        if (searchName != null && searchName != '' && isSaveSearch)
        {
            SaveUpdateSearches(thisSearch, editSearchID, searchName, false, SaveSearchAndstartSearch_Continue);
        }
        
        if (thisSearch.propID != null && thisSearch.searchBy == "id")
        {
            if (typeof(g_NavigationEngine) != "undefined")
            {
                window.location = g_NavigationEngine.PropertyDetailsPageForPropertyType(thisSearch.propID, "");                
            }
            else
            {
                window.location = '/PropertyDetails/PropertyDetails.aspx?propid=' + thisSearch.propID;
            }            
        }
        else
        {        
            if (thisSearch.propAPN != null)
            {
                window.location = '/mapsearch/mapsearch/mapsearch.aspx?searchType=id&txtAPN=' + thisSearch.propAPN;
            }
        }
    }
}

var NAME_YOUR_SEARCH_TO_SAVE_IT = 'Name your search to save it';
var ADDRESS_CITY_STATE_CNTY_STATE_OR_ZIP = 'Address, city/state, cnty/state, or ZIP';

function ExecuteSearch_Continue(addressValidationResponse)
{ 
    if (addressValidationResponse != null && typeof (gThisSearch) != "undefined" && gThisSearch != null)
    {
        if (!addressValidationResponse.IsValid)
        {
            FreeSearchOpenInvalidAddressPopup(addressValidationResponse.Suggestions);
        }
        else
        {
            var request = addressValidationResponse.SearchRequest;
            var serialized = "";
            
            request = SetsavedsearchForRequest(request);

            if (gSearchName != null && gSearchName != '' && gSearchName != NAME_YOUR_SEARCH_TO_SAVE_IT && g_isSaveSearch)
            {
                SetSavedSearchFromSearchRequest(gThisSearch, request);
                SaveUpdateSearches(gThisSearch, editSearchID, gSearchName, false, SaveSearchAndstartSearch_Continue);
            }

            var mapsearchURL = '/mapsearch/mapsearch/mapsearch.aspx?a=b' + addressValidationResponse.QueryString;
            
            if(IsAdvancedSearchVisible())
            {
                if (request != undefined && request != null)
                {
                    serialized = Sys.Serialization.JavaScriptSerializer.serialize(request);
                    serialized = (Base64.encode(serialized));
                }
                
                window.location = mapsearchURL + "#" + serialized;
            }
            else
            {
                window.location = mapsearchURL;
            }
        }
    }
}

function SetSavedSearchFromSearchRequest(thisSearch, searchRequest)
{
    thisSearch.address = '';
    
    switch (searchRequest.BasicRequest.SearchType)
    {
        case SEARCH_TYPE_CITY:
            thisSearch.searchBy = 'city';
            thisSearch.city = searchRequest.BasicRequest.City;
            break;
        case SEARCH_TYPE_COUNTY:
            thisSearch.searchBy = 'state';
            thisSearch.countyCode = searchRequest.BasicRequest.CountyCode;
            break;
        case SEARCH_TYPE_ADDRESS:
            thisSearch.searchBy = 'address';
            thisSearch.cityStateCode = searchRequest.BasicRequest.City;
            thisSearch.address = searchRequest.BasicRequest.Address;
            break;
        case SEARCH_TYPE_ZIP:
            thisSearch.searchBy = 'zip';
            thisSearch.zipCode = searchRequest.BasicRequest.Zip;
            break;
    }        
}

function FreeSearchOpenInvalidAddressPopup(suggestions)
{
    CreateSuggestionLinksForFreeSearch(suggestions);
    var divInvalidAddress = document.getElementById('divInvalidAddressPopup');
    divInvalidAddress.style.display = 'block';
    $find('ModalBehaviorInvalidAddress').show();
    return false;
}

function CloseInvalidAddressPopup()
{
    var divInvalidAddress = document.getElementById('divInvalidAddressPopup');
    $find('ModalBehaviorInvalidAddress').hide();
    divInvalidAddress.style.display = 'none';
    return false;
}

function CreateSuggestionLinksForFreeSearch(suggestions)
{
    var linksElement = document.getElementById("linksTitle");
    var listElement = document.getElementById("locationsList");

    while (listElement.childNodes[0])
    {
        listElement.removeChild(listElement.childNodes[0]);
    }

    if (suggestions != null && suggestions.length > 0)
    {
        linksElement.style.display = "block";

        var elCount = suggestions.length;

        if (suggestions.length > 5)
        {
            elCount = 5;
        }

        for (i = 0; i < elCount; i++)
        {
            var li = document.createElement('li');
            var link = document.createElement('a');
            var address = suggestions[i].Address;
            
            link.setAttribute("href", "#");
            link.setAttribute("address", address);
            link.innerHTML = address;
            
            Event.add(link, 'click',
                function(e)
                {
                    SelectSuggestionLink(address);
                });
            li.appendChild(link);

            listElement.appendChild(li);
        }

    }
    else
    {
        linksElement.style.display = "none";
    }
}

function SelectSuggestionLink(address)
{
    var txtSearchFor = document.getElementById(g_ModifySearchHelper.TxtSearchFor);

    if (txtSearchFor != null)
    {
        txtSearchFor.value = address;
    }
    
    return CloseInvalidAddressPopup();
}

function SetsavedsearchForRequest(request)
{
    if (request != null)
    {
        request.IsMf = true;

        if (request.AdvancedRequest != null)
        {
            if (gThisSearch.priceFrom != null)
            {
                request.AdvancedRequest.PriceFrom = gThisSearch.priceFrom.replace(/,/g, '');
            }
            if (gThisSearch.priceTo != null)
            {
                request.AdvancedRequest.PriceTo = gThisSearch.priceTo.replace(/,/g, '');
            }
            request.AdvancedRequest.BedroomCountFrom = gThisSearch.bedsNo;
            request.AdvancedRequest.BathroomCountFrom = gThisSearch.bathsNo;
            request.AdvancedRequest.SquareFeetFrom = gThisSearch.homeSize;
            request.AdvancedRequest.PropertyType = gThisSearch.propType;
            request.AdvancedRequest.SortField = gThisSearch.sortBy;
            request.AdvancedRequest.FromDate = gThisSearch.beginDate;
            request.AdvancedRequest.ToDate = gThisSearch.endDate;
            if (gThisSearch.databaseType != null)
            {
                request.AdvancedRequest.DatabaseType = gThisSearch.databaseType;
            }
        }
    }
    return request;
}

function SaveSearchAndstartSearch_Continue(result)
{

}

function SearchByAddressFreeSearch(addressValidationResponse)
{
    if (addressValidationResponse != null && typeof (gThisSearch) != "undefined" && gThisSearch != null)
    {
        if (!addressValidationResponse.IsValid)
        {
            OpenInvalidAddressPopup(addressValidationResponse.Suggestions, UpdateRequest_Continue);
        }
        else
        {
            var request = addressValidationResponse.SearchRequest;
            //UpdatePropertyCountWithEnteredValue(addressValidationResponse.Address);

            if (typeof (UpdateHeaderSearchField) != "undefined")
            {
                UpdateHeaderSearchField(addressValidationResponse.Address);
            }

            UpdateRequest_Continue(request);
        }
    }
}



/********************************************************************************************/



/* ---------------------- Update alert status fo the search ---------------------- */
function SavedSearchbyIDSetAlert(searchID, element)
{
    
    if (typeof (SearchService) != "undefined" && element != null)
    {
        var enabledAlert = (element.checked) ? 1 : 0;
        SearchService.SavedSearchbyIDSetAlert(searchID, enabledAlert, SavedSearchbyIDSetAlert_Continue);
    }
}

function SavedSearchbyIDSetAlert_Continue()
{
   
}

/* ---------------------- toogle Alert division ---------------------- */
function ToogleDivAlertMe(element)
{
    var div = document.getElementById(element);

    if (div)
    {
        div.style.display = (div.style.display == 'block') ? 'none' : 'block';
    }
}

//End Links actions


/******************  Advanced Search  *****************************/

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 FreeSearchPageBootstrap()
{
    g_ModifySearchHelper = new ModifySearchControlHelper(
        g_MSHConfig[0],
        g_MSHConfig[1],
        g_MSHConfig[2],
        g_MSHConfig[3],
        g_MSHConfig[4],
        g_MSHConfig[5],
        g_MSHConfig[6],
        g_MSHConfig[7],
        g_MSHConfig[8],
        g_MSHConfig[9],
        g_MSHConfig[10],
        g_MSHConfig[11],
        g_MSHConfig[12],
        g_MSHConfig[13],
        g_MSHConfig[14],
        g_MSHConfig[15],
        g_MSHConfig[16],
        g_MSHConfig[17],
        g_MSHConfig[18],
        g_MSHConfig[19],
        g_MSHConfig[20]
        );
        
   EnableDisableDateRange_Continue(document.getElementById('ddlSortBy'), true);  
   
   if(typeof(g_propertyIDForModifiedSearch) !== "undefined")
   {
        FillModifySearchFormWithSavedSearch(g_propertyIDForModifiedSearch) ;
   }
}

if(typeof(Sys) !== "undefined" && typeof(g_isFreeSearchPage) !== "undefined" && g_isFreeSearchPage == true) 
{
    Sys.Application.add_load(FreeSearchPageBootstrap);
}

function AddModifySerchExpanderFunc()
{
    $("a.freeSearchExpander").click(function(event) {
        event.preventDefault();
        $("div#divBottom").slideToggle("normal");
        $("div.modifySearch").toggleClass("modifySearchOn");
        $("#ddlSortBy").toggle();
    });
}

function ContactAgentExpanderFunc()
{
    $("a.contactAgentExpander").click(function(event) {

        event.preventDefault();
        $("div.contactAgentBannerContentContainer").slideToggle("normal");
    });
}


$("a.contactAgentExpander").click(function() {
    var isIE6 = ($.browser.msie && $.browser.version == "6.0") ? true : false;
    var visibleState = true; 
    
    if (isIE6) {
        $("select.visible").toggleClass("hidden");   
    }
});


//END RealtyTrac.Common.Web.Scripts.MapSearch.searchresults.js
//START RealtyTrac.Common.Web.Scripts.MapSearch.detailsmap.js


//Constants
var IMAGE_LINK_NA = "http://www.realtytrac.com/images/image_na.gif";
var STYLE_NONE = "none";
var STYLE_BLOCK = "block";
var STYLE_HIDDEN = "hidden";
var STYLE_VISIBLE = "visible";

var ELEMENT_JOIN_NOW_BALLOON_CONTAINER = "joinNowBalloonCnr";
var zoomLevelAdViews = 5;
var gMapServiceBusy = false; //TODO: delete the variable and cs code which assign it
var gSubjectProperty = false;
var gSubjectPropertyID = null;
var gSubjectPropertyLat = null;
var gSubjectPropertyLon = null;
var gSubjectPropertyLat = null;
var gSubjPropDecodedLatLong = new Object;
    gSubjPropDecodedLatLong._reserved = '';
var gIsPropertySearch = true;
var CRITERIA_TYPE_SEARCH_ZIP = "Zip";
var CRITERIA_TYPE_SEARCH_CITY = "City";
var CRITERIA_TYPE_SEARCH_COUNTY = "County";
var CRITERIA_TYPE_SEARCH_ADDRESS = "address";
var gImageArrayPosition = 0;
var gImageArray = new Array();
var gPinsPos = new Array();

var gOldMapStyle = '';
var gCreateMap = false;
var gMapCenter;
var gObjPOI;
var mainPropertyId;
var showPropertyDetailsPopup;
var isRecenterNeeded = false;
var gIsMapVisible = false;
var MAX_ZOOM_LEVEL = 15;
var ZIP_SEARCH_LOCATION_ZOOM = 14;
var SEARCH_LOCATION_ZOOM = 12;
var AFTER_SEARCH_LOCATION_ZOOM = 12;
var COUNTY_SEARCH_LOCATION_ZOOM = 10;
var MAP_WIDTH_WITH_MENU = 620;
var MAP_WIDTH_WITHOUT_MENU = 772;
var MAP_HEIGHT = 475;
var MAP_WIDTH_DECREASE = 'narrower';
var MAP_WIDTH_INCREASE = 'wider';

var WIDTH_DIFFERENCE = MAP_WIDTH_WITHOUT_MENU - MAP_WIDTH_WITH_MENU;
var MAP_HELP_DEFAULT_LOCATION = -10;
var MAP_HELP_CURRENT_LOCATION = MAP_HELP_DEFAULT_LOCATION;
var MINIMAP_DEFAULT_LOCATION = 470;
var MINIMAP_CURRENT_LOCATION = MINIMAP_DEFAULT_LOCATION;
var MINIMAP_CLOSE_DEFAULT = 124;
var TOO_MANY_PROPERTIES_DEFAULT_LOCATION = 160;
var JOINBALOONCNR_DEFAULT_LEFT = 100;

var BALOON_POPUP_LEFT_DEFAULT = 313;
var BALOON_POPUP_LEFT_LARGE_MAP = 315;
var BALOON_POPUP_LEFT = BALOON_POPUP_LEFT_DEFAULT;	

var MAP_OVERLAY_ICON_DEFAULT = 268;
var DEFAULT_SEARCH_TEXT = "Enter a full address or City, State, or ZIP";
var MSG_EMPTY_SEARCH_TEXT = "Please enter a full address or City, State, or ZIP";

var gSearchRequestObject = null;
var gIsMapLoaded = true;
var _layers;

var pins;
var TheMap;
var tempPropID = null;

var gIsGuestMember;
var gIsCancelledMember;
var gMainPropertyID = null;

   
function InvalidPassportReloadPage()
{
    try

    {
	    alert("Your map session has expired. Click OK to reload your browser.");
	    window.location.reload();
	}
    catch(ex)
    {
        LogErrorMessage("InvalidPassportReloadPage: ", ex);
    }
}

function IsDivVisible(divName)
{
    loPropInfoDiv = document.getElementById(divName);
    if(loPropInfoDiv)
    {
        return loPropInfoDiv.style.visibility == STYLE_VISIBLE || loPropInfoDiv.style.display == STYLE_BLOCK;
    }
    
    return false;
}
	    
function showDiv(divName)
{
    try
    {
	    loPropInfoDiv = document.getElementById(divName);
	    //SetOverlaySize(divName);
	    if(loPropInfoDiv)
	    {
	        loPropInfoDiv.style.visibility = STYLE_VISIBLE;
            loPropInfoDiv.style.display = STYLE_BLOCK;
	    }
	}
    catch(ex)
    {
        LogErrorMessage("showDiv: ", ex);
    }
}

function hideDiv(divName)
{
    try

    {
	    loPropInfoDiv = document.getElementById(divName);
	    if(loPropInfoDiv)
	    {
	        loPropInfoDiv.style.visibility = STYLE_HIDDEN;
	        loPropInfoDiv.style.display = STYLE_NONE;
	    }
	}
    catch(ex)
    {
        LogErrorMessage("hideDiv: ", ex);
    }
}

//----Sets the layers visibility---
//----Used in ctlDetailsMap.ascx---
function toggleLayers(whichLayer) 
{
    try

    {
	    if (document.getElementById(whichLayer).style.visibility == STYLE_VISIBLE) 
	    {
		    //Hide the div
		    hideDiv(whichLayer);
		    if(TheMap && TheMap.isMapVisible)
			{
				TheMap.HideOverLay();
			}
	    }
	    else 
	    {
		    //If the help center is clicked we need to make sure the property divs are removed
		    if(whichLayer == 'helpCenterBalloonCnr')
		    {
			    ClearDivs();
		    }
		    //Show the div
		    showDiv(whichLayer);
	    }
	}
    catch(ex)
    {
        LogErrorMessage("toggleLayers: ", ex);
    }
}

   
////////-------------  New Location Search -------------------///////////
function NewSearchRequest(elementID)
{
    if (!ValidateSearchRequest(elementID) )
    {
        OpenInvalidAddressPopup();
        return;
    }

    if(typeof(SetLastSearchCookieByElementID) == "function")
    {
        SetLastSearchCookieByElementID(elementID);
    }
    searchNewLocation(GetElementValue(elementID), false);
}


function NewMapSearchRequest(elementID)
{
    if (!ValidateSearchRequest(elementID) )
    {
        OpenInvalidAddressPopup();
        return;
    }

    if(typeof(SetLastSearchCookieByElementID) == "function")
    {
        SetLastSearchCookieByElementID(elementID);
    }
    
    searchNewLocation(GetElementValue(elementID), true);
}

function ValidateSearchRequest(elementID)
{
    var txtSearch = document.getElementById(elementID); 
    var txtSearchValue = '';

     if (txtSearch != null )
     {
         txtSearchValue = txtSearch.value.replace(/^\s+|\s+$/g, "");
         
        if (txtSearchValue == '' || txtSearchValue.toLowerCase() == DEFAULT_SEARCH_TEXT.toLowerCase())   
        {
          return false;
        }
     }
     return true;
}

function GetElementValue(elementID)
{
	var element = document.getElementById(elementID);
    var value = "";
    if (element != null)
    {
        value = element.value;
    }    
    
    return value;
}


function ProcessInternalSearch()
{
    var addressElement = document.getElementById("txtSmallSearchAddress");
    var cityStateZipElement = document.getElementById("txtSearchMapCity");
    var hasData = true;
    
    var address = "";
    
    if (addressElement != null && addressElement.value != "" && addressElement.value != "Address (optional)")
    {
        address = addressElement.value;
        address += ", ";
    }
    
    if (cityStateZipElement != null && cityStateZipElement.value != "" && cityStateZipElement.value != "City, State or ZIP (required)")
    {
        address += cityStateZipElement.value;
    }
    else if (address != "")
    {
        hasData = false;
        alert("You must enter a city, state or ZIP");
    } 
    
    if (hasData)
    {
        searchNewLocation(address, true);
    }
}

function searchNewLocation(address, displayMap)
{
    
	ShowOverlays();
	
	if (typeof(ToggleActivityImage) != "undefined")
	{
	    ToggleActivityImage(true);
    }
    
	if (typeof(Autocomplete.IsAddressValid) != "undefined")
	{
		if (displayMap != null)
		{
			gIsMapVisible = displayMap;				
		}
		
		Autocomplete.IsAddressValid(address, "MapSearch", g_PassportKey, searchNewLocation_Continue)
	}
}

function ShowOverlays()
{
    ShowSearchOverlay();
    if (TheMap && TheMap.isMapVisible)
    {
        TheMap.ShowOverLay();
    }
}

function HideOverlays()
{
    HideSearchOverlay();
    if (TheMap && TheMap.isMapVisible)
    {
        TheMap.HideOverLay();
    }
}
	
function searchNewLocation_Continue(addressValidationResponse)
{
    
	if (typeof(ToggleActivityImage) != "undefined")
	{
	    ToggleActivityImage(false);
    }
	
	if (addressValidationResponse != null)
	{
	    if(!addressValidationResponse.IsValid)
	    {
		    OpenInvalidAddressPopup(addressValidationResponse.Suggestions);
	    }
	    else
	    {
            switch (addressValidationResponse.Type)
            {
	            case 0:
	            case 1:
		            searchType = "address";
		            break;
	            case 2:
		            searchType = "county";
		            break;
		        case 7:		        
	            case 3:
		            searchType = "zip";
		            break;
	            case 4:
		            searchType = "city";
		            break;
            }
            
            gCriteriaType = searchType;
            gCriteriaValue = addressValidationResponse.Address;
            SwapSearchFunctions(gIsMapVisible);
			if (gIsMapVisible) 
			{
				var searchType = "";
				
				if (typeof(TheMap) == "undefined")
				{
				    CreateMap();
				}
				
				if (TheMap && !TheMap.isMapVisible)
				{
				    ShowMap();				    
				}
				
				if(TheMap && TheMap.isMapVisible)
				{
				    BtnImageToShow(true);
				}                
			}
			else 
			{
			    HideTheMap();
			}
			
            gModSearchOrdBy = null;
            							
			UpdatePropertyCountWithEnteredValue(addressValidationResponse.Address);
			
			if (typeof(UpdateHeaderSearchField) != "undefined")
			{
			    UpdateHeaderSearchField(addressValidationResponse.Address);
			}
			
		    SearchListForm(addressValidationResponse.SearchRequestEncoded);
		    
		    if (TheMap && TheMap.isMapVisible)
			{
                  gSubjectPropertyLat = null;
                  gSubjectPropertyLon = null;
                  gSubjPropDecodedLatLong._reserved = '';
                  if((TheMap.IsBirdEyeView() && addressValidationResponse.Type > 1) || (TheMap.IsBirdEyeView() && (!TheMap.isMember || gIsGuestMember || gIsCancelledMember)))
                  {
                    TheMap.gMapSearchObj.SetMapStyle(VEMapStyle.Road);
                  }
			    //We reset Parameters For The Main Property
			    TheMap.PinsOnMap.ReIniClassVariables();
			    gSubjectPropertyID = null;
			    tempPropID = null;  
			    AddPinsBySearchValues();
			}
	    }
	}
}

///Invalid address popup functions

function CloseInvalidAddressPopup()
{
    var divInvalidAddress = document.getElementById('divInvalidAddressPopup');
    $find('ModalBehaviorInvalidAddress').hide();
    divInvalidAddress.style.display = 'none';
    return false;
}

function OpenInvalidAddressPopup(suggestions, functionName)
{
    HideOverlays();
    CreateSuggestionLinks(suggestions, functionName);
    var divInvalidAddress = document.getElementById('divInvalidAddressPopup');
    divInvalidAddress.style.display = 'block';
    $find('ModalBehaviorInvalidAddress').show();    
    return false;
}

function OpenBuyersArmyPopup() {

    var request = GetSearchRequest(gSearchRequest);
    var lastSearch = document.getElementById('txtSearchRequestAddress');
    var searchCriteria = '';
    var divBuyersPopup = document.getElementById('divBuyersPopup');

    if (lastSearch != null && lastSearch.value != '') {
        searchCriteria = lastSearch.innerHTML;
    }
    
    var searchFromCookie = GetCookie("LastSearch")
    
    if (searchFromCookie)
    {
        searchCriteria  = searchFromCookie;
    }

    $find("buyersLocationBehaviorID").set_WatermarkText(searchCriteria);

    divBuyersPopup.style.display = 'block';
    
    ShowMakeOfferSubscribeSpinner(false);
    
    $find('BuyersPopupModalBehavior').show();
    
    return false;
}

function ShowMakeOfferSubscribeSpinner(isVisible)
{
    var divMakeOfferSubscribeButton = $get("divMakeOfferSubscribeButton");
    var divMakeOfferSubscribeSpinner = $get("divMakeOfferSubscribeSpinner");
    
    if (divMakeOfferSubscribeButton && divMakeOfferSubscribeSpinner)
    {
        if (isVisible)
        {
            divMakeOfferSubscribeSpinner.style["display"] = "";
            divMakeOfferSubscribeButton.style["display"] = "none";
        }
        else
        {
            divMakeOfferSubscribeSpinner.style["display"] = "none";
            divMakeOfferSubscribeButton.style["display"] = "";
        }
    }
}

function SendEmailAlerts() {
    try
    {
		var location = $find("buyersLocationBehaviorID").get_element().value;
		
		var isChecked = true;
		var emailAddress = "";
		var chkEmailAlert = $get("chkEmailAlert");
		var txtEmailAddress = $get("txtEmailAddress")

	    isChecked = chkEmailAlert ? chkEmailAlert.checked : isChecked;
	    emailAddress = txtEmailAddress ? txtEmailAddress.value : emailAddress;
	    
		if ( location != '' && location != DEFAULT_SEARCH_TEXT ) {
		    
		    ShowMakeOfferSubscribeSpinner(true);
		    
			SearchService.SendEmailAlerts(location, isChecked, emailAddress, SendEmailAlerts_Callback, SendEmailAlertsError_Callback);
		} else {
			alert('Please specify a location.');
		}
    }
    catch(e)
    {
		//alert(e.message);
		ShowMakeOfferSubscribeSpinner(false);
		CloseBuyersArmyPopup();
    }

    return false;
}

function SendEmailAlertsError_Callback()
{
		ShowMakeOfferSubscribeSpinner(false);
		CloseBuyersArmyPopup();
}

function SendEmailAlerts_Callback(errorMessage) {
    ShowMakeOfferSubscribeSpinner(false);

	if ( errorMessage != '' )
	{	
		alert(errorMessage);
	}
	else
	{
		alert('Location has been successfully saved.');
		$find("buyersLocationBehaviorID").set_Text( "" );
		CloseBuyersArmyPopup();
    }
}

function CloseBuyersArmyPopup() {

    var divBuyersPopup = document.getElementById('divBuyersPopup');
    
    divBuyersPopup.style.display = 'none';
    $find('BuyersPopupModalBehavior').hide();
    
    return false;
 }
    
function HideTheMap()
{
    if (TheMap != null && TheMap.isMapVisible)
    {
        TheMap.HideMap();
        BtnImageToShow(false);
    }
}

function CreateSuggestionLinks(suggestions, functionName)
{
    var linksElement = document.getElementById("linksTitle");
    var listElement = document.getElementById("locationsList");
   
    while (listElement.childNodes[0])
    {
        listElement.removeChild(listElement.childNodes[0]);
    }
    
    if (suggestions != null && suggestions.length > 0)
    {
        linksElement.style.display = "block";
        
        var elCount = suggestions.length;
        
        if (suggestions.length > 5)
        {
            elCount = 5;
        }
        
        if (typeof(functionName) == "undefined")
        {
            functionName = searchNewLocation_Continue;
        }
        
        for (i = 0; i < elCount; i++)
        {
            var li = document.createElement('li');
            var link = document.createElement('a');

            link.setAttribute("href", "#");
            link.setAttribute("address", suggestions[i].Address);
            link.innerHTML = suggestions[i].Address;
            Event.add(link, 'click', 
                function(e)
                {
                    SearchSuggestion(this.innerHTML, functionName, suggestions);
                    return CloseInvalidAddressPopup();
                });
            
            li.appendChild(link);
                        
            listElement.appendChild(li);
        }
        
    }
    else
    {
        linksElement.style.display = "none";
    }
}

function SearchSuggestion(address, functionName, suggestions)
{
    if (typeof(address) != "undefined" && address != null 
        && typeof(functionName) != "undefined" && functionName != null
        && typeof(suggestions) != "undefined" && suggestions != null && suggestions.length > 0)
    {
        var suggestion;
        for (var i = 0; i < suggestions.length; i++)
        {
            if (address == suggestions[i].Address)
            {
                suggestion = suggestions[i];
                break;
            }
        }
        
        if (suggestion != null)
        {
            functionName(suggestion);
        }
    }
}


///--- This allows to dinamically add elements to page and add events to them ---///
var Dom = 
{
  get: function(el) 
  {
    if (typeof el === 'string') 
    {
      return document.getElementById(el);
    } 
    else 
    {
      return el;
    }
  },
  
  add: function(el, dest) 
  {
    var el = this.get(el);
    var dest = this.get(dest);
    dest.appendChild(el);
  },
  
  remove: function(el) 
  {
    var el = this.get(el);
    el.parentNode.removeChild(el);
  }
};

var Event = 
{
  add: function() 
  {
    if (window.addEventListener) 
    {
        return function(el, type, fn) 
        {
            Dom.get(el).addEventListener(type, fn, false);
        };
    } 
    else if (window.attachEvent) 
    {
        return function(el, type, fn) 
        {
            var f = function() 
            {
                fn.call(Dom.get(el), window.event);
            };
            
            Dom.get(el).attachEvent('on' + type, f);
        };
    }
  }()
};

////////-------------  END new location search -------------------///////////


////////-------------  Check if pressed button is enter  -------------------///////////
function checkEnter(e, submitFunction, text, regex, message)
{ 
    try

    {
        //e is event object passed from function invocation
	    var characterCode; //literal character code will be stored in this variable
		
	    if(e && e.which)
	    { //if which property of event object is supported (NN4)
		    e = e;
		    characterCode = e.which; //character code is contained in NN4's which property
	    }
	    else
	    {
		    e = event;
		    characterCode = e.keyCode; //character code is contained in IE's keyCode property
	    }
		
	    if(characterCode == 13)//if generated character code is equal to ascii 13 (if enter key)
	    { 
		    if(regex && text)
		    {
		        if(text.match(regex))
		        {
		            eval(submitFunction);
		        }
		        else
		        {
		            alert(message);
		        }
		    }
		    else
		    {
		        eval(submitFunction);
		    }
			
		    return false;
	    }
	    else
	    {
		    return true;
	    }
	}
    catch(ex)
    {
        LogErrorMessage("checkEnter: ", ex);
    }
}

function isPreCondition(funcName)
{
    var isOk = false;
    
    if(funcName == 'ToggleMapDisplay')
    {
        if(gIsMapLoaded && typeof(g_NavigationEngine) != 'undefined' && g_NavigationEngine != null)
        {
            isOk = true;
        }
    }
    
    return isOk;
}

function IsMapBirdsEyeView()
{
    if(gMap)
    {
        var mapStyle = gMap.GetMapStyle();
        return  mapStyle == VEMapStyle.Birdseye || mapStyle == VEMapStyle.BirdseyeHybrid;
    }
    
    return false;
}
 
//This function is Atlas ads, no longer relevant
function RefreshBanners(dmaCode)
{
    if(typeof(RefreshRightBanner) != 'undefined')
    {
        RefreshRightBanner(dmaCode);
    }
    
    if(typeof(RefreshRightMiniSkyBanner) != 'undefined')
    {
        RefreshRightMiniSkyBanner(dmaCode);
    }
    
    if(typeof(RefreshTopBanner) != 'undefined')
    {
        RefreshTopBanner(dmaCode);
    }

}

//Refresh DoubleClick Banner
function RefreshDoubleClickBannerUtil()
{    
    if (typeof(RefreshAllDoubleClickBanner) != 'undefined')
    {
        RefreshAllDoubleClickBanner();
    }    
}

//----------------------------------------------------------------------------------------------------
//---------------------------------------------    Map    --------------------------------------------
//----------------------------------------------------------------------------------------------------

function InitMap(showMap)
{
    try

    {
        var showMapCookie = null;
        gCreateMap = showMap;			    
    }
	catch(ex)
	{
        LogErrorMessage("InitMap: ", ex);
	}   
}
  

//Attach the onload event
//addLoadEvent(OnPageLoad);

// Fix for the Map "jumping" in FF3
(function()
{
    var mouseEvt;
    if (typeof document.createEvent !== 'undefined')
    {
        mouseEvt = document.createEvent('MouseEvents');
    }
    if (mouseEvt && mouseEvt.__proto__ && mouseEvt.__proto__.__defineGetter__)
    {
        mouseEvt.__proto__.__defineGetter__('pageX', function()
        {
            return this.clientX - window.pageXOffset;
        });
        mouseEvt.__proto__.__defineGetter__('pageY', function()
        {
            return this.clientY - window.pageYOffset;
        });
    }
})();
    
if(typeof(Sys) !== "undefined") 
{
    Sys.Application.add_load(OnPageLoad);
}

	
//delays function to be run on window load.
function addLoadEvent(func) 
{ 
    var oldonload = window.onload; 
	
    if (typeof window.onload != 'function') 
    { 
	    window.onload = func; 
    } 
    else 
    { 
	    window.onload = function() { oldonload(); func(); } 
    }
}
	
//Function run on page load.
function OnPageLoad()
{ 
    try
    {   
	    //check for all scripts being loaded
	    if( typeof(isSupportedBrowser) === "function"
	      && typeof(ConfigureFramework)  === "function"
	      && typeof(HideSearchOverlay) === "function"
	      && typeof(GetSearchRequest) === "function")
        {
        
            if(!isSupportedBrowser())
	        {
	            alert('Your browser is not supported.');
	            //HideOverlayDiv();
	            HideSearchOverlay();
	            return;
	        }
	        
            // configure AJAX framework
            ConfigureFramework();
            
            InitializeGlobalObjects();
            
	        gSearchRequestObject = GetSearchRequest();		        
	        
            PassportRenew_Continue();
		
	    }
	    else
	    {
	        alert("Page wasn't completely loaded. Click OK to reload your browser.");
	        window.location.reload(true);		    
	    }
	}
	catch(ex)
	{
        LogErrorMessage("OnPageLoad: ", ex);
	}
}

function InitializeGlobalObjects()
{
    g_NavigationEngine = new NavigationEngine(
        g_NavigationEngineConfig.isMember, 
        g_NavigationEngineConfig.isWhiteSite,
        g_NavigationEngineConfig.isDataLink,
        g_NavigationEngineConfig.useNewPropertyDetails,
        g_NavigationEngineConfig.freeTrialLink,
        g_NavigationEngineConfig.moreDetailsLink,
        g_NavigationEngineConfig.isCustomFreeSite);
        
    InitMap(g_miscConfig.mapVisible);
    
    DisplayLenderBanner(g_miscConfig.lenderBannerVisible);
    DisplayLowMortageRatesBanner(g_miscConfig.mortgageBannerVisible);
    
    g_ModifySearchHelper = new ModifySearchControlHelper(
        g_MSHConfig[0],
        g_MSHConfig[1],
        g_MSHConfig[2],
        g_MSHConfig[3],
        g_MSHConfig[4],
        g_MSHConfig[5],
        g_MSHConfig[6],
        g_MSHConfig[7],
        g_MSHConfig[8],
        g_MSHConfig[9],
        g_MSHConfig[10],
        g_MSHConfig[11],
        g_MSHConfig[12],
        null, // 13
        null, // 14
        null, // 15
        null, // 16
        null, // 17
        null, // 18
        null, // 19
        null, // 20
        g_MSHConfig[13]);
            
    SetEnteredAuctionStartDate();
    SetSearchTypeControls();    
}
	
function PassportRenew_Continue()
{
    try
    {
        // we don't have any passport any more by because if some concurrency
        // issue we need to have a small timeout here...
        window.setTimeout('MapLoadContinue()', 100); 
    }
	catch(ex)
	{
        LogErrorMessage("PassportRenew_Continue: ", ex);
	}
}
	
function MapLoadContinue()
{
    try
    {
		if(gCreateMap)
	    {
           	ShowMap();
			
			var isRestored = TheMap.RestoreZoomAndPosition(gSearchRequestObject);
			 
            if(!isRestored)
            {
                if (typeof(gPropID) != "undefined" && gPropID > 0)
                {
                    tempPropID = gPropID;
                    TheMap.AddMainProperty(gPropID, AddMainProperty_Continue);
                }
                else
                {
                    
                }
            }
				
           	SwapSearchFunctions(true);   
        }
        
        OnSearchLoad(); 
        
        if (!gIsMapRestored)
        {
            AddPinsBySearchValues();                     
        }
        else
        {
            gIsMapRestored = false;
        }
    }	    
	catch(ex)
	{
        LogErrorMessage("MapLoadContinue: ", ex);
	}
}	

function CreateMap()
{
    try
    {
    	var isMapCreated = false;
		
		if (TheMap && TheMap.isMapCreated) 
		{
			isMapCreated = true;
		}
		else {
			TheMap = new MapSearch('myMap');
			isMapCreated = TheMap.CreateMapSearchMap();
			if (isMapCreated) {
				//will set the Height of the Menu to the hight of the Map button
				TheMap.MapMenu.SetHeightToOpenBtn();
				TheMap.MapMenu.ShowAvailableTabsAndCheckboxes();
			}
		}
		return isMapCreated;
    }
    catch(ex)       
    {
        LogErrorMessage("CreateMap: ", ex);
    }
}

function ShowMap()
{
    try
    {   
		if(CreateMap())
        {  
			//TheMap.MapMenu.SetHeightToOpenBtn(); We just done it in CreateMap() ???
			SetTrialUrl();
			//once created the Map we show it    				
			TheMap.ShowMap();			
			BtnImageToShow(true);	
	 	}             
        if(typeof(RefreshDoubleClickBannerUtil) !== "undefined")
        {
            RefreshDoubleClickBannerUtil();
		}
    }
	catch(ex)
	{
        LogErrorMessage("ShowMap: ", ex);
	}
}    

function ToggleMapDisplay()
{
    try

    {
        if(!isPreCondition('ToggleMapDisplay'))
        {
            return;
        }
        if(TheMap && TheMap.isMapVisible)
		{
			TheMap.HideMap();	
		}
		else
		{
			ShowMap();
		}		
    }
	catch(ex)
	{
        LogErrorMessage("ToggleMapDisplay: ", ex);
	} 
}


//----------------------------------------------------------------------------------------------------
//--------------------------------------------- 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
					{
					    TheMap.GetPinPopUpInfo(pinParamters, ServResultPinPropType);
					}					
				}
			}
		}
    }
	catch(ex)
	{
        LogErrorMessage("OnPinClick: ", ex);
	}
}

//--------------------------------------------------
//----------------- OnViewChanged  -----------------
//--------------------------------------------------

function OnViewChanged(event)
{
    try

    {
		TheMap.StoreMapSettingsInSearchRequest();
        
        TheMap.PinsOnMap.PopUpClass.RemoveGroupedPopup();
        
        if ((!TheMap.isMember || gIsGuestMember || gIsCancelledMember) && (event.mapStyle == VEMapStyle.Birdseye || event.mapStyle == VEMapStyle.BirdseyeHybrid)) 
		{			
            if (zoomLevelAdViews == MAX_ZOOM_LEVEL_NON_MEMBERS_5) {
				TheMap.PinsOnMap.PopUpClass.JoinNowPopUp();	
				TheMap.PinsOnMap.PopUpClass.CenterJoinNowPopUp((TheMap.MapMenu.GetMenuWidth() + 11) * -1);			
				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.PinsOnMap.PopUpClass.JoinNowPopUp();
			TheMap.PinsOnMap.PopUpClass.CenterJoinNowPopUp((TheMap.MapMenu.GetMenuWidth() + 11) * -1);
			return;
		}
		
		
		TheMap.PinsOnMap.PopUpClass.RemovePopupJoinNow();
		
		if(!TheMap.isCreatingPinsOnMap)
		{		    
		    TheMap.GetPinsByMapLatLon(GetPinsByLatLong_Continue);
		}
		TheMap.prevMapStyle = event.mapStyle;		
    }
	catch(ex)
	{
        LogErrorMessage("OnViewChanged: ", ex);
	}
}

//--------------------------------------------------
//----------------- On Mouse Over  -----------------
//--------------------------------------------------

function OnMouseOver(mapEvent)
{
    try
    {
		if (mapEvent && mapEvent.elementID != undefined && mapEvent.elementID != null) {			
			if (TheMap.GetMapZoomLevel() < 14) {
			
				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, DrawAreaBorder);
						}
					}
				}
			}
		}
    }
    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);
	}
}


//--------------------------------- Pin Pop up creation  ------------------------------------------------------------

function ServResultPinPropType(result)
{
	try
	{
		hideDiv("help_div_cnr");
	    hideDiv("helpCenterBalloonCnr");
	    
	    if(result == null)
	    {
	        TheMap.PinsOnMap.PopUpClass.NoDataFoundPopUp();
		}
		else
		{
		    TheMap.PinsOnMap.PopUpClass.PropertyTypePopUp(result);
		}
		
	    if (typeof (RefreshDoubleClickBannerUtil) !== "undefined") 
        {
            RefreshDoubleClickBannerUtil();
        }		
	}
	catch(ex)
	{
		LogErrorMessage("ServResultPinPropType: ", ex, true);
	}	
}

//-------------------------------------------------------------------------------------------------------------
//---------------------------------- Pin functions ------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------

//------------------------------------ Pins by search  ------------------------------------
function AddPinsBySearchValues()
{
    try
        { 
            if (IsMapOnPage() && tempPropID == null)
        {
            TheMap.isCreatingPinsOnMap = true;
            if(gCriteriaType != null && gCriteriaValue != null && gCriteriaType != '' && searchValue != '')
            {
                var searchValue = gCriteriaValue;
                if(gCriteriaType == CRITERIA_TYPE_ZIP && searchValue.length > 5)
                {
                    searchValue = searchValue.substring(0, searchValue.indexOf(','));
                }            
                
                TheMap.gMapSearchObj.Find(gCriteriaType, searchValue, VEFindType.Businesses, null, 0, 20, false, false, true, true, AddPinsBySearchValues_Continue);
            }
            else
            {
                
                AddPinsBySearchValues_Continue();
            }
        }
    }
	catch(ex)
	{
        LogErrorMessage("AddPinsBySearchValues: ", ex, true);
	}
}
	
function AddPinsBySearchValues_Continue()
{
    try

    {
       if(IsMapOnPage())
       { 
           if(TheMap.gMapSearchObj != null)
           {
               if(gCriteriaType.toLowerCase() == CRITERIA_TYPE_SEARCH_COUNTY.toLowerCase())
                {
                    
                    TheMap.gMapSearchObj.SetZoomLevel(COUNTY_SEARCH_LOCATION_ZOOM);
                }
                else if(gCriteriaType.toLowerCase() == CRITERIA_TYPE_SEARCH_ZIP.toLowerCase())
                {
                    
                    TheMap.gMapSearchObj.SetZoomLevel(ZIP_SEARCH_LOCATION_ZOOM);
                }
                else if(gCriteriaType.toLowerCase() == CRITERIA_TYPE_SEARCH_ADDRESS || gCriteriaType.toLowerCase() == 'full')
                {  
                    if(!TheMap.isMember || gIsGuestMember || gIsCancelledMember)
                    {                        
                        TheMap.gMapSearchObj.SetZoomLevel(ADDRESS_SEARCH_NON_MEMBER_ZOOM);
                    }
                    else
                    {
                        
                        TheMap.gMapSearchObj.SetZoomLevel(ADDRESS_SEARCH_MEMBER_ZOOM);
                    }
                }
                else
                {                    
                    
                    TheMap.gMapSearchObj.SetZoomLevel(SEARCH_LOCATION_ZOOM);
                }

                gMapCenter = TheMap.gMapSearchObj.GetCenter();
                TheMap.mapCenterFromSearch = TheMap.gMapSearchObj.GetCenter();
        		
		        if(TheMap)
		        {
			        TheMap.GetPinsByMapLatLon(GetPinsByLatLong_Continue);
		        }
        		
                TheMap.isCreatingPinsOnMap = false;
           }
        }
    }
	catch(ex)
	{
        LogErrorMessage("AddPinsBySearchValues_Continue: ", ex);
	}
}

function AddMainProperty_Continue(objPOI)
{
    try

    {
        if(IsMapOnPage())
        {               
            if(objPOI && objPOI.InvalidPassport)
	        {
		        if(TheMap && TheMap.isMapVisible)
			    {
				    TheMap.InvalidPassportReloadPage();
			    }			
		        return;
	        }
    			
	        if(!objPOI)
	        {
	            TheMap.HideOverLay();
	            alert("Sorry. This address is currently not available.");
		        return;
	        }
	        
		    if(objPOI)
		    {						    
				    TheMap.PinsOnMap.mainPropertyID = objPOI.PropID;
				    TheMap.SetCenterAndZoom(objPOI.Latitude, objPOI.Longitude);
				    
				    var propertyCheckbox = GetPropertyTypeCheckboxByPropertyStatus(objPOI.PropertyStatus);

				    if (propertyCheckbox)
				    {
				        propertyCheckbox.checked = true;
				    }
    				
				    if (TheMap.isMember || !TheMap.IsBirdEyeView()) 
				    {
					    TheMap.GetPinsByMapLatLon(GetPinsByLatLong_Continue);					
				    }
				    else 
				    {
					    TheMap.PinsOnMap.PopUpClass.JoinNowPopUp();
				    }
    				
				    if (!g_NavigationEngine._isWhiteSite && !g_NavigationEngine._isDataLink) {
					    TheMap.ScrollPageToMap();
				    }
    				
				    TheMap.HideOverLay();
		    }
        }
	}
	catch(ex)
	{
        LogErrorMessage("AddMainProperty_Continue: ", ex);
	}
}

function PositionMainProperty()
{
    try
    {
        MapService.GetPOI(gPassportKey, mainPropertyId, false, PositionMainProperty_Continue);
    }
	catch(ex)
	{
        LogErrorMessage("PositionMainProperty: ", ex);
	}
}

function IsMapOnPage()
{
    var result = false;
    
    if(TheMap != null)
    {
        if(TheMap.gMapSearchObj != null)
        {
            result = true;
        }
    }
    
    return result;
}
	
function PositionMainProperty_Continue(objPOI)
{
    try
    {        
        if(IsMapOnPage())
        {
            gObjPOI = objPOI;
            if(objPOI && objPOI.InvalidPassport)
	        {
	            gObjPOI = null;
			    if(TheMap && TheMap.isMapVisible)
			    {
				    TheMap.HideOverLay();
				    TheMap.InvalidPassportReloadPage();
			    }
		        return;
	        }
    			
	        if(!objPOI)
	        {
	            gObjPOI = null;
	            TheMap.HideOverLay();
	            alert("Sorry. This address is currently not available.");
		        return;
	        }
    		
	        var oldMapCenter = TheMap.gMapSearchObj.GetCenter();
		    TheMap.SetCenterAndZoom(objPOI.Latitude, objPOI.Longitude);	    		
	        var newMapCenter = TheMap.gMapSearchObj.GetCenter();
	    }
	    
    }
	catch(ex)
	{
        LogErrorMessage("PositionMainProperty_Continue: ", ex);
	}
 }

function GetPinsByLatLong_Continue(objPoiResult)
{  
    try {
		        PopulatePinsOnMap(objPoiResult);
    }
	catch(ex)
	{
        LogErrorMessage("GetPinsByLatLong_Continue: ", ex);
	} 
}

function PopulatePinsOnMap(objPoiResult)
{
    try
    {
        if(IsMapOnPage())
        {            
            if (objPoiResult.AreaCenters == null || objPoiResult.AreaCenters.AreaType == 1) 
		    {
			    if((!TheMap.IsBirdEyeView() && (!TheMap.isMember || gIsGuestMember || gIsCancelledMember)) || (TheMap.isMember && !gIsGuestMember && !gIsCancelledMember))
			    {
			        TheMap.PinsOnMap.DrawPins(objPoiResult);
			    }
			    
			    var noSubjectPin = (!TheMap.IsBirdEyeView() && (!TheMap.isMember || gIsGuestMember || gIsCancelledMember));
			    //var Member = (TheMap.isMember && !gIsGuestMember && !gIsCancelledMember);
			    if((gSubjectPropertyID != null && noSubjectPin) || (gSubjectPropertyID != null && TheMap.isMember && !noSubjectPin))
		        {
			            TheMap.PinsOnMap.PopUpClass.isSubjectPopUp = true;
                        TheMap.PinsOnMap.MapSubjectPropPin();
		        }		            
		            
			    // ------------------ If we have a Porperty ID Parameter then 
			    if(TheMap.PinsOnMap.mainPropertyPinID != null && TheMap.PinsOnMap.mainPropertyID != null && TheMap.PinsOnMap.mainPropertyShown)
			    {
				    var pinParamters = TheMap.PinsOnMap.mainPropertyPinID.split('|');
				    if (pinParamters) {
				        //call the service
				        TheMap.PinsOnMap.PopUpClass.positionX = pinParamters[0];//posx
				        TheMap.PinsOnMap.PopUpClass.positionY = pinParamters[1];//posy
				        TheMap.PinsOnMap.PopUpClass.latitude = pinParamters[2];//lat
				        TheMap.PinsOnMap.PopUpClass.longitude = pinParamters[3];//lon
					    TheMap.GetPinPopUpInfo(pinParamters, ServResultPinPropType);			
				    }
			    }
		    }
		       
		    if(objPoiResult.AreaCenters != null && objPoiResult.AreaCenters.AreaCenter != null)
		    {
			     TheMap.PinsOnMap.PopUpClass.GroupedPopup(objPoiResult.AreaCenters.AreaType);
			 	 TheMap.PinsOnMap.DrawGroupedPins(objPoiResult);
		    }          
                if (TheMap.IsBirdEyeView()) 
			    {
				    
				    if(TheMap.PinsOnMap.PinsOnBirdEyeview != null)
				    {
				        SetCount(TheMap.PinsOnMap.PinsOnBirdEyeview, objPoiResult.PropertyCountToShow);
				    }
			    }
			    else 
			    {
				    SetCount(objPoiResult.RangeCount, objPoiResult.PropertyCountToShow);
			    }			
    			 
            TheMap.AttachEvents();
            TheMap.HideOverLay();
            TheMap.PinsOnMap.pinsDrawn = true;
            TheMap.isCreatingPinsOnMap = false;
        }
    }
    catch(ex)
	{
        //LogErrorMessage("PopulatePinsOnMap: ", ex);
	} 
}

//------------------------------------ PopUp Image handler ------------------------------------------

function SetImage(obj)
{
    try

    {
	    var imageDiv = document.getElementById('propertyImageDiv');
		
	    if(imageDiv)
	    {
		    imageDiv.src = obj.src;
	    }
	}
    catch(ex)
    {
        LogErrorMessage("SetImage: ", ex);
    }
}
	
	
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);
    }
}


//------------------------------------ Clustered Pins (polygons) ------------------------------------

function DrawAreaBorder(areaPoints)
{
    try
    {
	    if(TheMap.PinsOnMap)
		{	
			TheMap.PinsOnMap.ShowSelectedGroupedPin(areaPoints);
		}
    }
	catch(ex)
	{
        LogErrorMessage("DrawAreaBorder: ", ex, true);
	}
}

function GetStartAreaType()
{
    try
    {
        var areaType = GEO_AREA_TYPE_POI;
        
        if(IsMapOnPage())
        {
            if(!TheMap.IsBirdEyeView() && TheMap.gMapSearchObj.GetZoomLevel() <= GEO_SEARCH_NATIONAL_ZOOM_LEVEL)
            {
                areaType = GEO_AREA_TYPE_NATIONAL;
            }
        }
                        
        return areaType;
    }
	catch(ex)
	{
        LogErrorMessage("GetStartAreaType: ", ex, true);
	}
}

//------------------------------------- Menu Handlers ------------------------------------------------

function ToggleMapMenuDisplay(element)
{
    try

    {	
		if (TheMap) {
				TheMap.DeAttachEvents();				
				TheMap.MapMenu.ShowHideMenu();
				TheMap.MapMenu.OffsetBtnTogMenuMap();				
				TheMap.ResizeMapOnMenuShowHide();				
				TheMap.PinsOnMap.PopUpClass.RePosGroupedPopUp();
				TheMap.AttachEvents();				
			}			
    }
	catch(ex)
	{
        LogErrorMessage("ToggleMapMenuDisplay: ", ex);
	}
}

function OnCheckChanged()
{
    try

    {
        if(TheMap)
		{
			TheMap.StoreMapSettingsInSearchRequest();
        	TheMap.GetPinsByMapLatLon(GetPinsByLatLong_Continue);
		}
		
    }
	catch(ex)
	{
        LogErrorMessage("OnCheckChanged: ", ex);
	}
}

//MainProperty    SearchResult
function GetPropertyStatusByPropertyRecordType(propertyRecordType)
{
    try

    {
        switch(propertyRecordType)
        {
	        case 'D':		    
	        case 'L':		    
		        return 'P'; // pre-foreclosure
	        case 'R':
	            return 'B'; // REO		        
	        case 'T':
	        case 'S':
	            return 'A'; // auction
	        case 'F':
		        return 'F'; // FSBO
	        case 'M':
		        return 'R'; // resale
	        case 'G':
	            return 'G'; // government
	        case 'E':
	            return 'E'; // online auction
        }
    }
    catch(ex)
    {
        LogErrorMessage("GetPropertyStatusByPropertyRecordType: ", ex);
    }
}
  //MainProperty    SearchResult  
function GetPropertyTypeCheckboxByPropertyStatus(propertyStatus)
{
    try
    {
        return document.getElementById(gPropertyCheckboxBaseName + propertyStatus);
    }
    catch(ex)
    {
        LogErrorMessage("GetPropertyTypeCheckboxByPropertyStatus: ", ex);
    }
}
 

//------------------------------------- Disclaimer -----------------------------------------------

function ShowHideDisclaimer()
{
    try

    {
        var parentDiv = document.getElementById("mapNav_TooManyProperties");
        var disclaimer = document.getElementById("disclaimer");
        var sign = document.getElementById("sign");
        
        if(disclaimer.style.display == "block")
        {
            parentDiv.style.height = "140px";
            parentDiv.style.top = "170px";
            disclaimer.style.display = "none";
            sign.innerText = '+';
        }
        else
        {
            parentDiv.style.height = "350px";
            parentDiv.style.top = "100px";
            disclaimer.style.display = "block";
            sign.innerText = '-';
        }
    }
	catch(ex)
	{
        LogErrorMessage("ShowHideDisclaimer: ", ex, true);
	}
}


//-------------------------------------------------------------------------------------------------------//
//------------------------------ General functions ------------------------------------------------------//
//-------------------------------------------------------------------------------------------------------//

function RemoveUnderlineFromAnchors(divID){
    try {
        var currentElement = document.getElementById(divID);
        
        if (currentElement && currentElement.lastChild != null) {
            currentElement.lastChild.style.textDecoration = 'none';
        }
    } 
    catch (ex) {
        LogErrorMessage("RemoveUnderlineFromAnchors: ", ex);
    }
}

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 SetTrialUrl()
{
    try

    {
        var freeTrialLink = document.getElementById("getTrialLink");
		if(freeTrialLink)
		{
			freeTrialLink.href = g_NavigationEngine.RegistrationPage();
		}        
    }
	catch(ex)
	{
        LogErrorMessage("SetTrialUrl: ", ex, true);
	}
}

function SetCount(count, propertyCountToShow)
{
    try

    {
	    var elementPropertyCount = document.getElementById('propertyCount');
	    var elementMapNavTooMany = document.getElementById('mapNav_TooManyProperties');		
	    elementPropertyCount.innerHTML = AddCommas(count);
	    var disclaimer = document.getElementById("disclaimer");
	    if(TheMap)
		{
			TheMap.HideOverLay();
		}
    }
	catch(ex)
	{
        LogErrorMessage("SetCount: ", ex, true);
	}
}

function PopulateSEOFooter(seoLinks)
{        
    var divNearby = document.getElementById('divSeoLinks');
    
    if(!seoLinks || seoLinks.length < 3 || typeof(divNearby) == "undefined" || !divNearby)
    {
        return;
    }
    
    var cityLinks = seoLinks[0];
    var zipLinks = seoLinks[1];
    var propertyLinks = seoLinks[2];
    
    var context;
    context =  '<div id="divNearbyCities" class="col1">';
    context += '<h2>' + cityLinks.Heading + '</h2>';
    context += '<ul>';
    for(var i=0; i<cityLinks.Links.length; i++)
    {
        context += '<li><a href="' + cityLinks.Links[i].Url + '">' + cityLinks.Links[i].Text + '</a></li>';
    }
    context += '</ul>';
    context += '</div>';
    
    context +=  '<div id="divZips" class="col2">';
    context += '<h2>' + zipLinks.Heading + '</h2>';
    context += '<ul>';
    for(var i=0; i < zipLinks.Links.length; i++)
    {
        context += '<li><a href="' + zipLinks.Links[i].Url + '">' + zipLinks.Links[i].Text + '</a></li>';
    }
    context += '</ul>';
    context += '</div>';
    
    context +=  '<div id="divPropertyTypes" class="col3">';
    context += '<h2>' + propertyLinks.Heading + '</h2>';
    context += '<ul>';
    for(var i=0; i < propertyLinks.Links.length; i++)
    {
        context += '<li><a href="' + propertyLinks.Links[i].Url + '">' + propertyLinks.Links[i].Text + '</a></li>';
    }
    context += '</ul>';
    context += '</div>';
    
    divNearby.innerHTML = context;
}

//END RealtyTrac.Common.Web.Scripts.MapSearch.detailsmap.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
//START AjaxControlToolkit.RoundedCorners.RoundedCornersBehavior.js
Type.registerNamespace('AjaxControlToolkit');AjaxControlToolkit.BoxCorners = function() {
throw Error.invalidOperation();}
AjaxControlToolkit.BoxCorners.prototype = {
None : 0x00,
TopLeft : 0x01,
TopRight : 0x02,
BottomRight : 0x04,
BottomLeft : 0x08,
Top : 0x01 | 0x02,
Right : 0x02 | 0x04,
Bottom : 0x04 | 0x08,
Left : 0x08 | 0x01,
All : 0x01 | 0x02 | 0x04 | 0x08
}
AjaxControlToolkit.BoxCorners.registerEnum("AjaxControlToolkit.BoxCorners", true);AjaxControlToolkit.RoundedCornersBehavior = function(element) {
AjaxControlToolkit.RoundedCornersBehavior.initializeBase(this, [element]);this._corners = AjaxControlToolkit.BoxCorners.All;this._radius = 5;this._color = null;this._parentDiv = null;this._originalStyle = null;this._borderColor = null;}
AjaxControlToolkit.RoundedCornersBehavior.prototype = {
initialize : function() {
AjaxControlToolkit.RoundedCornersBehavior.callBaseMethod(this, 'initialize');this.buildParentDiv();},
dispose : function() {
this.disposeParentDiv();AjaxControlToolkit.RoundedCornersBehavior.callBaseMethod(this, 'dispose');},
buildParentDiv : function() {
var e = this.get_element();if (!e) return;this.disposeParentDiv();var color = this.getBackgroundColor();var originalWidth = e.offsetWidth;var newParent = e.cloneNode(false);this.moveChildren(e, newParent);this._originalStyle = e.style.cssText;e.style.backgroundColor = "transparent";e.style.verticalAlign = "top";e.style.padding = "0";e.style.overflow = "";e.style.className = "";if (e.style.height) {
e.style.height = parseInt($common.getCurrentStyle(e, 'height')) + (this._radius * 2) + "px";} else {
if (!e.style.width && (0 < originalWidth)) {
e.style.width = originalWidth + "px";}
}
newParent.style.position = "";newParent.style.border = "";newParent.style.margin = "";newParent.style.width = "100%";newParent.id = "";newParent.removeAttribute("control");if (this._borderColor) {
newParent.style.borderTopStyle = "none";newParent.style.borderBottomStyle = "none";newParent.style.borderLeftStyle = "solid";newParent.style.borderRightStyle = "solid";newParent.style.borderLeftColor = this._borderColor;newParent.style.borderRightColor = this._borderColor;newParent.style.borderLeftWidth = "1px";newParent.style.borderRightWidth = "1px";if (this._radius == 0) {
newParent.style.borderTopStyle = "solid";newParent.style.borderBottomStyle = "solid";newParent.style.borderTopColor = this._borderColor;newParent.style.borderBottomColor = this._borderColor;newParent.style.borderTopWidth = "1px";newParent.style.borderBottomWidth = "1px";}
} else {
newParent.style.borderTopStyle = "none";newParent.style.borderBottomStyle = "none";newParent.style.borderLeftStyle = "none";newParent.style.borderRightStyle = "none";}
var lastDiv = null;var radius = this._radius;var lines = this._radius;var lastDelta = 0;for (var i = lines;i > 0;i--) {
var angle = Math.acos(i / radius);var delta = radius - Math.round(Math.sin(angle) * radius);var newDiv = document.createElement("DIV");newDiv.__roundedDiv = true;newDiv.style.backgroundColor = color;newDiv.style.marginLeft = delta + "px";newDiv.style.marginRight = (delta - (this._borderColor ? 2 : 0)) + "px";newDiv.style.height = "1px";newDiv.style.fontSize = "1px";newDiv.style.overflow = "hidden";if (this._borderColor) {
newDiv.style.borderLeftStyle = "solid";newDiv.style.borderRightStyle = "solid";newDiv.style.borderLeftColor = this._borderColor;newDiv.style.borderRightColor = this._borderColor;var offset = Math.max(0, lastDelta - delta - 1);newDiv.style.borderLeftWidth = (offset + 1) + "px";newDiv.style.borderRightWidth = (offset + 1) + "px";if (i == lines) {
newDiv.__roundedDivNoBorder = true;newDiv.style.backgroundColor = this._borderColor;}
}
e.insertBefore(newDiv, lastDiv);var topDiv = newDiv;newDiv = newDiv.cloneNode(true);newDiv.__roundedDiv = true;e.insertBefore(newDiv, lastDiv);var bottomDiv = newDiv;lastDiv = newDiv;lastDelta = delta;if (!this.isCornerSet(AjaxControlToolkit.BoxCorners.TopLeft)) {
topDiv.style.marginLeft = "0";if (this._borderColor) {
topDiv.style.borderLeftWidth = "1px";}
}
if (!this.isCornerSet(AjaxControlToolkit.BoxCorners.TopRight)) {
topDiv.style.marginRight = "0";if (this._borderColor) {
topDiv.style.borderRightWidth = "1px";topDiv.style.marginRight = "-2px";}
}
if (!this.isCornerSet(AjaxControlToolkit.BoxCorners.BottomLeft)) {
bottomDiv.style.marginLeft = "0";if (this._borderColor) {
bottomDiv.style.borderLeftWidth = "1px";}
}
if (!this.isCornerSet(AjaxControlToolkit.BoxCorners.BottomRight)) {
bottomDiv.style.marginRight = "0";if (this._borderColor) {
bottomDiv.style.borderRightWidth = "1px";bottomDiv.style.marginRight = "-2px";}
}
}
e.insertBefore(newParent, lastDiv);this._parentDiv = newParent;},
disposeParentDiv : function() {
if (this._parentDiv) {
var e = this.get_element();var children = e.childNodes;for (var i = children.length - 1;i >=0;i--) {
var child = children[i];if (child) {
if (child == this._parentDiv) {
this.moveChildren(child, e);}
try {
e.removeChild(child);} catch(e) {
}
}
}
if (this._originalStyle) {
e.style.cssText = this._originalStyle;this._originalStyle = null;}
this._parentDiv = null;}
},
getBackgroundColor : function() {
if (this._color) {
return this._color;}
return $common.getCurrentStyle(this.get_element(), 'backgroundColor');},
moveChildren : function(src, dest) {
var moveCount = 0;while (src.hasChildNodes()) {
var child = src.childNodes[0];child = src.removeChild(child);dest.appendChild(child);moveCount++;}
return moveCount;},
isCornerSet : function(corner) {
return (this._corners & corner) != AjaxControlToolkit.BoxCorners.None;},
setCorner : function(corner, value) {
if (value) {
this.set_Corners(this._corners | corner);} else {
this.set_Corners(this._corners & ~corner);}
},
get_Color : function() {
return this._color;},
set_Color : function(value) {
if (value != this._color) {
this._color = value;this.buildParentDiv();this.raisePropertyChanged('Color');}
},
get_Radius : function() {
return this._radius;},
set_Radius : function(value) {
if (value != this._radius) {
this._radius = value;this.buildParentDiv();this.raisePropertyChanged('Radius');}
},
get_Corners : function() {
return this._corners;},
set_Corners : function(value) {
if (value != this._corners) {
this._corners = value;this.buildParentDiv();this.raisePropertyChanged("Corners");}
},
get_BorderColor : function() {
return this._borderColor;},
set_BorderColor : function(value) {
if (value != this._borderColor) {
this._borderColor = value;this.buildParentDiv();this.raisePropertyChanged("BorderColor");}
}
}
AjaxControlToolkit.RoundedCornersBehavior.registerClass('AjaxControlToolkit.RoundedCornersBehavior', AjaxControlToolkit.BehaviorBase);
//END AjaxControlToolkit.RoundedCorners.RoundedCornersBehavior.js
//START AjaxControlToolkit.DropShadow.DropShadowBehavior.js
Type.registerNamespace('AjaxControlToolkit');AjaxControlToolkit.DropShadowBehavior = function(element) {
AjaxControlToolkit.DropShadowBehavior.initializeBase(this, [element]);this._opacity = 1.0;this._width = 5;this._shadowDiv = null;this._trackPosition = null;this._trackPositionDelay = 50;this._timer = null;this._tickHandler = null;this._roundedBehavior = null;this._shadowRoundedBehavior = null;this._rounded = false;this._radius = 5;this._lastX = null;this._lastY = null;this._lastW = null;this._lastH = null;}
AjaxControlToolkit.DropShadowBehavior.prototype = {
initialize : function() {
AjaxControlToolkit.DropShadowBehavior.callBaseMethod(this, 'initialize');var e = this.get_element();if ($common.getCurrentStyle(e, 'position', e.style.position) != "absolute") {
e.style.position = "relative";}
if (this._rounded) {
this.setupRounded();}
if (this._trackPosition) {
this.startTimer();}
this.setShadow();},
dispose : function() {
this.stopTimer();this.disposeShadowDiv();AjaxControlToolkit.DropShadowBehavior.callBaseMethod(this, 'dispose');},
buildShadowDiv : function() {
var e = this.get_element();if (!this.get_isInitialized() || !e || !this._width) return;var div = document.createElement("DIV");div.style.backgroundColor = "black";div.style.position= "absolute";if (e.id) {
div.id = e.id + "_DropShadow";}
this._shadowDiv = div;e.parentNode.appendChild(div);if (this._rounded ) {
this._shadowDiv.style.height = Math.max(0, e.offsetHeight - (2*this._radius)) + "px";if (!this._shadowRoundedBehavior) {
this._shadowRoundedBehavior = $create(AjaxControlToolkit.RoundedCornersBehavior, {"Radius": this._radius}, null, null, this._shadowDiv);} else {
this._shadowRoundedBehavior.set_Radius(this._radius);}
} else if (this._shadowRoundedBehavior) {
this._shadowRoundedBehavior.set_Radius(0);}
if (this._opacity != 1.0) {
this.setupOpacity();}
this.setShadow(false, true);this.updateZIndex();},
disposeShadowDiv : function() {
if (this._shadowDiv) {
if (this._shadowDiv.parentNode) {
this._shadowDiv.parentNode.removeChild(this._shadowDiv);} 
this._shadowDiv = null;}
if (this._shadowRoundedBehavior) {
this._shadowRoundedBehavior.dispose();this._shadowRoundedBehavior = null;}
},
onTimerTick : function() {
this.setShadow();},
startTimer : function() {
if (!this._timer) {
if (!this._tickHandler) {
this._tickHandler = Function.createDelegate(this, this.onTimerTick);}
this._timer = new Sys.Timer();this._timer.set_interval(this._trackPositionDelay);this._timer.add_tick(this._tickHandler);this._timer.set_enabled(true);}
},
stopTimer : function() {
if (this._timer) {
this._timer.remove_tick(this._tickHandler);this._timer.set_enabled(false);this._timer.dispose();this._timer = null;}
},
setShadow : function(force, norecurse) {
var e = this.get_element();if (!this.get_isInitialized() || !e || (!this._width && !force)) return;var existingShadow = this._shadowDiv;if (!existingShadow) {
this.buildShadowDiv();}
var location = $common.getLocation(e);if (force || this._lastX != location.x || this._lastY != location.y || !existingShadow) {
this._lastX = location.x;this._lastY = location.y;var w = this.get_Width();if((e.parentNode.style.position == "absolute") || (e.parentNode.style.position == "fixed") )
{
location.x = w;location.y = w;}
else if (e.parentNode.style.position == "relative")
{
location.x = w;var paddingTop = e.parentNode.style.paddingTop;paddingTop = paddingTop.replace("px", "");var intPaddingTop = 0;intPaddingTop = parseInt(paddingTop);location.y = w + intPaddingTop;}
else
{
location.x += w;location.y += w;}
$common.setLocation(this._shadowDiv, location);}
var h = e.offsetHeight;var w = e.offsetWidth;if (force || h != this._lastH || w != this._lastW || !existingShadow) {
this._lastW = w;this._lastH = h;if (!this._rounded || !existingShadow || norecurse) {
this._shadowDiv.style.width = w + "px";this._shadowDiv.style.height = h + "px";} else {
this.disposeShadowDiv();this.setShadow();}
}
if (this._shadowDiv) {
this._shadowDiv.style.visibility = $common.getCurrentStyle(e, 'visibility');}
},
setupOpacity : function() {
if (this.get_isInitialized() && this._shadowDiv) {
$common.setElementOpacity(this._shadowDiv, this._opacity);}
},
setupRounded : function() {
if (!this._roundedBehavior && this._rounded) {
this._roundedBehavior = $create(AjaxControlToolkit.RoundedCornersBehavior, null, null, null, this.get_element());}
if (this._roundedBehavior) {
this._roundedBehavior.set_Radius(this._rounded ? this._radius : 0);}
},
updateZIndex : function() {
if (!this._shadowDiv) return;var e = this.get_element();var targetZIndex = e.style.zIndex;var shadowZIndex = this._shadowDiv.style.zIndex;if (shadowZIndex && targetZIndex && targetZIndex > shadowZIndex) {
return;} else {
targetZIndex = Math.max(2, targetZIndex);shadowZIndex = targetZIndex - 1;}
e.style.zIndex = targetZIndex;this._shadowDiv.style.zIndex = shadowZIndex;},
updateRoundedCorners : function() {
if (this.get_isInitialized()) {
this.setupRounded();this.disposeShadowDiv();this.setShadow();}
},
get_Opacity : function() {
return this._opacity;},
set_Opacity : function(value) {
if (this._opacity != value) {
this._opacity = value;this.setupOpacity();this.raisePropertyChanged('Opacity');}
},
get_Rounded : function() {
return this._rounded;},
set_Rounded : function(value) {
if (value != this._rounded) {
this._rounded = value;this.updateRoundedCorners();this.raisePropertyChanged('Rounded');}
},
get_Radius : function() {
return this._radius;},
set_Radius : function(value) {
if (value != this._radius) {
this._radius = value;this.updateRoundedCorners();this.raisePropertyChanged('Radius');}
},
get_Width : function() {
return this._width;},
set_Width : function(value) {
if (value != this._width) {
this._width = value;if (this._shadowDiv) {
$common.setVisible(this._shadowDiv, value > 0);}
this.setShadow(true);this.raisePropertyChanged('Width');}
},
get_TrackPositionDelay : function() {
return this._trackPositionDelay;},
set_TrackPositionDelay : function(value) {
if (value != this._trackPositionDelay) {
this._trackPositionDelay = value;if (this._trackPosition) {
this.stopTimer();this.startTimer();}
this.raisePropertyChanged('TrackPositionDelay');}
},
get_TrackPosition : function() {
return this._trackPosition;},
set_TrackPosition : function(value) {
if (value != this._trackPosition) {
this._trackPosition = value;if (this.get_element()) {
if (value) {
this.startTimer();} else {
this.stopTimer();}
}
this.raisePropertyChanged('TrackPosition');}
}
}
AjaxControlToolkit.DropShadowBehavior.registerClass('AjaxControlToolkit.DropShadowBehavior', AjaxControlToolkit.BehaviorBase);
//END AjaxControlToolkit.DropShadow.DropShadowBehavior.js
//START AjaxControlToolkit.DynamicPopulate.DynamicPopulateBehavior.js
Type.registerNamespace('AjaxControlToolkit');AjaxControlToolkit.DynamicPopulateBehavior = function(element) {
AjaxControlToolkit.DynamicPopulateBehavior.initializeBase(this, [element]);this._servicePath = null;this._serviceMethod = null;this._contextKey = null;this._cacheDynamicResults = false;this._populateTriggerID = null;this._setUpdatingCssClass = null;this._clearDuringUpdate = true;this._customScript = null;this._clickHandler = null;this._callID = 0;this._currentCallID = -1;this._populated = false;}
AjaxControlToolkit.DynamicPopulateBehavior.prototype = {
initialize : function() {
AjaxControlToolkit.DynamicPopulateBehavior.callBaseMethod(this, 'initialize');$common.prepareHiddenElementForATDeviceUpdate();if (this._populateTriggerID) {
var populateTrigger = $get(this._populateTriggerID);if (populateTrigger) {
this._clickHandler = Function.createDelegate(this, this._onPopulateTriggerClick);$addHandler(populateTrigger, "click", this._clickHandler);}
}
},
dispose : function() {
if (this._populateTriggerID && this._clickHandler) {
var populateTrigger = $get(this._populateTriggerID);if (populateTrigger) {
$removeHandler(populateTrigger, "click", this._clickHandler);}
this._populateTriggerID = null;this._clickHandler = null;}
AjaxControlToolkit.DynamicPopulateBehavior.callBaseMethod(this, 'dispose');},
populate : function(contextKey) {
if (this._populated && this._cacheDynamicResults) {
return;}
if (this._currentCallID == -1) {
var eventArgs = new Sys.CancelEventArgs();this.raisePopulating(eventArgs);if (eventArgs.get_cancel()) {
return;}
this._setUpdating(true);}
if (this._customScript) {
var scriptResult = eval(this._customScript);this.get_element().innerHTML = scriptResult;this._setUpdating(false);} else {
this._currentCallID = ++this._callID;if (this._servicePath && this._serviceMethod) {
Sys.Net.WebServiceProxy.invoke(this._servicePath, this._serviceMethod, false,
{ contextKey:(contextKey ? contextKey : this._contextKey) },
Function.createDelegate(this, this._onMethodComplete), Function.createDelegate(this, this._onMethodError),
this._currentCallID);$common.updateFormToRefreshATDeviceBuffer();}
}
},
_onMethodComplete : function (result, userContext, methodName) {
if (userContext != this._currentCallID) return;var e = this.get_element();if (e) {
e.innerHTML = result;}
this._setUpdating(false);},
_onMethodError : function(webServiceError, userContext, methodName) {
if (userContext != this._currentCallID) return;var e = this.get_element();if (e) {
if (webServiceError.get_timedOut()) {
e.innerHTML = AjaxControlToolkit.Resources.DynamicPopulate_WebServiceTimeout;} else {
e.innerHTML = String.format(AjaxControlToolkit.Resources.DynamicPopulate_WebServiceError, webServiceError.get_statusCode());}
}
this._setUpdating(false);},
_onPopulateTriggerClick : function() {
this.populate(this._contextKey);},
_setUpdating : function(updating) {
this.setStyle(updating);if (!updating) {
this._currentCallID = -1;this._populated = true;this.raisePopulated(this, Sys.EventArgs.Empty);}
},
setStyle : function(updating) {
var e = this.get_element();if (this._setUpdatingCssClass) {
if (!updating) {
e.className = this._oldCss;this._oldCss = null;} else {
this._oldCss = e.className;e.className = this._setUpdatingCssClass;}
}
if (updating && this._clearDuringUpdate) {
e.innerHTML = "";}
},
get_ClearContentsDuringUpdate : function() {
return this._clearDuringUpdate;},
set_ClearContentsDuringUpdate : function(value) {
if (this._clearDuringUpdate != value) {
this._clearDuringUpdate = value;this.raisePropertyChanged('ClearContentsDuringUpdate');}
},
get_ContextKey : function() {
return this._contextKey;},
set_ContextKey : function(value) {
if (this._contextKey != value) {
this._contextKey = value;this.raisePropertyChanged('ContextKey');}
},
get_PopulateTriggerID : function() {
return this._populateTriggerID;},
set_PopulateTriggerID : function(value) {
if (this._populateTriggerID != value) {
this._populateTriggerID = value;this.raisePropertyChanged('PopulateTriggerID');}
},
get_ServicePath : function() {
return this._servicePath;},
set_ServicePath : function(value) {
if (this._servicePath != value) {
this._servicePath = value;this.raisePropertyChanged('ServicePath');}
},
get_ServiceMethod : function() {
return this._serviceMethod;},
set_ServiceMethod : function(value) {
if (this._serviceMethod != value) {
this._serviceMethod = value;this.raisePropertyChanged('ServiceMethod');}
},
get_cacheDynamicResults : function() {
return this._cacheDynamicResults;},
set_cacheDynamicResults : function(value) {
if (this._cacheDynamicResults != value) {
this._cacheDynamicResults = value;this.raisePropertyChanged('cacheDynamicResults');}
},
get_UpdatingCssClass : function() {
return this._setUpdatingCssClass;},
set_UpdatingCssClass : function(value) {
if (this._setUpdatingCssClass != value) {
this._setUpdatingCssClass = value;this.raisePropertyChanged('UpdatingCssClass');}
},
get_CustomScript : function() {
return this._customScript;}, 
set_CustomScript : function(value) {
if (this._customScript != value) {
this._customScript = value;this.raisePropertyChanged('CustomScript');}
},
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);}
}
}
AjaxControlToolkit.DynamicPopulateBehavior.registerClass('AjaxControlToolkit.DynamicPopulateBehavior', AjaxControlToolkit.BehaviorBase);
//END AjaxControlToolkit.DynamicPopulate.DynamicPopulateBehavior.js
//START AjaxControlToolkit.Compat.DragDrop.DragDropScripts.js
/////////////////////////////////////////////////////////////////////////////
Type.registerNamespace('AjaxControlToolkit');AjaxControlToolkit.IDragSource = function() {
}
AjaxControlToolkit.IDragSource.prototype = {
get_dragDataType: function() { throw Error.notImplemented();},
getDragData: function() { throw Error.notImplemented();},
get_dragMode: function() { throw Error.notImplemented();},
onDragStart: function() { throw Error.notImplemented();},
onDrag: function() { throw Error.notImplemented();},
onDragEnd: function() { throw Error.notImplemented();}
}
AjaxControlToolkit.IDragSource.registerInterface('AjaxControlToolkit.IDragSource');/////////////////////////////////////////////////////////////////////////////
AjaxControlToolkit.IDropTarget = function() {
}
AjaxControlToolkit.IDropTarget.prototype = {
get_dropTargetElement: function() { throw Error.notImplemented();},
canDrop: function() { throw Error.notImplemented();},
drop: function() { throw Error.notImplemented();},
onDragEnterTarget: function() { throw Error.notImplemented();},
onDragLeaveTarget: function() { throw Error.notImplemented();},
onDragInTarget: function() { throw Error.notImplemented();}
}
AjaxControlToolkit.IDropTarget.registerInterface('AjaxControlToolkit.IDropTarget');/////////////////////////////////////////////
AjaxControlToolkit.DragMode = function() {
throw Error.invalidOperation();}
AjaxControlToolkit.DragMode.prototype = {
Copy: 0,
Move: 1
}
AjaxControlToolkit.DragMode.registerEnum('AjaxControlToolkit.DragMode');//////////////////////////////////////////////////////////////////
AjaxControlToolkit.DragDropEventArgs = function(dragMode, dragDataType, dragData) {
this._dragMode = dragMode;this._dataType = dragDataType;this._data = dragData;}
AjaxControlToolkit.DragDropEventArgs.prototype = {
get_dragMode: function() {
return this._dragMode || null;},
get_dragDataType: function() {
return this._dataType || null;},
get_dragData: function() {
return this._data || null;}
}
AjaxControlToolkit.DragDropEventArgs.registerClass('AjaxControlToolkit.DragDropEventArgs');AjaxControlToolkit._DragDropManager = function() {
this._instance = null;this._events = null;}
AjaxControlToolkit._DragDropManager.prototype = {
add_dragStart: function(handler) {
this.get_events().addHandler('dragStart', handler);},
remove_dragStart: function(handler) {
this.get_events().removeHandler('dragStart', handler);},
get_events: function() {
if (!this._events) {
this._events = new Sys.EventHandlerList();}
return this._events;},
add_dragStop: function(handler) {
this.get_events().addHandler('dragStop', handler);},
remove_dragStop: function(handler) {
this.get_events().removeHandler('dragStop', handler);},
_getInstance: function() {
if (!this._instance) {
if (Sys.Browser.agent === Sys.Browser.InternetExplorer) {
this._instance = new AjaxControlToolkit.IEDragDropManager();}
else {
this._instance = new AjaxControlToolkit.GenericDragDropManager();}
this._instance.initialize();this._instance.add_dragStart(Function.createDelegate(this, this._raiseDragStart));this._instance.add_dragStop(Function.createDelegate(this, this._raiseDragStop));}
return this._instance;},
startDragDrop: function(dragSource, dragVisual, context) {
this._getInstance().startDragDrop(dragSource, dragVisual, context);},
registerDropTarget: function(target) {
this._getInstance().registerDropTarget(target);},
unregisterDropTarget: function(target) {
this._getInstance().unregisterDropTarget(target);},
dispose: function() {
delete this._events;Sys.Application.unregisterDisposableObject(this);Sys.Application.removeComponent(this);},
_raiseDragStart: function(sender, eventArgs) {
var handler = this.get_events().getHandler('dragStart');if(handler) {
handler(this, eventArgs);}
},
_raiseDragStop: function(sender, eventArgs) {
var handler = this.get_events().getHandler('dragStop');if(handler) {
handler(this, eventArgs);}
}
}
AjaxControlToolkit._DragDropManager.registerClass('AjaxControlToolkit._DragDropManager');AjaxControlToolkit.DragDropManager = new AjaxControlToolkit._DragDropManager();AjaxControlToolkit.IEDragDropManager = function() {
AjaxControlToolkit.IEDragDropManager.initializeBase(this);this._dropTargets = null;this._radius = 10;this._activeDragVisual = null;this._activeContext = null;this._activeDragSource = null;this._underlyingTarget = null;this._oldOffset = null;this._potentialTarget = null;this._isDragging = false;this._mouseUpHandler = null;this._documentMouseMoveHandler = null;this._documentDragOverHandler = null;this._dragStartHandler = null;this._mouseMoveHandler = null;this._dragEnterHandler = null;this._dragLeaveHandler = null;this._dragOverHandler = null;this._dropHandler = null;}
AjaxControlToolkit.IEDragDropManager.prototype = {
add_dragStart : function(handler) {
this.get_events().addHandler("dragStart", handler);},
remove_dragStart : function(handler) {
this.get_events().removeHandler("dragStart", handler);},
add_dragStop : function(handler) {
this.get_events().addHandler("dragStop", handler);},
remove_dragStop : function(handler) {
this.get_events().removeHandler("dragStop", handler);},
initialize : function() {
AjaxControlToolkit.IEDragDropManager.callBaseMethod(this, 'initialize');this._mouseUpHandler = Function.createDelegate(this, this._onMouseUp);this._documentMouseMoveHandler = Function.createDelegate(this, this._onDocumentMouseMove);this._documentDragOverHandler = Function.createDelegate(this, this._onDocumentDragOver);this._dragStartHandler = Function.createDelegate(this, this._onDragStart);this._mouseMoveHandler = Function.createDelegate(this, this._onMouseMove);this._dragEnterHandler = Function.createDelegate(this, this._onDragEnter);this._dragLeaveHandler = Function.createDelegate(this, this._onDragLeave);this._dragOverHandler = Function.createDelegate(this, this._onDragOver);this._dropHandler = Function.createDelegate(this, this._onDrop);},
dispose : function() {
if(this._dropTargets) {
for (var i = 0;i < this._dropTargets;i++) {
this.unregisterDropTarget(this._dropTargets[i]);}
this._dropTargets = null;}
AjaxControlToolkit.IEDragDropManager.callBaseMethod(this, 'dispose');},
startDragDrop : function(dragSource, dragVisual, context) {
var ev = window._event;if (this._isDragging) {
return;}
this._underlyingTarget = null;this._activeDragSource = dragSource;this._activeDragVisual = dragVisual;this._activeContext = context;var mousePosition = { x: ev.clientX, y: ev.clientY };dragVisual.originalPosition = dragVisual.style.position;dragVisual.style.position = "absolute";document._lastPosition = mousePosition;dragVisual.startingPoint = mousePosition;var scrollOffset = this.getScrollOffset(dragVisual,  true);dragVisual.startingPoint = this.addPoints(dragVisual.startingPoint, scrollOffset);if (dragVisual.style.position == "absolute") {
dragVisual.startingPoint = this.subtractPoints(dragVisual.startingPoint, $common.getLocation(dragVisual));}
else {
var left = parseInt(dragVisual.style.left);var top = parseInt(dragVisual.style.top);if (isNaN(left)) left = "0";if (isNaN(top)) top = "0";dragVisual.startingPoint = this.subtractPoints(dragVisual.startingPoint, { x: left, y: top });}
this._prepareForDomChanges();dragSource.onDragStart();var eventArgs = new AjaxControlToolkit.DragDropEventArgs(
dragSource.get_dragMode(),
dragSource.get_dragDataType(),
dragSource.getDragData(context));var handler = this.get_events().getHandler('dragStart');if(handler) handler(this,eventArgs);this._recoverFromDomChanges();this._wireEvents();this._drag( true);},
_stopDragDrop : function(cancelled) {
var ev = window._event;if (this._activeDragSource != null) {
this._unwireEvents();if (!cancelled) {
cancelled = (this._underlyingTarget == null);}
if (!cancelled && this._underlyingTarget != null) {
this._underlyingTarget.drop(this._activeDragSource.get_dragMode(), this._activeDragSource.get_dragDataType(),
this._activeDragSource.getDragData(this._activeContext));}
this._activeDragSource.onDragEnd(cancelled);var handler = this.get_events().getHandler('dragStop');if(handler) handler(this,Sys.EventArgs.Empty);this._activeDragVisual.style.position = this._activeDragVisual.originalPosition;this._activeDragSource = null;this._activeContext = null;this._activeDragVisual = null;this._isDragging = false;this._potentialTarget = null;ev.preventDefault();}
},
_drag : function(isInitialDrag) {
var ev = window._event;var mousePosition = { x: ev.clientX, y: ev.clientY };document._lastPosition = mousePosition;var scrollOffset = this.getScrollOffset(this._activeDragVisual,  true);var position = this.addPoints(this.subtractPoints(mousePosition, this._activeDragVisual.startingPoint), scrollOffset);if (!isInitialDrag && parseInt(this._activeDragVisual.style.left) == position.x && parseInt(this._activeDragVisual.style.top) == position.y) {
return;}
$common.setLocation(this._activeDragVisual, position);this._prepareForDomChanges();this._activeDragSource.onDrag();this._recoverFromDomChanges();this._potentialTarget = this._findPotentialTarget(this._activeDragSource, this._activeDragVisual);var movedToOtherTarget = (this._potentialTarget != this._underlyingTarget || this._potentialTarget == null);if (movedToOtherTarget && this._underlyingTarget != null) {
this._leaveTarget(this._activeDragSource, this._underlyingTarget);}
if (this._potentialTarget != null) {
if (movedToOtherTarget) {
this._underlyingTarget = this._potentialTarget;this._enterTarget(this._activeDragSource, this._underlyingTarget);}
else {
this._moveInTarget(this._activeDragSource, this._underlyingTarget);}
}
else {
this._underlyingTarget = null;}
},
_wireEvents : function() {
$addHandler(document, "mouseup", this._mouseUpHandler);$addHandler(document, "mousemove", this._documentMouseMoveHandler);$addHandler(document.body, "dragover", this._documentDragOverHandler);$addHandler(this._activeDragVisual, "dragstart", this._dragStartHandler);$addHandler(this._activeDragVisual, "dragend", this._mouseUpHandler);$addHandler(this._activeDragVisual, "drag", this._mouseMoveHandler);},
_unwireEvents : function() {
$removeHandler(this._activeDragVisual, "drag", this._mouseMoveHandler);$removeHandler(this._activeDragVisual, "dragend", this._mouseUpHandler);$removeHandler(this._activeDragVisual, "dragstart", this._dragStartHandler);$removeHandler(document.body, "dragover", this._documentDragOverHandler);$removeHandler(document, "mousemove", this._documentMouseMoveHandler);$removeHandler(document, "mouseup", this._mouseUpHandler);},
registerDropTarget : function(dropTarget) {
if (this._dropTargets == null) {
this._dropTargets = [];}
Array.add(this._dropTargets, dropTarget);this._wireDropTargetEvents(dropTarget);},
unregisterDropTarget : function(dropTarget) {
this._unwireDropTargetEvents(dropTarget);if (this._dropTargets) {
Array.remove(this._dropTargets, dropTarget);}
},
_wireDropTargetEvents : function(dropTarget) {
var associatedElement = dropTarget.get_dropTargetElement();associatedElement._dropTarget = dropTarget;$addHandler(associatedElement, "dragenter", this._dragEnterHandler);$addHandler(associatedElement, "dragleave", this._dragLeaveHandler);$addHandler(associatedElement, "dragover", this._dragOverHandler);$addHandler(associatedElement, "drop", this._dropHandler);},
_unwireDropTargetEvents : function(dropTarget) {
var associatedElement = dropTarget.get_dropTargetElement();if(associatedElement._dropTarget)
{
associatedElement._dropTarget = null;$removeHandler(associatedElement, "dragenter", this._dragEnterHandler);$removeHandler(associatedElement, "dragleave", this._dragLeaveHandler);$removeHandler(associatedElement, "dragover", this._dragOverHandler);$removeHandler(associatedElement, "drop", this._dropHandler);}
},
_onDragStart : function(ev) {
window._event = ev;document.selection.empty();var dt = ev.dataTransfer;if(!dt && ev.rawEvent) dt = ev.rawEvent.dataTransfer;var dataType = this._activeDragSource.get_dragDataType().toLowerCase();var data = this._activeDragSource.getDragData(this._activeContext);if (data) {
if (dataType != "text" && dataType != "url") {
dataType = "text";if (data.innerHTML != null) {
data = data.innerHTML;}
}
dt.effectAllowed = "move";dt.setData(dataType, data.toString());}
},
_onMouseUp : function(ev) {
window._event = ev;this._stopDragDrop(false);},
_onDocumentMouseMove : function(ev) {
window._event = ev;this._dragDrop();},
_onDocumentDragOver : function(ev) {
window._event = ev;if(this._potentialTarget) ev.preventDefault();},
_onMouseMove : function(ev) {
window._event = ev;this._drag();},
_onDragEnter : function(ev) {
window._event = ev;if (this._isDragging) {
ev.preventDefault();}
else {
var dataObjects = AjaxControlToolkit.IEDragDropManager._getDataObjectsForDropTarget(this._getDropTarget(ev.target));for (var i = 0;i < dataObjects.length;i++) {
this._dropTarget.onDragEnterTarget(AjaxControlToolkit.DragMode.Copy, dataObjects[i].type, dataObjects[i].value);}
}
},
_onDragLeave : function(ev) {
window._event = ev;if (this._isDragging) {
ev.preventDefault();}
else {
var dataObjects = AjaxControlToolkit.IEDragDropManager._getDataObjectsForDropTarget(this._getDropTarget(ev.target));for (var i = 0;i < dataObjects.length;i++) {
this._dropTarget.onDragLeaveTarget(AjaxControlToolkit.DragMode.Copy, dataObjects[i].type, dataObjects[i].value);}
}
},
_onDragOver : function(ev) {
window._event = ev;if (this._isDragging) {
ev.preventDefault();}
else {
var dataObjects = AjaxControlToolkit.IEDragDropManager._getDataObjectsForDropTarget(this._getDropTarget(ev.target));for (var i = 0;i < dataObjects.length;i++) {
this._dropTarget.onDragInTarget(AjaxControlToolkit.DragMode.Copy, dataObjects[i].type, dataObjects[i].value);}
}
},
_onDrop : function(ev) {
window._event = ev;if (!this._isDragging) {
var dataObjects = AjaxControlToolkit.IEDragDropManager._getDataObjectsForDropTarget(this._getDropTarget(ev.target));for (var i = 0;i < dataObjects.length;i++) {
this._dropTarget.drop(AjaxControlToolkit.DragMode.Copy, dataObjects[i].type, dataObjects[i].value);}
}
ev.preventDefault();},
_getDropTarget : function(element) {
while (element) {
if (element._dropTarget != null) {
return element._dropTarget;}
element = element.parentNode;}
return null;},
_dragDrop : function() {
if (this._isDragging) {
return;}
this._isDragging = true;this._activeDragVisual.dragDrop();document.selection.empty();},
_moveInTarget : function(dragSource, dropTarget) {
this._prepareForDomChanges();dropTarget.onDragInTarget(dragSource.get_dragMode(), dragSource.get_dragDataType(), dragSource.getDragData(this._activeContext));this._recoverFromDomChanges();},
_enterTarget : function(dragSource, dropTarget) {
this._prepareForDomChanges();dropTarget.onDragEnterTarget(dragSource.get_dragMode(), dragSource.get_dragDataType(), dragSource.getDragData(this._activeContext));this._recoverFromDomChanges();},
_leaveTarget : function(dragSource, dropTarget) {
this._prepareForDomChanges();dropTarget.onDragLeaveTarget(dragSource.get_dragMode(), dragSource.get_dragDataType(), dragSource.getDragData(this._activeContext));this._recoverFromDomChanges();},
_findPotentialTarget : function(dragSource, dragVisual) {
var ev = window._event;if (this._dropTargets == null) {
return null;}
var type = dragSource.get_dragDataType();var mode = dragSource.get_dragMode();var data = dragSource.getDragData(this._activeContext);var scrollOffset = this.getScrollOffset(document.body,  true);var x = ev.clientX + scrollOffset.x;var y = ev.clientY + scrollOffset.y;var cursorRect = { x: x - this._radius, y: y - this._radius, width: this._radius * 2, height: this._radius * 2 };var targetRect;for (var i = 0;i < this._dropTargets.length;i++) {
targetRect = $common.getBounds(this._dropTargets[i].get_dropTargetElement());if ($common.overlaps(cursorRect, targetRect) && this._dropTargets[i].canDrop(mode, type, data)) {
return this._dropTargets[i];}
}
return null;},
_prepareForDomChanges : function() {
this._oldOffset = $common.getLocation(this._activeDragVisual);},
_recoverFromDomChanges : function() {
var newOffset = $common.getLocation(this._activeDragVisual);if (this._oldOffset.x != newOffset.x || this._oldOffset.y != newOffset.y) {
this._activeDragVisual.startingPoint = this.subtractPoints(this._activeDragVisual.startingPoint, this.subtractPoints(this._oldOffset, newOffset));scrollOffset = this.getScrollOffset(this._activeDragVisual,  true);var position = this.addPoints(this.subtractPoints(document._lastPosition, this._activeDragVisual.startingPoint), scrollOffset);$common.setLocation(this._activeDragVisual, position);}
},
addPoints : function(p1, p2) {
return { x: p1.x + p2.x, y: p1.y + p2.y };},
subtractPoints : function(p1, p2) {
return { x: p1.x - p2.x, y: p1.y - p2.y };},
getScrollOffset : function(element, recursive) {
var left = element.scrollLeft;var top = element.scrollTop;if (recursive) {
var parent = element.parentNode;while (parent != null && parent.scrollLeft != null) {
left += parent.scrollLeft;top += parent.scrollTop;if (parent == document.body && (left != 0 && top != 0))
break;parent = parent.parentNode;}
}
return { x: left, y: top };},
getBrowserRectangle : function() {
var width = window.innerWidth;var height = window.innerHeight;if (width == null) {
width = document.body.clientWidth;}
if (height == null) {
height = document.body.clientHeight;}
return { x: 0, y: 0, width: width, height: height };},
getNextSibling : function(item) {
for (item = item.nextSibling;item != null;item = item.nextSibling) {
if (item.innerHTML != null) {
return item;}
}
return null;},
hasParent : function(element) {
return (element.parentNode != null && element.parentNode.tagName != null);}
}
AjaxControlToolkit.IEDragDropManager.registerClass('AjaxControlToolkit.IEDragDropManager', Sys.Component);AjaxControlToolkit.IEDragDropManager._getDataObjectsForDropTarget = function(dropTarget) {
if (dropTarget == null) {
return [];}
var ev = window._event;var dataObjects = [];var dataTypes = [ "URL", "Text" ];var data;for (var i = 0;i < dataTypes.length;i++) {
var dt = ev.dataTransfer;if(!dt && ev.rawEvent) dt = ev.rawEvent.dataTransfer;data = dt.getData(dataTypes[i]);if (dropTarget.canDrop(AjaxControlToolkit.DragMode.Copy, dataTypes[i], data)) {
if (data) {
Array.add(dataObjects, { type : dataTypes[i], value : data });}
}
}
return dataObjects;}
AjaxControlToolkit.GenericDragDropManager = function() {
AjaxControlToolkit.GenericDragDropManager.initializeBase(this);this._dropTargets = null;this._scrollEdgeConst = 40;this._scrollByConst = 10;this._scroller = null;this._scrollDeltaX = 0;this._scrollDeltaY = 0;this._activeDragVisual = null;this._activeContext = null;this._activeDragSource = null;this._oldOffset = null;this._potentialTarget = null;this._mouseUpHandler = null;this._mouseMoveHandler = null;this._keyPressHandler = null;this._scrollerTickHandler = null;}
AjaxControlToolkit.GenericDragDropManager.prototype = {
initialize : function() {
AjaxControlToolkit.GenericDragDropManager.callBaseMethod(this, "initialize");this._mouseUpHandler = Function.createDelegate(this, this._onMouseUp);this._mouseMoveHandler = Function.createDelegate(this, this._onMouseMove);this._keyPressHandler = Function.createDelegate(this, this._onKeyPress);this._scrollerTickHandler = Function.createDelegate(this, this._onScrollerTick);if (Sys.Browser.agent === Sys.Browser.Safari) {
AjaxControlToolkit.GenericDragDropManager.__loadSafariCompatLayer(this);}
this._scroller = new Sys.Timer();this._scroller.set_interval(10);this._scroller.add_tick(this._scrollerTickHandler);},
startDragDrop : function(dragSource, dragVisual, context) {
this._activeDragSource = dragSource;this._activeDragVisual = dragVisual;this._activeContext = context;AjaxControlToolkit.GenericDragDropManager.callBaseMethod(this, "startDragDrop", [dragSource, dragVisual, context]);},
_stopDragDrop : function(cancelled) {
this._scroller.set_enabled(false);AjaxControlToolkit.GenericDragDropManager.callBaseMethod(this, "_stopDragDrop", [cancelled]);},
_drag : function(isInitialDrag) {
AjaxControlToolkit.GenericDragDropManager.callBaseMethod(this, "_drag", [isInitialDrag]);this._autoScroll();},
_wireEvents : function() {
$addHandler(document, "mouseup", this._mouseUpHandler);$addHandler(document, "mousemove", this._mouseMoveHandler);$addHandler(document, "keypress", this._keyPressHandler);},
_unwireEvents : function() {
$removeHandler(document, "keypress", this._keyPressHandler);$removeHandler(document, "mousemove", this._mouseMoveHandler);$removeHandler(document, "mouseup", this._mouseUpHandler);},
_wireDropTargetEvents : function(dropTarget) {
},
_unwireDropTargetEvents : function(dropTarget) {
},
_onMouseUp : function(e) {
window._event = e;this._stopDragDrop(false);},
_onMouseMove : function(e) {
window._event = e;this._drag();},
_onKeyPress : function(e) {
window._event = e;var k = e.keyCode ? e.keyCode : e.rawEvent.keyCode;if (k == 27) {
this._stopDragDrop( true);}
},
_autoScroll : function() {
var ev = window._event;var browserRect = this.getBrowserRectangle();if (browserRect.width > 0) {
this._scrollDeltaX = this._scrollDeltaY = 0;if (ev.clientX < browserRect.x + this._scrollEdgeConst) this._scrollDeltaX = -this._scrollByConst;else if (ev.clientX > browserRect.width - this._scrollEdgeConst) this._scrollDeltaX = this._scrollByConst;if (ev.clientY < browserRect.y + this._scrollEdgeConst) this._scrollDeltaY = -this._scrollByConst;else if (ev.clientY > browserRect.height - this._scrollEdgeConst) this._scrollDeltaY = this._scrollByConst;if (this._scrollDeltaX != 0 || this._scrollDeltaY != 0) {
this._scroller.set_enabled(true);}
else {
this._scroller.set_enabled(false);}
}
},
_onScrollerTick : function() {
var oldLeft = document.body.scrollLeft;var oldTop = document.body.scrollTop;window.scrollBy(this._scrollDeltaX, this._scrollDeltaY);var newLeft = document.body.scrollLeft;var newTop = document.body.scrollTop;var dragVisual = this._activeDragVisual;var position = { x: parseInt(dragVisual.style.left) + (newLeft - oldLeft), y: parseInt(dragVisual.style.top) + (newTop - oldTop) };$common.setLocation(dragVisual, position);}
}
AjaxControlToolkit.GenericDragDropManager.registerClass('AjaxControlToolkit.GenericDragDropManager', AjaxControlToolkit.IEDragDropManager);if (Sys.Browser.agent === Sys.Browser.Safari) {
AjaxControlToolkit.GenericDragDropManager.__loadSafariCompatLayer = function(ddm) {
ddm._getScrollOffset = ddm.getScrollOffset;ddm.getScrollOffset = function(element, recursive) {
return { x: 0, y: 0 };}
ddm._getBrowserRectangle = ddm.getBrowserRectangle;ddm.getBrowserRectangle = function() {
var browserRect = ddm._getBrowserRectangle();var offset = ddm._getScrollOffset(document.body, true);return { x: browserRect.x + offset.x, y: browserRect.y + offset.y,
width: browserRect.width + offset.x, height: browserRect.height + offset.y };}
}
}

//END AjaxControlToolkit.Compat.DragDrop.DragDropScripts.js
//START AjaxControlToolkit.DragPanel.FloatingBehavior.js
AjaxControlToolkit.FloatingBehavior = function(element) {
AjaxControlToolkit.FloatingBehavior.initializeBase(this,[element]);var _handle;var _location;var _dragStartLocation;var _profileProperty;var _profileComponent;var _mouseDownHandler = Function.createDelegate(this, mouseDownHandler);this.add_move = function(handler) {
this.get_events().addHandler('move', handler);}
this.remove_move = function(handler) {
this.get_events().removeHandler('move', handler);}
this.get_handle = function() {
return _handle;}
this.set_handle = function(value) {
if (_handle != null) {
$removeHandler(_handle, "mousedown", _mouseDownHandler);}
_handle = value;$addHandler(_handle, "mousedown", _mouseDownHandler);}
this.get_profileProperty = function() {
return _profileProperty;}
this.set_profileProperty = function(value) {
_profileProperty = value;}
this.get_profileComponent = function() {
return _profileComponent;}
this.set_profileComponent = function(value) {
_profileComponent = value;}
this.get_location = function() {
return _location;}
this.set_location = function(value) {
if (_location != value) {
_location = value;if (this.get_isInitialized()) { 
$common.setLocation(this.get_element(), _location);}
this.raisePropertyChanged('location');}
}
this.initialize = function() {
AjaxControlToolkit.FloatingBehavior.callBaseMethod(this, 'initialize');AjaxControlToolkit.DragDropManager.registerDropTarget(this);var el = this.get_element();if (!_location) { 
_location = $common.getLocation(el);}
el.style.position = "fixed";$common.setLocation(el, _location);}
this.dispose = function() {
AjaxControlToolkit.DragDropManager.unregisterDropTarget(this);if (_handle && _mouseDownHandler) {
$removeHandler(_handle, "mousedown", _mouseDownHandler);}
_mouseDownHandler = null;AjaxControlToolkit.FloatingBehavior.callBaseMethod(this, 'dispose');}
this.checkCanDrag = function(element) {
var undraggableTagNames = ["input", "button", "select", "textarea", "label"];var tagName = element.tagName;if ((tagName.toLowerCase() == "a") && (element.href != null) && (element.href.length > 0)) {
return false;}
if (Array.indexOf(undraggableTagNames, tagName.toLowerCase()) > -1) {
return false;}
return true;}
function mouseDownHandler(ev) {
window._event = ev;var el = this.get_element();if (this.checkCanDrag(ev.target)) {
_dragStartLocation = $common.getLocation(el);ev.preventDefault();this.startDragDrop(el);}
}
this.get_dragDataType = function() {
return "_floatingObject";}
this.getDragData = function(context) {
return null;}
this.get_dragMode = function() {
return AjaxControlToolkit.DragMode.Move;}
this.onDragStart = function() { }
this.onDrag = function() { }
this.onDragEnd = function(canceled) {
if (!canceled) {
var handler = this.get_events().getHandler('move');if(handler) {
var cancelArgs = new Sys.CancelEventArgs();handler(this, cancelArgs);canceled = cancelArgs.get_cancel();} 
}
var el = this.get_element();if (canceled) {
$common.setLocation(el, _dragStartLocation);} else {
_location = $common.getLocation(el);this.raisePropertyChanged('location');}
}
this.startDragDrop = function(dragVisual) {
AjaxControlToolkit.DragDropManager.startDragDrop(this, dragVisual, null);}
this.get_dropTargetElement = function() {
return document.body;}
this.canDrop = function(dragMode, dataType, data) {
return (dataType == "_floatingObject");}
this.drop = function(dragMode, dataType, data) {}
this.onDragEnterTarget = function(dragMode, dataType, data) {}
this.onDragLeaveTarget = function(dragMode, dataType, data) {}
this.onDragInTarget = function(dragMode, dataType, data) {}
}
AjaxControlToolkit.FloatingBehavior.registerClass('AjaxControlToolkit.FloatingBehavior', AjaxControlToolkit.BehaviorBase, AjaxControlToolkit.IDragSource, AjaxControlToolkit.IDropTarget, Sys.IDisposable);
//END AjaxControlToolkit.DragPanel.FloatingBehavior.js
//START AjaxControlToolkit.ModalPopup.ModalPopupBehavior.js
Type.registerNamespace('AjaxControlToolkit');AjaxControlToolkit.ModalPopupRepositionMode = function() {
throw Error.invalidOperation();}
AjaxControlToolkit.ModalPopupRepositionMode.prototype = {
None : 0,
RepositionOnWindowResize : 1,
RepositionOnWindowScroll : 2,
RepositionOnWindowResizeAndScroll : 3
}
AjaxControlToolkit.ModalPopupRepositionMode.registerEnum('AjaxControlToolkit.ModalPopupRepositionMode');AjaxControlToolkit.ModalPopupBehavior = function(element) {
AjaxControlToolkit.ModalPopupBehavior.initializeBase(this, [element]);this._PopupControlID = null;this._PopupDragHandleControlID = null;this._BackgroundCssClass = null;this._DropShadow = false;this._Drag = false;this._OkControlID = null;this._CancelControlID = null;this._OnOkScript = null;this._OnCancelScript = null;this._xCoordinate = -1;this._yCoordinate = -1;this._repositionMode = AjaxControlToolkit.ModalPopupRepositionMode.RepositionOnWindowResizeAndScroll;this._backgroundElement = null;this._foregroundElement = null;this._relativeOrAbsoluteParentElement = null;this._popupElement = null;this._dragHandleElement = null;this._showHandler = null;this._okHandler = null;this._cancelHandler = null;this._scrollHandler = null;this._resizeHandler = null;this._windowHandlersAttached = false;this._dropShadowBehavior = null;this._dragBehavior = null;this._isIE6 = false;this._saveTabIndexes = new Array();this._saveDesableSelect = new Array();this._tagWithTabIndex = new Array('A','AREA','BUTTON','INPUT','OBJECT','SELECT','TEXTAREA','IFRAME');}
AjaxControlToolkit.ModalPopupBehavior.prototype = {
initialize : function() {
AjaxControlToolkit.ModalPopupBehavior.callBaseMethod(this, 'initialize');this._isIE6 = (Sys.Browser.agent == Sys.Browser.InternetExplorer && Sys.Browser.version < 7);if(this._PopupDragHandleControlID)
this._dragHandleElement = $get(this._PopupDragHandleControlID);this._popupElement = $get(this._PopupControlID);if(this._DropShadow)
{
this._foregroundElement = document.createElement('div');this._foregroundElement.id = this.get_id() + '_foregroundElement';this._popupElement.parentNode.appendChild(this._foregroundElement);this._foregroundElement.appendChild(this._popupElement);}
else
{
this._foregroundElement = this._popupElement;}
this._backgroundElement = document.createElement('div');this._backgroundElement.id = this.get_id() + '_backgroundElement';this._backgroundElement.style.display = 'none';this._backgroundElement.style.position = 'fixed';this._backgroundElement.style.left = '0px';this._backgroundElement.style.top = '0px';this._backgroundElement.style.zIndex = 10000;if (this._BackgroundCssClass) {
this._backgroundElement.className = this._BackgroundCssClass;}
this._foregroundElement.parentNode.appendChild(this._backgroundElement);this._foregroundElement.style.display = 'none';this._foregroundElement.style.position = 'fixed';this._foregroundElement.style.zIndex = $common.getCurrentStyle(this._backgroundElement, 'zIndex', this._backgroundElement.style.zIndex) + 1;this._showHandler = Function.createDelegate(this, this._onShow);$addHandler(this.get_element(), 'click', this._showHandler);if (this._OkControlID) {
this._okHandler = Function.createDelegate(this, this._onOk);$addHandler($get(this._OkControlID), 'click', this._okHandler);}
if (this._CancelControlID) {
this._cancelHandler = Function.createDelegate(this, this._onCancel);$addHandler($get(this._CancelControlID), 'click', this._cancelHandler);}
this._scrollHandler = Function.createDelegate(this, this._onLayout);this._resizeHandler = Function.createDelegate(this, this._onLayout);this.registerPartialUpdateEvents();},
dispose : function() {
this._hideImplementation();if (this._foregroundElement && this._foregroundElement.parentNode) {
this._foregroundElement.parentNode.removeChild(this._backgroundElement);if(this._DropShadow) {
this._foregroundElement.parentNode.appendChild(this._popupElement);this._foregroundElement.parentNode.removeChild(this._foregroundElement);}
}
this._scrollHandler = null;this._resizeHandler = null;if (this._cancelHandler && $get(this._CancelControlID)) {
$removeHandler($get(this._CancelControlID), 'click', this._cancelHandler);this._cancelHandler = null;}
if (this._okHandler && $get(this._OkControlID)) {
$removeHandler($get(this._OkControlID), 'click', this._okHandler);this._okHandler = null;}
if (this._showHandler) {
$removeHandler(this.get_element(), 'click', this._showHandler);this._showHandler = null;}
AjaxControlToolkit.ModalPopupBehavior.callBaseMethod(this, 'dispose');},
_attachPopup : function() {
if (this._DropShadow && !this._dropShadowBehavior) {
this._dropShadowBehavior = $create(AjaxControlToolkit.DropShadowBehavior, {}, null, null, this._popupElement);}
if (this._dragHandleElement && !this._dragBehavior) {
this._dragBehavior = $create(AjaxControlToolkit.FloatingBehavior, {"handle" : this._dragHandleElement}, null, null, this._foregroundElement);} 
$addHandler(window, 'resize', this._resizeHandler);$addHandler(window, 'scroll', this._scrollHandler);this._windowHandlersAttached = true;},
_detachPopup : function() {
if (this._windowHandlersAttached) {
if (this._scrollHandler) {
$removeHandler(window, 'scroll', this._scrollHandler);}
if (this._resizeHandler) {
$removeHandler(window, 'resize', this._resizeHandler);}
this._windowHandlersAttached = false;}
if (this._dragBehavior) {
this._dragBehavior.dispose();this._dragBehavior = null;} 
if (this._dropShadowBehavior) {
this._dropShadowBehavior.dispose();this._dropShadowBehavior = null;}
},
_onShow : function(e) {
if (!this.get_element().disabled) {
this.show();e.preventDefault();return false;}
},
_onOk : function(e) {
var element = $get(this._OkControlID);if (element && !element.disabled) {
if (this.hide() && this._OnOkScript) {
window.setTimeout(this._OnOkScript, 0);}
e.preventDefault();return false;}
},
_onCancel : function(e) {
var element = $get(this._CancelControlID);if (element && !element.disabled) {
if (this.hide() && this._OnCancelScript) {
window.setTimeout(this._OnCancelScript, 0);}
e.preventDefault();return false;}
},
_onLayout : function(e) {
var positioning = this.get_repositionMode();if (((positioning === AjaxControlToolkit.ModalPopupRepositionMode.RepositionOnWindowScroll) ||
(positioning === AjaxControlToolkit.ModalPopupRepositionMode.RepositionOnWindowResizeAndScroll)) && (e.type === 'scroll')) {
this._layout();} else if (((positioning === AjaxControlToolkit.ModalPopupRepositionMode.RepositionOnWindowResize) ||
(positioning === AjaxControlToolkit.ModalPopupRepositionMode.RepositionOnWindowResizeAndScroll)) && (e.type === 'resize')) {
this._layout();} else {
this._layoutBackgroundElement();}
},
show : function() {
var eventArgs = new Sys.CancelEventArgs();this.raiseShowing(eventArgs);if (eventArgs.get_cancel()) {
return;}
this.populate();this._attachPopup();this._backgroundElement.style.display = '';this._foregroundElement.style.display = '';this._popupElement.style.display = '';if (this._isIE6) {
this._foregroundElement.style.position = 'absolute';this._backgroundElement.style.position = 'absolute';var tempRelativeOrAbsoluteParent = this._foregroundElement.parentNode;while (tempRelativeOrAbsoluteParent && (tempRelativeOrAbsoluteParent != document.documentElement)) {
if((tempRelativeOrAbsoluteParent.style.position != 'relative') && (tempRelativeOrAbsoluteParent.style.position != 'absolute')) {
tempRelativeOrAbsoluteParent = tempRelativeOrAbsoluteParent.parentNode;} else {
this._relativeOrAbsoluteParentElement = tempRelativeOrAbsoluteParent;break;}
} 
} 
this.disableTab();this._layout();this._layout();this.raiseShown(Sys.EventArgs.Empty);},
disableTab : function() {
var i = 0;var tagElements;var tagElementsInPopUp = new Array();Array.clear(this._saveTabIndexes);for (var j = 0;j < this._tagWithTabIndex.length;j++) {
tagElements = this._foregroundElement.getElementsByTagName(this._tagWithTabIndex[j]);for (var k = 0 ;k < tagElements.length;k++) {
tagElementsInPopUp[i] = tagElements[k];i++;}
}
i = 0;for (var j = 0;j < this._tagWithTabIndex.length;j++) {
tagElements = document.getElementsByTagName(this._tagWithTabIndex[j]);for (var k = 0 ;k < tagElements.length;k++) {
if (Array.indexOf(tagElementsInPopUp, tagElements[k]) == -1) {
this._saveTabIndexes[i] = {tag: tagElements[k], index: tagElements[k].tabIndex};tagElements[k].tabIndex="-1";i++;}
}
}
i = 0;if ((Sys.Browser.agent === Sys.Browser.InternetExplorer) && (Sys.Browser.version < 7)) {
var tagSelectInPopUp = new Array();for (var j = 0;j < this._tagWithTabIndex.length;j++) {
tagElements = this._foregroundElement.getElementsByTagName('SELECT');for (var k = 0 ;k < tagElements.length;k++) {
tagSelectInPopUp[i] = tagElements[k];i++;}
}
i = 0;Array.clear(this._saveDesableSelect);tagElements = document.getElementsByTagName('SELECT');for (var k = 0 ;k < tagElements.length;k++) {
if (Array.indexOf(tagSelectInPopUp, tagElements[k]) == -1) {
this._saveDesableSelect[i] = {tag: tagElements[k], visib: $common.getCurrentStyle(tagElements[k], 'visibility')} ;tagElements[k].style.visibility = 'hidden';i++;}
}
}
},
restoreTab : function() {
for (var i = 0;i < this._saveTabIndexes.length;i++) {
this._saveTabIndexes[i].tag.tabIndex = this._saveTabIndexes[i].index;}
Array.clear(this._saveTabIndexes);if ((Sys.Browser.agent === Sys.Browser.InternetExplorer) && (Sys.Browser.version < 7)) {
for (var k = 0 ;k < this._saveDesableSelect.length;k++) {
this._saveDesableSelect[k].tag.style.visibility = this._saveDesableSelect[k].visib;}
Array.clear(this._saveDesableSelect);}
},
hide : function() {
var eventArgs = new Sys.CancelEventArgs();this.raiseHiding(eventArgs);if (eventArgs.get_cancel()) {
return false;}
this._hideImplementation();this.raiseHidden(Sys.EventArgs.Empty);return true;},
_hideImplementation : function() {
this._backgroundElement.style.display = 'none';this._foregroundElement.style.display = 'none';this.restoreTab();this._detachPopup();},
_layout : function() {
var scrollLeft = (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);var scrollTop = (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);var clientBounds = $common.getClientBounds();var clientWidth = clientBounds.width;var clientHeight = clientBounds.height;this._layoutBackgroundElement();var xCoord = 0;var yCoord = 0;if(this._xCoordinate < 0) {
var foregroundelementwidth = this._foregroundElement.offsetWidth? this._foregroundElement.offsetWidth: this._foregroundElement.scrollWidth;xCoord = ((clientWidth-foregroundelementwidth)/2);if (this._foregroundElement.style.position == 'absolute') {
xCoord += scrollLeft;}
this._foregroundElement.style.left = xCoord + 'px';} else {
if(this._isIE6) {
this._foregroundElement.style.left = (this._xCoordinate + scrollLeft) + 'px';xCoord = this._xCoordinate + scrollLeft;}
else {
this._foregroundElement.style.left = this._xCoordinate + 'px';xCoord = this._xCoordinate;}
}
if(this._yCoordinate < 0) {
var foregroundelementheight = this._foregroundElement.offsetHeight? this._foregroundElement.offsetHeight: this._foregroundElement.scrollHeight;yCoord = ((clientHeight-foregroundelementheight)/2);if (this._foregroundElement.style.position == 'absolute') {
yCoord += scrollTop;}
this._foregroundElement.style.top = yCoord + 'px';} else {
if(this._isIE6) {
this._foregroundElement.style.top = (this._yCoordinate + scrollTop) + 'px';yCoord = this._yCoordinate + scrollTop;}
else {
this._foregroundElement.style.top = this._yCoordinate + 'px';yCoord = this._yCoordinate;}
}
this._layoutForegroundElement(xCoord, yCoord);if (this._dropShadowBehavior) {
this._dropShadowBehavior.setShadow();window.setTimeout(Function.createDelegate(this, this._fixupDropShadowBehavior), 0);}
this._layoutBackgroundElement();},
_layoutForegroundElement : function(xCoord, yCoord) {
if (this._isIE6 && this._relativeOrAbsoluteParentElement) {
var foregroundLocation = $common.getLocation(this._foregroundElement);var relativeParentLocation = $common.getLocation(this._relativeOrAbsoluteParentElement);var getLocationXCoord = foregroundLocation.x;if (getLocationXCoord != xCoord) {
this._foregroundElement.style.left = (xCoord - relativeParentLocation.x) + 'px';} 
var getLocationYCoord = foregroundLocation.y;if (getLocationYCoord != yCoord) {
this._foregroundElement.style.top = (yCoord - relativeParentLocation.y) + 'px';} 
}
},
_layoutBackgroundElement : function() {
if(this._isIE6) { 
var backgroundLocation = $common.getLocation(this._backgroundElement);var backgroundXCoord = backgroundLocation.x;if (backgroundXCoord != 0) {
this._backgroundElement.style.left = (-backgroundXCoord) + 'px';} 
var backgroundYCoord = backgroundLocation.y;if (backgroundYCoord != 0) {
this._backgroundElement.style.top = (-backgroundYCoord) + 'px';} 
}
var clientBounds = $common.getClientBounds();var clientWidth = clientBounds.width;var clientHeight = clientBounds.height;this._backgroundElement.style.width = Math.max(Math.max(document.documentElement.scrollWidth, document.body.scrollWidth), clientWidth)+'px';this._backgroundElement.style.height = Math.max(Math.max(document.documentElement.scrollHeight, document.body.scrollHeight), clientHeight)+'px';},
_fixupDropShadowBehavior : function() {
if (this._dropShadowBehavior) {
this._dropShadowBehavior.setShadow();}
},
_partialUpdateEndRequest : function(sender, endRequestEventArgs) {
AjaxControlToolkit.ModalPopupBehavior.callBaseMethod(this, '_partialUpdateEndRequest', [sender, endRequestEventArgs]);if (this.get_element()) {
var action = endRequestEventArgs.get_dataItems()[this.get_element().id];if ("show" == action) {
this.show();} else if ("hide" == action) {
this.hide();}
}
this._layout();},
_onPopulated : function(sender, eventArgs) {
AjaxControlToolkit.ModalPopupBehavior.callBaseMethod(this, '_onPopulated', [sender, eventArgs]);this._layout();},
get_PopupControlID : function() {
return this._PopupControlID;},
set_PopupControlID : function(value) {
if (this._PopupControlID != value) {
this._PopupControlID = value;this.raisePropertyChanged('PopupControlID');}
},
get_X: function() {
return this._xCoordinate;},
set_X: function(value) {
if (this._xCoordinate != value) {
this._xCoordinate = value;this.raisePropertyChanged('X');}
},
get_Y: function() {
return this._yCoordinate;},
set_Y: function(value) {
if (this._yCoordinate != value) {
this._yCoordinate = value;this.raisePropertyChanged('Y');}
},
get_PopupDragHandleControlID : function() {
return this._PopupDragHandleControlID;},
set_PopupDragHandleControlID : function(value) {
if (this._PopupDragHandleControlID != value) {
this._PopupDragHandleControlID = value;this.raisePropertyChanged('PopupDragHandleControlID');}
},
get_BackgroundCssClass : function() {
return this._BackgroundCssClass;},
set_BackgroundCssClass : function(value) {
if (this._BackgroundCssClass != value) {
this._BackgroundCssClass = value;this.raisePropertyChanged('BackgroundCssClass');}
},
get_DropShadow : function() {
return this._DropShadow;},
set_DropShadow : function(value) {
if (this._DropShadow != value) {
this._DropShadow = value;this.raisePropertyChanged('DropShadow');}
},
get_Drag : function() {
return this._Drag;},
set_Drag : function(value) {
if (this._Drag != value) {
this._Drag = value;this.raisePropertyChanged('Drag');}
},
get_OkControlID : function() {
return this._OkControlID;},
set_OkControlID : function(value) {
if (this._OkControlID != value) {
this._OkControlID = value;this.raisePropertyChanged('OkControlID');}
},
get_CancelControlID : function() {
return this._CancelControlID;},
set_CancelControlID : function(value) {
if (this._CancelControlID != value) {
this._CancelControlID = value;this.raisePropertyChanged('CancelControlID');}
},
get_OnOkScript : function() {
return this._OnOkScript;},
set_OnOkScript : function(value) {
if (this._OnOkScript != value) {
this._OnOkScript = value;this.raisePropertyChanged('OnOkScript');}
},
get_OnCancelScript : function() {
return this._OnCancelScript;},
set_OnCancelScript : function(value) {
if (this._OnCancelScript != value) {
this._OnCancelScript = value;this.raisePropertyChanged('OnCancelScript');}
},
get_repositionMode : function() {
return this._repositionMode;},
set_repositionMode : function(value) {
if (this._repositionMode !== value) {
this._repositionMode = value;this.raisePropertyChanged('RepositionMode');}
},
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.ModalPopupBehavior.registerClass('AjaxControlToolkit.ModalPopupBehavior', AjaxControlToolkit.DynamicPopulateBehaviorBase);AjaxControlToolkit.ModalPopupBehavior.invokeViaServer = function(behaviorID, show) {
var behavior = $find(behaviorID);if (behavior) {
if (show) {
behavior.show();} else {
behavior.hide();}
}
}

//END AjaxControlToolkit.ModalPopup.ModalPopupBehavior.js
if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();
(function() {var fn = function() {$get('ctl00_scriptManager_HiddenField').value += ';;RealtyTrac.Common.Web.Scripts:en-US:437742a9-d041-4739-a331-f44e334f6da1:7565ef5a:8fbb96f4:adb12799:73373c4b:3f45754d:1b704c8b: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:8e72a662:acd642d2:596d588c:77c58d20:14b56adc:269a19ae';Sys.Application.remove_load(fn);};Sys.Application.add_load(fn);})();
