if (typeof (RE) == 'undefined')
    RE = {};

if (typeof (RE.EventManager) == 'undefined')
    RE.EventManager = {};

if (typeof (RE.Forms) == 'undefined')
    Ext.namespace('RE.Forms');

Ext.apply(Ext.form.VTypes, {
    username: function(val) {
        return /^[a-zA-Z0-9_\- @\.]+$/.test(val);
    },

    emailconf: function(val, field) {
        if (field.initialEmailField) {
            var eml = Ext.getCmp(field.initialEmailField);
            return (val == eml.getValue());
        }
        return true;
    },

    emailconfText: 'Emails do not match',

    passconf: function(val, field) {
        if (field.initialPassField) {
            var pwd = Ext.getCmp(field.initialPassField);
            return (val == pwd.getValue());
        }
        return true;
    },

    passconfText: 'Passwords do not match',

    captcha: function(val, field) {
        Ext.Ajax.request({
            url: '/handlers/captcha.ashx',
            scope: this,
            params:
            {
                hash: val
            },
            method: 'POST',
            failure: function(result, request) {
                field.markInvalid(result.responseText);
            }
        });
        return true;
    }
});


Ext.apply(RE.EventManager, function() {
    var loggedInEvent;
    return {
        onLoggedIn: function(fn, scope, options) {
            if (!loggedInEvent) {
                loggedInEvent = new Ext.util.Event();
                loggedInEvent.fire();
            }
            loggedInEvent.addListener(fn, scope, options);
        },
        fireLoggedIn: function(options) {
            if (loggedInEvent)
                loggedInEvent.fire(options);
        }
    };
} ());


RE.onLoggedIn = RE.EventManager.onLoggedIn;

Ext.apply(RE, function() {
    var authWindow;
    return {
        getExecutionID: function() {
            var a = new Date, b = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate(), a.getHours(), a.getMinutes(), a.getSeconds(), a.getMilliseconds());
            b += Math.round(Math.random() * 1000000);
            return b
        },

        Login: function(animationTarget) {
            Ext.QuickTips.init();

            var f = new Ext.FormPanel({
                baseCls: 'x-plain',
                id: 'login-form',
                labelAlign: 'top',
                labelWidth: 75,
                url: '/handlers/authenticate.ashx',
                defaults: { anchor: '65%', allowBlank: false, msgTarget: 'side' },
                items:
                [
                    { xtype: 'textfield', fieldLabel: 'Login', vtype: 'username', name: 'login' },
                    { xtype: 'textfield', inputType: 'password', fieldLabel: 'Password', name: 'password' },
                    { baseCls: 'x-plain', height: 10, html: '' },
                    { baseCls: 'x-plain', height: 20, html: '<a href=\'http://ts.realestate.com/user/EmailForgottenPassword.aspx\'>Forgot your password?</a>' },
                    { baseCls: 'x-plain', html: 'Don\'t have a MyRealEstate account? <a id="signUp">Sign-Up</a>',
                        listeners: {
                            afterrender: function(c) {
                                Ext.get("signUp").on('click', function() { w.close(); RE.SignUp(); });
                            }
                        }
                    }
                ]
            });

            function signinHandler() {
                if (f.getForm().isValid())
                    f.getForm().submit(
                    {
                        success: function(form, action) {
                            RE.EventManager.fireLoggedIn(action.result);
                            w.close();
                        },
                        failure: function(form, action) {
                            switch (action.failureType) {
                                case Ext.form.Action.CLIENT_INVALID:
                                    Ext.Msg.show({ title: 'Failure', icon: Ext.MessageBox.WARNING, buttons: Ext.Msg.OK, msg: 'Form fields may not be submitted with invalid values' });
                                    break;
                                case Ext.form.Action.CONNECT_FAILURE:
                                    Ext.Msg.show({ title: 'Failure', icon: Ext.MessageBox.WARNING, buttons: Ext.Msg.OK, msg: 'Ajax communication failed' });
                                    break;
                                case Ext.form.Action.SERVER_INVALID:
                                    Ext.Msg.show({ title: 'Failure', icon: Ext.MessageBox.WARNING, buttons: Ext.Msg.OK, msg: action.result.msg });
                            }
                        }
                    });
            }

            var w = new Ext.Window({
                title: 'Login',
                height: 300,
                width: 480,
                bodyStyle: 'padding:10px;',
                closable: true,
                resizable: false,
                cls: 're-login',
                closeAction: 'hide',
                plain: true,
                modal: true,
                layout: 'fit',
                items: f,
                keys: { key: [10, 13], fn: signinHandler },
                buttons:
                [
                    { text: 'Sign-In', minWidth: 75, handler: signinHandler },
                    { text: 'Cancel', minWidth: 75, handler: function() { w.close() } }
                ]
            });
            w.show(animationTarget);


        },

        SignUp: function(animationTarget) {
            Ext.QuickTips.init();

            var refreshClickHandler = function() {
                Ext.getDom("captchaImage").src = '/handlers/captcha.ashx?reset=true' + RE.getExecutionID();
            }

            var f = new Ext.FormPanel({
                id: 'signup-form',
                baseCls: 'x-plain',
                labelAlign: 'top',
                url: '/handlers/authenticate.ashx',
                defaults: { width: 200, anchor: '65%', allowBlank: false, msgTarget: 'side' },
                items:
                [
                    { xtype: 'textfield', fieldLabel: 'Sign in name', name: 'login', vtype: 'username' },
                    { xtype: 'textfield', vtype: 'email', fieldLabel: 'Email Address', name: 'email', id: 'email' },
                    { xtype: 'textfield', vtype: 'emailconf', fieldLabel: 'Re-enter Email Address', name: 'emailconf', initialEmailField: 'email' },
                    { xtype: 'textfield', inputType: 'password', fieldLabel: 'Password', name: 'password', id: 'password' },
                    { xtype: 'textfield', inputType: 'password', vtype: 'passconf', fieldLabel: 'Re-enter Password', name: 'passwordconf', initialPassField: 'password' },
                    {
                        layout: 'form',
                        defaults: { baseCls: 'x-plain' },
                        padding: 10,
                        cls: 're-captcha-item',
                        items:
                        [
                            {
                                layout: { type: 'hbox', align: 'stretch', pack: 'start' },
                                defaults: { baseCls: 'x-plain' },
                                height: 55,
                                items:
                                [
                                    { html: { tag: 'img', id: 'captchaImage', src: '/handlers/captcha.ashx', border: 1, width: 100, height: 40} },
                                    {
                                        style: 'text-align:center;margin-left:10px;',
                                        padding: 0,
                                        html:
                                        [
                                            { tag: 'div', html: 'Have trouble reading this?' },
                                            { tag: 'a', id: 'captchaRefresh', html: 'Refresh CAPTCHA' },
                                            { tag: 'div', children: { tag: 'a', id: 'captchaTooltip', html: 'What\'s this?'} }

                                        ],
                                        listeners: {
                                            afterrender: function(c) {
                                                Ext.get('captchaRefresh').on('click', refreshClickHandler, c);
                                                new Ext.ToolTip({ target: 'captchaTooltip', html: '<b>Captcha:</b><br />Please enter the letters you see in the box exactly how they appear. Doing so helps prevent automated programs from abusing this service.' });
                                            }
                                        }
                                    }
                                ]

                            },
                            { xtype: 'textfield', labelAlign: 'top', fieldClass: 'x-form-', fieldLabel: 'Enter code you see above', name: 'captcha', style: 'margin:0,padding:0', msgTarget: 'side', allowBlank: false, vtype: 'captcha' }
                        ]
                    },
                    { baseCls: 'x-plain', height: 10, html: '' },
                    { baseCls: 'x-plain', html: 'Already have an account? <a id="loginLink">Login</a>',
                        listeners: {
                            afterrender: function(c) {
                                Ext.get("loginLink").on('click', function() { w.close(); RE.Login(); });
                            }
                        }
                    }
                ]

            });

            function joinHandler() {
                if (f.getForm().isValid())
                    f.getForm().submit(
                      {
                          success: function(form, action) {
                              RE.EventManager.fireLoggedIn(action.result);
                              w.close();
                          },
                          failure: function(form, action) {
                              switch (action.failureType) {
                                  case Ext.form.Action.CLIENT_INVALID:
                                      Ext.Msg.show({ title: 'Failure', icon: Ext.MessageBox.WARNING, buttons: Ext.Msg.OK, msg: 'Form fields may not be submitted with invalid values' });
                                      break;
                                  case Ext.form.Action.CONNECT_FAILURE:
                                      Ext.Msg.show({ title: 'Failure', icon: Ext.MessageBox.WARNING, buttons: Ext.Msg.OK, msg: 'Ajax communication failed' });
                                      break;
                                  case Ext.form.Action.SERVER_INVALID:
                                      Ext.Msg.show({ title: 'Failure', icon: Ext.MessageBox.WARNING, buttons: Ext.Msg.OK, msg: action.result.msg });
                              }
                          }
                      });
            }

            var w = new Ext.Window({
                title: 'Sign-up',
                height: 500,
                width: 480,
                bodyStyle: 'padding:10px;',
                closable: true,
                resizable: false,
                cls: 're-signup',
                closeAction: 'close',
                plain: true,
                modal: true,
                layout: 'fit',
                items: f,
                keys: { key: [10, 13], fn: joinHandler },
                bbar: new Ext.ux.StatusBar({
                    id: 'form-statusbar',
                    items:
                    [
                        { text: 'Join', minWidth: 75, handler: joinHandler },
                        { text: 'Cancel', minWidth: 75, handler: function() { w.close() } }
                    ],
                    plugins: new Ext.ux.ValidationStatus({ form: 'signup-form', showText: 'Please Correct Errors on the Page &amp; Click Join.', onStatusClick: Ext.emptyFn })
                })
            });
            w.show(animationTarget);
        }
    }
} ());


