$jq(document).ready(function(){

if (typeof RS == "undefined") { RS = {}; }
RS.zip = document.newSearchForm.svar_ZIP.value;
RS.state = document.newSearchForm.svar_STATE.value;
RS.city = document.newSearchForm.svar_CITY.value;
RS.stateabbr = document.newSearchForm.svar_STATEABBR.value;
RS.h1tag = document.newSearchForm.svar_H1TAG.value;

     var e = document.newSearchForm.loc;
     if (RS.zip != "") {
       e.value = RS.zip;
     } else if (RS.city != "") {
       if (RS.stateabbr != "") {
         e.value = RS.city + ", " + RS.stateabbr;
       } else {
         e.value = RS.city;
       }
     }
     
     $jq("#facets .goButtonSprite").bind("mouseover", function(e){ flipImageHover(e.target); return false;}).bind("mouseout", function(e){ flipImageHover(e.target); return false;});
     $jq("#facetForm .goButtonSprite").bind("click", function(e) { facetChanged(e.target.id); });
     $jq("#facetLoc").autocomplete("/predict");
     $jq("#newSearchForm").bind("submit", function(e) { return doSubmit(e.target); });
     $jq("#facetForm").bind("submit", function(e) { return false; });
     $jq("#facetForm select").bind("change", function(e) { facetChanged(e.target.id); });
     $jq("#facetForm input.number").bind("keyup", function(e) { e.target.value = e.target.value.replace(/\D/,''); if (e.target.value > 99999999) {e.target.value = parseInt(e.target.value / 10);} });
     //$jq("#facetForm :checkbox").bind("change", function(e) { facetChanged(e.target.id); return false; });
     //$jq("#photoFacet").bind("change", function(e) { facetChanged(e.target.id); return true; });    
  });
  
var facetSort = "sort-default";

function showErrorNumber(text, elem) {
  $jq(elem).html(text);
  $jq(elem).css("display", "block");
  setTimeout($jq(elem).css("display", "none"), 2000);
}

function populateInteger(query, propname) {
  var e = document.facetForm[propname];
  if (!isEmpty(e.value) && e.value.match(/^\d+$/)) {
    query[propname] = e.value;
  } else {
    e.value = "";
  }
}


function populate(query, propname) {
  var e = document.facetForm[propname];
  if (!isEmpty(e.value)) {
    query[propname] = e.value;
  }
}

function populateRadio(query, propname) {
  var e = document.facetForm[propname];
  for (var i = 0; i < e.length; i++) {
    if (e[i].checked && e[i].value != "all") {
      query[propname] = e[i].value;
      break;
    }
  }
}

function handleCheckboxClick(facet) {
  var element = document.getElementById(facet);
  //alert("facet: " + facet + ", " + element.checked);

  var parts = facet.split(/-/, 2);
  var groupName= parts[0];
  var checkboxValue = parts[1];
  if (groupName == "pets" || groupName == "sort" || groupName == "page") {
    return;
  }

  var groupId = groupName + "CheckboxGroup";
  var allElement = document.getElementById(groupName + "-all");

  if (element.checked && checkboxValue != "all") {
    allElement.checked = false;
  }
}

function populateCheckboxGroup(query, groupName) {
  var values = [];
  var checkedCount = 0;  
  var groupId = groupName + "CheckboxGroup";
  var allElement = document.getElementById(groupName + "-all");
  $jq("#" + groupId + " :checkbox").each(function(i){
    if (this.checked) {
      if (!this.id.match(/-all/) && allElement.checked) {
        this.checked = false;
      } else {
        checkedCount++;
        values.push(this.value);
      }
    }
  });
  if (checkedCount === 0) {
    allElement.checked = true;
    values.push("all");
  }

  query[groupName] = values.join(",");
}
//code added by Harish for getting processing box with grey shade
function createErrorShade(className)
{
    if (!$jq("#bgShade")[0]) {
        $jq("body")[0].style.cssText="float:left;height:auto";
  var ht=$jq("body")[0].scrollHeight;
  $jq("body")[0].style.cssText="float:none;height:auto";
  if ($jq.browser.msie) {
   var msIe = parseInt($jq.browser.version);
             if (msIe == 6) {
    $jq("select").attr("disabled", 1);
            }
        }
        var myDiv = document.createElement("div");
        $jq(myDiv).attr('id', 'bgShade');
        $jq(myDiv).attr('class', className);
        $jq(myDiv).css('height',ht);
  $jq("body").append(myDiv);
    }
}

$jq(document).ready(function() {
     $jq("#preLoadListings").dialog({
             width: 485,
             height: 'auto',
             draggable: false,
             autoOpen: false,
             resizable: false,
             dialogClass: "preloader",
             position: 'auto',
             overlay: {'background-color' : '#aab1b1', 'filter' : 'alpha(opacity=50)', 'opacity' : '0.5'},
             option:{'position':'center'}
             });
          
 });

