function lookSubmit()
{
    var v = YAHOO.util.Dom.get('look-neighborhood').value;
    if (v != "Enter City & State or ZIP")
    {
        document.lookForm.submit();
    }
    else
    {  
        return false;
    }
}

/*************************/
/* Auto-Complete Scripts */
/*************************/
var CitiesXhr = {
    oACDS:null,
    oAutoComp:null,
    res:null,
    getCities:function(){
        return CitiesXhr.res.Utility.Cities;
    },
    handleSuccess:function(o){        
        // Instantiate JS Function DataSource
        CitiesXhr.res = YAHOO.lang.JSON.parse(o.responseText); 
        // add recent searches
        var recentSearches = YAHOO.util.Cookie.get("RS"); 
        if(recentSearches){
            var rs = recentSearches.split('|');
            CitiesXhr.res.Utility.Cities = CitiesXhr.res.Utility.Cities.concat(rs);
        }
        CitiesXhr.buildAutoComplete();
    },
    buildAutoComplete:function(){
        CitiesXhr.oACDS = new YAHOO.widget.DS_JSArray(CitiesXhr.res.Utility.Cities);
        CitiesXhr.oACDS.queryMatchContains = true;
        CitiesXhr.oACDS.queryMatchSubset = true;
        // Instantiate AutoComplete
        CitiesXhr.oAutoComp = new YAHOO.widget.AutoComplete('search-main','searchListingQueryContainer', CitiesXhr.oACDS);
        CitiesXhr.oAutoComp.minQueryLength = 1;
        CitiesXhr.oAutoComp.typeAhead = false;
        CitiesXhr.oAutoComp.formatResult = function(aResultItem, sQuery) {
           var sKey = aResultItem[0]; // the entire result key
           var mKey = aResultItem[0].toLowerCase();
           var mQuery = sQuery.toLowerCase();
           var begin = mKey.indexOf(mQuery) + 0;
           var end = mKey.indexOf(mQuery) + mQuery.length;
           var sKeyPre = (begin == 0) ? "" : sKey.substring(0, begin);
           var sKeyQuery = sKey.substring(begin, (end)); // the query itself
           var sKeyPost = sKey.substr(end); // the rest of the result
           var aMarkup = ["<div>",
              sKeyPre,
              "<span style='font-weight:bold'>",
              sKeyQuery,
              "</span>",
              sKeyPost,
              "</div>"];
          return (aMarkup.join(""));
        };        
    },
    handleFailure:function(o){
        //alert("No Xhr Response");
    },
    startRequest:function() {           
        //YAHOO.util.Connect.asyncRequest('POST', CONST_XHR_PATH+"cities.utility", citiesAsync, "");
    },
    rebuildCities:function(newVal){
        CitiesXhr.res.Utility.Cities = CitiesXhr.res.Utility.Cities.concat(newVal);
        CitiesXhr.buildAutoComplete();
    }
};
var citiesAsync = {
    success:CitiesXhr.handleSuccess,
    failure:CitiesXhr.handleFailure,
    scope: CitiesXhr
};
CitiesXhr.startRequest(); 


/****************************/
/* Search Options Scripts   */
/****************************/
var optionsOpen = null;
var optionsClose = null;
var errorOpen = null;
var errorClose = null;
/*YAHOO.util.Event.onContentReady("search-options", function(){
    optionsOpen = new YAHOO.util.Anim('search-options');
    optionsOpen.attributes.height = { to: 149 };
    optionsOpen.duration = 0.5;
    optionsOpen.method = YAHOO.util.Easing.easeOut;
    
    optionsClose = new YAHOO.util.Anim('search-options');
    optionsClose.attributes.height = { to: 1 };
    optionsClose.duration = 0.5;
    optionsClose.method = YAHOO.util.Easing.easeOut;
}, this); */

YAHOO.util.Event.onContentReady("search-error", function(){
    errorOpen = new YAHOO.util.Anim('search-error');
    errorOpen.attributes.height = { to: 66 };
    errorOpen.duration = 0.5;
    errorOpen.method = YAHOO.util.Easing.easeOut;

    errorClose = new YAHOO.util.Anim('search-error');
    errorClose.attributes.height = { to: 1 };
    errorClose.duration = 0.5;
    errorClose.method = YAHOO.util.Easing.easeOut;		
}, this); 

function getOnlyZip(v){        
    var z = /^(\d{5}$)|^(\d{5}-\d{4}$)/;
    var result = z.exec(v);
    return result ? result[0] : null;
}