RE.onLoggedIn(function(options) {

    Ext.getBody().replaceClass('user-anonymous', 'user-authenticated');

    var welcomeEl = Ext.get("CommonHeaderUserWelcome");
    var welcome =
        [
            { tag: 'a', html: options.username, href: String.format("http://{0}/members/{1}/default.aspx", options.baseUrl, options.username) },
            { tag: 'span', cls: 'sub',
                children:
                [
                    { tag: 'span', html: ' | ' },
                    { tag: 'a', href: String.format("http://{0}/user/EditProfile.aspx?ReturnUrl=%2fdefault.aspx", options.baseUrl), html: 'Edit' }
                ]
            },
            { tag: 'span', cls: 'sub',
                children:
                [
                    { tag: 'span', html: ' | ' },
                    { tag: 'a', href: String.format("http://{0}/logout.aspx", options.baseUrl), html: 'Sign out' },
                    { tag: 'span', html: ' | ' },
                    { tag: 'strong', children: { tag: 'a', href: String.format("http://{0}/user/conversations/default.aspx", options.baseUrl), html: 'Conversations'} },
                    { tag: 'span', html: ' | ' },
                    { tag: 'a', html: 'Friends', href: String.format("http://{0}/members/{1}/friends/default.aspx", options.baseUrl, options.username) }
                ]
            }
        ];

    Ext.DomHelper.overwrite(welcomeEl, welcome);
});


RE.DropMenu = function(el, config) {
    this.menu = Ext.get(el);
    this.parentMenu = Ext.get(this.menu.dom.parentNode);
    Ext.apply(this, config);
    this.attachEvents();
};
RE.DropMenu.prototype = {
    alignTo: 'tl-bl',
    initHeight: null,
    hidden: true,
    isInitialized: false,
    initialize: function() {

        this.menu.addClass('re-menu-drop');

        var layer = new Ext.Layer({
            shim: true,
            constrain: true
        });

        this.shim = layer.createShim();

        itemEls = this.menu.query('li.re-menu-leaf');
        for (var x = 0; x < itemEls.length; x++) {
            itm = Ext.get(itemEls[x]);
            itm.addClassOnOver('re-menu-item-over');
            itm.setWidth(this.menu.getComputedWidth());
            this.initHeight += itm.getComputedHeight();
        }

        this.menu.setWidth(this.menu.getComputedWidth());

        layer.setBox(this.menu.getBox());
        this.shim.setBox(this.menu.getBox());

        var ITEM_HORIZONTAL_PADDING = 17;
        this.shim.setWidth(this.menu.getWidth() + ITEM_HORIZONTAL_PADDING);
        layer.setWidth(this.menu.getWidth() + ITEM_HORIZONTAL_PADDING);

        layer.clearOpacity();
        layer.setHeight(0);

        this.menu.appendTo(layer);
        this.el = layer;
        this.isInitialized = true;
    },

    attachEvents: function() {
        this.parentMenu.hover(this.show, this.hide, this);
        this.menu.hover(this.show, this.hide, this);
    },
    hide: function(evt, t, o) {
        if (Ext.isIE) {
            if (evt.browserEvent.toElement && this.menu.contains(evt.browserEvent.toElement.id))
                return;
        }
        else {
            if (evt.within(this.menu, true))
                return;
        }

        this.el.hide();
        this.shim.hide();
        this.el.setHeight(0);
        this.parentMenu.removeClass('re-menu-hover');
        this.hidden = true;

    },
    show: function(evt, t, o) {
        if (evt.within(this.parentMenu)) {

            if (!this.isInitialized)
                this.initialize();

            this.el.alignTo(this.parentMenu, this.alignTo);
            this.shim.alignTo(this.parentMenu, this.alignTo);
            this.parentMenu.addClass('re-menu-hover');
            this.el.show();
            this.el.setHeight(this.initHeight, true);
            this.shim.setHeight(this.initHeight, false);
            this.shim.show();
            this.hidden = false;
        }
    }
}

var customSearchControl;
var popupSearchControl;
var w;
RE.initSiteSearch = function ()
{
	if (typeof(google) != 'undefined' && google)
	{
		google.load('search', '1');
		google.setOnLoadCallback(function() {
			if (!customSearchControl)
			{
			        customSearchControl = new google.search.CustomSearchControl('002509811938443575980:gq5m0ff2ido');
			        var drawOptions = new google.search.DrawOptions();
			        drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);
			        drawOptions.setSearchFormRoot(document.getElementById('searchForm'));
			
			        customSearchControl.setLinkTarget(google.search.Search.LINK_TARGET_BLANK);
			        customSearchControl.setUserDefinedLabel('RealEstate.com');
			        customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
			
			        var webSearcher = new google.search.WebSearch();
			        customSearchControl.addSearcher(webSearcher);
			
			        customSearchControl.setSearchCompleteCallback('RE', RE.siteSearchComplete);
			        customSearchControl.setSearchStartingCallback('RE', RE.siteSearchBegin);
			
			        customSearchControl.draw('cse-search-results', drawOptions);
			        
			}
			if (document.getElementById('poweredByGoogle')) {
			    document.getElementById('poweredByGoogle').appendChild(google.search.Search.getBranding(document.getElementById('poweredByGoogle'), google.search.Search.HORIZONTAL_BRANDING));
			}
		
		}, true);
	}
}

RE.siteSearchComplete = function(searchControl, searcher) {
	w.doLayout();
	w.show();
}

RE.siteSearchBegin = function(searchControl, searcher, query) {
	if (!w) {
	    w = new Ext.Window({
	        title: 'Search Results',
	        id: 'googleSiteSearchResults',
	        autoShow: true,
	        autoScroll: true,
	        height: 450,
	        width: 800,
	        closable: true,
	        contentEl: 'siteSearchResults',
	        resizable: false,
	        closeAction: 'hide',
	        plain: true,
	        modal: true,
	        layout: 'fit',
	        buttons:
	        [
	            { text: 'Close', minWidth: 75, handler: function() { w.hide() } }
	        ]
	    });
	}
	w.show();
	if (!popupSearchControl) 
	{
	        popupSearchControl = new google.search.CustomSearchControl('002509811938443575980:gq5m0ff2ido');
	        var drawOptions = new google.search.DrawOptions();
	        drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);
	        drawOptions.setSearchFormRoot(document.getElementById('popupSearchForm'));
	
	        popupSearchControl.setLinkTarget(google.search.Search.LINK_TARGET_BLANK);
	        popupSearchControl.setUserDefinedLabel('RealEstate.com');
	        popupSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
	
	        var webSearcher = new google.search.WebSearch();
	        popupSearchControl.addSearcher(webSearcher);
	
	        popupSearchControl.setSearchCompleteCallback('RE', RE.siteSearchComplete);
	        popupSearchControl.setSearchStartingCallback('RE', RE.popupSiteSearchBegin);
	        popupSearchControl.draw('cse-search-results', drawOptions);
	}
	popupSearchControl.input.value = customSearchControl.input.value= query;
	popupSearchControl.execute();
	customSearchControl.cancelSearch();
	
	try {
            var tracker = tracker || _pt._getTracker({
                visitorNamespace: "realestate",
                trackingServer: "tracking.tree.com",
                locationTrackImage: "trk/{0}.gif"
            });

            tracker._trackEvent("Form", "site-search", "ConsumerWeb Google Search", 0);
        } catch (ex) { }
}

RE.popupSiteSearchBegin = function(searchControl, searcher, query) {
	popupSearchControl.input.value = customSearchControl.input.value = s = query;
	//setCookie("realestate", "ssQ", s);
}

RE.submitSiteSearch = function() {
	RE.siteSearchBegin(this, null, customSearchControl.input.value);
	return false;
}

RE.submitPopupSearch = function() {
	popupSearchControl.execute();
	return false;
}

RE.initSiteSearch();

Ext.onReady(function() {
    initializeForms(Ext.query('.rac-autoinit'));
    initMenus(Ext.query('.re-menu-withchildren ul'));
    initializeRecruitForms(Ext.query('.recruit-autoinit'));
    initPriceFields(Ext.query('.re-pricefield'));
    initDropDownFields(Ext.query('.re-dropdown'));
    initAutoCompleteFields(Ext.query('.re-autocompletefield'));
    initPanel(Ext.query('.re-toolbox'));

});

function initMenus() {
    main_menu = Ext.get('mainMenu');
    if (main_menu) {
        var firstEl = main_menu.child('li');
        firstEl.addClass('firstChild');
        BuildMenuItems(main_menu.query('.re-menu-withchildren ul'), true);
    }

    sub_menu = Ext.get('re-subnav');
    if (sub_menu) {
        BuildMenuItems(sub_menu.query('.re-menu-withchildren ul'));
    }
}
function BuildMenuItems(els, modifyPositions) {
    for (var x = 0; x < els.length; x++) {
        var config;

        if (modifyPositions && x >= els.length - 2)
            config = { alignTo: 'tr-br' };

        new RE.DropMenu(els[x], config);
    }
}






function initPriceFields(els) {
    function currencyFormatEventHandler(evt, t, o) {

        var code = evt.getKey();

        if (code === 0 || code === 9)
            return;

        var num = t.value;
        num = num.toString().replace(/\$|\,/g, '');

        if (isNaN(num))
            num = "0";

        sign = (num == (num = Math.abs(num)));
        num = Math.floor(num * 100 + 0.50000000001);
        cents = num % 100;
        num = Math.floor(num / 100).toString();
        if (cents < 10)
            cents = "0" + cents;

        for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)  // use this to add , to numbers
            num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
        var temp = '$' + ((sign) ? '' : '-') + num //+ '.' + cents

        t.value = temp;
    }

    for (var x = 0; x < els.length; x++) {
        var fieldEl = Ext.get(els[x]);
        fieldEl.on({
            'keyup': { fn: currencyFormatEventHandler },
            'specialkey': { fn: currencyFormatEventHandler },
            'blur': { fn: currencyFormatEventHandler }
        });

        new Ext.form.TextField({
            applyTo: fieldEl
        });
    }
}

function initAutoCompleteFields(els) {

    var store = new Ext.data.SimpleStore({
        fields: ['name', 'count', 'type', 'id'],
        pruneModifiedRecords: true,
        proxy: new Ext.data.HttpProxy({ url: '/handlers/autoCompleteProxy.ashx' })

    });

    var item_template = new Ext.XTemplate('<tpl for="."><div class="re-criteria-item x-combo-list-item"><span style="float: left;">{name}</span>  {count} Listings</div></tpl>');
    item_template.compile();

    for (var x = 0; x < els.length; x++) {
        var fieldEl = Ext.get(els[x]);

        new Ext.form.ComboBox({
            store: store,
            id: 'searchTextBox',
            displayField: 'name',
            valueField: 'name',
            tpl: item_template,
            typeAhead: false,
            loadingText: 'Searching...',
            mode: 'remote',
            forceSelection: false,
            hideTrigger: true,
            triggerAction: 'all',
            width: 458,
            emptyText: '\'City,ST\', or Zip or MLS#',
            applyTo: fieldEl.id,
            selectOnFocus: true,
            minChars: 2,
            queryDelay: 10
        });
    }
}

