//========================================================
// dcb image loader test start
//========================================================
var gLoadSpinnerUrl = WebRoot + "images/loading_80x60_reloadem.gif";
var gFailImage = WebRoot + "images/no_photo_90x60.gif";

function LoadImage(pSelector, pCallback) {
    var loader = $(pSelector);
    loader.html('<img src="' + gLoadSpinnerUrl + '"/>');
    LoadThisImage($(img), loader, pCallback);
}

function LoadThisImage(loader, pCallback) {
    image_src = loader.attr('src');
    img = new Image();
    img.hide();

    img.load(function() {
        cb_js = loader.get(0).getAttribute('onload');
        onload_cb = function() {
            eval(cb_js);
        }

        loader.html(this);
        loader.removeClass('loadable-image');
        loader.removeAttr('src');
        loader.removeAttr('onload');
        $(this).show();
        if (onload_cb) {
            onload_cb($(this));
        }
        if (pCallback) {
            cb_js = pCallback;
            cb($(this));
        }
    })
    .error(function() { $(this).attr('src', gFailImage).show(); })
    .attr('src', image_src)
    .show();
}

function LoadAllImages() {
    $('loadable-image').each(function() {
        var loader = $(this);
        loader.html('<img src="' + gLoadSpinnerUrl + '"/>');
        LoadThisImage(loader);
    });
}
//========================================================
// dcb image loader test end
//========================================================

LeftNavBusy = 'false'
function setBusy(bool){
    if(bool == 'true'){
        LeftNavBusy = 'true';
    }else{
        LeftNavBusy = 'false';
    }
}

// javascript for results.aspx
$(function() {

    //demo 3
    $('select#valueAA, select#valueBB').selectToUISlider({
        labels: 5
    });

    //fix color
    fixToolTipColor();
    
});
//purely for theme-switching demo... ignore this unless you're using a theme switcher
//quick function for tooltip color match
function fixToolTipColor() {
    //grab the bg color from the tooltip content - set top border of pointer to same
    $('.ui-tooltip-pointer-down-inner').each(function() {
        var bWidth = $('.ui-tooltip-pointer-down-inner').css('borderTopWidth');
        var bColor = $(this).parents('.ui-slider-tooltip').css('backgroundColor')
        $(this).css('border-top', bWidth + ' solid #D8D8D8');
    });
}

function paginationWidth(){
     var width = $("#pagination_wrap").width()+3+'px';
     //alert(width);
     $('.pagination_results').css({'width':width});
     $('.pagination_wrap').css('visibility', 'visible');
     //$(".listing_morehide").css({ 'margin-top': '26px' });
}


function LeftNavSelection(SEOSearch, SEORefinements) {

    var i = 0;
    var val = "";
    SEORefinements = SEORefinements.toLowerCase();
    
    // bedrooms
    i = SEORefinements.indexOf('_beds');
    if (i > 0) {
        val = SEORefinements.substring(i - 2, i);
        gE('results_search_bedrooms').innerHTML = '<span id="45">'+val+'</span>';
        returnSelection(false, 'bedrooms');
    }

    //baths
    i = SEORefinements.indexOf('_baths');
    if (i > 0) {
        val = SEORefinements.substring(i - 2, i);
        gE('results_search_bathrooms').innerHTML = '<span id="46">'+val+'</span>';
        returnSelection(false, 'bathrooms');
    }
    //alert('SEORefinements' + SEORefinements);
    // property types
    i = SEORefinements.indexOf('_type');
    var title = new Array();
    if (i > 0) {
        if (SEORefinements.indexOf('single-family') > 0) { if (gE("results_Single-family") != null) {document.getElementById("results_Single-family").checked = true; title.push('Single Family') }}
        if (SEORefinements.indexOf('condo') > 0) { if (gE("results_Condo") != null) {document.getElementById("results_Condo").checked = true; title.push('Condo') }}
        if (SEORefinements.indexOf('townhouse') > 0) { if (gE("results_Townhouse") != null) {document.getElementById("results_Townhouse").checked = true; title.push('Townhouse') } }
        if (SEORefinements.indexOf('multi-family') > 0) { if (gE("results_Multi-family") != null) {document.getElementById("results_Multi-family").checked = true; title.push('Multi Family') } }
        if (SEORefinements.indexOf('land') > 0) { if (gE("results_Land") != null) {document.getElementById("results_Land").checked = true; title.push('Land')} }
        if (SEORefinements.indexOf('other') > 0) { if (gE("results_Other") != null){document.getElementById("results_Other").checked = true; title.push('Other')} }
        if (gE("results_All-Properties") != null) {document.getElementById("results_All-Properties").checked = false;}
        title.join(', ');
        returnSelection(false,'prop_type',title);
    }
    else {
        if(SEORefinements.indexOf('all') > 0){if (gE("results_All-Properties") != null) {document.getElementById("results_All-Properties").checked = true;} }
    }
    //alert('SEORefinements:-' + SEORefinements);
    // open houses
    i = SEORefinements.indexOf('_openhouses');
    
    var title = new Array();
    if (i > 0) {
        if (SEORefinements.indexOf('today') > 0) { document.getElementById("results_All-Dates").checked = false;document.getElementById("results_Today").checked = true; title.push('Today') }
        if (SEORefinements.indexOf('tomorrow') > 0) { document.getElementById("results_All-Dates").checked = false;document.getElementById("results_Tomorrow").checked = true; title.push('Tomorrow') }
        if (SEORefinements.indexOf('this-weekend') > 0) { document.getElementById("results_All-Dates").checked = false;document.getElementById("results_This-weekend").checked = true; title.push('This Weekend') }
        if (SEORefinements.indexOf('next-weekend') > 0) { document.getElementById("results_All-Dates").checked = false;document.getElementById("results_Next-weekend").checked = true; title.push('Next Weekend') }
        
//        if(SEORefinements.indexOf('today') == -1 && SEORefinements.indexOf('tomorrow') == -1 && SEORefinements.indexOf('this-weekend') == -1 && SEORefinements.indexOf('next-weekend') == -1)
//        {
//        
//            document.getElementById("results_All-Dates").checked = false;
//            title.push('All Dates');
//            alert(title)
//        }
        
        title.join(', ');
        if (title == '') title.push('All Dates');
        returnSelection(false, 'open_house', title);
    }
    else {
        // dcb OH todo - this could be a problem conflict with all-properties. Can the condition be expanded?
        if (SEORefinements.indexOf('all_openhouses') > 0) { document.getElementById("results_All-Dates").checked = true; }
        if (SEORefinements.indexOf('_openhouse') > 0) { if (gE("CustomDateRange") != null) {document.getElementById("CustomDateRange").checked = true; showOHcustomdates(gE("CustomDateRange")) ;  returnSelection(false, 'open_house', "Custom Date Range"); } }
    }
    
    //Check checkboxes if user comes straight in through url
    i = SEORefinements.indexOf('_virtualtours');
    var title = new Array();
    if (i > 0) {
        if (SEORefinements.indexOf('virtualtours') > 0) { 
        document.getElementById("results_With_virtualtours").checked = true;
        title.push('yes')
        title.join(', '); 
        returnSelection(false, 'virtual_tour', title);
        }
    }
    
    // sale types
    if(gE('foreclosures_only').checked === true) {var sType = 'Forclosures'; returnSelection(false, 'sale_type', sType); }
    if(gE('newHomes').checked === true){ var sType = 'New Construction'; returnSelection(false, 'sale_type', sType); } 
    
    // price
    i = SEORefinements.indexOf('_price');
    if (i > 0) {
        //go backwards
        var tmp = "";
        var x = "";
        for (y = i - 1; y > 0; y--) {
            x = SEORefinements.substring(y, y + 1);
            if (x == '/') { break; }
            tmp = x + tmp;
        }
        i = tmp.indexOf('-');
        var pricelow = tmp.substring(0, i);
        var pricehigh = tmp.substring(i + 1, tmp.length);
        if (pricelow == 0)
        {gE('results_search_pricemin').firstChild.innerHTML = "Any Price";}
        else
        {gE('results_search_pricemin').firstChild.innerHTML = formatCurrencyAfterFiltering(pricelow);}
        if (pricehigh == 999999999)
        {gE('results_search_pricemax').firstChild.innerHTML = "Any Price";}
        else
        {gE('results_search_pricemax').firstChild.innerHTML = formatCurrencyAfterFiltering(pricehigh);}
     
        returnSelection(false, 'price', 'min');
        returnSelection(false, 'price', 'max');        
    }

    // sqfeetinterior
    //Ma: I had to change the logic becuse the sqft on left nav clashes with the sqft of the sort in the SEORefinements
    var arrHref = SEORefinements.split('/');
    var tmpe = "";
    i = 0;
    for (var x = 0; x < arrHref.length; x++) {
        if (arrHref[x].substring(0,10).toLowerCase()!= 'price_sqft')
            {
                if (arrHref[x].indexOf('_sqft') > -1) 
                {
                    i = arrHref[x].indexOf('_sqft'); 
                    tmpe = arrHref[x];
                    break;               
                }
            }           
    }
    
    //i = SEORefinements.indexOf('_sqft');
    //alert('i:' + i);
    if (i > 0) {
        //go backwards
        //var tmp = "";
        var x = "";
//        for (y = i - 1; y > 0; y--) {
//            x = SEORefinements.substring(y, y + 1);
//            if (x == '/') { break; }
//            tmp = x + tmp;
//        }
        i = tmpe.indexOf('-');
        //alert('tmp:-'+ tmpe);
        tmpe = tmpe.replace('_sqft','');
        //alert(tmpe);
        var sqftlow = parseInt(tmpe.substring(0, i));
        var sqfthigh = parseInt(tmpe.substring(i + 1, tmpe.length));        
        if (tmpe == 'price')  {sqftlow =0;sqfthigh=5000;}
        if(sqfthigh > 5000){ sqfthigh = 5000;}
        $('.ui-slider').slider('values', 0, (sqftlow/100))
        $('.ui-slider').slider('values', 1, (sqfthigh/100))
        if(sqfthigh == 5000){sqfthigh = '5000+'}
        gE('ttFloor0').innerHTML = sqftlow;
        gE('ttFloor1').innerHTML = sqfthigh;
        returnSelection(false, 'sqft', 'min');
        returnSelection(false, 'sqft', 'max');        
    }

    // builtyear
    i = SEORefinements.indexOf('_builtyear');
    if (i > 0) {
        //go backwards
        var tmp = "";
        var x = "";
        for (y = i - 1; y > 0; y--) {
            x = SEORefinements.substring(y, y + 1);
            if (x == '/') { break; }
            tmp = x + tmp;
        }
        i = tmp.indexOf('-');
        var agelow = parseInt(tmp.substring(0, i));
        var agehigh = parseInt(tmp.substring(i + 1, tmp.length));
        gE('AgeFloorInput').value = agelow;
        gE('AgeCeilingInput').value = agehigh;
        returnSelection(false, 'age', 'min');
        returnSelection(false, 'age', 'max');        
    }

    // openhouse custom date range
    i = SEORefinements.indexOf('_openhouse');
    if (i > 0) {
        //go backwards
        var tmp = "";
        var x = "";
        for (y = i - 1; y > 0; y--) {
            x = SEORefinements.substring(y, y + 1);
            if (x == '/') { break; }
            tmp = x + tmp;
        }
        i = tmp.indexOf('-');
        var ohlow = parseInt(tmp.substring(0, i));
        var ohhigh = parseInt(tmp.substring(i + 1, tmp.length));
        if(isNaN(ohlow)){ohlow = "today";}
        if(isNaN(ohhigh)){ohhigh = "any";}
        
        if (gE('ohstart')!= null) {gE('ohstart').value = ohlow;}
        if (gE('ohend')!=null) {gE('ohend').value = ohhigh;}
        returnSelection(false, 'open_house', 'min');
        returnSelection(false, 'open_house', 'max');        
    }
}