function getZip(v){        
    var z = /(\d{5}$)|(\d{5}-\d{4}$)/;
    var result = z.exec(v);
    return result ? result[0] : null;
}
    
function checkCommandParameter(id){
    var val = document.getElementById(id).value;
    return (val != null && val != "") ? val : null;
}

function checkCommandNumberParameter(id){
    var val = document.getElementById(id).value;
    return (val != null && val > 0) ? val : null;
}

function checkCommandCheckboxParameter(id){
    var val = document.getElementById(id).value;
    return (val != null && val != "") ? val : 0;
}

function checkCommandCheckboxParameterToBool(id){
    var val = document.getElementById(id).value;
    return (val != null && val != "") ? ((val === 1 || val === "1") ? true : false) : false;
}


function syncFormToCommand(cmd){
    cmd.Query = checkCommandParameter('search-main');
    cmd.MinPrice = checkCommandParameter('search-min-price');
    cmd.MaxPrice = checkCommandNumberParameter('search-max-price');
    cmd.MinFootage = checkCommandParameter('search-min-lot');
    cmd.MaxFootage = checkCommandNumberParameter('search-max-lot');
    cmd.MinBedrooms = checkCommandParameter('bed-count');
    cmd.MinBathrooms = checkCommandParameter('bath-count');
    cmd.SingleFamily = checkCommandCheckboxParameterToBool('type-single');
    cmd.MultiFamily = checkCommandCheckboxParameterToBool('type-multi');
    cmd.Townhouse = checkCommandCheckboxParameterToBool('type-townhouse');
    cmd.Condo = checkCommandCheckboxParameterToBool('type-condo');
    cmd.Coop = checkCommandCheckboxParameterToBool('type-coop');
    cmd.Farm = checkCommandCheckboxParameterToBool('type-farm');
    cmd.Land = checkCommandCheckboxParameterToBool('type-land');
    cmd.OpenHousesOnly = checkCommandCheckboxParameterToBool('options-open');
    cmd.JustListedOnly = checkCommandCheckboxParameterToBool('options-just');
    cmd.MaxAge = checkCommandNumberParameter('form-home-age-max'); 
    cmd.MinAge = checkCommandParameter('form-home-age-min');
    return cmd;             
}

function syncFormToNewCommand(){
    var cmd = {};
    return syncFormToCommand(cmd);         
}

function updateSearchListings(){
    var clazz = document.getElementById('filter-update').className;
    if(clazz === "btn-filter-update"){
        doNotReloadState = true;
        makeAndPackSearchString();
        SearchXhr.startRequest(false);
        // disable the update button
        //document.getElementById('update-search-button').disabled = true;
	    document.getElementById('filter-update').className = "btn-filter-update-disabled";
	}
    return false;
}

function resetSearchCriteria(){
    document.getElementById('price-max').value = 0;
    checkNumber(document.getElementById('price-max'), 'price');
    document.getElementById('price-min').value = 0;
    checkNumber(document.getElementById('price-min'), 'price');
    unCheckCheckbox('type', 'single');
    unCheckCheckbox('type', 'multi');
    unCheckCheckbox('type', 'townhouse');
    unCheckCheckbox('type', 'condo');
    unCheckCheckbox('type', 'coop');
    unCheckCheckbox('type', 'farm');
    unCheckCheckbox('type', 'land');
    setSlider('set', 'bed', (0));
    setSlider('set', 'bath', (0));
    setMenu('home-age', 0);
    unCheckCheckbox('options', 'open');
    unCheckCheckbox('options', 'just');     
    document.getElementById('lot-max').value = 0;
    checkNumber(document.getElementById('lot-max'), 'lot');
    document.getElementById('lot-min').value = 0;
    checkNumber(document.getElementById('lot-min'), 'lot');
    // disable the update button
    //document.getElementById('update-search-button').disabled = true;
	document.getElementById('filter-update').className = "btn-filter-update-disabled";
}

var doNotReloadState = false;
function refineSearchListingsQuery(frm){
    var v = YAHOO.util.Dom.get('search-main').value;
    if(v === defaultSearchText || v === null || v === ""){
            // the user has not entered anything
            return false;
    } else {
        //SearchMlsXhr.startRequest(refineSearchListingsQueryCallback);
        IdxXhr.startRequest(SearchMlsXhr.startRefineRequest, search);
        return false;
    }
}

function refineSearchListingsQueryCallback(){
    // we have a new location
    doNotReloadState = true;
    makeAndPackSearchString();
    // call virtual earth's find method again
    VeMap.newSearch(document.getElementById('search-main').value);      
}