function initDropDownFields(els) {
    for (var x = 0; x < els.length; x++) {
        var fieldEl = Ext.get(els[x]);
        var converted = new Ext.form.ComboBox({
            typeAhead: true,
            triggerAction: 'all',
            transform: fieldEl,
            width: fieldEl.parent('div').getWidth(),
            forceSelection: true
        });
        converted.el.set({ componentId: converted.id });
    }
}

function initPanel(els) {
    Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

    for (var x = 0; x < els.length; x++) {
        var fieldEl = Ext.get(els[x]);
        new Ext.Panel({
            collapsible: true,
            stateEvents: ['collapse', 'expand'],
            stateful: true,
            stateId: fieldEl.id,
            collapsed: true,
            autoShow: true,
            baseCls: 're-toolbox',
            applyTo: fieldEl,
            getState: function() {
                return { collapsed: this.collapsed };
            },
            applyState: function(state) {
                this.collapsed = state.collapsed;
            }
        });
    }
}

function initializeForms(els) {
    for (var x = 0; x < els.length; x++) {
        new RE.Forms.RequestCall({ applyTo: els[x] });
    }
}

function initializeRecruitForms(els) {
    for (var x = 0; x < els.length; x++) {
        new RE.Forms.AgentRecruit({ applyTo: els[x] });
    }
}

RE.ArrayScroll = function(config) {
    Ext.apply(this, config);
    RE.ArrayScroll.superclass.constructor.call(this);

    if (this.renderTo)
        this.render(renderTo);
};

Ext.extend(RE.ArrayScroll, Ext.Component, {
    pagesize: 5,
    pageStep: 1,
    startIndex: 0,
    data: null,
    next: function() {
        this.startIndex = Math.min(this.data.length - 1, this.startIndex + this.pageStep);
        this.refresh();
    },
    prev: function() {
        this.startIndex = Math.max(0, this.startIndex - this.pageStep);
        this.refresh();
    },
    template: null,
    onRender: function(renderTo) {

        this.refresh();
    },
    refresh: function() {
        this.bodyEl.update('');
        var lastIndex = Math.min(this.data.length, this.startIndex + this.pagesize);
        for (var i = this.startIndex; i < lastIndex; i++) {
            this.template.append(this.bodyEl, this.data[i]);
        }
    }
});

RE.Map = function(config) {
    Ext.apply(this, config);
    RE.Map.superclass.constructor.call(this);

    if (this.renderTo)
        this.render(renderTo);
};
Ext.extend(RE.Map, Ext.Component, {
    latitude: null,
    longitude: null,
    bounds: null,
    enableScrollWheelZoom: false,
    enableDragging: false,
    enableSmallTools: false,
    enableMapType: false,
    mapTypeOptions: null,
    zoomLevel: 13,
    visibleMapType: null,
    markerImage: null,
    onRender: function(renderTo) {

        var btnElem = Ext.get('btn-map-hide');
        if (btnElem) {
            btnElem.on('click', this.toggleMap, this);
            var showMap = readCookie("realestate", "mapVisible");
            if (typeof (showMap) == 'undefined' || showMap == null)
            { setCookie("realestate", "mapVisible", "1"); showMap = '1'; }
            if (showMap != "1") { //toggle if not default
                this.toggleMap(null);
            }
        }

        if (typeof (VEMap) != 'undefined') {
            this.internalMap = new VEMap(renderTo.id);

            if (this.internalMap) {
                if (this.latitude && this.longitude) {
                    var point = new VELatLong(parseFloat(this.latitude), parseFloat(this.longitude));

                    if (this.visibleMapType == null)
                        this.visibleMapType = VEMapStyle.Road;


                    this.internalMap.SetClientToken(VEMAP_TOKEN);

                    this.internalMap.LoadMap(point, 12, this.visibleMapType);
                    if (this.height && this.width) {
                        this.internalMap.Resize(this.width, this.height);
                    }
                }
            }
        }
    },
    /**
    * Returns the button's underlying element
    * @return {Ext.Element} The element
    */
    getEl: function() {
        return this.el;
    },
    addMarker: function(lat, lng, isActive, customIconPath, infoPopup) {
        if (lat && lng && typeof (VEMap) != 'undefined' && this.internalMap) {
            var point = new VELatLong(parseFloat(lat), parseFloat(lng));

            marker = new VEShape(VEShapeType.Pushpin, point);

            if (isActive) {
                marker.SetCustomIcon('<img src="/ListingsWeb/App_Themes/RealEstate/Images/map/houseBlue.gif"/>');
            }
            else {
                marker.SetCustomIcon('<img src="/ListingsWeb/App_Themes/RealEstate/Images/map/houseGray_tiny.gif"/>');
            }

            if (this.markerImage)
                marker.SetCustomIcon(this.markerImage);

            if (customIconPath && customIconPath.length > 0) {
                marker.SetCustomIcon('<img src="' + customIconPath + '"/>');
            }
            if (infoPopup && infoPopup.length > 0) {
                marker.SetDescription(infoPopup);
            }

            this.internalMap.AddShape(marker)

            return marker;
        }
    },
    setMapType: function(type) {
        //this.internalMap.SetMapStyle(type);
    },
    setZoom: function(zoom) {
        if (this.internalMap) {
            this.internalMap.SetZoomLevel(zoom);
        }
    },
    removeOverlay: function(overlay) {
        if (overlay && this.internalMap)
            this.internalMap.DeleteShape(overlay);
    },
    clearOverlays: function() {
        if (this.internalMap) {
            this.internalMap.DeleteAllShapes();
        }
    },
    showAllMarkers: function() {
        if (this.internalMap) {
            this.internalMap.ShowAllShapeLayers();
        }
    },
    toggleMap: function(e, sender) {
        var el = Ext.get('listings-map');
        var expandButton = Ext.get('btn-map-hide');
        if (el && expandButton) {
            var showMap = readCookie("realestate", "mapVisible");
            if (typeof (showMap) == 'undefined' || showMap == null)
            { showMap = '1'; }
            if (e != null)
            { showMap = showMap.toggle("0", "1"); }
            if (!sender || (sender && sender.id == expandButton.id)) {
                var opt = {
                    easing: 'backIn',
                    duration: .3
                };
                el.parent().setVisibilityMode(Ext.Element.DISPLAY);

                el.setVisible(showMap == '1' ? true : false);
                el.parent().setVisible(showMap == '1' ? true : false);
                expandButton.dom.innerText = (showMap == '1' ? "Hide Map" : "Show Map");
            }
            setCookie("realestate", "mapVisible", showMap);
        }
    }
});