function showOHcustomdates(e) {
    //alert('showOHcustomdates' + e.checked);
    if  (document.getElementById("ohcustom") != null){
        if (e.checked == true){
            document.getElementById("ohcustom").style.display = "block";
            
            //Set all OH dates checkbox to false when OH custom date range is selected
            //*******************************************************************
            gE("results_All-Dates").checked = false;
            if(gE("results_Tomorrow")){
                gE("results_Tomorrow").checked = false;
            }
            
            if(gE("results_This-weekend")){
                gE("results_This-weekend").checked = false;
            }
            
            if(gE("results_Next-weekend")){
                gE("results_Next-weekend").checked = false;
            }
            if(gE("results_Today")){
                gE("results_Today").checked = false;
            }
            //***********************************************************************
            ///End custom date range selection to false
            
        //Remove OH dates
        //****************************************************************************
            var all_li = new Array();
            all_li = getElemsByClass('li', 'selected_li');
            for (var i = 0; i < all_li.length; i++) {
                var childnode = all_li[i].getAttribute('id');  //prop_type_li0
                if (childnode.match('open_house_')) {
                    var deletedchild = all_li[i].getAttribute('id');
                    gE('selected_ul').removeChild(gE(deletedchild));
                }
            }
         //***************************************************************************
         //End remove all oh dates   
        
        //Add the custom date range to what you've selected
        AddCustomDateRangeToWhatYouSelected("Custom Date Range")
        
            
            
        }
        else {
          document.getElementById("ohcustom").style.display = "none"; 
          if (gE("ohstart")!=null) {gE("ohstart").value = ""; }
          if (gE("ohend")!=null)   {gE("ohend").value = "";}
          results_OpenHouseChange(e);
         }
    }
    //LeftNavBusy = 'true';
}    


function AddCustomDateRangeToWhatYouSelected(title)
{
         var currUL = gE('selected_ul').innerHTML;
           var ohGroup = '';
           var calculate_date = -1;
           var ohArr = new Array();
           var tempArr = new Array();

           var oh_type = new Array();

           ohArr = getElemsByClass('li', 'oh_item');
           for (i = 0; i < ohArr.length; i++) {
               if (ohArr[i].firstChild.checked) {
                   if (ohArr[i].firstChild.id == "CustomDateRange")
                   { tempArr.push("Custom Date Range"); }
                   else
                   { tempArr.push(ohArr[i].firstChild.value); }
                   if (ohArr[i].firstChild.value == "All Dates") { calculate_date = 0; } else { calculate_date = 1; }
               }
           }
           //alert('ohArr' + tempArr.length);
           if (ohArr.length == 0) // NO Open Houses are available 
           {
               tempArr.push("All Dates");
           }
           //MA: get the last index of prop_type_li and increment by 1 
           var all_li = new Array();
           var index = 0;
           all_li = getElemsByClass('li', 'selected_li');
           for (var i = 0; i < all_li.length; i++) {
               var childnode = all_li[i].getAttribute('id');  //prop_type_li0
               if (childnode.match('open_house_')) {
                   index = parseInt(childnode.replace('open_house_li', '')) + 1; //index of the last child node increment by 1                                
               }
           }
           //if (calculate_date == 0) {gE("results_All-Dates").checked = true;}
           var valArr = tempArr.slice();
           for (j = 0; j < tempArr.length; j++) {
               if (title.toString().toLowerCase().indexOf(tempArr[j].toString().toLowerCase()) > -1) {
                   if (tempArr[j].toString().length > 10) { tempArr[j] = tempArr[j].toString().substr(0, 7) + '...' }
                   oh_type[j] = String.format("<li style='' name='openHouse' class='selected_li' id='open_house_li" + index + "'><span class='close' onclick='clearFilter(&#39;oh_type&#39;,&#39;{0}&#39;)'><img src='/images/tab-drop-close.gif' height='12' width='12'/></span>Open House: <span class='selection-value'><span id='selected_prop_type" + i + "'>" + tempArr[j] + "</span></span></li>", valArr[j]);
                   //MA:To do an extra check to see if the prop is already added in the selection box..
                   var selected_items = new Array();
                   var added = false;
                   var selected_items = getElemsByClass('span', 'selection-value');
                   for (var s = 0; s < selected_items.length; s++) {
                       if (tempArr[j].substr(0, 7) == selected_items[s].firstChild.innerHTML.substr(0, 7)) {
                           added = true;
                           break;
                       }
                   }

                   // alert(added);
                   if (added == false) { gE('selected_ul').innerHTML = currUL + oh_type[j]; currUL = currUL + oh_type[j]; index = index + 1; }
               }
           } //end of for loop 
            
           //MA: This function is to pop only "All Open houses" from the selection box            

       var all_li = new Array();
       all_li = getElemsByClass('li', 'selected_li');
       for (var i = 0; i < all_li.length; i++) {
           var childnode = all_li[i].getAttribute('id');  //open_house_li0
           if (childnode.match('open_house_')) {
               if (calculate_date == 1) 
               {
                   // pop "All Dates" from temp arr if other dates already added
                   if (all_li[i].lastChild != null) 
                   {
                       //alert('pop:' + all_li[i].lastChild.firstChild.innerHTML.toString().substring(0, 3));
                       var deletedchild = all_li[i].getAttribute('id');
                       if (all_li[i].lastChild.firstChild.innerHTML.toString().substring(0, 3) == "All") { gE('selected_ul').removeChild(gE(deletedchild)); break; }
                   }
               } //end cal date if         
               else if (calculate_date == 0)  // For other dates if "ALL Dates" added
               {
                    if (all_li[i].lastChild != null) 
                   {
                       var deletedchild = all_li[i].getAttribute('id');
                       if (all_li[i].lastChild.firstChild.innerHTML.toString().substring(0, 3) != "All") { gE('selected_ul').removeChild(gE(deletedchild)); break; }
                   }
               }
               
           }  //end of open house if 
       } //end for loop      
      //pop child from the node

}

function resetSlider(){
      $('.ui-slider').slider('values',0,0);
      $('.ui-slider').slider('values',1,50);
}

function MoreInfo(i) {

    var but = "moreinfobutton_" + i;
    var ele = "moreinfo_listing_" + i;
    var oc = gE(ele).style.display;

    if (oc != 'block' || oc == '') {
        gE(ele).style.display = 'block';
        gE(but).innerHTML = 'Less Info';
        gE(but).style.backgroundImage = "url(/images/grey_up_arrow.gif)";
        gE(but).style.backgroundPosition = "0 50%";
        gE(but).style.backgroundRepeat = "no-repeat";
        gE(but).onclick=function(){
                         OmReportEventAndEvar(this,'Property_Listings','32','Hide Information');      };
        GetMoreInfoMapView(i);
    }
    else {
        gE(ele).style.display = 'none';
        gE(but).innerHTML = 'More info';
        gE(but).style.backgroundImage = "url(/images/grey_down_arrow.gif)";
        gE(but).style.backgroundPosition = "0 50%";
        gE(but).style.backgroundRepeat = "no-repeat";
        gE(but).onclick=function(){
                         OmReportEventAndEvar(this,'Property_Listings','32','More Information');      };
    }
}

