//date check functions
var monthsDays = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

function isLeapYear(y) {
  return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
}

function checkDate(d,m,y) {
//  alert(d+'-'+m+'-'+y);
  if(isNaN(d) || isNaN(m) || isNaN(y)) return false;
  d = parseInt(d,10); m = parseInt(m,10); y = parseInt(y,10);
  if(isLeapYear(y)) monthsDays[1] = 29;
  if((d>monthsDays[m-1]) || (d<1) || (m<1) || (m>12) || (y<1)) return false;
  return true;
}
//date check functions

  var AreasRange = new Array(0,0,0,0);
  var head = 0;
  //var MaxAreas = 40;

  function checkRadio(rtc, itz){
    var rbts=document.getElementsByName(rtc);
    for(var i=0;i<2;i++) {
      if(rbts[i].value=="wildcard"&&rbts[i].checked&&itz.value.length>0&&itz.value.substring(itz.value.length-1)!="*") itz.value+="*";
    }
  }

function SCGeoArea(src){
  this.rangeStart = new Array();
  this.rangeEnd = new Array();
  this.areas = new Array();
  this.contain = SCGeoAreaContain;
  var tmpAreas = new Array();
  var tmp = src;
  var i,j;
  while ((i=tmp.indexOf(';'))!=-1){
    tmpAreas[tmpAreas.length]=tmp.substring(0, i);
    tmp=tmp.substring(i+1);
  }
  tmpAreas[tmpAreas.length]=tmp;
  for(i=0;i<tmpAreas.length;i++)
    if((j=tmpAreas[i].indexOf('-'))!=-1){
    this.rangeStart[this.rangeStart.length]=tmpAreas[i].substring(0, j);
    this.rangeEnd[this.rangeEnd.length]=tmpAreas[i].substring(j+1);
  } else
    this.areas[this.areas.length]=tmpAreas[i];
}
function SCGeoAreaContain(anotherGeoArea){
  // another geo area must have only 1 element
  if (anotherGeoArea.rangeEnd.length>0||anotherGeoArea.areas.length>1) return 0;
  var i;
  for(i=0;i<this.rangeEnd.length;i++)
    if(this.rangeStart[i]<=anotherGeoArea.areas[0]&&this.rangeEnd[i]>=anotherGeoArea.areas[0])
    return 1;
  for(i=0;i<this.areas.length;i++)
    if(this.areas[i]==anotherGeoArea.areas[0]) return 1;
  return 0;
}

function checkMrisAreasNumber(dest, fromZip){
    var zipCodesVal = dest['zip'].value;
    zipCodesVal = zipCodesVal.lastIndexOf(',')==zipCodesVal.length-1?zipCodesVal.substring(0,zipCodesVal.length-1):zipCodesVal;
    var zipCodes = zipCodesVal.split(",",41);
    var target = dest['area_target'];
    var ret = true;
    var zipLength = fromZip||zipCodes[0]==''?zipCodes.length:zipCodes.length+1;
    if(zipLength + target.length > MaxAreas){
        alert("You can select up to " + MaxAreas + " areas and zip codes");
        if(fromZip && zipCodes[0]!=''){
            if(target.length >= MaxAreas){
                dest['zip'].value = "";
            }else{
                for(var i = zipLength + target.length; i > MaxAreas; i--){
                    zipCodesVal = zipCodesVal.substring(0, zipCodesVal.lastIndexOf(','));
                }
                dest['zip'].value = zipCodesVal;
            }
        }
        ret = false;
    }
    zipCodesVal = null;
    zipCodes = null;
    target = null;
    return ret;
}

function AddArea(dest,mls) {
  var source = dest['area_source'];
  var target = dest['area_target'];

  if(source && target) {
    for (q=0; q < source.options.length; q++ ) {
      if (source.options[q].selected) {
        if (mls&&mls=='MRIS'){
            if(!checkMrisAreasNumber(dest,false)) return;
        }else if(target.length > MaxAreas - 1) {
          alert("You can select up to " + MaxAreas + " areas");
          return;
        }
        var insert = true;
        for (i=0; i < target.options.length; i++ ) {
          if (target.options[i].value == source.options[q].value) {
            insert = false;break;
          }
          /*intersection(target.options[i].value);
          intersection(source.options[q].value);
          if( (AreasRange[0] >= AreasRange[2] && AreasRange[0] <= AreasRange[3]) ||
              (AreasRange[2] >= AreasRange[0] && AreasRange[2] <= AreasRange[1]) ) {
            if(!confirm("This area is a part of other already selected area. \n\nWould you like to add it anyway? [press OK to add it, or Cancel to continue]")) {
              insert = false;
              break;
            }
          }*/
      var conrain1=false;
      var conrain2=false;
      var v1=target.options[i].value;
      var v2=source.options[q].value;
      if (mls&&mls=='PIN'){
        contain1 = (v1.indexOf('/')==-1)&&(v2.indexOf('/')!=-1)&&(v1==v2.substring(0,v2.indexOf('/')));
          contain2 = (v2.indexOf('/')==-1)&&(v1.indexOf('/')!=-1)&&(v2==v1.substring(0,v1.indexOf('/')));
      } else {
            var targetArea = new SCGeoArea(v1);
            var sourceArea = new SCGeoArea(v2);
      contain1 = targetArea.contain(sourceArea);
      contain2 = sourceArea.contain(targetArea);
      }
          if (contain1) {
            if(!confirm("This area is covered by another area that has already been selected. \n\nDo you want to add it anyway? [press OK to add it, or Cancel to continue]"))
              insert = false;
            break;
          } else
          if (contain2){
            if(!confirm("This choice covers multiple areas and one or more areas have already been selected.\nWe recommend to review and remove areas that appear to be duplicated. \n\nWould you like to continue and add this area? [press OK to add it, or Cancel to continue]"))
              insert = false;
            break;
          }
        }
        if (insert) {
          target.options[target.options.length] = new Option( source.options[q].text,source.options[q].value,false,false);
        }
      }
    }
    source.selectedIndex = -1;
    target.selectedIndex = -1;
  }
}

function intersection(SourceString) {
  if(head >= 3) head = 0;
  if(SourceString.indexOf("-")!=-1) {
    AreasRange[head++]=SourceString.substring(0, SourceString.indexOf("-"));
    AreasRange[head++]=SourceString.substring(SourceString.indexOf("-")+1);
  } else {
    AreasRange[head++]=AreasRange[head++]=SourceString;
  }
}


function DeleteArea(dest) {
  var target = dest['area_source'];
  var source = dest['area_target'];
  if(source && target) {
    while (source.selectedIndex >= 0) {
		source.options[source.selectedIndex] = null;
    }
	
    target.selectedIndex = -1;
  }
}

function changeAreasToSearch() {
  var target = document.forms.SearchForm['area_target'];
  if(target&&target.options) {
    var targetOptions = new Array;
    for(var i = 0; i<target.options.length; i++){
      targetOptions[i] = new Object;
      targetOptions[i].text = target.options[i].text;
      targetOptions[i].val = target.options[i].value;
    }
    target.options.length=0;
    if(last_target_area_vals&&last_target_area_vals.length>0){
      for(var i = 0; i<last_target_area_vals.length; i++){
        if(last_target_area_vals[i].text&&last_target_area_vals[i].val)
          target.options[i] = new Option(last_target_area_vals[i].text,last_target_area_vals[i].val);
      }
    }
    last_target_area_vals = targetOptions;
  }
}

function IncludeArea(dest, checkarea,As,idx_param){
  checkarea = trim(checkarea);
  for(var i=0; i<As.length; i++){
    if(checkarea == As[i].area_code){
      if(idx_param == "idx"){
        document.forms.SearchForm.area_target.options[document.forms.SearchForm.area_target.options.length] =
           new Option(As[i].area_name,As[i].area_code,false,false);
        break;
      }
      else{
        if (As[i].is_delimiter == "true"){
          document.forms.SearchForm.area_target.options[document.forms.SearchForm.area_target.options.length] =
             new Option(As[i].area_code+" - "+As[i].area_name,As[i].area_code,false,false);
        }
        else{
          document.forms.SearchForm.area_target.options[document.forms.SearchForm.area_target.options.length] =
             new Option(As[i].area_name,As[i].area_code,false,false);
        }
        break;
      }
    }
  }
}