RE.Forms.RequestCall = function(config) {
    config = config || {};

    Ext.apply(this, config);
    this.addEvents(
        'submit'
    );
    RE.Forms.RequestCall.superclass.constructor.call(this);
};
Ext.extend(RE.Forms.RequestCall, Ext.Component, {
    referrer: 0,
    listingId: 0,
    getTimeZone: function() {
        if (!this.timezone)
            this.timezone = new Date().getTimezone();

        return this.timezone;
    },
    reOneOrMoreDigits: /[\d+]/,
    reNoDigits: /[^\d]/gi,
    setDisplayed: function(value) {
        this.el.setDisplayed(value);
    },
    onRender: function(ct, position) {
        if (this.el) {
            this.el = Ext.get(this.el);
        }

        if (!this.cookieProvider)
            this.cookieProvider = new Ext.state.CookieProvider({ domain: ".realestate.com" });

        var formObject = this.cookieProvider.get('rac_values');

        var id = Ext.id();
        if (!this.template) {
            this.template = new Ext.XTemplate(
                '<div id="rac-inline-content_' + id + '" class="rac-form block shaded">',
                    '<div class="squeeze">',
                        '<p class="title">Get Immediate Callback</p>',
                        '<div class="body">',
                            '<div class="subCopy">Have a question? Want to see a home?</div>',
                            '<div class="form-bwrap">',
                                '<div class="firstName">',
                                    '<label for="fname_' + id + '">First Name:</label>',
                                    '<input class="re-fname" name="fname_' + id + '" maxlength="20" id="fname_' + id + '"',
                                    'tabindex="21" type="text" />',
                                '</div>',
                                '<div class="lastName">',
                                    '<label for="lname_' + id + '">Last Name:</label>',
                                    '<input class="re-lname" name="anHttpWebRequesttxtLastName" maxlength="20" id="lname_' + id + '"',
                                    'tabindex="22" type="text" />',
                                '</div>',
                                '<div class="phone">',
                                    '<span class="phonemain">',
                                        '<label for="phone_' + id + '">Phone:</label>',
                                        '<br />',
                                        '<input class="re-phone" name="phone_' + id + '" maxlength="14" id="phone_' + id + '"',
                                        'tabindex="23" type="text" />',
                                    '</span><span class="ext">',
                                        '<label for="extension_' + id + '">ext:</label>',
                                        '<br />',
                                        '<input class="re-ext" name="extension_' + id + '" id="extension_' + id + '" tabindex="24"',
                                        'type="text" />',
                                    '</span>',
                                '</div>',
                                '<a id="submit_' + id + '" class="thinButton submit" tabindex="25">Call Me</a>',
                                '<div class="legalLinks">',
                                    '<a href="/ListingsWeb/CustomerSupport/Privacy.aspx" id="A5" target="_blank" class="novisit legalese"',
                                        'tabindex="16">Privacy Policy</a> <span class="seperator">&nbsp;|&nbsp;</span>',
                                    '<a href="/ListingsWeb/CustomerSupport/TermsOfUse.aspx" id="A6" target="_blank" class="novisit legalese"',
                                        'tabindex="17">Terms of Use</a>',
                                '</div>',
                                '<div class="footer"></div>',

                        '</div>',
                    '</div>',
                '</div>'

                );

            this.template.compile();
        }

        if (this.el == null) {
            this.el = this.template.append(ct, { timezone: this.getTimeZone() }, true);
        }
        this.el.addClass('re-rac-form');

        if (this.referrer == 0) {

            referrerEl = this.el.child('input#referrerid');
            if (referrerEl)
                this.referrer = referrerEl.getValue();
        }

        if (this.listingId == 0) {

            listingEl = this.el.child('#listingid');
            if (listingEl)
                this.listingId = listingEl.getValue();
        }

        Ext.QuickTips.init();
        this.firstName = new Ext.form.TextField({
            allowBlank: false,
            vtype: 'alpha',
            applyTo: this.el.child("input.re-fname")
        });

        if (formObject)
            this.firstName.setRawValue(formObject.firstName);

        this.lastName = new Ext.form.TextField({
            allowBlank: false,
            vtype: 'alpha',
            applyTo: this.el.child("input.re-lname")
        });

        if (formObject)
            this.lastName.setRawValue(formObject.lastName);

        var phoneNumberExpr = /^([\(]{1}[0-9]{3}[\)]{1}[ ]{1}[0-9]{3}[\-]{1}[0-9]{4})$/;

        this.phone = new Ext.form.TextField({
            enableKeyEvents: true,
            allowBlank: false,
            regex: phoneNumberExpr,
            invalidText: 'The format is wrong, ie: (###) ###-####',
            regexText: 'the format is (###) ###-####',
            applyTo: this.el.child("input.re-phone"),
            plugins: [new RE.InputTextMask('(999) 999-9999', true)]
        });

        if (formObject)
            this.phone.setRawValue(formObject.phone);

        this.ext = new Ext.form.TextField({
            allowBlank: true,
            maskRe: /[0-9]/,
            applyTo: this.el.child("input.re-ext")
        });

        if (formObject)
            this.ext.setRawValue(formObject.ext);

        this.button = this.el.child("a.submit");
        this.button.on('click', this.submit, this);
    },
    /**
    * Returns the button's underlying element
    * @return {Ext.Element} The element
    */
    getEl: function() {
        return this.el;
    },
    submit: function() {

        if (!this.firstName.isValid())
            return false;

        if (!this.lastName.isValid())
            return false;

        if (!this.phone.isValid())
            return false;

        //this.el.mask("Loading...", 'x-mask-loading');
        if (!this.cookieProvider)
            this.cookieProvider = new Ext.state.CookieProvider({ domain: ".realestate.com" });

        var formObject = this.cookieProvider.get('rac_values');

        if (!formObject)
            formObject = new Object();

        formObject.firstName = this.firstName.getValue();
        formObject.lastName = this.lastName.getValue();
        formObject.phone = this.phone.getValue();
        formObject.ext = this.ext.getValue();

        this.cookieProvider.set('rac_values', formObject)

        Ext.Ajax.request({
            url: '/handlers/RequestCall.ashx',
            params:
                {
                    fname: this.firstName.getValue(),
                    lname: this.lastName.getValue(),
                    phone: this.phone.getValue(),
                    ext: this.ext.getValue(),
                    timeZone: this.getTimeZone(),
                    listingId: this.listingId,
                    providerId: this.providerId,
                    referrer: this.referrer,
                    icode: this.icode,
                    treeComputerId: (typeof Tree != 'undefined') ? Tree.Pixel.Api.GetTreeComputerId() : null,
                    treeSessionId: (typeof Tree != 'undefined') ? Tree.Pixel.Api.GetTreeSessionId() : null
                },
            method: 'POST',
            scope: this,
            success: function(result, request) {
                this.fireEvent("submit");
                responseObject = Ext.decode(result.responseText);

                if (responseObject.success) {

                    win = new Ext.Window({
                        layout: 'fit',
                        width: 420,
                        autoHeight: true,
                        baseCls: 're-window',
                        cls: 're-thankyou',
                        title: '<div class="header-icon"></div><p>Thank You!</p>',
                        modal: true,
                        border: false,
                        draggable: false,
                        resizable: false,
                        closeAction: 'hide',
                        plain: true,
                        html: '<iframe src="/ListingsWeb/CustomerSupport/Thankyou.aspx?messageOnly=1" width="400" height="160" frameborder="0" scrolling="no" ></iframe>',
                        buttons: { text: 'Close', handler: function() { win.hide(); } }
                    });

                    win.show();
                }
                else {
                    this.fireEvent("submit");
                    Ext.MessageBox.alert('Failed', responseObject.errors.reason);
                }
                //this.el.unmask();

            },
            failure: function(result, request) {
                Ext.MessageBox.alert('Failed', 'Failed posting to');
                this.el.unmask();
            }
        });

    }
});



RE.Forms.EmailFriend = function(config) {
    config = config || {};

    Ext.apply(this, config);
    this.addEvents(
        'submit'
    );
    RE.Forms.EmailFriend.superclass.constructor.call(this);
};
Ext.extend(RE.Forms.EmailFriend, Ext.Component, {
    reOneOrMoreDigits: /[\d+]/,
    reNoDigits: /[^\d]/gi,
    setDisplayed: function(value) {
        this.el.setDisplayed(value);
    },
    onRender: function(ct, position) {
        if (this.el) {
            this.el = Ext.get(this.el);
        }

        Ext.QuickTips.init();
        this.myName = new Ext.form.TextField({
            allowBlank: false,
            vtype: 'alpha',
            applyTo: this.el.child("input.re-fname")
        });

        this.friendName = new Ext.form.TextField({
            allowBlank: false,
            vtype: 'alpha',
            applyTo: this.el.child("input.re-lname")
        });

        this.myMail = new Ext.form.TextField({
            allowBlank: false,
            vtype: 'email',
            applyTo: this.el.child("input.re-fname")
        });

        this.friendMail = new Ext.form.TextField({
            allowBlank: false,
            vtype: 'email',
            applyTo: this.el.child("input.re-lname")
        });

        this.ext = new Ext.form.TextField({
            allowBlank: true,
            maskRe: /[0-9]/,
            applyTo: this.el.child("input.re-ext")
        });

        if (formObject)
            this.ext.setRawValue(formObject.ext);

        this.button = this.el.child("a.submit");
        this.button.on('click', this.submit, this);
    },
    /**
    * Returns the button's underlying element
    * @return {Ext.Element} The element
    */
    getEl: function() {
        return this.el;
    },
    submit: function() {

        if (!this.firstName.isValid())
            return false;

        if (!this.lastName.isValid())
            return false;

        if (!this.phone.isValid())
            return false;

        //this.el.mask("Loading...", 'x-mask-loading');
        if (!this.cookieProvider)
            this.cookieProvider = new Ext.state.CookieProvider({ domain: ".realestate.com" });
        var formObject = this.cookieProvider.get('rac_values');
        if (!formObject)
            formObject = new Object();
        formObject.firstName = this.firstName.getValue();
        formObject.lastName = this.lastName.getValue();
        formObject.phone = this.phone.getValue();
        formObject.ext = this.ext.getValue();

        this.cookieProvider.set('rac_values', formObject)

        Ext.Ajax.request({
            url: '/handlers/email.ashx',
            params:
                {
                    fname: this.firstName.getValue(),
                    lname: this.lastName.getValue(),
                    phone: this.phone.getValue(),
                    ext: this.ext.getValue(),
                    timeZone: this.getTimeZone(),
                    listingId: this.listingId,
                    providerId: this.providerId,
                    referrer: this.referrer,
                    icode: this.icode
                },
            method: 'POST',
            scope: this,
            success: function(result, request) {
                responseObject = Ext.decode(result.responseText);

                if (responseObject.success) {
                    this.fireEvent("submit");
                    win = new Ext.Window({
                        layout: 'fit',
                        width: 420,
                        autoHeight: true,
                        baseCls: 're-window',
                        cls: 're-thankyou',
                        title: '<div class="header-icon"></div><p>Thank You!</p>',
                        modal: true,
                        border: false,
                        draggable: false,
                        resizable: false,
                        closeAction: 'hide',
                        plain: true,
                        html: '<iframe src="/ListingsWeb/CustomerSupport/Thankyou.aspx?messageOnly=1" width="400" height="160" frameborder="0" scrolling="no" ></iframe>',
                        buttons: { text: 'Close', handler: function() { win.hide(); } }
                    });

                    win.show(this.button);
                }
                else {
                    this.fireEvent("submit");
                    Ext.MessageBox.alert('Failed', responseObject.errors.reason);
                }
                //this.el.unmask();
            },
            failure: function(result, request) {
                Ext.MessageBox.alert('Failed', 'Failed posting to');
                this.el.unmask();
            }
        });

    }
});