function ShowSearchField(locationfield) {
    if (gE("results_search_submit").style.display != 'none') {
        document.getElementById("txtAboutPageSearch").value = locationfield;
    }
}
function ShowSearchButton() {
    gE('txtAboutPageSearch').style.width = '108px'; 
    gE('txtAboutPageSearch').style.zIndex = '10';
    gE('txtAboutPageSearch').style.float = 'left';
    gE('txtAboutPageSearch').style.display = 'inline';
    document.getElementById("results_search_submit").style.display = "inline";
}
function HideSearchButton() { 
    gE('txtAboutPageSearch').style.width = '160px'; 
    document.getElementById("results_search_submit").style.display = "none";
    document.getElementById("txtAboutPageSearch").value = FDS.locationfield;
}
function ShowPriceMinOkButton() {
    document.getElementById("results_priceminCustomOKbutton").style.display = "block";
}
function HidePriceMinOkButton() {
    document.getElementById("results_priceminCustomOKbutton").style.display = "none";
}
function ShowPriceMaxOkButton() {
    document.getElementById("results_pricemaxCustomOKbutton").style.display = "block";
}
function HidePriceMaxOkButton() {
    document.getElementById("results_pricemaxCustomOKbutton").style.display = "none";
}
var BevtQueue = "clicked off"; // constant value to determine if it's time to close bar
function results_Bevt(e) {

    var IE7 = (navigator.appVersion.indexOf("MSIE 7.") == -1) ? false : true;
    var IE6 = (navigator.appVersion.indexOf("MSIE 6.") == -1) ? false : true;

    var theTarget;
    if (!e || IE7 || IE6) {
        e = window.event;
        e.cancelBubble = true;
    }
    else {
        e.stopPropagation();
    }
    if (e.target) {
        theTarget = e.target;
    }
    else if (e.srcElement) {
        theTarget = e.srcElement;
    }
    if (theTarget.nodeType == 3) // defeat Safari bug
    {
        theTarget = theTarget.parentNode;
    }

    //alert("type:" + e.type);
    switch (e.type) {
        case "focus":
            BarStatus.value = "event: " + e.type + "\nTarget ID: " + theTarget.id;
            break;
        // **TEMPORARILY COMMENTED OUT TO MAKE RESKINNING SEARCH BAR EASIER 
        case "blur":
            BarStatus.value = BevtQueue;
            window.clearTimeout(BarStatus.timeout);
            BarStatus.timeout = window.setTimeout(function() {
                if (BarStatus.value == BevtQueue) // status value has not changed
                {
                    if (PageCache != null) {
                        // PageCache defined in /results.aspx
                        SwitchSearch('sales', 'small', PageCache.QueryString);
                    }
                    else {
                        // DefaultQueryString defined in /Controls/SearchBar/Global.ascx
                        SwitchSearch('sales', 'small', DefaultQueryString);
                    }
                }
            }, 200);
            break;
    }
    //gE("NavStatus").value = BarStatus.value; 
}


function formatCurrency(num) {
    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++)
    num = num.substring(0,num.length-(4*i+3))+','+
    num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + num);
}


function results_SelectMinPrice(e, id, selectedIndex) {
   // alert('selectedIndex:' + selectedIndex);
    if (selectedIndex == -1)
    {
        if(!(IsNumeric(id)))
        {
            gE('min_price_drop').className = 'results_drop-down results_price_drop_error';
            gE('results_pricemin'+'ErrorMessage').style.display = 'block';
            gE('results_pricemin'+'ErrorMessage').innerHTML = 'Please check your custom price.';
            return;
        }	                
    }
    id = id.replace(",", "")
    if(id.indexOf("Million") != -1 || id.indexOf("No Limit") != -1 || id.indexOf("Any Price") != -1)
    {
        gE("results_search_pricemin").innerHTML = "<span  id='" + selectedIndex + "'>" + id + "</span>";
    
    }
    else
    {
        gE("results_search_pricemin").innerHTML = "<span  id='" + selectedIndex + "'>" + formatCurrency(id) + "</span>";
    }
    dropStateToggle("results_search_max_price");
    returnSelection(true, 'price', 'min');
    //repositionAd();
}

function results_SelectMaxPrice(e, id, selectedIndex) {
    if (selectedIndex == -1)
    {
        if(!(IsNumeric(id)))
        {
            //alert('results_priceminErrorMessage');
            gE('max_price_drop').className = 'results_drop-down results_price_drop_error';
            gE('results_pricemax'+'ErrorMessage').style.display = 'block';
            gE('results_pricemax'+'ErrorMessage').innerHTML = 'Please check your custom price.';
            //e.stop();
            return;
        }	       
     }
    id = id.replace(",", "")
    if(id.indexOf("Million") != -1 || id.indexOf("No Limit") != -1 || id.indexOf("Any Price") != -1)
    {
        gE("results_search_pricemax").innerHTML = "<span  id='" + selectedIndex + "'>" + id + "</span>";
    }
    else
    {
        gE("results_search_pricemax").innerHTML = "<span  id='" + selectedIndex + "'>" + formatCurrency(id) + "</span>";
    }
    dropStateToggle("results_search_min_price");
    returnSelection(true, 'price', 'max');
 }

function results_SelectBed(id, selectedIndex) {
    gE("results_search_bedrooms").innerHTML = "<span id='" + selectedIndex + "'>" + id + "</span>";
}

function results_SelectBath(id, selectedIndex) {
    gE("results_search_bathrooms").innerHTML = "<span id='" + selectedIndex + "'>" + id + "</span>";
}

function results_PropertyTypeChange(e) {
    //alert("e.id: " + e.id);
    if (e.id != "results_All-Properties") {
        document.getElementById("results_All-Properties").checked = false;
    }
    
    //MA: removes the selection from what you have selected by unchecking a box
    if (e.checked == false)
    {
        var all_li = new Array();
        all_li = getElemsByClass('li','selected_li');
        for (var i = 0; i < all_li.length; i++)
         {
            var childnode = all_li[i].getAttribute('id');  //prop_type_li0
            if (childnode.match('prop_type_')) {
                //alert('get the child value' + all_li[i].lastChild.firstChild.innerHTML);
                if (e.value.substr(0,7) == all_li[i].lastChild.firstChild.innerHTML.substr(0,7)) 
                {
                   // gE(all_li[i].getAttribute('id')).style.display = 'none';   
                    var deletedchild = all_li[i].getAttribute('id');
                   //   alert(deletedchild);
                    gE('selected_ul').removeChild(gE(deletedchild));   // MA: removed the element instaed of displaying as none.
                }
            }
         }
          
          
        //Display default message
        displayDefaultMessage()
          
    }  
    else
    {
        //MA: call this function only when the checkbox is selected.
        returnSelection(false,'prop_type',e.value); 
        OmReportRefine(this,'refine','Property_Type',e.value);
    }  
    NewRefinementSearch(LeftNavBusy);
    //repositionAd();
}

var StartDateSelected = false;
function results_OpenHouseChange(e) {
        
       /*Uncheck everything else if custom date range has been checked.*/
        if(e.id == "CustomDateRange" && e.checked == true)
        {
         //Remove OH dates
        //****************************************************************************
            var all_li = new Array();
            all_li = getElemsByClass('li', 'selected_li');
            for (var i = 0; i < all_li.length; i++) {
                var childnode = all_li[i].getAttribute('id');  //prop_type_li0
                if (childnode.match('open_house_')) {
                    var deletedchild = all_li[i].getAttribute('id');
                    gE('selected_ul').removeChild(gE(deletedchild));
                }
            }
         //***************************************************************************
            //End remove all oh dates 
            
            //Un check custom date range
            e.checked = false  
            
        }
        /*End */
        
        if(e.id != "CustomDateRange" && e.id != "ohstart" && e.id != "ohend")
        {
              //Remove OH dates
        //****************************************************************************
            var all_li = new Array();
            all_li = getElemsByClass('li', 'selected_li');
            for (var i = 0; i < all_li.length; i++) {
                var childnode = all_li[i].getAttribute('id');  //prop_type_li0
                if (childnode.match('open_house_')) {
                    var deletedchild = all_li[i].getAttribute('id');
                    if(all_li[i].lastChild.firstChild.innerHTML.indexOf('Custom') != -1)
                    {
                        gE('selected_ul').removeChild(gE(childnode));
                    }
                    
                }
            }
            
         //***************************************************************************
         //End remove all oh dates   
            
            gE("CustomDateRange").checked = false;
            gE("ohstart").value = "";
            gE("ohend").value = "";
            gE("ohcustom").style.display = "none";
        }
       
       /*Uncheck everything else if all dates have been checked.*/
       if(gE("results_All-Dates").checked == true)
       {
        //Remove everything all openhouse filters from what you've selected because all dates
        // was selected
        //****************************************************************************
            var all_li = new Array();
            all_li = getElemsByClass('li', 'selected_li');
            for (var i = 0; i < all_li.length; i++) {
                var childnode = all_li[i].getAttribute('id');  //prop_type_li0
                if (childnode.match('open_house_')) {
                    var deletedchild = all_li[i].getAttribute('id');
                    gE('selected_ul').removeChild(gE(deletedchild));
                }
            }
         //***************************************************************************
            //End remove all
       } 
       /*End remove all dates */
       
        
        
        
    if (e.id == "ohstart" || e.id == "ohend") {
        returnSelection(false, 'open_house', "Custom Date Range" + e.value);
        OmReportRefine(this,'refine','Open_Houses','Custom Date Range');
    }    
    else
    { 
        //If anything else has been checked besides all dates, then uncheck all dates
        if (e.id != "results_All-Dates") {
            gE("results_All-Dates").checked = false;
        }
        
        //MA: removes the selection from what you have selected by unchecking a box
        if (e.checked == false) {
            var all_li = new Array();
            all_li = getElemsByClass('li', 'selected_li');
            for (var i = 0; i < all_li.length; i++) {
                var childnode = all_li[i].getAttribute('id');  //prop_type_li0
                if (childnode.match('open_house_')) {
                    //if (e.value == "All Dates")  { e.value = "All Open Houses" ;}
                    if (e.id == "CustomDateRange") { e.value = "Custom Date Range" ;} 
                    if (e.value.substr(0, 7) == all_li[i].lastChild.firstChild.innerHTML.substr(0, 7)) {
                        var deletedchild = all_li[i].getAttribute('id');
                        gE('selected_ul').removeChild(gE(deletedchild));
                    }
                }
            }
            
            
           //Display default message
           displayDefaultMessage()
          
              
        }
        else {
            //alert('calling rs with open_house');
            returnSelection(false, 'open_house', e.value);
        }
    }
    
    //Only execute if every except for enddate has been executed. End date executes in the return selection function
    //This will stop the loading image to display twice
    if (e.id != "ohend"){
        StartDateSelected = true
    }
    
    if(StartDateSelected == true)
    {
        NewRefinementSearch(LeftNavBusy);
        StartDateSelected = false;
    }
    //repositionAd();
}