function validateSearchListingQuery(frm){
    var v = YAHOO.util.Dom.get('search-main').value;
    if(v === defaultSearchText){
        return false;
    } else {
        //SearchMlsXhr.startRequest(validateSearchListingQueryCallback);
        IdxXhr.startRequest(SearchMlsXhr.startValidateRequest, null);
        return false;
    }
}

function validateSearchListingQueryCallback(){
    var frm = document.getElementById('searchListingForm');
    var searchStr = makeSearchString(false);
    currentSearchString = searchStr;
    frm.action = CONST_BASE_PATH+"Views/Listings/Default.aspx#s=" + (searchStr !== null ? searchStr : "");
    frm.submit();    
}

function addSearchParam(id){
    var ele = document.getElementById(id);
    return ele.value != null && ele.value !== '' && ele.value !== defaultSearchText;
}

var currentSearchString = null;
function makeAndPackSearchString(){
    var searchStr = makeSearchString(true);
    search.SearchString = searchStr;
    currentSearchString = searchStr;
    YAHOO.util.History.navigate("s", searchStr);
}

function makeSearchString(fromResults){
    var searchStr = "";
    if(addSearchParam('search-main')){
        searchStr += (('search-main') + '=' + (checkCommandParameter('search-main')));
    }
    if(addSearchParam('search-min-price')){
        searchStr += (searchStr !== "" ? "|" : "") + (('search-min-price') + '=' + (checkCommandParameter('search-min-price')));
    }
    if(addSearchParam('search-max-price')){
        searchStr += (searchStr !== "" ? "|" : "") + (('search-max-price') + '=' + (checkCommandNumberParameter('search-max-price')));
    }
    if(addSearchParam('search-min-lot')){
        searchStr += (searchStr !== "" ? "|" : "") + (('search-min-lot') + '=' + (checkCommandParameter('search-min-lot')));
    }
    if(addSearchParam('search-max-lot')){
        searchStr += (searchStr !== "" ? "|" : "") + (('search-max-lot') + '=' + (checkCommandNumberParameter('search-max-lot')));
    }
    if(addSearchParam('bed-count')){
        searchStr += (searchStr !== "" ? "|" : "") + (('bed-count') + '=' + (checkCommandParameter('bed-count')));
    }
    if(addSearchParam('bath-count')){
        searchStr += (searchStr !== "" ? "|" : "") + (('bath-count') + '=' + (checkCommandParameter('bath-count')));
    }
    if(addSearchParam('type-single')){
        searchStr += (searchStr !== "" ? "|" : "") + (('type-single') + '=' + (checkCommandCheckboxParameter('type-single')));
    }
    if(addSearchParam('type-multi')){
        searchStr += (searchStr !== "" ? "|" : "") + (('type-multi') + '=' + (checkCommandCheckboxParameter('type-multi')));
    }
    if(addSearchParam('type-townhouse')){
        searchStr += (searchStr !== "" ? "|" : "") + (('type-townhouse') + '=' + (checkCommandCheckboxParameter('type-townhouse')));
    }
    if(addSearchParam('type-condo')){
        searchStr += (searchStr !== "" ? "|" : "") + (('type-condo') + '=' + (checkCommandCheckboxParameter('type-condo')));
    }
    if(addSearchParam('type-coop')){
        searchStr += (searchStr !== "" ? "|" : "") + (('type-coop') + '=' + (checkCommandCheckboxParameter('type-coop')));
    }
    if(addSearchParam('type-farm')){
        searchStr += (searchStr !== "" ? "|" : "") + (('type-farm') + '=' + (checkCommandCheckboxParameter('type-farm')));
    }
    if(addSearchParam('type-land')){
        searchStr += (searchStr !== "" ? "|" : "") + (('type-land') + '=' + (checkCommandCheckboxParameter('type-land')));
    }
    if(addSearchParam('options-open')){
        searchStr += (searchStr !== "" ? "|" : "") + (('options-open') + '=' + (checkCommandCheckboxParameter('options-open')));
    }
    if(addSearchParam('options-just')){
        searchStr += (searchStr !== "" ? "|" : "") + (('options-just') + '=' + (checkCommandCheckboxParameter('options-just')));
    }
    if(addSearchParam('form-home-age-max')){
        searchStr += (searchStr !== "" ? "|" : "") + (('form-home-age-max') + '=' + (checkCommandNumberParameter('form-home-age-max')));
    }
    if(addSearchParam('form-home-age-min')){
        searchStr += (searchStr !== "" ? "|" : "") + (('form-home-age-min') + '=' + (checkCommandParameter('form-home-age-min')));
    }
    if(fromResults === true){
        searchStr += (searchStr !== "" ? "|" : "") + "center-lat=" + search.CenterLat + "|center-long=" + search.CenterLong;
    }
    return searchStr;
}