RE.Forms.NewHomesRequestCall = function(renderTo, config) {
    Ext.apply(this, config);
    this.addEvents(
        'submit'
    );
    RE.Forms.NewHomesRequestCall.superclass.constructor.call(this);
};
Ext.extend(RE.Forms.NewHomesRequestCall, Ext.Component, {
    reOneOrMoreDigits: /[\d+]/,
    reNoDigits: /[^\d]/gi,
    setDisplayed: function(value) {
        this.el.setDisplayed(value);
    },
    onRender: function(renderTo) {
        var form;
        if (!this.cookieProvider)
            this.cookieProvider = new Ext.state.CookieProvider({ domain: ".realestate.com" });

        var formObject = this.cookieProvider.get('rac_values');

        if (!this.template) {
            if (!RE.Forms.NewHomesRequestCall.Template) {
                RE.Forms.NewHomesRequestCall.Template = new Ext.XTemplate(
    	            '<div class="re-box-body rac re-nhsrac-form">',
                    '<fieldset>',
                        '<input name="anHttpWebRequesthdnListingId" type="hidden" value="{listingId}" />',
                        '<input name="anHttpWebRequesthdnSourceId" type="hidden" value="{sourceId}" />',
                       '<div class="squeeze">',
                        '<div class="x-form-item firstName">',
                            '<label for="nhsRAC-fname" class="x-form-item-label">First Name:</label>',
                            '<div class="x-form-element" style="padding-left: 0pt;">',
                            '<input class="x-form-item re-fname" name="anHttpWebRequesttxtFirstName" maxlength="50" type="text" />',
                            '</div>',
                                '<div class="x-form-clear-left"></div>',
                        '</div>',
                        '<div class="x-form-item lastName">',
                            '<label for="nhsRAC-lname" class="x-form-item-label">Last Name:</label>',
                            '<div class="x-form-element" style="padding-left: 0pt;">',
                            '<input class="x-form-item re-lname" name="anHttpWebRequesttxtLastName" maxlength="50" type="text" />',
                            '</div>',
                                '<div class="x-form-clear-left"></div>',
                        '</div>',
                        '<div class="x-form-item address">',
                            '<label for="nhsRAC-address" class="x-form-item-label">Address:</label>',
                            '<div class="x-form-element" style="padding-left: 0pt;">',
                            '<input class="x-form-item re-address" name="anHttpWebRequesttxtAddress" maxlength="50" type="text" />',
                            '</div>',
                                '<div class="x-form-clear-left"></div>',
                        '</div>',
                        '<div class="x-form-item city">',
                            '<label for="nhsRAC-city" class="x-form-item-label">City:</label>',
                            '<div class="x-form-element" style="padding-left: 0pt;">',
                            '<input class="x-form-item re-city" name="anHttpWebRequesttxtCity" maxlength="50" type="text" />',
                            '</div>',
                        '</div>',
                        '<div class="x-form-item state">',
                            '<label for="nhsRAC-state" class="x-form-item-label">State:</label>',
                            '<div class="x-form-element" style="padding-left: 0pt;">',
                            '<input class="x-form-item re-state" name="anHttpWebRequesttxtState" maxlength="20" type="text" />',
                            '</div>',
                         '</div>',
                        '<div class="x-form-item zip">',
                            '<span class="zip"><label for="nhsRAC-zip" class="x-form-item-label">Zip Code:</label>',
                            '<div class="x-form-element" style="padding-left: 0pt;">',
                                '<input class="x-form-item re-zip" name="anHttpWebRequesttxtZip" type="text" maxlength="5"/>',
                                '</div>',
                                '<div class="x-form-clear-left"></div>',
                            '</span>',
                        '</div>',
                        '<div class="x-form-item phone">',
                            '<label for="nhsRAC-phone" class="x-form-item-label">Phone:</label>',
                            '<div class="x-form-element" style="padding-left: 0pt;">',
                            '<input class="x-form-item re-phone" name="anHttpWebRequesttxtPhone" maxlength="20" type="text" />',
                            '</div>',
                            '<span class="ext"><label for="nhsRAC-ext" class="x-form-item-label">Ext:</label>',
                            '<div class="x-form-element" style="padding-left: 0pt;">',
                                '<input class="x-form-item re-ext" name="anHttpWebRequesttxtPhoneExt" type="text" />',
                                '</div>',
                                '<div class="x-form-clear-left"></div>',
                            '</span>',
                        '</div>',
                        '<div class="x-form-item email">',
                            '<label for="nhsRAC-email" class="x-form-item-label" >Email:</label>',
                            '<div class="x-form-element" style="padding-left: 0pt;">',
                            '<input class="x-form-item re-email" name="anHttpWebRequesttxtEmail" maxlength="50" type="text" />',
                            '</div>',
                                '<div class="x-form-clear-left"></div>',
                        '</div>',
                        '<a class="thinButton submit" >Go</a>',
                        '<div class="x-form-clear-left"></div>',
                        '<div class="legalLinks">',
                            '<a href="/ListingsWeb/CustomerSupport/Privacy.aspx" id="nhsRACPrivacy" rel="nofollow" target="_blank" class="novisit legalese" tabindex="77">Privacy Policy</a> ',
                            '<span class="seperator">&nbsp;|&nbsp;</span>',
                            '<a href="/ListingsWeb/CustomerSupport/TermsOfUse.aspx" id="nhsRACTerms" rel="nofollow" target="_blank" class="novisit legalese" tabindex="78">Terms of Use</a>',
                        '</div>',
                    '</div>',
                    '</fieldset>',
                    '</div>'
                );

            }
            this.template = RE.Forms.NewHomesRequestCall.Template;
            this.template.compile();
        }

        if (this.applyTo != null) {
            form = Ext.get(this.applyTo);
        }
        else {
            form = this.template.append(renderTo, { listingId: this.listingId, sourceId: this.sourceId }, true);
        }

        form.addClass('re-nhsrac-form');

        Ext.QuickTips.init();
        this.firstName = new Ext.form.TextField({
            allowBlank: false,
            vtype: 'alpha',
            applyTo: form.child("input.re-fname")
        });

        if (formObject)
            this.firstName.setRawValue(formObject.firstName);

        this.lastName = new Ext.form.TextField({
            allowBlank: false,
            maskRe: /[A-Za-z ]/,
            applyTo: form.child("input.re-lname")
        });

        if (formObject)
            this.lastName.setRawValue(formObject.lastName);

        this.address = new Ext.form.TextField({
            allowBlank: false,
            maskRe: /[A-Za-z0-9 ]/,
            applyTo: form.child("input.re-address")
        });

        if (formObject)
            this.address.setRawValue(formObject.address);

        this.city = new Ext.form.TextField({
            allowBlank: false,
            maskRe: /[A-Za-z ]/,
            applyTo: form.child("input.re-city")
        });

        if (formObject)
            this.city.setRawValue(formObject.city);

        this.state = new Ext.form.TextField({
            allowBlank: false,
            vtype: 'alpha',
            applyTo: form.child("input.re-state")
        });

        if (formObject)
            this.state.setRawValue(formObject.state);

        this.zip = new Ext.form.TextField({
            allowBlank: false,
            maskRe: /[0-9]/,
            applyTo: form.child("input.re-zip")
        });

        if (formObject)
            this.zip.setRawValue(formObject.zip);

        Ext.QuickTips.init();
        var phoneNumberExpr = /^([\(]{1}[0-9]{3}[\)]{1}[ ]{1}[0-9]{3}[\-]{1}[0-9]{4})$/;

        this.phone = new Ext.form.TextField({
            enableKeyEvents: true,
            allowBlank: false,
            regex: phoneNumberExpr,
            invalidText: 'The format is wrong, ie: (###) ###-####',
            regexText: 'the format is (###) ###-####',
            applyTo: form.child("input.re-phone"),
            plugins: [new RE.InputTextMask('(999) 999-9999', true)]
        });

        if (formObject)
            this.phone.setRawValue(formObject.phone);

        this.ext = new Ext.form.TextField({
            allowBlank: true,
            maskRe: /[0-9]/,
            applyTo: form.child("input.re-ext")
        });

        if (formObject)
            this.ext.setRawValue(formObject.ext);

        this.email = new Ext.form.TextField({
            allowBlank: false,
            vtype: 'email',
            applyTo: form.child("input.re-email")
        });

        if (formObject)
            this.email.setRawValue(formObject.email);

        this.button = form.child("a.submit");
        this.button.on('click', this.submit, this);

        this.el = form;
    },
    /**
    * Returns the button's underlying element
    * @return {Ext.Element} The element
    */
    getEl: function() {
        return this.el;
    },
    submit: function() {

        if (!this.firstName.isValid())
            return false;

        if (!this.lastName.isValid())
            return false;

        if (!this.address.isValid())
            return false;

        if (!this.city.isValid())
            return false;

        if (!this.state.isValid())
            return false;

        if (!this.zip.isValid())
            return false;

        if (!this.phone.isValid())
            return false;

        if (!this.email.isValid())
            return false;

        //this.el.mask("Loading...", 'x-mask-loading');
        if (!this.cookieProvider)
            this.cookieProvider = new Ext.state.CookieProvider({ domain: ".realestate.com" });

        var formObject = this.cookieProvider.get('rac_values');
        if (!formObject)
            formObject = new Object();
        formObject.firstName = this.firstName.getValue();
        formObject.lastName = this.lastName.getValue();
        formObject.address = this.address.getValue();
        formObject.city = this.city.getValue();
        formObject.state = this.state.getValue();
        formObject.zip = this.zip.getValue();
        formObject.phone = this.phone.getValue();
        formObject.ext = this.ext.getValue();
        formObject.email = this.email.getValue();

        this.cookieProvider.set('rac_values', formObject)

        Ext.Ajax.request({
            url: '/handlers/NewHomeSourcePost.ashx',
            params:
                {
                    fname: this.firstName.getValue(),
                    lname: this.lastName.getValue(),
                    address: this.address.getValue(),
                    city: this.city.getValue(),
                    state: this.state.getValue(),
                    zip: this.zip.getValue(),
                    phone: this.phone.getValue(),
                    ext: this.ext.getValue(),
                    email: this.email.getValue(),
                    listingId: this.listingId,
                    providerId: this.providerId,
                    sourceId: this.sourceId,
                    referrer: this.referrer
                },
            method: 'POST',
            scope: this,
            success: function(result, request) {
                responseObject = Ext.decode(result.responseText);

                if (responseObject.success) {
                    this.fireEvent("submit");
                    win = new Ext.Window({
                        layout: 'fit',
                        width: 400,
                        height: 160,
                        baseCls: 're-window',
                        cls: 're-thankyou',
                        title: '<div class="header-icon"></div><p>Thank You!</p>',
                        modal: true,
                        border: false,
                        draggable: false,
                        resizable: false,
                        closeAction: 'hide',
                        plain: true,
                        floating: true,
                        html: '<iframe src="/ListingsWeb/CustomerSupport/ThankyouNewHome.aspx?messageOnly=1" width="450" height="80" frameborder="0" scrolling="no" ></iframe>',
                        buttons: { text: 'Close', handler: function() { win.hide(); } }
                    });

                    win.show(this.button);

                    var closeLink = win.body.createChild({ tag: "a", cls: "x-tool-close", href: "#", html: "Return to your search" });
                    closeLink.on({
                        'click': function() { win.hide() }
                    });
                }
                else {
                    Ext.MessageBox.alert('Failed', responseObject.errors.reason);
                }
                //this.el.unmask();
            },
            failure: function(result, request) {
                responseObject = Ext.decode(result.responseText);
                var strError = null;
                try {
                    strError = responseObject.errors.reason;
                }
                catch (e) { }
                Ext.MessageBox.alert('Failed', strError ? strError : "Failed Posting");
                this.el.unmask();
            }
        });

    }
});

RE.InputTextMask = function(mask, clearWhenInvalid) {

    if (clearWhenInvalid === undefined)
        this.clearWhenInvalid = true;
    else
        this.clearWhenInvalid = clearWhenInvalid;

    this.rawMask = mask;
    this.viewMask = '';
    this.maskArray = new Array();
    var mai = 0;
    var regexp = '';
    for (var i = 0; i < mask.length; i++) {
        if (regexp) {
            if (regexp == 'X') {
                regexp = '';
            }
            if (mask.charAt(i) == 'X') {
                this.maskArray[mai] = regexp;
                mai++;
                regexp = '';
            } else {
                regexp += mask.charAt(i);
            }
        } else if (mask.charAt(i) == 'X') {
            regexp += 'X';
            this.viewMask += '_';
        } else if (mask.charAt(i) == '9' || mask.charAt(i) == 'L' || mask.charAt(i) == 'l' || mask.charAt(i) == 'A') {
            this.viewMask += '_';
            this.maskArray[mai] = mask.charAt(i);
            mai++;
        } else {
            this.viewMask += mask.charAt(i);
            this.maskArray[mai] = RegExp.escape(mask.charAt(i));
            mai++;
        }
    }

    this.specialChars = this.viewMask.replace(/(L|l|9|A|_|X)/g, '');
};