function results_VirtualTourChange(e) {
    //This block only executes if vitural tours are not selected   
    if (e.id != "results_With_virtualtours") {
        document.getElementById("results_With_virtualtours").checked = false;
    }
    
    //MA: removes the selection from what you have selected by unchecking a box
    if (e.checked == false)
    {
        var all_li = new Array();
        all_li = getElemsByClass('li','selected_li');
        for (var i = 0; i < all_li.length; i++)
         {
            var childnode = all_li[i].getAttribute('id');  //prop_type_li0
            if (childnode.match('virtual_tour_')) {
                if (e.value.substr(0,7).toLowerCase() == all_li[i].lastChild.firstChild.innerHTML.substr(0,7).toLowerCase() || all_li[i].lastChild.firstChild.innerHTML.substr(0,7).toLowerCase() == "on") 
                {
                    var deletedchild = all_li[i].getAttribute('id');
                    gE('selected_ul').removeChild(gE(deletedchild));   // MA: removed the element instaed of displaying as none.
                }
            }
         }
          //Display default message
           displayDefaultMessage()
    }  
    //Dynamically create items in the What you've selected box.
    else
    {
        //MA: call this function only when the checkbox is selected.
        returnSelection(false,'virtual_tour',e.value); 
    }  
    NewRefinementSearch(LeftNavBusy);
    //repositionAd();
}

//Display default message in What You've Selected(normally executed when check box is unchecked
/*
    Displays default message in What You've Selected box, 
    but only if there are no that the user has selected
*/
function displayDefaultMessage()
{

    //Check if anything is in the What you have selected module
      var all_li = new Array();
      all_li = getElemsByClass('li', 'selected_li');
      for (var i = 0; i < all_li.length; i++) {
        var childnode = all_li[i].getAttribute('id');  //prop_type_li0
        var childnodeInnerHTML = all_li[i].innerHTML;
        var atLeastOneNodeHasHTML = false;
        
        //Check to see if any node has html, if it does set boolean flag to true
        if(childnodeInnerHTML != ''){atLeastOneNodeHasHTML = true;}
        
        //if there are no nodes with html display default message
        if(atLeastOneNodeHasHTML == false){   
            //Display default message
            gE("no_selections_detail").style.display = ""; 
            //Hide save button
            gE("selections_detail").style.display = "none";     
        }
        //If there is at least one node with html hide default message and show save button
        else
        {
            gE("no_selections_detail").style.display = "none"; 
            gE("selections_detail").style.display = "";     
        }
     }
}



var valExist = false

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
//Drop and Close functions for filters
//on left rail. 'filter' is the first half
//of the wrapper string.
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


function closeDrop (current, toggle){
    var filterArr = new Array();
    if(current != ''){
        filterArr = ['bedrooms','bathrooms','pricemin','pricemax','subscribe','sort'];
        for(j=0; j<filterArr.length; j++){
            if(current == filterArr[j]){
                filterArr[j]='';
            }
        }
    }else{
        filterArr = ['bedrooms','bathrooms','pricemin','pricemax','subscribe','sort'];
    }
    for(i = 0; i<filterArr.length; i++){
        if(filterArr[i] != ''){
            filterClose(filterArr[i], toggle);
        }
    }
}


function filterClose(filter, toggle){
    var wrap = '_drop_wrapper';
    //alert(filter+wrap);
    if (gE(filter + wrap) != null)
    {
        if(gE(filter + wrap).style.display != 'none'){
            gE(filter + wrap).style.display = 'none';        
        }
    }
    dropStateToggle("results_search_"+filter, false);
    
    
    if(toggle == false){
        gE('close-drop').style.display = 'none';
        gE('close-drop').style.zIndex = '-1';
        LeftNavBusy = 'false';
    }
}

function filterDrop(filter){
    var wrap = '_drop_wrapper';
    
    if(gE(filter + wrap).style.display != 'block'){
        gE(filter + wrap).style.display = 'block';
    }
    dropStateToggle("results_search_"+filter, true);
    
    
    gE('close-drop').style.display = 'block';
    gE('close-drop').style.zIndex = '1';

    LeftNavBusy = 'true';
    
    closeDrop(filter, true);  
    
}

function dropStateToggle(menu, toggle){
    var filter = menu.replace('results_search_','')+'_drop_wrapper';
    if(menu == 'results_search_sort'){
         if(toggle == true ){
            gE(menu).style.background = 'transparent url( /images/search_type_active.gif ) no-repeat 0 0px';
        }else if (toggle == false && gE(filter).style.display == 'none'){
            gE(menu).style.background = 'transparent url( /images/search_type.gif ) no-repeat 0 0px';
        }
    }else if(menu == 'results_search_subscribe'){
        if(toggle == true ){
            gE(menu).style.background = 'transparent url( /images/subscribe_active_btn.png ) no-repeat 0 0px';
        }else if (toggle == false && gE(filter).style.display == 'none'){
            gE(menu).style.background = 'transparent url( /images/subscribe_btn.gif ) no-repeat 0 0px';
        }
    }else{    
        if(toggle == true){
            gE(menu).style.background = 'transparent url( /images/list_view-btn.png ) no-repeat 0 -20px';
        }else if (toggle == false && gE(filter).style.display == 'none'){
            gE(menu).style.background = 'transparent url( /images/list_view-btn.png ) no-repeat 0 0px';
        }
    }
}
function clearFilter(filter, value){
    if(filter != 'prop_type' && filter != 'oh_type' && filter != 'virtual_tour'){
        gE(filter+'_li').style.display = 'none';
    }
    if(filter == 'price_min' || filter == 'price_max' || filter == 'bed' || filter == 'bath'){
        gE('selected_'+filter).innerHTML = '';
        if(filter == 'price_min'){gE('results_search_pricemin').firstChild.innerHTML='Any Price';}
        if(filter == 'price_max'){gE('results_search_pricemax').firstChild.innerHTML='Any Price';}
        if(filter == 'bed'){gE('results_search_bedrooms').firstChild.innerHTML='Any';}
        if(filter == 'bath'){gE('results_search_bathrooms').firstChild.innerHTML='Any';}
      
        var filter1;
        if (filter == 'bed' || filter == 'bath') 
        {
            filter1 = filter + 'rooms'; // Passing bathrooms instead of bath to the Omniture.
        }
        else
        {
            filter1 = filter;
        }        
        OmReportRefine(this, 'remove', filter1, value);
    }
    if(filter == 'sqft'){
        gE('sqft_floor').innerHTML = '0';
        gE('sqft_ceiling').innerHTML = '5000+';
        resetSlider();
        OmReportRefine(this, 'remove', filter, value);
    }
    if(filter == 'age'){
        gE('age_floor').innerHTML='any'; 
        gE('age_ceiling').innerHTML='any';
        gE('AgeFloorInput').value = 'Year';
        gE('AgeCeilingInput').value = 'Year';
        OmReportRefine(this, 'remove', filter, value);
    }

    
    if(filter == 'prop_type' || filter == 'oh_type' || filter == 'virtual_tour'){ 
        
        if (filter == 'prop_type' && value != "all") OmReportRefine(this, 'remove','Property Type', value);
        if (filter == 'oh_type') OmReportRefine(this, 'remove','Open House', value);
        if (filter == 'virtual_tour'){
            gE("results_With_virtualtours").checked = false;
            OmReportRefine(this, 'remove','Virtual Tour', value);
        }
        
        var typeArr = new Array();
        var tempArr = new Array();
        var all = 0;
        
        if (filter == 'prop_type') typeArr = getElemsByClass('li','type_item');
        if (filter == 'oh_type') typeArr = getElemsByClass('li','oh_item');
        if (filter == 'virtual_tour') typeArr = getElemsByClass('li','type_item');
        
        if (value == "Custom Date Range")
        {
           if (gE("ohstart")!=null) {gE("ohstart").value = ""; }
           if (gE("ohend")!=null)   {gE("ohend").value = "";}
        }
        //uncheck boxes
        for(i=0; i<typeArr.length; i++){
            if(typeArr[i].firstChild.checked){
                if (typeArr[i].firstChild.id == "CustomDateRange")
                   { tempArr.push("Custom Date Range");}
                else
                   { tempArr.push(typeArr[i].firstChild.value); }  
                    
                if(typeArr[i].firstChild.value == value){
                    typeArr[i].firstChild.checked = false;
                }
            }
            if(typeArr[i].firstChild.checked == false){all++}    
        }
        

        if(filter == 'prop_type' && typeArr.length == all){gE('results_All-Properties').checked = true;}
        //if(filter == 'oh_type' && typeArr.length == all){gE('results_All-Dates').checked = true;}
        
        //Byron Fix For IE        
        var all_li = new Array();
        all_li = getElemsByClass('li','selected_li');
        
        
        if(value != 'all'){
            for (var i = 0; i < all_li.length; i++)
             {
                var childnode = all_li[i].getAttribute('id');  //prop_type_li0
                if (childnode.match('prop_type_')) {         
                    if (value.substr(0,7) == all_li[i].lastChild.firstChild.innerHTML.substr(0,7)) 
                    {
                        gE('selected_ul').removeChild(gE(childnode)); 
                    }
                }
                if(childnode.match('open_house_')){
                    //if (value == "All Dates")  { value = "All Open Houses" ;}
                    if (value.substr(0,7) == all_li[i].lastChild.firstChild.innerHTML.substr(0,7)) 
                    {
                        gE('selected_ul').removeChild(gE(childnode)); 
                    }
                }
                if(childnode.match('virtual_tour_')){
                    if (value.substr(0,7).toLowerCase() == all_li[i].lastChild.firstChild.innerHTML.substr(0,7).toLowerCase() || all_li[i].lastChild.firstChild.innerHTML.substr(0,7).toLowerCase() == "on") 
                    {
                        gE('selected_ul').removeChild(gE(childnode)); 
                    }
                }
                
             }
         }else{
            var propTypeArr = new Array();
            var propKillArr = new Array();
            var indexelement = "prop_type_li";
            
            propTypeArr = getElemsByClass('li', 'selected_li');
            
            if (filter == 'oh_type') indexelement = "open_house_li";
            if(filter == 'virtual_tour') indexelement = "virtual_tour_li";
            
            for(var p=0; p<propTypeArr.length; p++){
                if(propTypeArr[p].id.indexOf(indexelement) > -1){
                    propKillArr.push(gE(propTypeArr[p].id));
                }
            }
            
            for(var i=0; i<propKillArr.length; i++){
                gE('selected_ul').removeChild(propKillArr[i]);
            }
            
            var inputArr = new Array();
            inputArr = document.getElementsByTagName('input');
            for(i=0; i<inputArr.length; i++){
                if(inputArr[i].type == 'checkbox'){
                    if(inputArr[i].id.indexOf('results_')>-1)
                        {
                             if(filter == 'prop_type' && inputArr[i].id != 'results_All-Properties'){
                                            gE(inputArr[i].id).checked=false;
                                         }
                             if(filter == 'oh_type' && inputArr[i].id != 'results_All-Dates'){
                                            gE(inputArr[i].id).checked=false;
                                         }           
                        }
                }
            }
         }
    }
    
    var selLiArr = new Array();
    selLiArr = getElemsByClass('li','selected_li');
    
    function isAllClear(){
            //alert('isAllClear')
        var b = 0;
        for(n=0; n<selLiArr.length; n++){
            if(selLiArr[n].style.display=='none'){b++}
            
        }
        if (selLiArr.length == b) return true
    }
    
    if(isAllClear()){
        gE('selections_detail').style.display = 'none';
        gE('no_selections_detail').style.display = '';    
    }
    
    if(filter == 'sale_type'){ gE('foreclosures_sales').checked = true; gE('selected_sale_type').value = value;}
    
    if(filter == 'sale_type' && value.indexOf('.') > -1)
    {
        //omniture 
        if (value.substring(0,3).toLowerCase() == "for")  {OmReportRefine(this, 'remove', 'sale type', 'Foreclosure');}
        if (value.substring(0,3).toLowerCase() == "new")  {OmReportRefine(this, 'remove', 'sale type', 'New Construction');}    
        if (value.substring(0,3).toLowerCase() == "all")  {OmReportRefine(this, 'remove', 'sale type', 'All Properties');}    
    }
  
    RFQuery(LeftNavBusy);
    //repositionAd();
}