function IncludeCity(dest, checkarea,As,idx_param){
  checkarea = trim(checkarea);
  for(var i=0; i<As.length; i++){
    if(checkarea == As[i].area_code.toUpperCase()){
      if(idx_param == "idx"){
        document.forms.SearchForm.area_target.options[document.forms.SearchForm.area_target.options.length] =
           new Option(As[i].area_name,As[i].area_code,false,false);
        break;
      }
      else{
        if (As[i].is_delimiter == "true"){
          document.forms.SearchForm.area_target.options[document.forms.SearchForm.area_target.options.length] =
             new Option(As[i].area_name,As[i].area_code,false,false);
        }
        else{
          document.forms.SearchForm.area_target.options[document.forms.SearchForm.area_target.options.length] =
             new Option(As[i].area_name,As[i].area_code,false,false);
        }
        break;
      }
    }
  }
}

function trim(val){
  while(true){
    if(val.charAt(0) == " "){
      val=val.substring(1,val.length);
    }
    else{
      break;
    }
  }
  while(true){
    if(val.charAt(val.length-1) == " "){
      val=val.substring(0,val.length-1);
    }
    else{
      break;
    }
  }
  return val;
}

function InitAreas( storedValue,As,idx_param){
  while(document.forms.SearchForm.area_target.options.length!=0){
    document.forms.SearchForm.area_target.options[0] = null;
  }
  if ( (storedValue) && (storedValue != 0) && storedValue != ""){
    _InitAreas(storedValue,As,idx_param);
    return;
  }
  if (document.forms["SearchForm"]["areas_defaults"]) {
    storedValue = document.forms["SearchForm"]["areas_defaults"].value;
    _InitAreas(storedValue,As,idx_param);
  }
}

function InitCities( storedValue,As,idx_param){
  while(document.forms.SearchForm.area_target.options.length!=0){
    document.forms.SearchForm.area_target.options[0] = null;
  }
  if ( (storedValue) && (storedValue != 0) && storedValue != ""){
    _InitCities(storedValue,As,idx_param);
    return;
  }
  if (document.forms["SearchForm"]["areas_defaults"]) {
    storedValue = document.forms["SearchForm"]["areas_defaults"].value;
    _InitCities(storedValue,As,idx_param);
  }
}

function _InitAreas( storedValue,As,idx_param){
  if ( (storedValue) && (storedValue != 0) && storedValue != ""){
    do {
      var w = storedValue.substring(0, storedValue.indexOf(","));
      var k = storedValue.substring(storedValue.indexOf(",")+1);
      storedValue = k;
      IncludeArea(document.forms.SearchForm,w,As,idx_param);
    } while ( storedValue.substring(storedValue.indexOf(",")+1) != k )
    var w = k;
    IncludeArea(document.forms.SearchForm,w,As,idx_param);
  }
}


function _InitCities( storedValue,As,idx_param){
  if ( (storedValue) && (storedValue != 0) && storedValue != ""){
    do {
      var w = storedValue.substring(0, storedValue.indexOf(","));
      var k = storedValue.substring(storedValue.indexOf(",")+1);
      storedValue = k;
      IncludeCity(document.forms.SearchForm,w,As,idx_param);
    } while ( storedValue.substring(storedValue.indexOf(",")+1) != k )
    var w = k;
    IncludeCity(document.forms.SearchForm,w,As,idx_param);
  }
}

/*
*  par              - old input parameter.
*  oper             - current operation for servlet.
*  location         - current location id (callbacks).
*  prev_operation   - operation to retrieve current location (callbacks).
*  ls               - listing system id.
*  c_ca             - callback transition action.
*  callback_prev_id - callback to return to previous page.
*/
function MLSSearch(par,oper,location,prev_operation,ls,c_ca,callback_prev_id,search_id,label) {
  if ( par == '_' ){
    document.forms.oper.submit();
  }
  if ( document.forms.SearchForm['area_target'].options.length > 0 ){
    var results = document.forms.SearchForm['area_target'][0].value;
    var k = '';
    for (i = 1; i < document.forms.SearchForm['area_target'].options.length; i++){
      k = document.forms.SearchForm['area_target'].options[i].value;
      results = results + ',' + k;
    }
    document.forms['SearchForm']['area'].value = results;
  }
  else {
    document.forms['SearchForm']['area'].value = "";
  }
  if ( par == 'test' ) {
    document.forms.SearchForm['operation'].value = oper;
  }
  if ( par == 'save' ) {
    document.forms.SearchForm['operation'].value = oper;
  }
  location = location.substring(0,location.indexOf("("));
  document.forms['SearchForm'].action = "/Navigator?location_id="+location+"(operation="+prev_operation+",ls="+ls+")&c_ca="+c_ca+"&callback_prev_id="+callback_prev_id+"&ls="+ls+label;
  document.forms['SearchForm'].submit();
}

function searchApostr(frm,except){
  for(i=0;i<frm.elements.length;i++){
    var current_element = frm.elements[i];
    if( (except.indexOf(current_element.name) == -1) && current_element.type == "text"){
      if(current_element.value.indexOf("'") != -1){
        current_element.focus();
        return alert("Illegal symbol ' in field!");
      }
    }
  }
  return true;
}

/*
*  frm              - form name.
*  p1               - old input parameter.
*  op               - current operation for servlet.
*  location         - current location id (callbacks).
*  prev_operation   - operation to retrieve current location (callbacks).
*  ls               - listing system id.
*  c_ca             - callback transition action.
*  callback_prev_id - callback to return to previous page.
*/

function checkLocationFieldsUni(frm,p1,op,location,prev_operation,ls,c_ca,callback_prev_id,lclass,search_id,label) {
  if(validateLocationFieldsUni(frm,p1,op,location,prev_operation,ls,c_ca,callback_prev_id,lclass,search_id,label)){
    handleFormUni(frm,op,location,prev_operation,ls,c_ca,callback_prev_id,lclass,search_id,label);
  }
}