RE.InputTextMask.prototype = {

    init: function(field) {
        this.field = field;

        if (field.rendered) {
            this.assignEl();
        } else {
            field.on('render', this.assignEl, this);
        }

        field.on('blur', this.removeValueWhenInvalid, this);
        field.on('focus', this.processMaskFocus, this);
    },

    assignEl: function() {
        this.inputTextElement = this.field.getEl().dom;
        this.field.getEl().on('keypress', this.processKeyPress, this);
        this.field.getEl().on('keydown', this.processKeyDown, this);
        if (Ext.isSafari || Ext.isIE) {
            this.field.getEl().on('paste', this.startTask, this);
            this.field.getEl().on('cut', this.startTask, this);
        }
        if (Ext.isGecko || Ext.isOpera) {
            this.field.getEl().on('mousedown', this.setPreviousValue, this);
        }
        if (Ext.isGecko) {
            this.field.getEl().on('input', this.onInput, this);
        }
        if (Ext.isOpera) {
            this.field.getEl().on('input', this.onInputOpera, this);
        }
    },
    onInput: function() {
        this.startTask(false);
    },
    onInputOpera: function() {
        if (!this.prevValueOpera) {
            this.startTask(false);
        } else {
            this.manageBackspaceAndDeleteOpera();
        }
    },

    manageBackspaceAndDeleteOpera: function() {
        this.inputTextElement.value = this.prevValueOpera.cursorPos.previousValue;
        this.manageTheText(this.prevValueOpera.keycode, this.prevValueOpera.cursorPos);
        this.prevValueOpera = null;
    },

    setPreviousValue: function(event) {
        this.oldCursorPos = this.getCursorPosition();
    },

    getValidatedKey: function(keycode, cursorPosition) {
        var maskKey = this.maskArray[cursorPosition.start];
        if (maskKey == '9') {
            return keycode.pressedKey.match(/[0-9]/);
        } else if (maskKey == 'L') {
            return (keycode.pressedKey.match(/[A-Za-z]/)) ? keycode.pressedKey.toUpperCase() : null;
        } else if (maskKey == 'l') {
            return (keycode.pressedKey.match(/[A-Za-z]/)) ? keycode.pressedKey.toLowerCase() : null;
        } else if (maskKey == 'A') {
            return keycode.pressedKey.match(/[A-Za-z0-9]/);
        } else if (maskKey) {
            return (keycode.pressedKey.match(new RegExp(maskKey)));
        }
        return (null);
    },

    removeValueWhenInvalid: function() {
        if (this.clearWhenInvalid && this.inputTextElement.value.indexOf('_') > -1) {
            this.inputTextElement.value = '';
        }
    },

    managePaste: function() {
        if (this.oldCursorPos == null) {
            return;
        }
        var valuePasted = this.inputTextElement.value.substring(this.oldCursorPos.start, this.inputTextElement.value.length - (this.oldCursorPos.previousValue.length - this.oldCursorPos.end));
        if (this.oldCursorPos.start < this.oldCursorPos.end) {//there is selection...
            this.oldCursorPos.previousValue =
            this.oldCursorPos.previousValue.substring(0, this.oldCursorPos.start) +
            this.viewMask.substring(this.oldCursorPos.start, this.oldCursorPos.end) +
            this.oldCursorPos.previousValue.substring(this.oldCursorPos.end, this.oldCursorPos.previousValue.length);
            valuePasted = valuePasted.substr(0, this.oldCursorPos.end - this.oldCursorPos.start);
        }
        this.inputTextElement.value = this.oldCursorPos.previousValue;
        keycode = { unicode: '',
            isShiftPressed: false,
            isTab: false,
            isBackspace: false,
            isLeftOrRightArrow: false,
            isDelete: false,
            pressedKey: ''
        }
        var charOk = false;
        for (var i = 0; i < valuePasted.length; i++) {
            keycode.pressedKey = valuePasted.substr(i, 1);
            keycode.unicode = valuePasted.charCodeAt(i);
            this.oldCursorPos = this.skipMaskCharacters(keycode, this.oldCursorPos);
            if (this.oldCursorPos === false) {
                break;
            }
            if (this.injectValue(keycode, this.oldCursorPos)) {
                charOk = true;
                this.moveCursorToPosition(keycode, this.oldCursorPos);
                this.oldCursorPos.previousValue = this.inputTextElement.value;
                this.oldCursorPos.start = this.oldCursorPos.start + 1;
            }
        }
        if (!charOk && this.oldCursorPos !== false) {
            this.moveCursorToPosition(null, this.oldCursorPos);
        }
        this.oldCursorPos = null;
    },

    processKeyDown: function(e) {
        this.processMaskFormatting(e, 'keydown');
    },

    processKeyPress: function(e) {
        this.processMaskFormatting(e, 'keypress');
    },

    startTask: function(setOldCursor) {
        if (this.task == undefined) {
            this.task = new Ext.util.DelayedTask(this.managePaste, this);
        }
        if (setOldCursor !== false) {
            this.oldCursorPos = this.getCursorPosition();
        }
        this.task.delay(0);
    },

    skipMaskCharacters: function(keycode, cursorPos) {
        if (cursorPos.start != cursorPos.end && (keycode.isDelete || keycode.isBackspace))
            return (cursorPos);
        while (this.specialChars.match(RegExp.escape(this.viewMask.charAt(((keycode.isBackspace) ? cursorPos.start - 1 : cursorPos.start))))) {
            if (keycode.isBackspace) {
                cursorPos.dec();
            } else {
                cursorPos.inc();
            }
            if (cursorPos.start >= cursorPos.previousValue.length || cursorPos.start < 0) {
                return false;
            }
        }
        return (cursorPos);
    },

    isManagedByKeyDown: function(keycode) {
        if (keycode.isDelete || keycode.isBackspace) {
            return (true);
        }
        return (false);
    },

    processMaskFormatting: function(e, type) {
        this.oldCursorPos = null;
        var cursorPos = this.getCursorPosition();
        var keycode = this.getKeyCode(e, type);
        if (keycode.unicode == 0) {//?? sometimes on Safari
            return;
        }
        if ((keycode.unicode == 67 || keycode.unicode == 99) && e.ctrlKey) {//Ctrl+c, let's the browser manage it!
            return;
        }
        if ((keycode.unicode == 88 || keycode.unicode == 120) && e.ctrlKey) {//Ctrl+x, manage paste
            this.startTask();
            return;
        }
        if ((keycode.unicode == 86 || keycode.unicode == 118) && e.ctrlKey) {//Ctrl+v, manage paste....
            this.startTask();
            return;
        }
        if ((keycode.isBackspace || keycode.isDelete) && Ext.isOpera) {
            this.prevValueOpera = { cursorPos: cursorPos, keycode: keycode };
            return;
        }
        if (type == 'keydown' && !this.isManagedByKeyDown(keycode)) {
            return true;
        }
        if (type == 'keypress' && this.isManagedByKeyDown(keycode)) {
            return true;
        }
        if (this.handleEventBubble(e, keycode, type)) {
            return true;
        }
        return (this.manageTheText(keycode, cursorPos));
    },

    manageTheText: function(keycode, cursorPos) {
        if (this.inputTextElement.value.length === 0) {
            this.inputTextElement.value = this.viewMask;
        }
        cursorPos = this.skipMaskCharacters(keycode, cursorPos);
        if (cursorPos === false) {
            return false;
        }
        if (this.injectValue(keycode, cursorPos)) {
            this.moveCursorToPosition(keycode, cursorPos);
        }
        return (false);
    },

    processMaskFocus: function() {
        if (this.inputTextElement.value.length == 0) {
            var cursorPos = this.getCursorPosition();
            this.inputTextElement.value = this.viewMask;
            this.moveCursorToPosition(null, cursorPos);
        }
    },

    isManagedByBrowser: function(keyEvent, keycode, type) {
        if (((type == 'keypress' && keyEvent.charCode === 0) ||
            type == 'keydown') && (keycode.unicode == Ext.EventObject.TAB ||
            keycode.unicode == Ext.EventObject.RETURN ||
            keycode.unicode == Ext.EventObject.ENTER ||
            keycode.unicode == Ext.EventObject.SHIFT ||
            keycode.unicode == Ext.EventObject.CONTROL ||
            keycode.unicode == Ext.EventObject.ESC ||
            keycode.unicode == Ext.EventObject.PAGEUP ||
            keycode.unicode == Ext.EventObject.PAGEDOWN ||
            keycode.unicode == Ext.EventObject.END ||
            keycode.unicode == Ext.EventObject.HOME ||
            keycode.unicode == Ext.EventObject.LEFT ||
            keycode.unicode == Ext.EventObject.UP ||
            keycode.unicode == Ext.EventObject.RIGHT ||
            keycode.unicode == Ext.EventObject.DOWN)) {
            return (true);
        }
        return (false);
    },

    handleEventBubble: function(keyEvent, keycode, type) {
        try {
            if (keycode && this.isManagedByBrowser(keyEvent, keycode, type)) {
                return true;
            }
            keyEvent.stopEvent();
            return false;
        } catch (e) {
            alert(e.message);
        }
    },

    getCursorPosition: function() {
        var s, e, r;
        if (this.inputTextElement.createTextRange) {
            r = document.selection.createRange().duplicate();
            r.moveEnd('character', this.inputTextElement.value.length);
            if (r.text === '') {
                s = this.inputTextElement.value.length;
            } else {
                s = this.inputTextElement.value.lastIndexOf(r.text);
            }
            r = document.selection.createRange().duplicate();
            r.moveStart('character', -this.inputTextElement.value.length);
            e = r.text.length;
        } else {
            s = this.inputTextElement.selectionStart;
            e = this.inputTextElement.selectionEnd;
        }
        return this.CursorPosition(s, e, r, this.inputTextElement.value);
    },

    moveCursorToPosition: function(keycode, cursorPosition) {
        var p = (!keycode || (keycode && keycode.isBackspace)) ? cursorPosition.start : cursorPosition.start + 1;
        if (this.inputTextElement.createTextRange) {
            cursorPosition.range.move('character', p);
            cursorPosition.range.select();
        } else {
            this.inputTextElement.selectionStart = p;
            this.inputTextElement.selectionEnd = p;
        }
    },

    injectValue: function(keycode, cursorPosition) {
        if (!keycode.isDelete && keycode.unicode == cursorPosition.previousValue.charCodeAt(cursorPosition.start))
            return true;
        var key;
        if (!keycode.isDelete && !keycode.isBackspace) {
            key = this.getValidatedKey(keycode, cursorPosition);
        } else {
            if (cursorPosition.start == cursorPosition.end) {
                key = '_';
                if (keycode.isBackspace) {
                    cursorPosition.dec();
                }
            } else {
                key = this.viewMask.substring(cursorPosition.start, cursorPosition.end);
            }
        }
        if (key) {
            this.inputTextElement.value = cursorPosition.previousValue.substring(0, cursorPosition.start)
                + key +
                cursorPosition.previousValue.substring(cursorPosition.start + key.length, cursorPosition.previousValue.length);
            return true;
        }
        return false;
    },

    getKeyCode: function(onKeyDownEvent, type) {
        var keycode = {};
        keycode.unicode = onKeyDownEvent.getKey();
        keycode.isShiftPressed = onKeyDownEvent.shiftKey;

        keycode.isDelete = ((onKeyDownEvent.getKey() == Ext.EventObject.DELETE && type == 'keydown') || (type == 'keypress' && onKeyDownEvent.charCode === 0 && onKeyDownEvent.keyCode == Ext.EventObject.DELETE)) ? true : false;
        keycode.isTab = (onKeyDownEvent.getKey() == Ext.EventObject.TAB) ? true : false;
        keycode.isBackspace = (onKeyDownEvent.getKey() == Ext.EventObject.BACKSPACE) ? true : false;
        keycode.isLeftOrRightArrow = (onKeyDownEvent.getKey() == Ext.EventObject.LEFT || onKeyDownEvent.getKey() == Ext.EventObject.RIGHT) ? true : false;
        keycode.pressedKey = String.fromCharCode(keycode.unicode);
        return (keycode);
    },

    CursorPosition: function(start, end, range, previousValue) {
        var cursorPosition = {};
        cursorPosition.start = isNaN(start) ? 0 : start;
        cursorPosition.end = isNaN(end) ? 0 : end;
        cursorPosition.range = range;
        cursorPosition.previousValue = previousValue;
        cursorPosition.inc = function() { cursorPosition.start++; cursorPosition.end++; };
        cursorPosition.dec = function() { cursorPosition.start--; cursorPosition.end--; };
        return (cursorPosition);
    }
};