/****************************/
/* Search Scripts   */
/****************************/
var SearchMlsXhr = {
    search:null,
    callback:null,
    handleSuccess:function(o){  
        var cmd = YAHOO.lang.JSON.parse(o.responseText); 
        if(cmd.Results !== null &&  cmd.Results.length > 0){
            if(SearchMlsXhr.search !== null){
                document.getElementById('search-main').value = SearchMlsXhr.search.cookiePlace;
            }
            // we're in business
            if(cmd.Results.length === 1){
                // go to the listing
                window.location = CONST_BASE_PATH + 'Views/Listings/Detail.aspx?listingId=' + cmd.Results[0].ListingId; 
            } else {
                YAHOO.util.Dom.removeClass(['search-listings-btn'], 'btn-search-loading');
                YAHOO.util.Dom.addClass(['search-listings-btn'], 'btn-search');
                // we have too many build the panel
                document.getElementById('search-error-title').innerHTML = "Search Error";
                document.getElementById('search-error-sub').innerHTML = "Multiple MLS Listings";
                var theList = document.getElementById('search-error');
                theList.innerHTML = '';
                var error = YAHOO.util.Dom.getElementsByClassName('mls-error-item-tmp', 'div')[0];
                 for(var i=0;i<cmd.Results.length;i++){
                    var item = error.cloneNode(true);
                    YAHOO.util.Dom.removeClass([item], 'mls-error-item-tmp');
                    var itemInfo = YAHOO.util.Dom.getElementsByClassName('error-info', 'span', item)[0];
                    var itemAdd = YAHOO.util.Dom.getElementsByClassName('error-address', 'a', item)[0];
                    itemAdd.innerHTML = cmd.Results[i].Street1 + ', ' + cmd.Results[i].City + ', ' + cmd.Results[i].State;
                    itemAdd.href = CONST_BASE_PATH + 'Views/Listings/Detail.aspx?listingId=' + cmd.Results[i].ListingId;
                    //YAHOO.util.Event.addListener(itemAdd, 'click', function(evt, id){
                        //window.location = CONST_BASE_PATH + 'Views/Listings/Detail.aspx?listingId=' + id; 
                    //}, cmd.Results[i].ListingId);
                    itemInfo.innerHTML = "MLS#: " + cmd.MlsId;
                    YAHOO.util.Dom.setStyle(item, 'display', 'block');
                    
                    if((i+1) === cmd.Results.length){
                        YAHOO.util.Dom.addClass([item], 'last');
                    }
                    
                    theList.appendChild(item);
                }

                if (CONST_SEARCH_MODE == "refine") {
                    //if we are "refining"
                    toggleSearchOptions('hide', VeMap);
                } else {
                    //if we are "searching"
                    toggleSearchOptions('hide', null)
                }

                setError('show');
            }
        }  else {
            // call the given handler
            SearchMlsXhr.callback();
        }       
    },
    handleFailure:function(o){
        return SearchMlsXhr.callback();    
    },
    startRefineRequest:function() {
        SearchMlsXhr.search = search;
        SearchMlsXhr.callback = refineSearchListingsQueryCallback;
        return SearchMlsXhr.startRequest();
    },
    startValidateRequest:function() {
        SearchMlsXhr.search = null;
        SearchMlsXhr.callback = validateSearchListingQueryCallback;
        return SearchMlsXhr.startRequest();
    },
    startRequest:function() {
        var v = document.getElementById("search-main").value;
        var zip = getOnlyZip(v);
        if(zip != null){
            // we have a zip, just go search
            SearchMlsXhr.callback();
        } else {
            // we do not have a zip, so try the mls first
            var cmd = {
                MlsId: v
            }; 
            var jsonStr = YAHOO.lang.JSON.stringify(cmd);            
            YAHOO.util.Connect.asyncRequest('POST', CONST_XHR_PATH+"search.mls", searchMlsAsync, "mls_json=" + jsonStr);
        }
        return;
    }
};

var searchMlsAsync = {
    success:SearchMlsXhr.handleSuccess,
    failure:SearchMlsXhr.handleFailure,
    scope: SearchMlsXhr
};

YAHOO.util.Event.onContentReady("idxMessage", function(){
    YAHOO.com.bhg.idxMessage = new YAHOO.widget.Panel("idxMessage", { zIndex: 202, width:"400px", visible:false, close: false, modal:true, fixedcenter:true, constraintoviewport:true } );
    YAHOO.com.bhg.idxMessage.render();
    YAHOO.util.Dom.setStyle(['idxMessage'], 'display', 'block');
}, this); 