function facetChanged(facet) {
  var url;
  var query = {};
  
  if (facet.match(/-/)) {
    handleCheckboxClick(facet);
  }
  
  facet = facet.replace("Facet", "");
  
  if (isEmpty(document.newSearchForm.loc.value)) {
    if (RS.zip != "") {
      query.location = RS.zip;
    } else {
      query.location = RS.zip+","+RS.stateabbr;
    }
  } else {
    query.location = encodeURIComponent(encodeURIComponent(document.newSearchForm.loc.value));
  }

  populate(query, "distance");
  populateInteger(query, "minSqft");
  populateInteger(query, "maxSqft");
  populateInteger(query, "minPrice");
  populateInteger(query, "maxPrice");
  populate(query, "keywords");
  populateCheckboxGroup(query, "category");
  populateCheckboxGroup(query, "bedrooms");
  populateCheckboxGroup(query, "bathrooms");
  populateRadio(query, "pets");

  if (document.facetForm.hasPhoto.checked === true) {
    query.hasPhoto = "yes";
  } else {
    query.hasPhoto = "no";
  }
  
  if (facet == "photo") {
    if (document.facetForm.hasPhoto.checked === true) {
      facet = "photo-yes";
    } else {
      facet = "photo-no";
    }
  }
  
  if (facet == "fee") {
    if (document.facetForm.hasNoFee.checked === true) {
      query.hasFee = "no";
      facet = "fee-no";
    } else {
      query.hasFee = "yes";
      facet = "fee-yes";
    }
  }
  
  if (facet.match("^page")) {
    page = facet.match("[0-9]+");
    query.page = page[0];
  }
  
  if (facet.match("^sort")) {
    facetSort = facet;
  }

  
  if (facet == "price") {
    if (typeof query.minPrice == "undefined" && typeof query.maxPrice == "undefined") {
      return;
    }
  }

  if (facet == "sqft") {
    if (typeof query.minSqft == "undefined" && typeof query.maxSqft == "undefined") {
      return;
    }
  }
  
  if (facet == "keywords") {
    if (typeof query.keywords == "undefined") {
      return;
    }
  }
  
  query.sort = facetSort;
  query.h1tag = encodeURIComponent(RS.h1tag);
 
  var queryString = "";  
  for (var k in query) {
    queryString += "&";
    queryString += k + "=" + query[k];
  }
  url = "/blog/searchListingsAjax/" + encodeURIComponent(encodeURIComponent(encodeURIComponent(queryString.slice(1))));

  //alert("Using url: " + url);
  
  if (facet.match("^page")) {
   /* sonar.add(
    {
      obj: document.getElementById("adBlockRight"),
      call: function(object) { adsReloadAd("adBlockRight"); },
      px: 0
    });*/
  }

  document.body.style.cursor = 'wait';    
  //code added by Harish for getting processing box with grey shade
   createErrorShade("preloaderModal");
    $jq("#preLoadListings").empty();
    $jq('<div id="preloaderDiv" style="display:none;">;<img src="http://o.aolcdn.com/art/ch_realestate/preloader" alt="Processsing"/>;</div>').appendTo($jq("#preLoadListings"));
    $jq("#preloaderDiv").show();
    $jq("#preLoadListings").dialog('open');
   $jq("#preLoadListings").dialog().parents(".ui-dialog").find(".ui-dialog-titlebar").remove();
   $jq("#preloaderDiv").show();

  var pagenum = "1";
  
  $jq.get(url, function(data) { 
    var e = document.getElementById("results");
    e.innerHTML = data;

  if (facet.match("^page") || facet.match("^sort")) {
        getAFSLinks(sponsoredLinksConfig.query, sponsoredLinksConfig.qry_ctxt, pagenum);

    } else {
        getAFSLinks('', getRandomAFSKeyword(), pagenum);
    }
  //code added by Harish for getting processing box with grey shade  
    $jq("#bgShade").remove(); 
    $jq("#preLoadListings").dialog("close");  
window.location.hash = "#" + queryString.slice(1);

    if (facet.match("^page")) {
      page = facet.match("[0-9]+");
      pagenum = page[0];
      s_265.pageName = "SRP-P";
    } else {
      s_265.prop16 = facet;
      s_265.pageName = "SRP-F";
    }

  
    s_265.events = "";
    s_265.disablepipath = true;
    s_265.mmxtitle = "Rented Spaces";
    s_265.mmxgo = true;

    s_265.t();
    window.location.hash = "#" + queryString.slice(1);
    /*scroll(0,0);*/
    document.body.style.cursor = 'auto';    
 
  });
}