Ext.applyIf(RegExp, {
    escape: function(str) {
        return new String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
    }
});

RE.CookiePanel = function(config) {
    config = config || {};

    Ext.apply(config);
    RE.CookiePanel.superclass.constructor.call(this, config);
};
Ext.extend(RE.CookiePanel, Ext.Panel, {
    data: new Array(),
    max: 50,
    add: function(o) {


        this.data.unshift(o);
        this.data = this.data.unique(this.key);

        if (this.max && this.data.length > this.max)
            this.data.removeIndex(-1);

        this.cookieProvider.set(this.cookie, this.data)

        this.refresh();
    },
    // private
    doAutoLoad: function() {
        if (!this.cookieProvider)
            this.cookieProvider = new Ext.state.CookieProvider({ domain: ".realestate.com" });

        if (!this.cookie)
            this.cookie = typeof this.autoLoad == 'object' ? this.autoLoad : { cookie: this.autoLoad }

        this.data = this.cookieProvider.get(this.cookie) || new Array();

        this.refresh();
    },
    load: function(cookie) {
        if (!this.cookieProvider)
            this.cookieProvider = new Ext.state.CookieProvider({ domain: ".realestate.com" });

        if (!this.cookie)
            this.cookie = cookie;

        this.data = this.cookieProvider.get(this.cookie) || new Array();

        this.refresh();
    },
    refresh: function() {
        //this.tpl.overwrite(this.body,this.data);

        this.body.update('');
        var el = this.body.createChild({ tag: "ul" });
        Ext.each(
            this.data,
            function(item, index, all) {
                item.index = index;
                item.index++;

                var itm = this.tpl.append(el, item, true);

                if (this.canDelete == true) {
                    var delBtn = itm.createChild(
                        {
                            tag: "a",
                            href: "#",
                            children: { tag: "img", cls: "re-refine-item-icon", src: "/Images/Buttons/closebox_orange.gif" }
                        },
                        itm.child('a', true)
                    );

                    delBtn.on({
                        'click': {
                            fn: this.remove,
                            scope: this,
                            single: true,
                            dataId: index
                        }
                    });

                }

            }
            , this);

        var links = this.body.createChild({ tag: "div", cls: "re-refine-links" });
        var clear_link = links.createChild({ tag: "a", cls: "re-refine-clear", href: "#", html: String.format('Clear {0}', this.title) });
        clear_link.on({
            'click': {
                fn: this.clear,
                scope: this,
                single: true
            }
        });
    },
    remove: function(e, t, o) {
        this.data.removeIndex(o.dataId);
        this.refresh();
    },
    clear: function() {
        if (!this.cookieProvider)
            this.cookieProvider = new Ext.state.CookieProvider({ domain: ".realestate.com" });

        if (this.cookie) {
            this.cookieProvider.clear(this.cookie);
            this.data = this.cookieProvider.get(this.cookie) || new Array();
        }
        this.refresh();
    }
});

Ext.util.Format.usMoney = function(v) {
    v = (Math.round((v - 0) * 100)) / 100;
    v = (v == Math.floor(v)) ? v + "" : ((v * 10 == Math.floor(v * 10)) ? v + "0" : v);
    v = String(v);
    var ps = v.split('.');
    var whole = ps[0];
    var sub = ps[1] ? '.' + ps[1] : '';
    var r = /(\d+)(\d{3})/;
    while (r.test(whole)) {
        whole = whole.replace(r, '$1' + ',' + '$2');
    }
    v = whole + sub;
    if (v.charAt(0) == '-') {
        return '-$' + v.substr(1);
    }
    return "$" + v;
};
Ext.util.Format.toDate = function(v) {

    var dY = parseInt(v.substring(0, 4));
    var dM = parseInt(v.substring(5, 7));
    var dD = parseInt(v.substring(8, 10));
    var d = new Date(dY, dM, dD);

    return d.format("MM/dd/yyyy");

};

// String.startsWith() 
if (typeof String.prototype.startsWith === 'undefined') {
    String.prototype.startsWith = function(str) {
        return (this.match("^" + str) == str)
    };
}
// String.endsWith() 
if (typeof String.prototype.endsWith === 'undefined') {
    String.prototype.endsWith = function(str) {
        return (this.match(str + "$") == str)
    };
}
// Array.unshift() - Add an element to the beginning of an array
if (typeof Array.prototype.unshift === 'undefined') {
    Array.prototype.unshift = function() {
        this.reverse();
        var a = arguments, i = a.length;
        while (i--) { this.push(a[i]); }
        this.reverse();
        return this.length;
    };
}

// Array.indexOf( value, begin, strict ) - Return index of the first element that matches value
Array.prototype.indexOf = function(v, b, s, key) {
    for (var i = +b || 0, l = this.length; i < l; i++) {
        if (typeof this[i] == "object") {
            if (this[i][key] === v[key])
                return i;
            /*
            if(typeof Array.prototype.toSource==='undefined' )
            {
            if(Ext.encode(this[i])==Ext.encode(v))
            return i;
            }
            else
            {
            if(this[i].toSource()==v.toSource())
            return i;
            }
            */
        }
        if (this[i] === v || s && this[i] == v)
            return i;
    }
    return -1;
};

// Array.unique( strict ) - Remove duplicate values
Array.prototype.unique = function(key, b) {
    var a = [], i, l = this.length;
    for (i = 0; i < l; i++) {
        if (a.indexOf(this[i], 0, b, key) < 0)
            a.push(this[i]);
    }
    return a;
};
Array.prototype.removeIndex = function(from, to) {
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
};

function cloneObject(what) {
    for (i in what) {
        if (typeof what[i] == 'object') {
            this[i] = new cloneObject(what[i]);
        }
        else
            this[i] = what[i];
    }
}



function init() { }
var iPropId = 0;

function addEvent(obj, evType, fn) {
    if (obj.addEventListener) {
        obj.addEventListener(evType, fn, true);
        return true;
    } else if (obj.attachEvent) {
        var r = obj.attachEvent("on" + evType, fn);
        return r;
    } else {
        return false;
    }
}

function removeEvent(obj, evType, fn, useCapture) {
    if (obj.removeEventListener) {
        obj.removeEventListener(evType, fn, useCapture);
        return true;
    } else if (obj.detachEvent) {
        var r = obj.detachEvent("on" + evType, fn);
        return r;
    } else {
        alert("Handler could not be removed");
    }
}

function cursor_wait() {
    var rules = document.styleSheets[0].cssRules ? document.styleSheets[0].cssRules[0] : document.styleSheets[0].rules[0];
    rules.style.cursor = 'wait';
}

function cursor_clear() {
    var rules = document.styleSheets[0].cssRules ? document.styleSheets[0].cssRules[0] : document.styleSheets[0].rules[0];
    rules.style.cursor = 'default';
}

function RequestCallPopup(title, referrer, listingId) {
    if (!this.rac)
        this.rac = new RE.Forms.RequestCall({ applyTo: 'nextStepsRequestCall', referrer: referrer, listingId: listingId });

    var windowHeight = 178;

    if (Ext.isIE)
        windowHeight = 200;

    this.racwin = new Ext.Window({
        width: 615,
        height: windowHeight,
        shim: true,
        baseCls: 're-window',
        cls: 're-thankyou',
        title: '<div class="header-icon"></div><p>' + title + '</p>',
        items: this.rac,
        modal: true,
        border: false,
        draggable: false,
        resizable: false,
        closeAction: 'hide',
        plain: true,
        buttons: { text: 'Close', handler: function() { racwin.close(); } }
    });
    this.rac.on('submit', function() { this.racwin.hide(); }, this);
    this.rac.setDisplayed(true);
    this.racwin.show(this.button);
}