var IdxXhr = {
    search:null,
    url:null,
    callback:null,
    idxInterval:null,
    openIdxPopupTimer:function(){
        var eNWindow = null;
        eNWindow = window.open(IdxXhr.url,'eN','width=840,height=650,scrollbars=yes,toolbar=yes,titlebar=yes,menubar=yes,location=yes,status=yes,resizable=yes,directories=yes'); 
        if (eNWindow != null)
        {
            eNWindow.focus();
            YAHOO.util.Dom.setStyle(['idx-problem', 'idx-wait'], 'display', 'none');
            YAHOO.util.Dom.setStyle(['idx-success'], 'display', 'block');
            YAHOO.com.bhg.idxMessage.show();
        } else {
            YAHOO.util.Dom.setStyle(['idx-success', 'idx-wait'], 'display', 'none');
            YAHOO.util.Dom.setStyle(['idx-problem'], 'display', 'block');
            YAHOO.com.bhg.idxMessage.show();
        }
        window.clearInterval(IdxXhr.idxInterval);              
    },
    openIdxPopup:function(){
        var eNWindow = null;
        eNWindow = window.open(IdxXhr.url,'eN','width=840,height=650,scrollbars=yes,toolbar=yes,titlebar=yes,menubar=yes,location=yes,status=yes,resizable=yes,directories=yes'); 
        if (eNWindow != null)
        {
            eNWindow.focus();
        }               
    },
    closeIdxPopup:function(){
        YAHOO.com.bhg.idxMessage.hide();
        window.clearInterval(IdxXhr.idxInterval);
    },
    handleSuccess:function(o){              
        var listings = YAHOO.lang.JSON.parse(o.responseText);
        if (listings.IdxUrl != null)
        {
            YAHOO.util.Dom.removeClass(['search-listings-btn'], 'btn-search-loading');
            YAHOO.util.Dom.addClass(['search-listings-btn'], 'btn-search');
            if(IdxXhr.search !== null){
                document.getElementById('search-main').value = IdxXhr.search.cookiePlace;
            }
            IdxXhr.url = listings.IdxUrl;
            YAHOO.util.Dom.setStyle(['idx-success', 'idx-problem'], 'display', 'none');
            YAHOO.util.Dom.setStyle(['idx-wait'], 'display', 'block');
            YAHOO.com.bhg.idxMessage.show();               
            IdxXhr.idxInterval = window.setInterval(IdxXhr.openIdxPopupTimer, 4000);
        } else {
            // call the given handler
            IdxXhr.callback();
        } 
    },
    handleFailure:function(o){
        // if we had a failure, just call the callback.
        IdxXhr.callback();
    },
    startRequest:function(cb, s) {        
        var clazz = document.getElementById('search-listings-btn').className;
        if(clazz.indexOf('btn-search-loading') === -1){
            YAHOO.util.Dom.addClass(['search-listings-btn'], 'btn-search-loading');
            YAHOO.util.Dom.removeClass(['search-listings-btn'], 'btn-search');
            IdxXhr.search = s;
            IdxXhr.callback = cb;
            // serialize the search values            
            var v = document.getElementById("search-main").value;
            var zip = getZip(v);
            var cmd = syncFormToNewCommand();
            cmd.MlsId = v;  // always setting MLSId, will be ignored if invalid
            if(zip !== null){
                cmd.Zipcode = zip;
                var jsonStr = YAHOO.lang.JSON.stringify(cmd);            
                YAHOO.util.Connect.asyncRequest('POST', CONST_XHR_PATH+"search.idx", idxAsync, "idx_json=" + jsonStr);
                return;
            } else {
                var address = processAddressInput(v);
                if(address !== null){
                    // take the address and call the idx handler
                    cmd.Zipcode = address.postalCode;
                    cmd.City = address.city;
                    cmd.State = address.state;
                    cmd.Address = address.street;        
                    var jsonStr = YAHOO.lang.JSON.stringify(cmd);            
                    YAHOO.util.Connect.asyncRequest('POST', CONST_XHR_PATH+"search.idx", idxAsync, "idx_json=" + jsonStr);
                    return;
                }
            }
            // could not determine an address, call the given handler
            IdxXhr.callback();
            return;
        }
    }
};
var idxAsync = {
    success:IdxXhr.handleSuccess,
    failure:IdxXhr.handleFailure,
    scope: IdxXhr
};