function validateLocationFieldsUni(frm,p1,op,location,prev_operation,ls,c_ca,callback_prev_id,lclass,search_id,label) {
  var snameFld = frm['search_name'];
  if(!window.area_specified_text){
    var area_specified_text = "The area, map, city, zip, school district or exact address is required!";
  } else {
    var area_specified_text = window.area_specified_text;
  }

  if (snameFld != null) {
    var val = snameFld.value;
    if (val=="") {
      alert("Search name is required");
      return false;
    }
    //if (!checkValueSize(snameFld, 0, 255, false, true)){
    // alert("Search name may not exceed 255 characters. Now size is: " + snameFld.value.length);
    // return;
    //}
  }

  if(!searchApostr(frm,'search_name,email_subject,description')){
    return false;
  }

  if (! ((frm["status_active"].value == '1' || frm["status_active"].checked) ||
    (frm["status_sold"] && frm["status_sold"].checked) ||
    (frm["status_lease"] && frm["status_lease"].checked) ||
    (frm["status_backup_offers"] && frm["status_backup_offers"].checked) ||
    (frm["status_first_right"] && frm["status_first_right"].checked) ||
    (frm["status_withdrawn"] && frm["status_withdrawn"].checked) ||
    (frm["status_canceled"] && frm["status_canceled"].checked) ||
    (frm["status_offmarket"] && frm["status_offmarket"].checked) ||
    (frm["status_tempoffmarket"] && frm["status_tempoffmarket"].checked) ||
    (frm["status_expired"] && frm["status_expired"].checked) ||
    (frm["status_pending"] && frm["status_pending"].checked) ||
    (frm["status_pending_wr"] && frm["status_pending_wr"].checked) ||
    (frm["status_pending_wor"] && frm["status_pending_wor"].checked) ||
    (frm["status_penddns"] && frm["status_penddns"].checked) ||
    (frm["status_contingent"] && frm["status_contingent"].checked) ||
    (frm["status_under_agreement"] && frm["status_under_agreement"].checked) ||
    (frm["status_cntg_ko"] && frm["status_cntg_ko"].checked) ||
    (frm["status_cntg_no_ko"] && frm["status_cntg_no_ko"].checked) ||
    (frm["status_contract"] && frm["status_contract"].checked)||
    (frm["status_pend_backup"] && frm["status_pend_backup"].checked) ||
    (frm["status_app_reg"] && frm["status_app_reg"].checked) ||
    (frm["status_under_contract"] && frm["status_under_contract"].checked) ||
    (frm["status_contingent_cond"] && frm["status_contingent_cond"].checked) ||
    (frm["status_active_due"] && frm["status_active_due"].checked) ||
    (frm["status_pend_over"] && frm["status_pend_over"].checked)
    )){
    alert("Property status is required!");
    return false;
  }


  if(parseInt(frm["price"].value) > 1000000000) {
    alert("List Price value should be less!\nPlease click Ok and correct your input.");
    frm["price_l"].focus();
    return false;
  }
  if(parseInt(frm["price_high"].value) > 1000000000) {
    alert("List Price value should be less!\nPlease click Ok and correct your input.");
    frm["price_h"].focus();
    return false;
  }
  if(parseInt(frm["price_high"].value) < parseInt(frm["price"].value)) {
    alert("Min price is higher than max!");
    frm["price_h"].focus();
    return false;
  }
  var dh = null;
  var lh = null;
  if(frm["list_date"] && frm["list_date"].value.length > 0) {
    vals = frm["list_date"].value.replace(/\s/g,"").replace(/[\\\/\.\-]/g," ").split(" ");
    if(vals[0]=="" || vals[1]=="" || vals[2]==""){
      alert("List Date format is invalid!\nPlease click Ok and correct your input.");
      frm["list_date"].focus();
      return false;
    }
    if(vals[2] != null){
      if(vals[2].length > 4){
        alert("List Date format is invalid!\nPlease click Ok and correct your input.");
        frm["list_date"].focus();
        return false;
      }
    }
    year = (vals[2] < 100) ? 2000 + eval(vals[2]): vals[2];
    if (!checkDate(vals[1],vals[0], year)) {
      alert("List Date format is invalid!\nPlease click Ok and correct your input.");
      frm["list_date"].focus();
      return false;
    }
    lh = new Date(year, vals[0], vals[1]);
    frm["list_date"].value = vals[0]+"/"+vals[1]+"/"+vals[2];
  }
  if(frm["list_date_high"] && frm["list_date_high"].value.length > 0) {
    vals = frm["list_date_high"].value.replace(/\s/g,"").replace(/[\\\/\.\-]/g," ").split(" ");
    if(vals[0]=="" || vals[1]=="" || vals[2]==""){
      alert("List Date format is invalid!\nPlease click Ok and correct your input.");
      frm["list_date_high"].focus();
      return false;
    }
    if(vals[2] != null){
      if(vals[2].length > 4){
        alert("List Date format is invalid!\nPlease click Ok and correct your input.");
        frm["list_date_high"].focus();
        return false;
      }
    }
    year = (vals[2] < 100) ? 2000 + eval(vals[2]): vals[2];
    if (!checkDate(vals[1],vals[0], year)) {
      alert("List Date format is invalid!\nPlease click Ok and correct your input.");
      frm["list_date_high"].focus();
      return false;
    }
    dh = new Date(year, vals[0], vals[1]);
    frm["list_date_high"].value = vals[0]+"/"+vals[1]+"/"+vals[2];
  }
  if ((lh!=null) && (dh!=null) && (lh.getTime() >= dh.getTime())) {
    alert("List Date range is incorrect!\nPlease click Ok and correct your input.");
    frm["list_date_high"].focus();
    return false;
  }

//  if (! (frm["active"].checked | frm["pending"].checked)) {
//    alert("Property status is required!");
//    return;
//  }
  if(frm["age_high"]!=null){
    var agere = /^\d*$/g;
    if(frm["age_high"].value.search(agere) < 0) {
      alert("Age should be a number!");
      frm["age_high"].focus();
      return false;
    }
  }
  if(frm["age"]!=null){
    var agere = /^\d*$/g;
    if(frm["age"].value.search(agere) < 0) {
      alert("Age should be a number!");
      frm["age"].focus();
      return false;
    }
  }
  if(frm["age"]!=null && frm["age_high"]!=null){
    if(parseInt(frm["age"].value) > parseInt(frm["age_high"].value)) {
      alert("Min age is higher than max!");
      frm["age"].focus();
      return false;
    }
  }
  if(frm["sq_feet"] && parseInt(frm["sq_feet"].value) > 10000000) {
    alert("Square Footage value should be less!\nPlease click Ok and correct your input.");
    frm["sq_feet"].focus();
    return false;
  }
  if(frm["lot_a"]&&frm["lot_acres"] && parseInt(frm["lot_acres"].value) > 10000000) {
    alert("Lot Acres value should be less!\nPlease click Ok and correct your input.");
    frm["lot_a"].focus();
    return false;
  }
  if(frm["lot_a_high"]&&frm["lot_acres_high"] && parseInt(frm["lot_acres_high"].value) > 10000000) {
    alert("Lot Acres value should be less!\nPlease click Ok and correct your input.");
    frm["lot_a_high"].focus();
    return false;
  }
  if(frm["lot_a_high"]&&frm["lot_acres_high"] && parseInt(frm["lot_acres_high"].value) < parseInt(frm["lot_acres"].value)) {
    alert("Min lot acres is higher than max!");
    frm["lot_a_high"].focus();
    return false;
  }
  if(frm["lot_feet"] && parseInt(frm["lot_feet"].value) > 10000000) {
    alert("Lot Feet value should be less!\nPlease click Ok and correct your input.");
    frm["lot_f"].focus();
    return false;
  }
  if(frm["lot_feet_high"] && parseInt(frm["lot_feet_high"].value) > 10000000) {
    alert("Lot Feet value should be less!\nPlease click Ok and correct your input.");
    frm["lot_f_high"].focus();
    return false;
  }
  if(frm["lot_feet_high"] && parseInt(frm["lot_feet_high"].value) < parseInt(frm["lot_feet"].value)) {
    alert("Min lot feet is higher than max!");
    frm["lot_f_high"].focus();
    return false;
  }

  if(frm["rooms_high"]!=null){
    var agere = /^\d*$/g;
    if(frm["rooms_high"].value.search(agere) < 0) {
      alert("Rooms should be a number!");
      frm["rooms_high"].focus();
      return false;
    }
  }
  if(frm["rooms"]!=null){
    var agere = /^\d*$/g;
    if(frm["rooms"].value.search(agere) < 0) {
      alert("Rooms should be a number!");
      frm["rooms"].focus();
      return false;
    }
  }
  if(frm["rooms"]!=null && frm["rooms_high"]!=null && frm["rooms"].type=='text'){
    if(parseInt(frm["rooms"].value) > parseInt(frm["rooms_high"].value)) {
      alert("Min rooms is higher than max!");
      frm["rooms"].focus();
      return false;
    }
  }

  if(frm["homeowner_assoc_fee"] != null && parseInt(frm["homeowner_assoc_fee"].value) > 10000000) {
    alert("Homeowner Association Fee value should be less!\nPlease click Ok and correct your input.");
    frm["list_h"].focus();
    return false;
  }
  if(frm["buyer_broker_comp"] != null && parseInt(frm["buyer_broker_comp"].value) > 10000000) {
    alert("Buyers agent comp. value should be less!\nPlease click Ok and correct your input.");
    frm["buyer_broker_c"].focus();
    return false;
  }
  if (frm["zip"]){
    var zipre = /^[\d,\s]*$/g;
    if(frm["zip"].value.search(zipre) < 0) {
      alert("Zip should contains only digits!");
      frm["zip"].focus();
      return false;
    }
  }
  if (frm["zip_exclude"]){
    var zipre = /^[\d,\s]*$/g;
    if(frm["zip_exclude"].value.search(zipre) < 0) {
      alert("Zip should contains only digits!");
      frm["zip_exclude"].focus();
      return false;
    }
  }

    if (frm['area_target'].options.length == 0 && isCityFieldsEmpty(frm["city"])
            && (!frm["zip"]||frm["zip"].value=="") && !checkSchoolsUni(frm) && EmptyProximityFields()
            && !checkExactAddressUni(frm)) {
      var area_specified = false;
      for(var i=0; i<frm.elements.length;i++) {
        if( frm[i].tagName.toUpperCase() == 'FIELDSET') continue;
        var nm = frm[i].name;
        if(nm.indexOf("map_",0) != -1 && frm[i].value!="" && nm!="map_include") {
          area_specified = true;
          if(nm.indexOf("Barclay") == -1) if(
             (nm.indexOf("map_page_adc") != -1 && !checkRanges(frm[i], 4, 'Map codes are invalid!')) ||
             (nm.indexOf("map_x_adc") != -1 && !checkRanges(frm[i], 1, 'Map codes are invalid!', '[A-Za-z]')) ||
             (nm.indexOf("map_y_adc") != -1 && !checkRanges(frm[i], 2, 'Map codes are invalid!')) ||
             (nm.indexOf("map_page_adc") == -1 && nm.indexOf("map_page") != -1 && !checkRanges(frm[i], 4, 'Map codes are invalid!')) ||
             (nm.indexOf("map_x_adc") == -1 && nm.indexOf("map_x") != -1 && !checkRanges(frm[i], 1, 'Map codes are invalid!', '[A-Za-z]')) ||
             (nm.indexOf("map_y_adc") == -1 && nm.indexOf("map_y") != -1 && !checkRanges(frm[i], 1, 'Map codes are invalid!'))
          ) {
            frm[i].focus();
            return false;
          }
          if(nm.indexOf("map_x") != -1 || nm.indexOf("map_y") != -1) {
            if(frm["map_page_" + nm.substring(6)].value == "") {
              frm["map_page_" + nm.substring(6)].focus();
              alert("Please specify map page!");
              return false;
            }
          }
        }
      }

      if(isDrawPolygonMode(frm) && !checkPolygonFields(frm)){
        alert("Draw a shape on map.");
        return false;
      }

      var locations_specified = (frm['locations_serialized_as_url'] && frm['locations_serialized_as_url'].value);
      if(!isDrawPolygonMode(frm)  && !locations_specified && !area_specified
          && frm['mls_numbers'] && (frm['mls_numbers'].value=='')
          && ( (frm['dist_neighborhood_subdiv'] && frm['dist_neighborhood_subdiv'].value=='')
          || (frm['neighborhood'] && frm['neighborhood'].value=='') )) {
        alert(area_specified_text);
        return false;
      }
    } else {
      if (is_proximity_error) {
        alert("Proximity search could not be performed by entered address.");
        frm.geo_street_vis.focus();
        return false;
      }
    }

  if ( frm['email_header'] ){
    if (frm['email_header'].value==""){
      frm['email_header'].value=" ";
    }
    if (!checkValueSize(frm['email_header'], 0, 800, false, true)){
      alert("Mail header may not exceed 800 characters. Now size is: " + frm['email_header'].value.length);
      return false;
    }
    if (frm['email_header'].value.indexOf("<")!=-1 || frm['email_header'].value.indexOf(">")!=-1){
      alert("Mail header contains illegal characters. Symbols '<' and '>' are not allowed.");
      frm['email_header'].focus();
      return false;
    }
  }

  if ( frm['email_footer'] ){
    if (frm['email_footer'].value==""){
      frm['email_footer'].value=" ";
    }
    if (!checkValueSize(frm['email_footer'], 0, 800, false, true)){
      alert("Mail footer may not exceed 800 characters. Now size is: " + frm['email_footer'].value.length);
      return false;
    }
    if (frm['email_footer'].value.indexOf("<")!=-1 || frm['email_footer'].value.indexOf(">")!=-1){
      alert("Mail footer contains illegal characters. Symbols '<' and '>' are not allowed.");
      frm['email_footer'].focus();
      return false;
    }
  }

  // Search on Demand block.

  if(frm.hide_address){
    if(frm.hide_address.checked){
      frm.sod_hide_address.value="1";
    }else{
      frm.sod_hide_address.value="0";
    }
  }

  if(frm.map_include){
    if(frm.map_include.checked){
      frm.sod_show_map_link.value="1";
    }else{
      frm.sod_show_map_link.value="0";
    }
  }

  if(frm.hide_virtual_tour){
    if(frm.hide_virtual_tour.checked){
      frm.sod_hide_vt_link.value="1";
    }else{
      frm.sod_hide_vt_link.value="0";
    }
  }

  if(frm.hide_description){
    if(frm.hide_description.checked){
      frm.sod_hide_listing_description.value="1";
    }else{
      frm.sod_hide_listing_description.value="0";
    }
  }
  //prepareFormUni(frm,op,location,prev_operation,ls,c_ca,callback_prev_id,lclass,search_id,label);
  return true;
}