function NewHomePopup(title, referrer, listingId, sourceId) {
    if (!this.nhs)
        this.nhs = new RE.Forms.NewHomesRequestCall('nhs-inline-popup', { referrer: referrer, listingId: listingId, sourceId: sourceId });

    this.nhswin = new Ext.Window({
        width: 450,
        autoHeight: true,
        baseCls: 're-window',
        cls: 're-thankyou',
        title: '<div class="header-icon"></div><p>' + title + '</p>',
        items: this.nhs,
        modal: true,
        border: false,
        draggable: false,
        resizable: false,
        closeAction: 'hide',
        plain: true,
        floating: true,
        buttons: { text: 'Close', handler: function() { nhswin.close(); } }
    });
    this.nhs.on('submit', function() { this.nhswin.hide(); }, this);
    //this.nhs.setDisplayed(true);
    this.nhswin.show(this.button);
}

//todo: implement all popup feature options?
function OpenPopup(page, title, width, height) {
    OpenPopup(page, title, width, height, "yes");
}

function OpenPopup(page, title, width, height, scrollbars) {
    var strWindowsFeatures = 'width=' + width + ',height=' + height + ',scrollbars=' + scrollbars + ',resizable=no,toolbar=no,menubar=no,location=no,directories=no,x=50,y=50';
    OpenWin = this.open(page, title, strWindowsFeatures);
}


function getAnElement(elementId) {
    var elemReturn = null;
    if (document.getElementById) // this is the way the standard browsers work
        elemReturn = document.getElementById(elementId);
    else if (document.all) // this is the way old msie versions work
        elemReturn = document.all[elementId];
    else if (document.layers) // this is the way nn4 works
        elemReturn = document.layers[elementId];

    return elemReturn;
}
function toggleVisibility(strElementId) {

    var elem = getAnElement(strElementId);
    if (elem != null) {
        elem.style.display = (elem.style.display == 'block' ? 'none' : 'block');
        elem.style.visibility = (elem.style.visibility == 'visible' ? 'hidden' : 'visible');
    }
}
function CreateBookmark(url, title) {
    if (window.sidebar) { // Mozilla Firefox Bookmark		
        window.sidebar.addPanel(title, url, "");
    }
    else if (window.external) { // IE Favorite		
        window.external.AddFavorite(url, title);
    }
    else if (window.opera && window.print) { // Opera Hotlist		
        var mbm = document.createElement('a');
        mbm.setAttribute('rel', 'sidebar');
        mbm.setAttribute('href', url);
        mbm.setAttribute('title', title);
        mbm.click();
    }
}

function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
    }
    return [curleft, curtop];
}

// Move an element directly on top of another element (and optionally
// make it the same size)
function Cover(aBottomElement, aTopElement, ignoreSize) {
    var location = Sys.UI.DomElement.getLocation(aBottomElement);
    aTopElement.style.position = 'absolute';
    aTopElement.style.top = location.y + getScrollY() + 'px';
    aTopElement.style.left = location.x + 'px';
    if (!ignoreSize) {
        aTopElement.style.height = aBottomElement.offsetHeight + 'px';
        aTopElement.style.width = aBottomElement.offsetWidth + 'px';
        aTopElement.style.height = '0px';
        aTopElement.style.width = '0px';
    }
}
function getScrollY() {
    var scrOfY = 0;
    if (typeof (window.pageYOffset) == 'number') {
        //Netscape compliant
        scrOfY = window.pageYOffset;
        scrOfY = 0;
    } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
        //DOM compliant
        scrOfY = document.body.scrollTop;
    } else if (document.documentElement &&
      (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
        //IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
    }
    return scrOfY;
}
function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name, keyName) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) {
            if (keyName) {
                var va = c.substring(nameEQ.length, c.length).split('&');
                var keyNameEQ = keyName + "=";
                for (var j = 0; j < va.length; j++) {
                    var v = va[j];
                    while (v.charAt(0) == ' ') v = v.substring(1, v.length);
                    if (v.indexOf(keyNameEQ) == 0) return v.substring(keyNameEQ.length, v.length);
                }
            }
            else { return c.substring(nameEQ.length, c.length); }
        }
    }
    return null;
}

function setCookie(name, keyName, value) {
    var bCookieFound = false;
    var bKeyFound = false;
    var nameEQ = name + "=";
    var cookieValue = "";
    var ca = document.cookie.split(';');
    var expDate;
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) {
            if (keyName) {
                var va = c.substring(nameEQ.length, c.length).split('&');
                var keyNameEQ = keyName + "=";
                for (var j = 0; j < va.length; j++) {
                    if (cookieValue.length > 0)
                    { cookieValue += "&"; }
                    var v = va[j];
                    while (v.charAt(0) == ' ') v = v.substring(1, v.length);
                    if (v.indexOf(keyNameEQ) == 0) {
                        bKeyFound = true;
                        cookieValue += keyNameEQ + value;
                    }
                    else {
                        cookieValue += v;
                    }
                }
                if (!bKeyFound) {
                    if (cookieValue.length > 0)
                    { cookieValue += "&"; }
                    cookieValue += keyNameEQ + value;
                }
            }
            else { cookieValue = value; }
            bCookieFound = true;
            expDate = unescape(c).split('expireDate=')[1]; // split out date to reuse
            break;
        }
    }
    if (!bCookieFound) {
        cookieValue = value;
    }
    if (typeof (expDate) == 'undefined')
    { expDate = new Date(new Date().setTime(new Date().getTime() + 180 * 24 * 60 * 60 * 1000)); } // 180 days
    document.cookie = name + "=" + cookieValue + "; domain=.realestate.com; expires=" + expDate + "; path=/";
}

function toggleFilters(e, filterToggle) {
    var showFields = readCookie("realestate", "searchMore");

    if (typeof (showFields) == 'undefined' || showFields == null) {
        showFields = '1';
    }
    if (e != null)
    { filterToggle = this; showFields = showFields.toggle("0", "1"); }

    var parent = Ext.get("searchCriteria");
    if (parent) {
        var wrapper = parent.child(".sc-bwrap");

        wrapper.toggleClass("sc-collapsed");

        var s = filterToggle.dom.innerHTML;
        var i = parent.getHeight().toString();

        s = wrapper.hasClass('sc-collapsed') ? 'Show Search Options' : 'Hide Search Options';
        i = i.toggle('90', '165');

        filterToggle.dom.innerHTML = s;
        parent.setHeight(i, true);
        wrapper.setHeight(i - 20, false);
        setCookie("realestate", "searchMore", showFields);
    }
}

function updateListingType(e, dd) {
    if (e != null)
        dd = this;
    if (dd.hiddenName.indexOf('ListingType') > 0) {
        var propertyType = new Ext.Element(Ext.select('.search-types-col').elements[0]);
        if (typeof (propertyType) != 'undefined' && propertyType != null) {
            var title = Ext.select('.alert-title').elements[0];
            var label = Ext.select('.alert-label').elements[0];
            var searchCombo = Ext.getCmp('searchTextBox');
            propertyType.setVisibilityMode(Ext.Element.VISIBILITY);
            if (typeof (label) != 'undefined' && label != null) {
                label.innerText = 'Search by City and State, or Zip';
                label.innerHTML = label.innerText;
            }
            if (dd.getValue() == 'Rental') {
                //clear the value
                var hdnInput = propertyType.child('input[type=hidden]');
                if (typeof (hdnInput) != 'undefined' && hdnInput != null)
                { hdnInput.value = ''; hdnInput.dom.value = ''; }
                propertyType.hide();
                if (typeof (title) != 'undefined' && title != null) {
                    title.innerText = 'Find Rentals';
                    title.innerHTML = title.innerText;
                }
                if (typeof (searchCombo) != 'undefined' && searchCombo != null) {
                    if (searchCombo.getRawValue() == '')
                        searchCombo.setValue('City and State or Zip');
                    searchCombo.emptyText = 'City and State or Zip';
                }
            }
            else {
                propertyType.show();
                if (typeof (title) != 'undefined' && title != null) {
                    switch (dd.getValue()) {
                        case "NewHomes":
                            title.innerText = 'Find New Homes for Sale';
                            title.innerHTML = title.innerText;
                            if (typeof (searchCombo) != 'undefined' && searchCombo != null) {
                                if (searchCombo.getRawValue() == '')
                                    searchCombo.setValue('City and State or Zip');
                                searchCombo.emptyText = 'City and State or Zip';
                            }
                            break;
                        case "Foreclosed":
                            title.innerText = 'Find Foreclosures';
                            title.innerHTML = title.innerText;
                            if (typeof (searchCombo) != 'undefined' && searchCombo != null) {
                                if (searchCombo.getRawValue() == '')
                                    searchCombo.setValue('City and State or Zip');
                                searchCombo.emptyText = 'City and State or Zip';
                            }
                            break;
                        case "Existing":
                            title.innerText = 'Find Homes for Sale';
                            title.innerHTML = title.innerText;
                            if (typeof (label) != 'undefined' && label != null) {
                                label.innerText = 'Search by City and State, or Zip, or MLS#';
                                label.innerHTML = label.innerText;
                            }
                            if (typeof (searchCombo) != 'undefined' && searchCombo != null) {
                                if (searchCombo.getRawValue() == '')
                                    searchCombo.setValue('\'City,ST\', or Zip or MLS#');
                                searchCombo.emptyText = '\'City,ST\', or Zip or MLS#';
                            }
                            break;
                    }
                }
            }
        }
        dd.on('select', updateListingType);
    }
}

function initCriteriaControl(controlID) {
    function submitKeyEventHandler(evt, t, o) {
        if (evt != 13)
            return;

        b = Ext.getDom(el.child('a.submit-button'));
        window.location.href = (b.href);
    }

    if (typeof (controlID) === 'undefined')
        return;

    var el = Ext.get(controlID);

    if (!el)
        return;

    var filterToggle = Ext.get("filtersToggle");
    var advancedFields = Ext.get("alert-advanced");
    var showAdvanced = readCookie("realestate", "searchMore");

    var fieldEls = el.query('.x-form-field');
    for (var x = 0; x < fieldEls.length; x++) {
        fieldEl = Ext.get(fieldEls[x]);
        fieldEl.addKeyListener(13, submitKeyEventHandler);

        if (fieldEl.up('.search-cat-col'))
            updateListingType(null, Ext.getCmp(fieldEl.dom.getAttribute("componentId")));
    }

    if (typeof (showAdvanced) == 'undefined' || showAdvanced == null) {
        setCookie("realestate", "searchMore", "1");
        showAdvanced = "1";
    }

    if (filterToggle && advancedFields) {
        filterToggle.on('click', toggleFilters);

        if (showAdvanced != "1") // if not default, toggle
            toggleFilters(null, filterToggle);
    }
}

function isdefined(variable) {
    return (typeof (window[variable]) == "undefined") ? false : true;
}