/*___AGE FUNCTIONS___*/
function ageFocus(div){
   // gE('AgeWrap').style.background = 'url("/images/lr_gutter-box-inside-active-bg.png")';
    //gE('Selections_Bottom').style.background = 'url("/images/lr_gutter-box-bottom-active-bg.png")';
    gE(div).value='';
    if(div == 'AgeCeilingInput'){
    
        gE('AgeCeilingInput').style.width = '32px'; 
        gE('AgeFloorInput').style.width = '66px'; 
        gE('AgeCeilingOk').style.display = '';
        gE('AgeFloorOk').style.display = 'none';
    }else if(div == 'AgeFloorInput'){
        gE('AgeFloorInput').style.width = '32px'; 
        gE('AgeCeilingInput').style.width = '66px'; 
        gE('AgeFloorOk').style.display = '';
        gE('AgeCeilingOk').style.display = 'none';
    }
    gE('close-age').style.display = 'block';
    gE('close-age').style.zIndex = '1'; 
}

function ageBlur(div){
    gE('AgeWrap').style.background = 'url("/images/lr_gutter-box-inside-bg.gif")';
    gE('Selections_Bottom').style.background = 'url("/images/lr_gutter-box-bottom-bg.gif")';
    if(gE(div).value==''){
        gE(div).value= 'Year';
    }
    
}

function ageFix(div){
    gE('AgeFloorOk').style.display = 'none';
    gE('AgeCeilingOk').style.display = 'none';
    gE('close-age').style.display = 'none';
    gE('close-age').style.zIndex = '-1';
}


//function show_coords(event)
//{
//x=event.clientX;
//y=event.clientY;
//alert("X coords: " + x + ", Y coords: " + y);
//}

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
//END Drop and Close Functions
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
//Show or Hid Selections Module
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
function makeSelection(valExist) {
    if (valExist == true) {
        gE('no_selections_detail').style.display = 'none';
        gE('selections_detail').style.display = '';
    }
}

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
//Main Filter function.
//Required: filter ... Optional: title
//Utilizes filterClose();
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
function returnSort(name, query){
    gE('results_search_sort').innerHTML = name;
    loading(true);
    RunQuery(query);
    //paginationWidth();
    loading(false);
    toogle_map_view(false);
}



function switchPriceRange()
{     //alert("switchPriceRange");
    var priceMin =  gE('results_search_pricemin').firstChild.innerHTML.replace(/,/g,"")
    var priceMax  = gE("results_search_pricemax").firstChild.innerHTML.replace(/,/g,"")
//alert(priceMin)
//alert(priceMax)
    
    var priceMinTemp = gE('results_search_pricemin').innerHTML
    var priceMaxTemp = gE('results_search_pricemax').innerHTML

    var priceMinSelectedTemp = gE('results_search_pricemin').firstChild.innerHTML
    var priceMaxSelectedTemp = gE('results_search_pricemax').firstChild.innerHTML
    
     if(priceMin.indexOf("No Limit") == -1 && priceMax.indexOf("No Limit") == -1 && priceMin.indexOf("Any Price") == -1 && priceMax.indexOf("Any Price") == -1)
    {
     //alert("Did not contain no limit or any price");
        //Both min price and max fields did not contain million now see if min is greater than max
        if(priceMin.indexOf("Million") == -1 && priceMax.indexOf("Million") == -1)
        {
//         alert("Prices did not contain Million");
//         alert(priceMin);
//         alert(priceMax)
           if(parseInt(priceMin) > parseInt(priceMax))
           {
            //alert("Million not selected");
              
             gE("results_search_pricemax").innerHTML = priceMinTemp;
             gE("results_search_pricemin").innerHTML = priceMaxTemp;
             gE("selected_price_max").innerHTML = priceMinSelectedTemp;
             gE("selected_price_min").innerHTML = priceMaxSelectedTemp;
           }
        }
        //Million for max or min was selected so now check if min is greater than max
        else
        {//alert("Min or max was selected")
            if(priceMin.indexOf("Million") != -1 && priceMax.indexOf("Million") != -1)
            {    
                if(parseInt(priceMin) > parseInt(priceMax)){
                     //alert("All selections are millions, but min is greater than max")
                      gE("results_search_pricemax").innerHTML = priceMinTemp;
                      gE("results_search_pricemin").innerHTML = priceMaxTemp;
                      gE("selected_price_max").innerHTML = priceMinSelectedTemp;
                      gE("selected_price_min").innerHTML = priceMaxSelectedTemp;
                }      
            }
            else if(priceMin.indexOf("Million") != -1 && priceMax.indexOf("Million")== -1){
                //alert("Min million selected max regluar number")
                gE("results_search_pricemax").innerHTML = priceMinTemp;
                gE("results_search_pricemin").innerHTML = priceMaxTemp;
                gE("selected_price_max").innerHTML = priceMinSelectedTemp;
                gE("selected_price_min").innerHTML = priceMaxSelectedTemp;
            }
        }
    }
    //No limit minimum
    else{
        if(priceMin.indexOf("No Limit") != -1)
        {
               gE("results_search_pricemax").innerHTML = priceMinTemp;
               gE("results_search_pricemin").innerHTML = priceMaxTemp;
               gE("selected_price_max").innerHTML = priceMinSelectedTemp;
               gE("selected_price_min").innerHTML = priceMaxSelectedTemp;
        }
    }
}

//Format currency after user has already filtered
function formatCurrencyAfterFiltering(text)
{
    text = text.replace(/,/g,"")
    if(text.indexOf("Million") != -1 || text.indexOf("No Limit") != -1 || text.indexOf("Any Price") != -1)
    {
        return text
    }
    else
    {
        return formatCurrency(text)
    }    
}

function foreclosuresOnly(Query) {
    gE("foreclosures_sales").checked = false;
    gE("newHomes").checked = false;
    gE("foreclosures_only").checked = true;
    //RefinementQuery(fc_query);   
    //MA: A new refinement satrting with the new page.
    var UGquery = new UrlGen(fc_query);
    UGquery.RemoveParam("No");
    RefinementQuery(UGquery.ToString());    
    //repositionAd();
}
function foreclosuresSales(Query) {
    gE("foreclosures_only").checked = false;
    gE("newHomes").checked = false;
    gE("foreclosures_sales").checked = true;
    RefinementQuery(ap_query);
    //repositionAd();
}
function newHomes(Query) {
    gE("foreclosures_only").checked = false;
    gE("foreclosures_sales").checked = false;
    gE("newHomes").checked = true;
    var UGquery = new UrlGen(nh_query);
    UGquery.RemoveParam("No");
    RefinementQuery(UGquery.ToString());
    //repositionAd();
}