function checkLocationFieldsLmls(frm,p1,op,location,prev_operation,ls,c_ca,callback_prev_id,lclass,search_id,label) {
  if(validateLocationFieldsLmls(frm,p1,op,location,prev_operation,ls,c_ca,callback_prev_id,lclass,search_id,label)){
    handleFormLmls(frm,op,location,prev_operation,ls,c_ca,callback_prev_id,lclass,search_id,label);
  }
}

function validateLocationFieldsLmls(frm,p1,op,location,prev_operation,ls,c_ca,callback_prev_id,lclass,search_id,label) {
  var snameFld = frm['search_name'];
  if(!window.area_specified_text){
    var area_specified_text = "The area, map, city, zip, school district or exact address is required!";
  } else {
    var area_specified_text = window.area_specified_text;
  }

  if (snameFld != null) {
    var val = snameFld.value;
    if (val=="") {
      alert("Search name is required");
      return false;
    }
    //if (!checkValueSize(snameFld, 0, 255, false, true)){
    // alert("Search name may not exceed 255 characters. Now size is: " + snameFld.value.length);
    // return;
    //}
  }

  if(!searchApostr(frm,'search_name,email_subject,description')){
    return false;
  }

  if (! ((frm["status_active"].value == '1' || frm["status_active"].checked) ||
    (frm["status_sold"] && frm["status_sold"].checked) ||
    (frm["status_lease"] && frm["status_lease"].checked) ||
    (frm["status_backup_offers"] && frm["status_backup_offers"].checked) ||
    (frm["status_first_right"] && frm["status_first_right"].checked) ||
    (frm["status_withdrawn"] && frm["status_withdrawn"].checked) ||
    (frm["status_canceled"] && frm["status_canceled"].checked) ||
    (frm["status_offmarket"] && frm["status_offmarket"].checked) ||
    (frm["status_tempoffmarket"] && frm["status_tempoffmarket"].checked) ||
    (frm["status_expired"] && frm["status_expired"].checked) ||
    (frm["status_pending"] && frm["status_pending"].checked) ||
    (frm["status_pending_wr"] && frm["status_pending_wr"].checked) ||
    (frm["status_pending_wor"] && frm["status_pending_wor"].checked) ||
    (frm["status_penddns"] && frm["status_penddns"].checked) ||
    (frm["status_contingent"] && frm["status_contingent"].checked) ||
    (frm["status_under_agreement"] && frm["status_under_agreement"].checked) ||
    (frm["status_contingent_cond"] && frm["status_contingent_cond"].checked) ||
    (frm["status_active_due"] && frm["status_active_due"].checked) ||
    (frm["status_cntg_ko"] && frm["status_cntg_ko"].checked) ||
    (frm["status_cntg_no_ko"] && frm["status_cntg_no_ko"].checked) ||
    (frm["status_contract"] && frm["status_contract"].checked)||
    (frm["status_pend_backup"] && frm["status_pend_backup"].checked) ||
    (frm["status_app_reg"] && frm["status_app_reg"].checked) ||
    (frm["status_under_contract"] && frm["status_under_contract"].checked) ||
    (frm["status_pend_over"] && frm["status_pend_over"].checked)
    )){
    alert("Property status is required!");
    return false;
  }


  if(parseInt(frm["price"].value) > 1000000000) {
    alert("List Price value should be less!\nPlease click Ok and correct your input.");
    frm["price_l"].focus();
    return false;
  }
  if(parseInt(frm["price_high"].value) > 1000000000) {
    alert("List Price value should be less!\nPlease click Ok and correct your input.");
    frm["price_h"].focus();
    return false;
  }
  if(parseInt(frm["price_high"].value) < parseInt(frm["price"].value)) {
    alert("Min price is higher than max!");
    frm["price_h"].focus();
    return false;
  }
  var dh = null;
  var lh = null;
  if(frm["list_date"] && frm["list_date"].value.length > 0) {
    vals = frm["list_date"].value.replace(/\s/g,"").replace(/[\\\/\.\-]/g," ").split(" ");
    if(vals[0]=="" || vals[1]=="" || vals[2]==""){
      alert("List Date format is invalid!\nPlease click Ok and correct your input.");
      frm["list_date"].focus();
      return false;
    }
    if(vals[2] != null){
      if(vals[2].length > 4){
        alert("List Date format is invalid!\nPlease click Ok and correct your input.");
        frm["list_date"].focus();
        return false;
      }
    }
    year = (vals[2] < 100) ? 2000 + eval(vals[2]): vals[2];
    if (!checkDate(vals[1],vals[0], year)) {
      alert("List Date format is invalid!\nPlease click Ok and correct your input.");
      frm["list_date"].focus();
      return false;
    }
    lh = new Date(year, vals[0], vals[1]);
    frm["list_date"].value = vals[0]+"/"+vals[1]+"/"+vals[2];
  }
  if(frm["list_date_high"] && frm["list_date_high"].value.length > 0) {
    vals = frm["list_date_high"].value.replace(/\s/g,"").replace(/[\\\/\.\-]/g," ").split(" ");
    if(vals[0]=="" || vals[1]=="" || vals[2]==""){
      alert("List Date format is invalid!\nPlease click Ok and correct your input.");
      frm["list_date_high"].focus();
      return false;
    }
    if(vals[2] != null){
      if(vals[2].length > 4){
        alert("List Date format is invalid!\nPlease click Ok and correct your input.");
        frm["list_date_high"].focus();
        return false;
      }
    }
    year = (vals[2] < 100) ? 2000 + eval(vals[2]): vals[2];
    if (!checkDate(vals[1],vals[0], year)) {
      alert("List Date format is invalid!\nPlease click Ok and correct your input.");
      frm["list_date_high"].focus();
      return false;
    }
    dh = new Date(year, vals[0], vals[1]);
    frm["list_date_high"].value = vals[0]+"/"+vals[1]+"/"+vals[2];
  }
  if ((lh!=null) && (dh!=null) && (lh.getTime() >= dh.getTime())) {
    alert("List Date range is incorrect!\nPlease click Ok and correct your input.");
    frm["list_date_high"].focus();
    return false;
  }

//  if (! (frm["active"].checked | frm["pending"].checked)) {
//    alert("Property status is required!");
//    return;
//  }
  if(frm["age_high"]!=null){
    var agere = /^\d*$/g;
    if(frm["age_high"].value.search(agere) < 0) {
      alert("Age should be a number!");
      frm["age_high"].focus();
      return false;
    }
  }
  if(frm["age"]!=null){
    var agere = /^\d*$/g;
    if(frm["age"].value.search(agere) < 0) {
      alert("Age should be a number!");
      frm["age"].focus();
      return false;
    }
  }
  if(frm["age"]!=null && frm["age_high"]!=null){
    if(parseInt(frm["age"].value) > parseInt(frm["age_high"].value)) {
      alert("Min age is higher than max!");
      frm["age"].focus();
      return false;
    }
  }
  if(frm["sq_feet"] && parseInt(frm["sq_feet"].value) > 10000000) {
    alert("Square Footage value should be less!\nPlease click Ok and correct your input.");
    frm["sq_feet"].focus();
    return false;
  }
  if(frm["lot_a"]&&frm["lot_acres"] && parseInt(frm["lot_acres"].value) > 10000000) {
    alert("Lot Acres value should be less!\nPlease click Ok and correct your input.");
    frm["lot_a"].focus();
    return false;
  }
  if(frm["lot_a_high"]&&frm["lot_acres_high"] && parseInt(frm["lot_acres_high"].value) > 10000000) {
    alert("Lot Acres value should be less!\nPlease click Ok and correct your input.");
    frm["lot_a_high"].focus();
    return false;
  }
  if(frm["lot_a_high"]&&frm["lot_acres_high"] && parseInt(frm["lot_acres_high"].value) < parseInt(frm["lot_acres"].value)) {
    alert("Min lot acres is higher than max!");
    frm["lot_a_high"].focus();
    return false;
  }
  if(frm["lot_feet"] && parseInt(frm["lot_feet"].value) > 10000000) {
    alert("Lot Feet value should be less!\nPlease click Ok and correct your input.");
    frm["lot_f"].focus();
    return false;
  }
  if(frm["lot_feet_high"] && parseInt(frm["lot_feet_high"].value) > 10000000) {
    alert("Lot Feet value should be less!\nPlease click Ok and correct your input.");
    frm["lot_f_high"].focus();
    return false;
  }
  if(frm["lot_feet_high"] && parseInt(frm["lot_feet_high"].value) < parseInt(frm["lot_feet"].value)) {
    alert("Min lot feet is higher than max!");
    frm["lot_f_high"].focus();
    return false;
  }

  if(frm["rooms_high"]!=null){
    var agere = /^\d*$/g;
    if(frm["rooms_high"].value.search(agere) < 0) {
      alert("Rooms should be a number!");
      frm["rooms_high"].focus();
      return false;
    }
  }
  if(frm["rooms"]!=null){
    var agere = /^\d*$/g;
    if(frm["rooms"].value.search(agere) < 0) {
      alert("Rooms should be a number!");
      frm["rooms"].focus();
      return false;
    }
  }
  if(frm["rooms"]!=null && frm["rooms_high"]!=null && frm["rooms"].type=='text'){
    if(parseInt(frm["rooms"].value) > parseInt(frm["rooms_high"].value)) {
      alert("Min rooms is higher than max!");
      frm["rooms"].focus();
      return false;
    }
  }

  if(frm["homeowner_assoc_fee"] != null && parseInt(frm["homeowner_assoc_fee"].value) > 10000000) {
    alert("Homeowner Association Fee value should be less!\nPlease click Ok and correct your input.");
    frm["list_h"].focus();
    return false;
  }
  if(frm["buyer_broker_comp"] != null && parseInt(frm["buyer_broker_comp"].value) > 10000000) {
    alert("Buyers agent comp. value should be less!\nPlease click Ok and correct your input.");
    frm["buyer_broker_c"].focus();
    return false;
  }
  if (frm["zip"]){
    var zipre = /^[\d,\s]*$/g;
    if(frm["zip"].value.search(zipre) < 0) {
      alert("Zip should contains only digits!");
      frm["zip"].focus();
      return false;
    }
  }
  if (frm["zip_exclude"]){
    var zipre = /^[\d,\s]*$/g;
    if(frm["zip_exclude"].value.search(zipre) < 0) {
      alert("Zip should contains only digits!");
      frm["zip_exclude"].focus();
      return false;
    }
  }

    if (frm['area_target'].options.length == 0
            && (!frm["zip"]||frm["zip"].value=="") && !checkSchoolsUni(frm) && EmptyProximityFields()
            && !checkExactAddressUni(frm)) {
      var area_specified = false;
      for(var i=0; i<frm.elements.length;i++) {
        if( frm[i].tagName.toUpperCase() == 'FIELDSET') continue;
        var nm = frm[i].name;
        if(nm.indexOf("map_",0) != -1 && frm[i].value!="" && nm!="map_include") {
          area_specified = true;
          if(nm.indexOf("Barclay") == -1) if(
             (nm.indexOf("map_page_adc") != -1 && !checkRanges(frm[i], 4, 'Map codes are invalid!')) ||
             (nm.indexOf("map_x_adc") != -1 && !checkRanges(frm[i], 1, 'Map codes are invalid!', '[A-Za-z]')) ||
             (nm.indexOf("map_y_adc") != -1 && !checkRanges(frm[i], 2, 'Map codes are invalid!')) ||
             (nm.indexOf("map_page_adc") == -1 && nm.indexOf("map_page") != -1 && !checkRanges(frm[i], 4, 'Map codes are invalid!')) ||
             (nm.indexOf("map_x_adc") == -1 && nm.indexOf("map_x") != -1 && !checkRanges(frm[i], 1, 'Map codes are invalid!', '[A-Za-z]')) ||
             (nm.indexOf("map_y_adc") == -1 && nm.indexOf("map_y") != -1 && !checkRanges(frm[i], 1, 'Map codes are invalid!'))
          ) {
            frm[i].focus();
            return false;
          }
          if(nm.indexOf("map_x") != -1 || nm.indexOf("map_y") != -1) {
            if(frm["map_page_" + nm.substring(6)].value == "") {
              frm["map_page_" + nm.substring(6)].focus();
              alert("Please specify map page!");
              return false;
            }
          }
        }
      }

      if(isDrawPolygonMode(frm) && !checkPolygonFields(frm)){
        alert("Draw a shape on map.");
        return false;
      }

      var locations_specified = (frm['locations_serialized_as_url'] && frm['locations_serialized_as_url'].value);
      if(!isDrawPolygonMode(frm)
          && !locations_specified
          && !area_specified
          && frm['mls_numbers']
          &&(frm['mls_numbers'].value==''))
      {
        alert(area_specified_text);
        return false;
      }
    } else {
      if (is_proximity_error) {
        alert("Proximity search could not be performed by entered address.");
        frm.geo_street_vis.focus();
        return false;
      }
    }

  if ( frm['email_header'] ){
    if (frm['email_header'].value==""){
      frm['email_header'].value=" ";
    }
    if (!checkValueSize(frm['email_header'], 0, 800, false, true)){
     alert("Mail header may not exceed 800 characters. Now size is: " + frm['email_header'].value.length);
      return false;
    }
    if (frm['email_header'].value.indexOf("<")!=-1 || frm['email_header'].value.indexOf(">")!=-1){
     alert("Mail header contains illegal characters. Symbols '<' and '>' are not allowed.");
     frm['email_header'].focus();
      return false;
    }
  }

  if ( frm['email_footer'] ){
    if (frm['email_footer'].value==""){
      frm['email_footer'].value=" ";
    }
    if (!checkValueSize(frm['email_footer'], 0, 800, false, true)){
     alert("Mail footer may not exceed 800 characters. Now size is: " + frm['email_footer'].value.length);
      return false;
    }
    if (frm['email_footer'].value.indexOf("<")!=-1 || frm['email_footer'].value.indexOf(">")!=-1){
     alert("Mail footer contains illegal characters. Symbols '<' and '>' are not allowed.");
     frm['email_footer'].focus();
      return false;
    }
  }

  // Search on Demand block.

  if(frm.hide_address){
    if(frm.hide_address.checked){
      frm.sod_hide_address.value="1";
    }else{
      frm.sod_hide_address.value="0";
    }
  }

  if(frm.map_include){
    if(frm.map_include.checked){
      frm.sod_show_map_link.value="1";
    }else{
      frm.sod_show_map_link.value="0";
    }
  }

  if(frm.hide_virtual_tour){
    if(frm.hide_virtual_tour.checked){
      frm.sod_hide_vt_link.value="1";
    }else{
      frm.sod_hide_vt_link.value="0";
    }
  }

  if(frm.hide_description){
    if(frm.hide_description.checked){
      frm.sod_hide_listing_description.value="1";
    }else{
      frm.sod_hide_listing_description.value="0";
    }
  }
  //prepareFormUni(frm,op,location,prev_operation,ls,c_ca,callback_prev_id,lclass,search_id,label);

  return true;
}

function isDrawPolygonMode(frm){
  return (frm['by_polygon'] && frm['by_polygon'].checked);
}

function checkPolygonFields(frm){
  var polygon_specified = (frm['polygon_serialized_as_url'] && frm['polygon_serialized_as_url'].value);
  return polygon_specified;
}

function checkGeoProximity(frm){
  return     (!isEmpty(frm['proximity_street']) && !isEmpty(frm['proximity_zip']) && !isEmpty(frm['latitude']) && !isEmpty(frm['longitude']) && !isEmpty(frm['proximity_dist']))
          || (!isEmpty(frm['proximity_street']) && !isEmpty(frm['proximity_city']) && isEmpty(frm['proximity_state']) && !isEmpty(frm['latitude']) && !isEmpty(frm['longitude']) && !isEmpty(frm['proximity_dist']));
}

function isEmpty(element){
  return element==null||element.value=="";
}

function checkExactAddressUni(frm){
  if(frm['exact_addr_zip']!=null&&frm['exact_addr_zip'].value!='' ||
     (frm['exact_addr_city']!=null&&frm['exact_addr_city'].value!=''&&frm['exact_addr_state']!=null&&frm['exact_addr_state'].value!='')
  )return true;
  return false;
}

function checkSchoolsUni(frm){
  if(frm['high_school_distr'] != null && frm['high_school_distr'].value!=""){
    return true;
  }
  if(frm['jun_school_distr'] != null && frm['jun_school_distr'].value!=""){
    return true;
  }
  if(frm['jun_sch_distr'] != null && frm['jun_sch_distr'].value!=""){
    return true;
  }
  if(frm['elem_school_distr'] != null && frm['elem_school_distr'].value!=""){
    return true;
  }
  if(frm['high_school'] != null && frm['high_school'].value!=""){
    return true;
  }
  if(frm['elem_school'] != null && frm['elem_school'].value!=""){
    return true;
  }
  if(frm['middle_school'] != null && frm['middle_school'].value!=""){
    return true;
  }
  if(frm['elem_sch_distr'] != null && frm['elem_sch_distr'].value!=""){
    return true;
  }
  if(frm['school_elem'] != null && frm['school_elem'].value!=""){
    return true;
  }
  if(frm['school_elem_b'] != null && frm['school_elem_b'].value!=""){
    return true;
  }
  if(frm['high_school_distr'] != null && frm['high_school_distr'].value!=""){
    return true;
  }
  if(frm['jun_school'] != null && frm['jun_school'].value!=""){
    return true;
  }
  if(frm['school_middle'] != null && frm['school_middle'].value!=""){
    return true;
  }
  if(frm['grade_school'] != null && frm['grade_school'].value!=""){
    return true;
  }

  if(frm['other_school'] != null && frm['other_school'].value!=""){
    return true;
  }

  if(frm['other_school_distr'] != null && frm['other_school_distr'].value!=""){
    return true;
  }
  if(frm['school_distr'] != null && frm['school_distr'].value!=""){
    return true;
  }

  return false;
}