//function AgeFromOnBlur() {
//    if (ValidateDate("to")) {
//        gE("AgeToError").style.display = 'none';
//        gE("AgeOfHomTo").setfocus();
//        RFQuery();
//    }
//}

//function AgeToOnBlur() {
//    if (ValidateDate("from")) {
//        gE("AgeFromError").style.display = 'none';
//        RFQuery();
//    }
//}

function ValidateDate(sentfrom) {
    return true;
}

function NewRefinementSearch(LeftNavBusy) {

    /*  This fucntion should be called by each refenments onblur to 
    submit a new search to either RfefinementQuery or RunQuery().
    It shoud take the original query string, strip it done, and add the DimValIds for the 
    selected refinemnet options.
    */
    // maybe here stop e.onstart e.ond end from processing... see gts-search
    
    window.setTimeout("RFQuery(LeftNavBusy)", 3000);
}


jQuery(document).ready(function() {
    jQuery('.handCursor').mouseover(function() { $(this).css('cursor', 'pointer') });

    //set property type checkboxes
    document.getElementById("results_All-Properties").checked = false;
    document.getElementById("results_Single-family").checked = false;
    document.getElementById("results_Condo").checked = false;
    document.getElementById("results_Townhouse").checked = false;
    document.getElementById("results_Multi-family").checked = false;
    document.getElementById("results_Land").checked = false;
    document.getElementById("results_Other").checked = false;

    document.getElementById("results_All-Dates").checked = false;
    document.getElementById("results_Today").checked = false;
    document.getElementById("results_Tomorrow").checked = false;
    document.getElementById("results_This-weekend").checked = false;
    document.getElementById("results_Next-weekend").checked = false;
    
    document.getElementById("moreinfo_listing_0").style.display = 'none';
    document.getElementById("moreinfo_listing_1").style.display = 'none';
    document.getElementById("moreinfo_listing_2").style.display = 'none';
    document.getElementById("moreinfo_listing_3").style.display = 'none';
    document.getElementById("moreinfo_listing_4").style.display = 'none';
    document.getElementById("moreinfo_listing_5").style.display = 'none';
    document.getElementById("moreinfo_listing_6").style.display = 'none';
    document.getElementById("moreinfo_listing_7").style.display = 'none';
    document.getElementById("moreinfo_listing_8").style.display = 'none';
    document.getElementById("moreinfo_listing_9").style.display = 'none';

    var ptypes = "<%=PropertyTypes%>";
    if (ptypes.indexOf('all-properties') > 0) { document.getElementById("results_All-Properties").checked = true; }
    if (ptypes.indexOf('single-family') > 0) { document.getElementById("results_Single-family").checked = true; }
    if (ptypes.indexOf('condo') > 0) { document.getElementById("results_Condo").checked = true; }
    if (ptypes.indexOf('townhouse') > 0) { document.getElementById("results_Townhouse").checked = true; }
    if (ptypes.indexOf('multi-family') > 0) { document.getElementById("results_Multi-family").checked = true; }
    if (ptypes.indexOf('land') > 0) { document.getElementById("results_Land").checked = true; }
    if (ptypes.indexOf('other') > 0) { document.getElementById("results_Other").checked = true; }

    var ptypes = "<%=OpenHouses%>";
    if (ptypes.indexOf('all-dates') > 0) { document.getElementById("results_All-Properties").checked = true; }
    if (ptypes.indexOf('today') > 0) { document.getElementById("results_Single-family").checked = true; }
    if (ptypes.indexOf('tomorrow') > 0) { document.getElementById("results_Condo").checked = true; }
    if (ptypes.indexOf('this-weekend') > 0) { document.getElementById("results_Townhouse").checked = true; }
    if (ptypes.indexOf('next-weekend') > 0) { document.getElementById("results_Multi-family").checked = true; }
    
     var ptypes = "<%=VirtualTours%>";
    if (ptypes.indexOf('Virtual-Tour') > 0) { document.getElementById("results_With_virtualtours").checked = true; }
    
    
});

function OpenRSS() {
    gE("rss_wrap").style.display = "block";
}

function CloseRSS() {
    gE("rss_wrap").style.display = "none";
}
function SaveListing(Idlisting, Address, price, bedroom, bathFull, bathaprtial, dateCreated) {
    var querystring = "Id=" + Idlisting + "&Address=" + escape(Address);
    querystring += '&Price=' + price + '&Bedroom=' + bedroom;
    querystring += '&BathsFull=' + bathFull + '&BathsPartial=' + bathaprtial;
    querystring += '&DateCreated=' + dateCreated;
    querystring += '&PathInfo=' + GetPageName() + '&action=addlisting';
    $AJAX.GetForDelegate(UserOptionsDelegate, PersonalizationRoot + "AjaxCalls/My_Options.aspx?" + querystring);
}
function DisplayDebug() {
    gE('DebugTrigger').style.display = 'none';
    gE('DebugInfo').style.display = 'block';
}
function OpenXML() {
    window.open('/results_xml.aspx?' + gE('testingQuery').value, '_new');
}

function Numericvalidation(e, filter, pos, value) {
    //alert(e.which);
    var restrictionType = /[0-9\,{0,1}]/g;
    
      if (filter == 'age') 
      {
        restrictionType = /[0-9]/g;
      }  

      if (!e) var e = window.event

      if (e.keyCode) code = e.keyCode; //IE
      else if (e.which) code = e.which; //firefox, netscape.

      var character = String.fromCharCode(code);

      // if they pressed esc... remove focus from field...

      if (code==27) { this.blur(); return false; }

      if (code==13)   {return false;} // disabling the enter key.

      

      //9 is the tab key , 8 is backspace 127 is delete key.

      if(code == 8 || code == 127){
        gE('AgeError').style.display = 'none';                    
        gE(pos).style.display = 'none';
      }
        
      if (!e.ctrlKey && code!=9 && code!=8 && code!=127) {

            if (character.match(restrictionType)) {
                if(filter == 'price'){
                    gE(pos+'_price_drop').className = 'results_drop-down';
                    gE('results_price'+pos+'ErrorMessage').style.display = 'none';
                    return true;
                }else if(filter =='age'){
                    if (gE('floor').style.display=='block' || gE('ceiling').style.display=='block'){ 
                        gE('AgeError').style.display='none';
                    }                        
                    else{
                        gE('AgeError').style.display='none';                    
                        gE(pos).style.display = 'none';
                    }
                }
            }else{
                if(filter == 'price'){
                    gE(pos+'_price_drop').className = 'results_drop-down results_price_drop_error';
                    gE('results_price'+pos+'ErrorMessage').style.display = 'block';
                    gE('results_price'+pos+'ErrorMessage').innerHTML = 'Please check your custom price.';
                    return false;
                }else if(filter == 'age'){
                    gE('AgeError').style.display='block';
                    gE(pos).style.display = 'block';
                    return false;
                }

            }           

      } 

}

function ReturnSelectionWithEnterKey(e, ele)
{
    var val = ele.value;
    var id = ele.id;
    var age_value = "";
    if (window.event)
    {
        keynum = e.keyCode;
    }
    else if(e.which)
    {
        keynum = e.which;
    }
    switch(keynum)
    {
     case 13:    
        //alert('dispaly' + gE('AgeError').style.display + 'display');
        if (gE('AgeError').style.display == "" || gE('AgeError').style.display == "block")
            {
                   StopProcessingEvents(e);
                   return false;
            }
        if (id.toLowerCase() == 'agefloorinput')
            age_value = 'age_min';
        else{
            age_value = 'age_max';}
        if (val!= '')
            {                           
               // alert('Shod get fired');   
                returnSelection(true, 'age', age_value);
            }
        break;
    }
    //repositionAd();
}

//Loading gif and overlay function

function loading(state){
    if(state == true){
        gE('waiting').style.display = 'block';
        gE('loading-over').style.display = 'block';
    }else if (state == false){
        gE('waiting').style.display = 'none';
        gE('loading-over').style.display = 'none';
    }
}

//Function for small location search
function locDisFix(){
    gE('close-loc').style.display = 'block';
   gE('close-loc').style.zIndex = '1';
}

function setSliderBar(){
    var divArr = new Array();
    divArr = document.getElementsByTagName('div');
    for(var i=0; i<divArr.length; i++){
        if(divArr[i].className == 'ui-slider-range ui-widget-header'){
            divArr[i].id = 'sliderBar';
        }
    }
}

//Function for ad-text under listings

//function setListingHeight(){
//    var btArr = new Array();
//    var heightArr = new Array();

//    btArr = getElemsByClass('div', 'bottom_text');
//    
//    for (var i=1; i<=btArr.length; i++){
//        heightArr.push($('#bottom_text_'+i).height());
//    }
//    
//    for (var i=0; i<heightArr.length; i++){
//        var topHeight = 108;

//        if(gE('lw_'+(i+1)).firstChild.className == 'featured_label'){
//            topHeight += 16;
//        }
//        
//        if(gE('icon_'+(i+1))){ 
//        }else{
//           topHeight -= 18;
//        }
//        
//        $('#lw_'+(i+1)).height(topHeight+heightArr[i]);
//        
//       $('#bottom_text_'+(i+1)).css('top', topHeight+'px');
//        gE('bottom_text_'+(i+1)).style.position = 'absolute';
//          
//    }
//    
//}