function checkLocationFields(frm,p1,op,location,prev_operation,lsName,c_ca,callback_prev_id,lclass,search_id,label) {
    checkLocationFieldsUni(frm, p1, op,location,prev_operation,lsName,c_ca,callback_prev_id,lclass,search_id,label);
}

function checkLocationFieldsForLmls(frm,p1,op,location,prev_operation,lsName,c_ca,callback_prev_id,lclass,search_id,label) {
    checkLocationFieldsLmls(frm, p1, op,location,prev_operation,lsName,c_ca,callback_prev_id,lclass,search_id,label);
}


var flag = 0;


function checkRanges(input, size, alertstr, symbolsclass) {
  var val = input.value;
  filler = '0';
  if(val.length == 0) return true;
  if (!symbolsclass || symbolsclass == "") symbolsclass = "\\d";
  numbers = "\\s*("+symbolsclass+"{1,"+size+"}|"+symbolsclass+"{1,"+size+"}\\s*-\\s*"+symbolsclass+"{1,"+size+"})\\s*";
  var regexp = new RegExp("^"+numbers+"(,"+numbers+")*$");//
  var str = "";
  if(!regexp.test(val)) {
    if(alertstr != '') {
      alert(alertstr);
      input.focus();
    }
    return false;
  }
  val = val.replace(/\s/g, "");
  while((i = val.search(/,|-/)) >= 0) {
    number = val.substring(0,i);
    delim = val.substring(i,i+1);
    if(number.length > 0) str += fillLeftWith(number, size, filler) + delim;
    val = val.substring(i+1);
  }
  if(val.length > 0) str += fillLeftWith(val, size, filler);
  input.value = str;
  return true;
}

function checkRes(target){
//  alert(target.form);
  frm = target.form;
  if ( target.name == 'include_details' ) {
    if ( (target.checked == true) && (frm['update_organizer'].checked == false) ) target.checked = false;
  }
  if ( (target.name == 'update_organizer') && (target.checked == false) ) frm['include_details'].checked = false;
}

//function stripSpaces(field){
//  var re = /^\s*(.*?)\s*$/;
//  field.value = field.value.replace(re, "$1");
//}

function stripSpaces(field){
  var source_str = field.value;
  var result_str = strip(source_str);
  field.value = result_str;

}

function strip(str){
  var result_str = str;
  var source_str = str;
  var flag = false;
  var strip_class = "   ";

  for(i=0;i < source_str.length;i++){
    var cur_char = source_str.substring(i,i+1);
    if ( (strip_class.indexOf(cur_char) != -1) && (flag != true) ) {
      result_str = source_str.substring(i+1)
    } else {
      flag = true;
      break;
    }
  }

  flag = false;

  for(i=source_str.length;i > 0;i--){
    var cur_char = result_str.substring(i,i-1);
    if ( (strip_class.indexOf(cur_char) != -1) && (flag != true) ) {
      result_str = result_str.substring(0,i-1)
    } else {
      flag = true;
      break;
    }
  }
  return result_str;
}


/* 
 * This function eliminates both outer and internal spaces for values separated with specified symbol.
 */
function stripSeparatedValues(field, separator){
  var source_str = field.value;
  var strSource = new String(source_str);
  var arr = strSource.split(separator);
  var result = "";

  for(var i=0; i<arr.length; i++){
    arr[i] = strip(arr[i]);
    result += arr[i];
    if(i < (arr.length - 1)){
      result += separator;
    }
  }
  field.value = result;
}

function helpScools(){
    var myBars = 'directories=no,location=no,menubar=yes,toolbar=yes,status=no,titlebar=no,scrollbars=yes,resizable=yes,alwaysRaised=yes,width=600,height=400';
    var newWinUrl = '/Help?topic=reil_schools';
    var windowName = 'helpreil';
    var newWin = open (newWinUrl, windowName, myBars);
    newWin.focus();
}

function helpShcoolsLMetroco(){
    var myBars = 'directories=no,location=no,menubar=yes,toolbar=yes,status=no,titlebar=no,scrollbars=yes,resizable=yes,alwaysRaised=yes,width=600,height=400';
    var newWinUrl = '/Help?topic=lmetroco_schools';
    var windowName = 'helplmetroco';
    var newWin = open (newWinUrl, windowName, myBars);
    newWin.focus();
}

function doDetails(num, ls) {
  var myBars = 'directories=no,location=no,menubar=no,status=no,titlebar=no,toolbar=yes,scrollbars=yes,resizable=yes,alwaysRaised=yes,width=680,height=580';
  var newWinUrl = "http://" + realtor_homepage_url + "/PropertyDetails?ls=" + ls + "&pid=" + num;
  var newWin = open (newWinUrl, "viewDetails", myBars);
  newWin.focus();
}


function fillAreaCode(frm) {
  var temp = '';
  if (frm['area_target'].options.length > 0) {
    temp = frm['area_target'][0].value;
  }
  for (i = 1; i < frm['area_target'].options.length; i++){
    temp = temp + ',' + frm['area_target'].options[i].value;
  }
  handleLocationSearchType(frm, temp);
  if(frm['area_code']) frm['area_code'].value = temp.toUpperCase();
}

function prepareFormUni(frm, oper,location,prev_operation,ls,c_ca,callback_prev_id,lclass,search_id,label) {
  fillAreaCode(document.forms.SearchForm);
  document.forms.SearchForm['operation'].value = oper;
  location = location.substring(0,location.indexOf("("));
  if(!search_id){
    search_id="";
  }
}

function handleFormUni(frm, oper,location,prev_operation,ls,c_ca,callback_prev_id,lclass,search_id,label) {
  prepareFormUni(frm, oper,location,prev_operation,ls,c_ca,callback_prev_id,lclass,search_id,label);
  if(isNoSubmitOperation(oper)){
    return;
  }
  document.forms['SearchForm'].action = "/Navigator?location_id="+location+"(operation="+prev_operation+",ls="+ls+",lclass="+lclass+")&c_ca="+c_ca+"&callback_prev_id="+callback_prev_id+"&ls="+ls+label;
  document.forms.SearchForm.submit();
}

function handleFormLmls(frm, oper,location,prev_operation,ls,c_ca,callback_prev_id,lclass,search_id,label) {
  prepareFormUni(frm, oper,location,prev_operation,ls,c_ca,callback_prev_id,lclass,search_id,label);
  if(isNoSubmitOperation(oper)){
    return;
  }
  document.forms['SearchForm'].action = "/Navigator?location_id="+location+"(operation="+prev_operation+",ls="+ls+",lclass="+lclass+")&c_ca="+c_ca+"&callback_prev_id="+callback_prev_id+"&ls="+ls+label;
  document.forms.SearchForm.submit();
}

function handleLocationSearchType(sform, val){
    if(sform["hdn_location_search_type"]&&sform['city']&&sform["hdn_location_search_type"].value=="city_name"){
      if(sform['geo_area']) sform['geo_area'].value = "";
      sform['city'].value = val.toUpperCase();
    }else{
      sform['geo_area'].value = val.toUpperCase();
      if(sform['city']) sform['city'].value = "";
    }
}

function getAreasForCounty(county,target,As,idx_param){
  while(target.options.length!=0){
    target.options[0] = null;
  }
  getAreasByData(county,target,As);
}

function getPreselectedAreasForCounty(county,target,As,idx_param,preselectedVals){
  if(county != " - select county - " && county != "001"){
    while(target.options.length!=0){
      target.options[0] = null;
    }
    getPreselectedAreasByData(county,target,As,idx_param, preselectedVals);
  }
  if(county == "001"){
    getPreselectedAllAreas(target,As,preselectedVals);
  }
}


function getAreasForCountyIdx(county,target,As){
  if(county != " - select county - " && county != "001"){
    while(target.options.length!=0){
      target.options[0] = null;
    }
    getAreasByData(county,target,As);
  }
  if(county == "001"){
    getAllAreas(target,As);
  }
}


function getAllAreas(target,As,idx_param){
  while(target.options.length!=0){
    target.options[0] = null;
  }
  var county = 0;
  getAreasByData(county,target,As);
}

function getPreselectedAllAreas(target,As,idx_param, preselectedVals){
  while(target.options.length!=0){
    target.options[0] = null;
  }
  var county = 0;
  county = document.forms.SearchForm.SelectedCounty.value;
  getPreselectedAreasByData(county,target,As,idx_param, preselectedVals);
}

function appendAreaToSelector(selector, area) {
    if( selector.options.length == 0
           || selector.options[selector.options.length - 1].value != area.area_code){
        if (document.forms.SearchForm.ls.value == "SOCAL") {
            var matchResult = area.area_code.match(/\w+\/(\w+)/);
            // area.area_code+
            if (matchResult) {
                selector.options[selector.options.length]
                    = new Option(matchResult[1] + " - " + area.area_name, area.area_code,0,0);
            }
            else {
                // OA means out of area - this is the city without areas
                selector.options[selector.options.length]
                    = new Option("OA - " + area.area_name, area.area_code,0,0);
            }
        }else if(area.is_delimiter=="true"){
            selector.options[selector.options.length]
                    = new Option(area.area_code+" - " + area.area_name, area.area_code,0,0);
        }
        else{
            selector.options[selector.options.length] = new Option(area.area_name, area.area_code,0,0);
        }
   }
}

/**
 * This method append areas to selector 
 *
 * @param county
 * @param target Select object
 * @param As areas array
 * @param idx_param I think, that this parameter redulant. It means, that selector is on the
 * idx-page. (It means on the web-site)
 */
function getAreasByData(county,target,As){
  if(county == 0){
    for(var i=0; i<As.length; i++){
      appendAreaToSelector(target, As[i]);
    }
  }
  else{
    for(var i=0; i<As.length; i++){
      if(As[i].county_number == county){
        appendAreaToSelector(target, As[i]); 
      }
    }
  }
}


function getPreselectedAreasByData(county,target,As,idx_param, preselectedVals){
  var pArr = preselectedVals.split(",");
  if(county == 0){
    for(var i=0; i<As.length; i++){
      if( target.options.length > 0 && target.options[target.options.length - 1].value == As[i].area_code){   
      }else{
        if(idx_param=="idx"){
          var sel=0;
          for(var ii=0; ii<pArr.length; ii++){
            if(pArr[ii]==As[i].area_code){
              sel=1;
              break;
            }
          }
          target.options[target.options.length] = new Option(As[i].area_name,As[i].area_code,0,sel);
        } else if (idx_param=="reil") {
            var sel=0;
            for(var ii=0; ii<pArr.length; ii++){
              if(pArr[ii]==As[i].area_code){
                sel=1;
                break;
              }
            }
            target.options[target.options.length] = new Option(As[i].area_code+" - "+As[i].area_name,As[i].area_code,0,sel);
        } else {
          if(As[i].is_delimiter == "true"){
              var sel=0;
              for(var ii=0; ii<pArr.length; ii++){
                if(pArr[ii]==As[i].area_code){
                  sel=1;
                  break;
                }
              }
            target.options[target.options.length] = new Option(As[i].area_code+" - "+As[i].area_name,As[i].area_code,0,sel);
          } else {
            var sel=0;
              for(var ii=0; ii<pArr.length; ii++){
                if(pArr[ii]==As[i].area_code){
                  sel=1;
                  break;
                }
              }
            target.options[target.options.length] = new Option(As[i].area_name,As[i].area_code,0,sel);
          }
        }
      }
    }
  }
  else{
    for(var i=0; i<As.length; i++){
      if(As[i].county_number == county){
        if( target.options.length > 0 && target.options[target.options.length - 1].value == As[i].area_code){
        }else{
          if(idx_param=="idx"){
            var sel=0;
              for(var ii=0; ii<pArr.length; ii++){
                if(pArr[ii]==As[i].area_code){
                  sel=1;
                  break;
                }
              }
            target.options[target.options.length] = new Option(As[i].area_name,As[i].area_code,0,sel);
          } else{
            if(As[i].is_delimiter=="true"){
              var sel=0;
              for(var ii=0; ii<pArr.length; ii++){
                if(pArr[ii]==As[i].area_code){
                  sel=1;
                  break;
                }
              }
              target.options[target.options.length] = new Option(As[i].area_code+" - "+As[i].area_name,As[i].area_code,0,sel);
            } else if (idx_param=="reil") {
              var sel=0;
              for(var ii=0; ii<pArr.length; ii++){
                if(pArr[ii]==As[i].area_code){
                  sel=1;
                  break;
                }
              }
              target.options[target.options.length] = new Option(As[i].area_code+" - "+As[i].area_name,As[i].area_code,0,sel);
            } else{
              var sel=0;
              for(var ii=0; ii<pArr.length; ii++){
                if(pArr[ii]==As[i].area_code){
                  sel=1;
                  break;
                }
              }
              target.options[target.options.length] = new Option(As[i].area_name,As[i].area_code,0,sel);
            }
          }
        }
      }
    }
  }
}