function IsNumeric(strString)
   {
  //check for multiple occcurence of the comma. 	
   var strValidChars = "0123456789,";
   var strChar;
   var pos = 0;
   var blnResult = true;

   if (strString.length == 0) return false;
   
   //test strString consists of valid characters listed above
   for (i = 0; i < strString.length; i++)
      {
          strChar = strString.charAt(i);
          if (strChar == "," && i==0)  { blnResult = false;return;} // comma at the beginning. return;           
          if (strChar == "," && i==strString.length-1)  {blnResult = false; return;}// comma at the end.
          if (strValidChars.indexOf(strChar) == -1) { blnResult = false;return;} 
          else
             {
                  if (pos > 0){
                  if (strChar == "," && i == pos + 1)
                  {
                     blnResult = false; // multiple occurence of comma.
                     return;
                  }}
                  if (strChar == ",")  pos = i;
             }            
      }
   return blnResult;
   }

   //**************************************************
   //  Start returnSelection
   //**************************************************
   function returnSelection(requery, filter, title) {
       var dblQuo = '&quot;';
       var matchtag = /<(?:.|\s)*?>/g;

       // alert('filter=' + filter + ' requery=' + requery + ' title=' + title);

       //Price
       if (filter == 'price') {

           //switchPriceRange()

           var priceminHTML = String.format("<span class='close' onclick='clearFilter(&#39;price_min&#39;,&#39;{0}&#39;)'><img src='/images/tab-drop-close.gif' height='12' width='12'/></span>Price Min($): <span class='selection-value'><span id='selected_price_min'>0</span></span>", gE('results_search_pricemin').firstChild.innerHTML);
           var pricemaxHTML = String.format("<span class='close' onclick='clearFilter(&#39;price_max&#39;,&#39;{0}&#39;)'><img src='/images/tab-drop-close.gif' height='12' width='12'/></span>Price Max($): <span class='selection-value'><span id='selected_price_max'>9999999999</span></span>", gE('results_search_pricemax').firstChild.innerHTML);
           if(title == 'max' || requery == true){
            gE('price_max_li').innerHTML = pricemaxHTML;         
            switchPriceRange()
            if (gE('results_search_pricemax').firstChild.innerHTML == "No Limit" || gE('results_search_pricemax').firstChild.innerHTML == "Any Price") 
            {gE('selected_price_max').innerHTML = "No Limit";}
            else
            {gE('selected_price_max').innerHTML = formatCurrencyAfterFiltering(gE('results_search_pricemax').firstChild.innerHTML);}           
            gE('price_max_li').style.display = '';
            filterClose('pricemax', false);            

        }
        
        if(title == 'min' || requery == true){  
            gE('price_min_li').innerHTML = priceminHTML;
            switchPriceRange()
            if (gE('results_search_pricemin').firstChild.innerHTML == "Any Price")
            {gE('selected_price_min').innerHTML = "Any Price";}
            else
            {gE('selected_price_min').innerHTML = formatCurrencyAfterFiltering(gE('results_search_pricemin').firstChild.innerHTML);}
            gE('price_min_li').style.display = '';
            filterClose('pricemin', false);
        }
           if (requery == true) { OmReportRefine(this, 'refine', 'PriceRange:Min-Max', gE('results_search_pricemin').firstChild.innerHTML + "-" + gE('results_search_pricemax').firstChild.innerHTML); }
       }
       //Bathrooms
       if (filter == 'bathrooms') {
           var bath = String.format("<span class='close' onclick='clearFilter(&#39;bath&#39;,&#39;{0}&#39;)'><img src='/images/tab-drop-close.gif' height='12' width='12'/></span>Bathrooms: <span class='selection-value'><span id='selected_bath'></span></span>", gE('results_search_bathrooms').innerHTML.replace(matchtag, ""));

           gE('bath_li').innerHTML = bath;
           gE('selected_bath').innerHTML = gE('results_search_bathrooms').innerHTML;
           gE('bath_li').style.display = '';

           filterClose(filter, false);
           if (requery == true) {OmReportRefine(this, 'refine', 'bathrooms', gE('selected_bath').firstChild.innerHTML);}
       }

       //Bedrooms
       if (filter == 'bedrooms') {
           var bed = String.format("<span class='close' onclick='clearFilter(&#39;bed&#39;,&#39;{0}&#39;)'><img src='/images/tab-drop-close.gif' height='12' width='12'/></span>Bedrooms: <span class='selection-value'><span id='selected_bed'></span></span>", gE('results_search_bedrooms').innerHTML.replace(matchtag, ""));

           gE('bed_li').innerHTML = bed;
           gE('selected_bed').innerHTML = gE('results_search_bedrooms').innerHTML;
           gE('bed_li').style.display = '';

           filterClose(filter, false);

           if (requery == true) {OmReportRefine(this, 'refine', 'bedrooms', gE('selected_bed').firstChild.innerHTML);}
       }
       //Square Feet
       if (filter == 'sqft') {
           var sqft = '';
           var range = document.getElementById('ttFloor0').innerHTML + "-" + document.getElementById('ttFloor1').innerHTML;
           sqft = String.format("<span class='close' onclick='clearFilter(&#39;sqft&#39;,&#39;{0}&#39;)'>", range);
           sqft += "<img src='/images/tab-drop-close.gif' height='12' width='12'/></span>Square Feet: <span class='selection-value'><span id='sqft_floor'>0</span>-<span id='sqft_ceiling'>5000+</span></span>";
           gE('sqft_li').innerHTML = sqft;
           gE('sqft_li').style.display = '';

           gE('sqft_floor').innerHTML = document.getElementById('ttFloor0').innerHTML;
           gE('sqft_ceiling').innerHTML = document.getElementById('ttFloor1').innerHTML;
           if (requery == true) { OmReportRefine(this, 'refine', 'Square footage slider', range); }
           //alert(gE('sqft_ceiling').innerHTML);
           gE('handle_valueAA').className = 'ui-slider-handle ui-state-default ui-corner-all';
           gE('handle_valueBB').className = 'ui-slider-handle ui-state-default ui-corner-all';
       }
       //Age of Home
       if (filter == 'age') {
           var d = new Date();
           var age = '';
           var age1 = '';
           age1 += "Age of Home: <span class='selection-value'><span id='age_floor'>" + gE('AgeFloorInput').value + "</span>";
           age1 += "-<span id='age_ceiling'>" + gE('AgeCeilingInput').value + "</span></span>";

           if (gE('AgeFloorInput').value == '' || gE('AgeFloorInput').value == 'Year') { gE('AgeFloorInput').value = '1900' }
           if (gE('AgeCeilingInput').value == '' || gE('AgeCeilingInput').value == 'Year') { gE('AgeCeilingInput').value = d.getFullYear() }

           var floor = gE('AgeFloorInput').value;
           var ceiling = gE('AgeCeilingInput').value;
           //Switch values if user is backwords.
           if (floor > ceiling) {
               ceiling = gE('AgeFloorInput').value;
               floor = gE('AgeCeilingInput').value;
               gE('AgeFloorInput').value = floor;
               gE('AgeCeilingInput').value = ceiling;
           }
           age = String.format("<span class='close' onclick='clearFilter(&#39;age&#39;,&#39;{0}&#39;)'><img src='/images/tab-drop-close.gif' height='12' width='12'/></span>", floor + "-" + ceiling) + age1;
           gE('age_li').innerHTML = age;

           gE('age_floor').innerHTML = floor;
           gE('age_ceiling').innerHTML = ceiling;
           gE('age_li').style.display = '';
           gE('AgeCeilingOk').style.display = 'none';
           gE('AgeFloorOk').style.display = 'none';
           gE('close-age').style.display = 'none';
           gE('close-age').style.zIndex = '-1';
           gE('AgeError').style.display = 'none';
           if (requery == true) { OmReportRefine(this, 'refine', 'Age_of_Home', floor + "-" + ceiling); }
       }

       //Property Type
       if (filter == 'prop_type') {
           //if(title.length > 10){title = title.substr(0,7)+'...'}
           var currUL = gE('selected_ul').innerHTML;
           //alert(currUL);
           var propGroup = '';
           var typeArr = new Array();
           var tempArr = new Array();

           var prop_type = new Array();

           typeArr = getElemsByClass('li', 'type_item');
           for (i = 0; i < typeArr.length; i++) {

               if (typeArr[i].firstChild.checked) {
                   tempArr.push(typeArr[i].firstChild.value);
               }
           }

           //MA: get the last index of prop_type_li and increment by 1 
           var all_li = new Array();
           var index = 0;
           all_li = getElemsByClass('li', 'selected_li');
           for (var i = 0; i < all_li.length; i++) {
               var childnode = all_li[i].getAttribute('id');  //prop_type_li0
               if (childnode.match('prop_type_')) {
                   index = parseInt(childnode.replace('prop_type_li', '')) + 1; //index of the last child node increment by 1 
               }
           }

           //alert('index' + index);
           //alert(tempArr.length);
           //alert(currUL);
           var valArr = tempArr.slice();
           for (j = 0; j < tempArr.length; j++) {
               if (title.toString().toLowerCase().indexOf(tempArr[j].toString().toLowerCase()) > -1) {
                   if (tempArr[j].toString().length > 10) { tempArr[j] = tempArr[j].toString().substr(0, 7) + '...' }
                   prop_type[j] = String.format("<li style='' name='propType' class='selected_li' id='prop_type_li" + index + "'><span class='close' onclick='clearFilter(&#39;prop_type&#39;,&#39;{0}&#39;)'><img src='/images/tab-drop-close.gif' height='12' width='12'/></span>Property Type: <span class='selection-value'><span id='selected_prop_type" + i + "'>" + tempArr[j] + "</span></span></li>", valArr[j]);
                   //alert('prop type:-' + prop_type[j]);
                   //MA:To do an extra check to see if the prop is already added in the selection box..            
                   var selected_items = new Array();
                   var added = false;
                   var selected_items = getElemsByClass('span', 'selection-value');
                   for (var s = 0; s < selected_items.length; s++) {
                       if (tempArr[j].substr(0, 7) == selected_items[s].firstChild.innerHTML.substr(0, 7)) {
                           added = true;
                           break;
                       }
                   }

                   // alert(added);
                   if (added == false) { gE('selected_ul').innerHTML = currUL + prop_type[j]; currUL = currUL + prop_type[j]; index = index + 1; }
               } // end of the if loop.
           }   // end of the for loop.   
       }

       //Open House
       if (filter == 'open_house') {
           var currUL = gE('selected_ul').innerHTML;
           var ohGroup = '';
           var calculate_date = -1;
           var ohArr = new Array();
           var tempArr = new Array();

           var oh_type = new Array();

           ohArr = getElemsByClass('li', 'oh_item');
           for (i = 0; i < ohArr.length; i++) {
               if (ohArr[i].firstChild.checked) {
                   if (ohArr[i].firstChild.id == "CustomDateRange")
                   { tempArr.push("Custom Date Range"); }
                   else
                   { tempArr.push(ohArr[i].firstChild.value); }
                   if (ohArr[i].firstChild.value == "All Dates") { calculate_date = 0; } else { calculate_date = 1; }
               }
           }
           //alert('ohArr' + tempArr.length);
           if (ohArr.length == 0) // NO Open Houses are available 
           {
               tempArr.push("All Dates");
           }
           //MA: get the last index of prop_type_li and increment by 1 
           var all_li = new Array();
           var index = 0;
           all_li = getElemsByClass('li', 'selected_li');
           for (var i = 0; i < all_li.length; i++) {
               var childnode = all_li[i].getAttribute('id');  //prop_type_li0
               if (childnode.match('open_house_')) {
                   index = parseInt(childnode.replace('open_house_li', '')) + 1; //index of the last child node increment by 1                                
               }
           }
           //if (calculate_date == 0) {gE("results_All-Dates").checked = true;}
           var valArr = tempArr.slice();
           for (j = 0; j < tempArr.length; j++) {
               if (title.toString().toLowerCase().indexOf(tempArr[j].toString().toLowerCase()) > -1) {
                   if (tempArr[j].toString().length > 10) { tempArr[j] = tempArr[j].toString().substr(0, 7) + '...' }
                   oh_type[j] = String.format("<li style='' name='openHouse' class='selected_li' id='open_house_li" + index + "'><span class='close' onclick='clearFilter(&#39;oh_type&#39;,&#39;{0}&#39;)'><img src='/images/tab-drop-close.gif' height='12' width='12'/></span>Open House: <span class='selection-value'><span id='selected_prop_type" + i + "'>" + tempArr[j] + "</span></span></li>", valArr[j]);
                   //MA:To do an extra check to see if the prop is already added in the selection box..
                   var selected_items = new Array();
                   var added = false;
                   var selected_items = getElemsByClass('span', 'selection-value');
                   for (var s = 0; s < selected_items.length; s++) {
                       if (tempArr[j].substr(0, 7) == selected_items[s].firstChild.innerHTML.substr(0, 7)) {
                           added = true;
                           break;
                       }
                   }

                   // alert(added);
                   if (added == false) { gE('selected_ul').innerHTML = currUL + oh_type[j]; currUL = currUL + oh_type[j]; index = index + 1; }
               }
           } //end of for loop 
            
           //MA: This function is to pop only "All Open houses" from the selection box            
           
                       var all_li = new Array();
                       all_li = getElemsByClass('li', 'selected_li');
                       for (var i = 0; i < all_li.length; i++) {
                           var childnode = all_li[i].getAttribute('id');  //open_house_li0
                           if (childnode.match('open_house_')) {
                               if (calculate_date == 1) 
                               {
                                   // pop "All Dates" from temp arr if other dates already added
                                   if (all_li[i].lastChild != null) 
                                   {
                                       //alert('pop:' + all_li[i].lastChild.firstChild.innerHTML.toString().substring(0, 3));
                                       var deletedchild = all_li[i].getAttribute('id');
                                       if (all_li[i].lastChild.firstChild.innerHTML.toString().substring(0, 3) == "All") { gE('selected_ul').removeChild(gE(deletedchild)); break; }
                                   }
                               } //end cal date if         
                               else if (calculate_date == 0)  // For other dates if "ALL Dates" added
                               {
                                    if (all_li[i].lastChild != null) 
                                   {
                                       var deletedchild = all_li[i].getAttribute('id');
                                       if (all_li[i].lastChild.firstChild.innerHTML.toString().substring(0, 3) != "All") { gE('selected_ul').removeChild(gE(deletedchild)); break; }
                                   }
                               }
                               
                           }  //end of open house if 
                       } //end for loop      
                      //pop child from the node
       
       }

       if (filter == 'virtual_tour') {
           var currUL = gE('selected_ul').innerHTML;
           var propGroup = '';
           var typeArr = new Array();
           var tempArr = new Array();

           var prop_type = new Array();

           typeArr = getElemsByClass('li', 'type_item');
           for (i = 0; i < typeArr.length; i++) {

               if (typeArr[i].firstChild.checked) {
                   tempArr.push(typeArr[i].firstChild.value);
               }
           }

           //MA: get the last index of prop_type_li and increment by 1 
           var all_li = new Array();
           var index = 0;

           all_li = getElemsByClass('li', 'selected_li');
           for (var i = 0; i < all_li.length; i++) {
               var childnode = all_li[i].getAttribute('id');  //prop_type_li0
               if (childnode.match('virtual_tour_')) {
                   index = parseInt(childnode.replace('virtual_tour_li', '')) + 1; //index of the last child node increment by 1 
               }
           }
           
          
           var valArr = tempArr.slice();
           for (j = 0; j < tempArr.length; j++) {
               if (tempArr[j].toString() == title || title == "yes") {
                   if (tempArr[j].toString().length > 10) { tempArr[j] = tempArr[j].toString().substr(0, 7) + '...' }
                  
                   prop_type[j] = String.format("<li style='' name='virtual_tour' class='selected_li' id='virtual_tour_li" + index + "'><span class='close' onclick='clearFilter(&#39;virtual_tour&#39;,&#39;{0}&#39;)'><img src='/images/tab-drop-close.gif' height='12' width='12'/></span>Virtual Tours Only: <span class='selection-value'><span id='selected_virtual_tour" + i + "'>On</span></span></li>", "on");
                   //MA:To do an extra check to see if the prop is already added in the selection box..
                   var selected_items = new Array();
                   var added = false;
                   var selected_items = getElemsByClass('span', 'selection-value');
                   for (var s = 0; s < selected_items.length; s++) {
                       if (tempArr[j].substr(0, 7) == selected_items[s].firstChild.innerHTML.substr(0, 7)) {
                           added = true;
                           break;
                       }
                   }
                   if (added == false) {gE('selected_ul').innerHTML = currUL + prop_type[j]; }
               }
           }
       }


       //Sale Type
       if (filter == 'sale_type') {
           if (title.length > 10) { title = title.substr(0, 7) + '...' }
           var sale_type = String.format("<span class='close' onclick='clearFilter(&#39;sale_type&#39;,&#39;{0}&#39;)'><img src='/images/tab-drop-close.gif' height='12' width='12'/></span>Type of Sale: <span class='selection-value'><span id='selected_sale_type'>" + title + "</span></span>", title);

           gE('sale_type_li').innerHTML = sale_type;
           gE('sale_type_li').style.display = '';
       }


       //Show Selections.
       if (gE('search_settings')) {
           if (gE('selections_detail').style.display == 'none') {
               makeSelection(true);
           }
       }

       //alert('filter=' + filter + '\nrequery=' + requery);
       if (requery) {
           if (filter == 'age' ||
               filter == 'price' ||
               filter == 'bedrooms' ||
               filter == 'bathrooms' ||
               filter == 'sqft') // || filter == 'open_house')
           {
               window.setTimeout("RFQuery(LeftNavBusy)", 3000);
           }
    
           else if (filter == 'open_house') {
               window.setTimeout("RFQuery(LeftNavBusy)", 5000);
           }
           else {
               //alert('calling rfquery');
               RFQuery(LeftNavBusy);
           }
       }
   }
   /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
   //END Return Selections.
   /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

   function ClearCustomDateRange() {
     if (gE('results_All-Dates') != null)
       {
           if (gE('results_All-Dates').checked == true) 
           {
               if (gE('results_Next-weekend')!= null) {gE('results_Next-weekend').checked = false;}
               if (gE('results_This-weekend')!= null) {gE('results_This-weekend').checked = false;}
               if (gE('results_Today')!= null)        {gE('results_Today').checked = false;}
               if (gE('results_Tomorrow')!= null)     {gE('results_Tomorrow').checked = false;}
               if (gE('ohstart')!= null)              {gE('ohstart').value = "";}
               if (gE('ohend')!= null)                {gE('ohend').value = "";}
               if (gE('CustomDateRange')!= null)      {gE("CustomDateRange").checked = false;}               
           }
       }
   }

function repositionAd() {
    var leftRailHeight = $('#global_content_left').height();
    var centerRailHeight = $('#center-rail').height();
    var rightRail = gE('right_rail');
    
    if( leftRailHeight > centerRailHeight){
        rightRail.style.height = leftRailHeight+'px';
    }else{
        if(gE('pagination_results') != null){
            rightRail.style.height = (centerRailHeight - 85)+'px';
        }else{
            rightRail.style.height = (centerRailHeight - 59)+'px';
        }
    }
}