function InitCounty(storedValue,target,As,idx_param){
  var idx = "";
  if(document.forms.SearchForm.ls.value == "MAX"){
    idx = "idx";
  }
  if ( (storedValue) && storedValue != ""){
    for(var i=0; i<document.forms.SearchForm.county_source.options.length; i++){
      if(document.forms.SearchForm.county_source.options[i].value == storedValue){
        document.forms.SearchForm.county_source.options[i].selected = true;
        break;
      }
    }
    getAreasForCounty(storedValue,target,As, idx_param);
  }
  else{
    getAllAreas(document.forms.SearchForm.area_source,As,idx);
  }
}

function InitCountyIdx(storedValue,target,As){
  if ( (storedValue) && storedValue != ""){
    for(var i=0; i<document.forms.SearchForm.county_source.options.length; i++){
      if(document.forms.SearchForm.county_source.options[i].value == storedValue){
        document.forms.SearchForm.county_source.options[i].selected = true;
        break;
      }
    }
    getAreasForCountyIdx(storedValue,target,As);
  }
  else{
    getAllAreas(document.forms.SearchForm.area_source,As,"idx");
  }
}



function setWildCriteria(control,value){
  var val = control.value;
  if(val.length > 0){
    if(value == "exact"){
      var pos = 0;
      while(pos < val.length){
        if(val.substring(pos,pos + 1) == "*"){
          val=val.substring(0,pos) + val.substring(pos + 1,val.length);
        }
        else{
          pos++;
        }
      }
    }
    else{
      var pos = 0;
      while(pos < val.length){
        if(val.substring(pos,pos + 1) == ","){
          //val = val.substring(0, pos);
          var temp = val.substring(0, pos);
          if(val.substring(pos-1,pos+1)!="*,"){
             val = temp + "*," + val.substring(pos+1,val.length);
           pos+=2;
          }
          else{
            val = temp + "," + val.substring(pos+1,val.length);
            pos++;
          }
        }
        else{
          pos++;
        }
      }
      if(val.substring(val.length-1,val.length) != "*"){
        val = val + "*";
      }
    }
  }
  control.value=val;
}


function helpWildCard(){
    var myBars = 'directories=no,location=no,menubar=no,status=no,titlebar=no,toolbar=no,scrollbars=no,resizable=yes,width=250,height=200';
    var newWinUrl = '/Help?topic=wild_card';
    var newWin = open (newWinUrl,'helpWildCard',myBars);
    newWin.focus();
}



  function parse_counties(counties){
    var ret_val = new Array;
    while(true){
      var tmp=counties.substring(0,counties.indexOf(','));
      counties = counties.substring(tmp.length+1,counties.length);
      ret_val[ret_val.length] = tmp;
      if(counties.indexOf(",") == -1){
        break;
      }
    }
    return ret_val;
  }


  function sortCounties(preset_counties,all_counties,ids,selected_num,states,ss, selectObjectToFill){
    var arr_preset_counties = new Array;
    arr_preset_counties = parse_counties(preset_counties);
    var sorted_counties = new Array;
    var sorted_ids = new Array;
    var sorted_states = new Array;
    var ret_val = "";
    for(var i=0; i<arr_preset_counties.length; i++){
      for(var j=0; j<all_counties.length; j++){
        if(all_counties[j]==""){
          continue;
        }
        if(arr_preset_counties[i].indexOf(all_counties[j])!=-1){
          sorted_counties[sorted_counties.length]=all_counties[j];
          sorted_ids[sorted_ids.length]=ids[j];
          if(states)sorted_states[sorted_states.length]=states[j];
          all_counties[j]="";
        }
      }
    }

    for(var i=0; i<all_counties.length; i++){
      if(all_counties[i]!=""){
        sorted_counties[sorted_counties.length]=all_counties[i];
        sorted_ids[sorted_ids.length] = ids[i];
        if(states)sorted_states[sorted_states.length] = states[i];
      }
    }

    for(var i=0; i<sorted_counties.length; i++){
      if(sorted_counties[i]=='Other counties') continue;
      var text = sorted_counties[i]+(ss&&sorted_states[i]!=""?", "+sorted_states[i]:"");
      var val = sorted_ids[i];
      if(selectObjectToFill!=null&&selectObjectToFill.options){
        var option = new Option(text,val);
        if(sorted_ids[i]==selected_num) option.selected=true;
        selectObjectToFill.options[selectObjectToFill.options.length] = option;
      }else{
        var selected = "";
        if(sorted_ids[i]==selected_num) selected="selected";
        ret_val += "<option value='"+val+"'"+(selected)+">"+text+"</option>";
      }
    }
    return ret_val;
  }


  function sortCountiesWithParam(preset_counties,all_counties,ids,mls,states,ss){
    var arr_preset_counties = new Array;
    arr_preset_counties = parse_counties(preset_counties);
    var sorted_counties = new Array;
    var sorted_ids = new Array;
    var sorted_states = new Array;
    var ret_val = "";
    for(var i=0; i<arr_preset_counties.length; i++){
      for(var j=0; j<all_counties.length; j++){
        if(all_counties[j]==""){
          continue;
        }
        var preset_full = states?all_counties[j]+" "+states[j]:all_counties[j];
        if(arr_preset_counties[i].indexOf(preset_full)!=-1){
          sorted_counties[sorted_counties.length]=all_counties[j];
          sorted_ids[sorted_ids.length]=ids[j];
          if(states)sorted_states[sorted_states.length]=states[j];
          all_counties[j]="";
        }
      }
    }

    for(var i=0; i<all_counties.length; i++){
      if(all_counties[i]!=""){
        sorted_counties[sorted_counties.length]=all_counties[i];
        sorted_ids[sorted_ids.length] = ids[i];
        if(states)sorted_states[sorted_states.length] = states[i];
      }
    }

    for(var i=0; i<sorted_counties.length; i++){
      if(sorted_counties[i]!='Other counties')ret_val += "<option value='/Listings?ls="+mls+"&amp;county="+sorted_ids[i]+"'>"+sorted_counties[i]+(ss&&sorted_states[i]!=""?", "+sorted_states[i]:"")+"</option>";
    }
    return ret_val;
  }
  function checkLetterForIllegalSymbols(field){
    var val = field.value;
    if((val.indexOf("<")!=-1) || (val.indexOf(">")!=-1)){
      return "Mail contains illegal characters. Symbols '<' and '>' are not allowed.";
    }
    return "";
  }

function prepareCountiesSearch(){
  var counties_cities = document.SearchForm.counties_cities.value;
  var counties_ids_cities = document.SearchForm.counties_ids_cities.value;
  var counties_states_cities = document.SearchForm.counties_states_cities.value;
  arr_cities = parse_counties(counties_cities);
  arr_ids_cities = parse_counties(counties_ids_cities);
  arr_states_cities = parse_counties(counties_states_cities);

  var counties_areas = document.SearchForm.counties_areas.value;
  var counties_ids_areas = document.SearchForm.counties_ids_areas.value;
  var counties_states_areas = document.SearchForm.counties_states_areas.value;
  arr_areas = parse_counties(counties_areas);
  arr_ids_areas = parse_counties(counties_ids_areas);
  arr_states_areas = parse_counties(counties_states_areas);
}

function makeCountiesSearch(searchType,defaultCounty){
  var searchForm = document.SearchForm;
  var preset_counties=searchForm.meta_counties.value;
  var selectControl = searchForm.county_source;
  var uni_arr;
  var uni_arr_ids;
  var uni_arr_states;
  if (searchType=='area_code'){
    uni_arr = arr_areas;
    uni_arr_ids = arr_ids_areas;
    uni_arr_states = arr_states_areas;
  }else {
    uni_arr = arr_cities;
    uni_arr_ids = arr_ids_cities;
    uni_arr_states = arr_states_cities;
  }
  //                        width_style="style='width:150px;' width='150'";
  //clean select control
  selectControl.options.length = 0;
  // fill select control
  selectControl.options[selectControl.options.length] = new Option("All Available Areas",0);
  sortCounties(preset_counties,uni_arr,uni_arr_ids,defaultCounty,uni_arr_states,1,selectControl);
}

function isNoSubmitOperation(oper) {
  return (oper == "prepare_search_preview");
}

function isCityFieldsEmpty(cityFields) {
  if(!cityFields||cityFields.value=="") {
    return true;
  }
  if(cityFields.length && cityFields.length>1) {
    for(var i=0; i<cityFields.length; i++) {
      if(cityFields[i] && cityFields[i].value!="") {
        return false;
      }
    }
    return true; 
  }
  return false;
}
