// $Id: script.js 964 2010-11-11 11:48:17Z SLaVeZ $

var timer = new Array;
var request = new Array;
request['test'] = createRequest();
request['test'] = null;
var func = {
  _showCountryMap: function(in_array) {
    _showCountryMap(in_array);
  },
  _close_metro_advert: function() {
    adv.metro.send_data();
  },
  _close_highway_advert: function() {
	adv.highway.send_data();
  },
  _changeTopTextSearch: function(in_array) {
    _changeTopTextSearch(in_array);
  },
  _setHandlerListRegion: function(in_array) {
    _setHandlerListRegion(in_array);
  },
  _closeListRegion: function(in_array) {
    _closeListRegion(in_array);
  },
  _mapMetroStep2: function(in_array) {
    _mapMetroStep2(in_array);
  },
  _mapMetroStep3: function(in_array) {
    _mapMetroStep3(in_array);
  },
  _closeMetroMapStep2: function(in_array) {
    _closeMetroMapStep2(in_array);
  },
  _mapHighwayStep2: function(in_array) {
    _mapHighwayStep2(in_array);
  },
  _mapHighwayStep3: function(in_array) {
    _mapHighwayStep3(in_array);
  },
  _closeHighwayMapStep2: function(in_array) {
    _closeHighwayMapStep2(in_array);
  },
  _mapCityStep2: function(in_array) {
    _mapCityStep2(in_array);
  },
  _mapCityStep3: function(in_array) {
    _mapCityStep3(in_array);
  },
  _closeCityMapStep2: function(in_array) {
    _closeCityMapStep2(in_array);
  },
  _showMessageBox: function(in_array) {
    _showMessageBox(in_array);
  },
  _office_mapCityStep2: function(in_array) {
    _office_mapCityStep2(in_array);
  },
  _office_mapCityStep3: function(in_array) {
    _office_mapCityStep3(in_array);
  },
  _office_closeCityMapStep2: function(in_array) {
    _office_closeCityMapStep2(in_array);
  }
  
  
};

//var height_arr = new Array();

var MIN_WIDTH_SCREEN = 768;

var REGION_ALL = 9999;
var REGION_MOSCOW_AND_OBL = 7750;
var REGION_S_PETER_AND_OBL = 7847;
// Максимальное допустимое количество сохранённых шаблонов поиска для одного пользователя.
var SEARCH_TEMPLATE_MAX = 10;
// Тип сделки: 0 - продажа, 1 - сдача в аренду, 2 - покупка, 3 - аренда.
var DEAL_TYPE_SALE = 0;
var DEAL_TYPE_RENT = 1;
var DEAL_TYPE_BUY = 2;
var DEAL_TYPE_LEASE = 3;
// Тип недвижимости:
// 0 - загородная недвижимость (участки, коттеджи и т.д.).
// 1 - городская недвижимость (комнаты, квартиры и т.д.).
// 2 - коммерческая недвижимость (офисы, первые этажи и т.д.).
var TYPE_BUILD_COMMERCIAL = 2;
var TYPE_BUILD_CITY = 1;
var TYPE_BUILD_AREA = 0;
// Айди недвижимости:
// 2 - дом,
// 3 - дача,
// 4 - коттедж,
// 5 - таунхаус,
// 6 - участок.
var BUILD_HOUSE = 2;
var BUILD_DACHA = 3;
var BUILD_COTTAGE = 4;
var BUILD_TOWNHOUSE = 5;
var BUILD_LOT = 6;

// Форма расширенного поиска 'form-search-ext'.
var df = null;

// Определяем браузер пользователя
isNS4 = (document.layers) ? true : false;
isIE4 = (document.all && !document.getElementById) ? true : false;
isIE5 = (document.all && document.getElementById) ? true : false;
isNS6 = (!document.all && document.getElementById) ? true : false;

var globalTopText = ''; // Сохраняет шаблон текста 'Я хочу...'.
var js_load = false; // статус отработка всех скриптов в InitPage (true - когда все скрипты выполнятся).

/**
 * Выполняет необходимые действия после загрузки страницы.
 */
function initPage() {
  //alert(window.navigator.userAgent);
  // Растягиваем центральную ячейку основной таблицы.
  if (gebi("search-price-ot")) set_format_price(gebi("search-price-ot"));
  if (gebi("search-price-do")) set_format_price(gebi("search-price-do"));
  if (gebi("search-ext-price-ot")) set_format_price(gebi("search-ext-price-ot"));
  if (gebi("search-ext-price-do")) set_format_price(gebi("search-ext-price-do"));
  setHeightCellCenter();
  gebi("cell_center").className = gebi("cell_right") ? 'small_cell_center' : 'big_cell_center';
  if (gebi('log')) setTimeout(setTrigersAuthInputText, 500);
  if (isIE) {
    if (gebi('register')) {
      setTimeout(function () {display_priv_office(gebi('auth_block'));}, 500);
    }
    if (gebi("cat_com_header_lease")) {
      setTimeout(function () {display_catalogue_com(gebi("cat_com_header_lease"), "cat_lease_img_com", "cat_lease_com");}, 500);
    }
    if (gebi("cat_com_header_buy")) {
      setTimeout(function () {display_catalogue_com(gebi("cat_com_header_buy"), "cat_buy_img_com", "cat_buy_com");}, 500);
    }
    if (gebi("cat_com_header_rent")) {
      setTimeout(function () {display_catalogue_com(gebi("cat_com_header_rent"), "cat_rent_img_com", "cat_rent_com");}, 500);
    }
    if (gebi("cat_com_header_sale")) {
      setTimeout(function () {display_catalogue_com(gebi("cat_com_header_sale"), "cat_sale_img_com", "cat_sale_com");}, 500);
    }
  }
  
  // Растягиваем ячейки с новыми объявлениями.
  /*if (gebi('index_ad_div1')) {
    var tdPad = 16; // сумма верхнего и нижнего паддинга в ячейках новых объявлений.
    var resize = false;
    var tSpan = new Array;
    for (var i = 1; i <= 9 ; i++) {
      var hDiv = gebi('index_ad_div' + i).offsetHeight;
      gebi('index_ad_div' + i).style.height = gebi('index_ad_div' + i).parentNode.offsetHeight - tdPad + 'px';
    }
  }*/
  if (gebi('search-displaylist') && !(gebi('build_lot'))) {
    // Показываем список с метро|шоссе|городами|районами городов в расширенном поиске.
    gebi('search-ext-' + gebi('search-displaylist').value + 'list').style.display = 'block';
  }
  // Форма расширенного поиска 'form-search-ext'.
  df = (gebi('form-search-ext')) ? document.forms['form-search-ext'] : null;
  
  // Показываем верхний блок для расширенного поиска и устанавливаем тригеры для переключения между
  // верхними блоками популярного и расширенного поисков.
  if (gebi('search_popular') && gebi('search-ext-top') && isIE5) changeTabSearch('extended');

  // Сотки или метры площади в популярном поиске.
  if (gebi('search-mesure-area') && !(gebi('auth-login-text'))) mesureAreaFull();

  // Устанавливаем тригеры на заполнение полей цены, площади, сроков расширенного поиска.
  if (gebi('srch_filter')) {
    var extra = gebi('idsearch-extra-' + gebi("search-type").value).value;
    var type = gebi('idtypes-value-' + extra).value;
    var alt_input_ext_srch = type == DEAL_TYPE_RENT || type == DEAL_TYPE_SALE;
    setTrigersListInputText(alt_input_ext_srch);
    disabledAreaFull(alt_input_ext_srch);
  }
  if (gebi('search-ext-submit')) {
    var extra = gebi('idsearch-extra-' + gebi("search-ext-type").value).value;
    var type = gebi('idtypes-value-' + extra).value;
    var alt_input_ext_srch = type == DEAL_TYPE_RENT || type == DEAL_TYPE_SALE;
    setTrigersSearchExtInputText(alt_input_ext_srch);
  }
  var extra = gebi('idsearch-extra-' + gebi("search-type").value).value;
  var type = gebi('idtypes-value-' + extra).value;
  var alt_input_srch = type == DEAL_TYPE_RENT || type == DEAL_TYPE_SALE;
  if (gebi('search-area-ot')) setTrigersSearchInputText(alt_input_srch);

  if (gebi('search-ext-type') && gebi('build_lot')) {
    $(function(){
    	$("#search-ext-street").autocomplete('/search/street_autocomplete.php', {
			  scroll : 1000
			, autoFill : false
			, minChars : 1
			, cacheLength : 1
			, delay : 10
			, matchSubset : false
			, extraParams : {region_id : function(){return $('#search-ext-region').val();}}
		});
    });
    disabledAreaFull(alt_input_ext_srch);
  }
  if (gebi('captcha')) {
    $(function(){
    	load_captcha();
    	$('#refresh_captcha, .refresh_captcha').click(
    		function()
    		{
    			load_captcha();
    			return false;
    		}
    	);
    });
  }
  if (gebi('search-ext-city2')) checkMapCity('search-ext-city2');
  if (gebi('form-search-ext')) changeTopTextSearch();
  
  request['stat'] = createRequest();
  sendRequest(request['stat'], "/statistic/update.php", 'date='+ new Date().getTime(), false, 'GET');
  request['stat'].abort();
  js_load = true;
}

/**
 * Выполянет действия, которые должны происходить при покидании страницы.
 */
function leavePage() {
  
}

/**
 * Растягивает центральную ячейку основной таблицы.
 */
function setHeightCellCenter() {
  var hTop = 166; // высота верхнего блока
  if (gebi("cell_center").offsetHeight < gebi("div_left").offsetHeight - hTop && isIE) {
    //setInterval(function () {gebi("cell_center").style.height = gebi("div_left").offsetHeight - hTop + 'px';}, 1);
    gebi("cell_center").style.height = gebi("div_left").offsetHeight - hTop + 'px';
  }
}

/**
 * Меняет цвет фона строки в таблице с отобранными объявлениями при наведении мышки.
 *
 * @param in_el (object) элемент tr, на котором произошло событие onmouseover или onmouseout.
 * @param in_hover (boolean) true - произошло наведение, false - мышка была убрана.
 */
function onMouseSelobj(in_el, in_hover) {
  if ((in_el.nodeName == null) || (in_el.nodeName != null && in_el.nodeName.toLowerCase() != 'tr')) return;
  var parity = in_el.id.substr(7) - 1;
  switch (in_hover) {
    case true:
      in_el.className = 'search-tr-bgon';
      _setVisibleImg(in_el, 'active');
      break;
    case false:
      if (parity % 2) {
        in_el.className = 'search-tr-bgparity';
        _setVisibleImg(in_el, 'on');
      } else {
        in_el.className = 'search-tr-bgoff';
        _setVisibleImg(in_el, 'off');
      }
      break;      
  }
}

/**
 * Показывает в расширенном поиске селект с городами, метро или шоссе в зависимости от радиокнопки.
 * @param el (object) - радиокнопка.
 */
function onChangeSearchExtSelect(el) {
  if (!el.checked) return;
  var showCitySel = el.id == "srch_city_radio" || el.id == "srch_city_radio1";
  var showMetroSel = el.id == "srch_metro_radio";
  var showHighwaySel = el.id == "srch_highway_radio";
  var metrolist = gebi("search-ext-metrolist") ? gebi("search-ext-metrolist") : null;
  var citylist = gebi("search-ext-citylist") ? gebi("search-ext-citylist") : null;
  var highwaylist = gebi("search-ext-highwaylist") ? gebi("search-ext-highwaylist") : null;
  if (citylist) {
    //citylist.className = showCitySel ? "block" : "none";
    if (showCitySel) {
      $('#search-ext-citylist').fadeIn('slow');
    } else {
      $('#search-ext-citylist').fadeOut(0);
    }
  }
  if (metrolist) {
    //metrolist.className = showMetroSel ? "block" : "none";
    if (showMetroSel) {
      $('#search-ext-metrolist').fadeIn('slow');
    } else {
      $('#search-ext-metrolist').fadeOut(0);
    }
  }
  if (highwaylist) {
    //highwaylist.className = showHighwaySel ? "block" : "none";
    if (showHighwaySel) {
      $('#search-ext-highwaylist').fadeIn('slow');
    } else {
      $('#search-ext-highwaylist').fadeOut(0);
    }
  }
  if (showCitySel) {
    if (highwaylist) {
      resetSelectHighway(selects_highway);
    }
    if (metrolist) {
      resetSelectMetro(srch_selects_metro);
    }
  } else if (showHighwaySel) {
    if (citylist) {
      resetSelectCity();
    }
    if (metrolist) {
      resetSelectMetro(srch_selects_metro);
    }
  } else if (showMetroSel) {
    if (citylist) {
      resetSelectCity();
    }
    if (highwaylist) {
      resetSelectHighway(selects_highway);
    }
  }
}

/**
 * Показывает или скрывают фотку при наведении на иконку фотографии в таблице с новыми объявлениями.
 * @param icon object - иконка фотки.
 * @param div object - слой, в котором содержится фотка.
 * @param act boolean - true показывает, false скрывает.
 */
var div = ifr = null;
function mouseNewAdPhoto(icon, div, act) {
  if (!js_load) return;
  if (act) {
    var pos = offsetPosition(icon);
    var ieTop = 0;//(isIE6) ? 166 : 0;
    var hImg = gebi(div.id + "_img").offsetHeight;
    var wIcon = 14;
    var pad = 10;
    var wBord = 2;
    div.style.left = pos[0] + wIcon + 'px';
    div.style.top = pos[1] - ieTop - hImg - pad * 2 + 'px';
    gebi(div.id + "_div").style.height = hImg + pad * 2 + 'px';
    gebi(div.id + "_ifr").style.height = hImg + pad * 2 + 'px';
    div.style.visibility = 'visible';
  } else {
    div.style.visibility = 'hidden';
  }
}

/**
 * Показывает или скрывают фотку при наведении на иконку фотографии в таблице с результатми поиска.
 * 
 * @param el object - фотка.
 * @param act boolean - true показывает, false скрывает.
 */
var td = div = null;
function mouseListPhoto(el, act) {
  if (!js_load) return;
  if (act) {
    el.style.visibility = "visible";
    td = el.parentNode;
    var icon = td.firstChild;
    icon = (icon.nodeName.toLowerCase() != 'img') ? icon.nextSibling : icon;
    var pos = offsetPosition(icon);
    var ieTop = 0;//(isIE6) ? 166 : 0;
    var hImg = el.offsetHeight;
    var wIcon = 12;
    var pad = 10;
    var wBord = 2;
    var dy = (gebi('search-table-result') && (isIE6 || isIE7)) ? 8 : 0;
    el.style.left = pos[0] + wIcon + pad + wBord + 'px';
    el.style.top = pos[1] - ieTop - hImg - pad - dy + 'px';
    div = ce('div');
    div.className = "srch_photo_div";
    div.style.left = pos[0] + wIcon + 'px';
    div.style.top = pos[1] - ieTop - hImg - pad * 2 - wBord - dy + 'px';
    gebtn('body')[0].appendChild(div);
    gebtn('body')[0].appendChild(el);
    var hImg = el.offsetHeight;
    div.style.height = hImg + 20 + 'px';
    div.style.width = el.offsetWidth + pad * 2 + 'px';
  } else {
    el.style.visibility = "hidden";
    td.appendChild(el);
    rn(div);
  }
}

/**
 * Выход с сайта.
 * @param in_sid (string): sid пользователя на форуме.
 */
function exitLogin() {
  location.href = '/?SID=cl';
}

/**
 * Подчёркивает текст при наведении на него мышкой.
 *
 * in_el (object): элемент из которого вызывается функция.
 * in_act (string): on - подчёркивание текста, off - убирает подчёркивание.
 */
function link(in_el, in_act) {
  var clname = (in_act == 'on') ? 'text-decor-underline' : 'text-decor-none';
  in_el.className = clname;
}

/**
 * Показывает или скрывает блок личного кабинета.
 */
function display_priv_office(el) {
  var id_auth_block = 'auth_block';
  var is_open = gebi(id_auth_block).style.display != "none" ? true : false;
  if (isIE) {
    gebi(id_auth_block).style.display = is_open ? "none" : "block";
    gebi('auth_head').style.backgroundImage = is_open ? 'url(' + gebi('src_blue_230_close').value + ')' : 'url(' + gebi('src_blue_230_open').value + ')';
  } else {
    if (!is_open) {
      gebi('auth_head').style.backgroundImage = 'url(' + gebi('src_blue_230_open').value + ')';
    }
    $('#'+id_auth_block).slideToggle('fast', function () {gebi('auth_head').style.backgroundImage = is_open ? 'url(' + gebi('src_blue_230_close').value + ')' : 'url(' + gebi('src_blue_230_open').value + ')';});
  }
  el.title = is_open ? 'Раскрыть' : 'Свернуть';
}

/**
 * Показывает или скрывает блоки в каталоге объявлений.
 */
function display_catalogue(el, id_img, id_block) {
  var is_open = gebi(id_block).style.display != "none" ? true : false;
  if (isIE) {
    gebi(id_block).style.display = is_open ? "none" : "block";
  } else {
    $('#'+id_block).slideToggle('fast');
  }
  gebi(id_img).src =  is_open ?  gebi('src_arrow_down2').value : gebi('src_arrow_up2').value;
  gebi(id_img).title =  is_open ? 'Раскрыть' : 'Свернуть';
  el.title =  is_open ? 'Раскрыть' : 'Свернуть';
}

function display_catalogue_com(el, id_img, id_block_com) {
  var is_open = gebi(id_block_com).style.display != "none" ? true : false;
  if (isIE) {
    gebi(id_block_com).style.display = is_open ? "none" : "block";
  } else {
    $('#'+id_block_com).slideToggle('fast');
  }
  gebi(id_img).src =  is_open ?  gebi('src_but_down_com').value : gebi('src_but_up_com').value;
  el.title =  is_open ? 'Раскрыть' : 'Свернуть';
}

/**
 * Отмечает или снимает галочки во всех чекбоксах просмотра отобранных объектов.
 *
 * @param in_el (object): чекбокс.
 */
function checkAllSelAdv(in_el) {
  var chboxes = document.forms['adv-form'].elements;
  var len = chboxes.length;
  var chbox_all = chboxes[0];
  chbox_all.title = (chbox_all.checked) ? 'Снять все' : 'Отметить все';
  var count = 0;
  for (var i = 1; i < len; i++) {
    chboxes[i].checked = (in_el == chbox_all) ? chbox_all.checked : chboxes[i].checked;
    count = (in_el != chbox_all && chboxes[i].checked) ? count + 1 : count;
  }
  if (in_el != chbox_all) {
    chbox_all.checked = (count == len - 1) ? true : false;
    chbox_all.checked = (count == 0) ? false : chbox_all.checked;
  }
  gebi('sel_but_del').disabled = (count > 0 || chbox_all.checked) ? false : true;
}

/**
 * Отправляет на сервер запрос об удалении отмеченных отобранных объектов.
 */
function getViewSelAdv() {
  var chboxes = document.forms['adv-form'].elements;
  var len = chboxes.length;
  var del_tr = new Array;
  var values = '';
  for (var i = 1; i < len; i++) {
    del_tr[i] = (chboxes[i].checked) ? true : false;
    values += (chboxes[i].checked) ? chboxes[i].id.substr(10) + ' ' : '';
  }
  if (values == '') return;
  //alert(values);
  values = 'del_num=' + escape(values);
  request['search-adv'] = createRequest();
  request['search-adv'].onreadystatechange = function() {updateViewSelAdv(request['search-adv'], del_tr, len);};
  var url = '/advertisment/save.php';
  sendRequest(request['search-adv'], url, values);
}

/**
 * Удаляет отобранный объект и обновляет таблицу просмотра отобранных объектов.
 */
function updateViewSelAdv(in_req, in_del_tr, in_len) {
  if (in_req.readyState == 4) {
    if (in_req.status == 200) {
      //alert(in_req.responseText);
      var res = in_req.responseText;
      in_req = null;
      if (res != 1) return;
      for (var i = 1; i < in_len; i++) {
        if (in_del_tr[i]) rn(gebi('adv-tr-' + i));
      }
      if (document.forms['adv-form'].elements.length <= 1) {
        gebi('sel_form').innerHTML = '<div class="text_div">Все отобранные объявления удалены.</div>';
        if (gebi('menu-adv-count')) gebi('menu-adv-count').innerHTML = 0;
        gebi('adv-sel-count').innerHTML = 0;
        gebi('sel_ad').innerHTML = "Отобранных объявлений нет";
        setHeightCellCenter();
        return;
      }
      for (var i = 0; i < gebi('adv-table').childNodes.length; i++) {
        if (gebi('adv-table').childNodes[i].nodeName.toLowerCase() == 'tbody') {
          var count = 0;
          for (var j = 0; j < gebi('adv-table').childNodes[i].childNodes.length; j++) {
            var tr = gebi('adv-table').childNodes[i].childNodes[j];
            // Перебираем все tr.
            if (tr.nodeName.toLowerCase() == 'tr' && tr.id != '') {
              count++;
              tr.id = 'adv-tr-' + count;
              tr.className = (count % 2) ? 'search-tr-bgoff' : 'search-tr-bgparity';
            }
          } 
        }
      }
      if (gebi('menu-adv-count')) gebi('menu-adv-count').innerHTML = count;
      gebi('adv-sel-count').innerHTML = count;
      if (count > 0) {
        gebi('sel_ad').innerHTML = (count > 0) ? '<a href="/advertisment/">' + gebi("msg_adv_selected").value + ': <span id="sel_ad_count">' + count + '</span></a>' : gebi("msg_adv_selected").value;
      }
      gebi('sel_but_del').disabled = true;
    }
  }
}

/**
 * Добавляет или удаляет объявление в отобранные объекты в результатах поиска.
 *
 * @param in_el (object): картинка.
 * @param in_id (int): айди объявления.
 * @param in_build_type (int): тип недвижимости.
 * @param in_act (string): 'add' - добавить, 'del' - удалить.
 */
function saveAdv(in_el, in_id, in_build_type, in_act) {
  var trEl = in_el.parentNode;
  trEl.innerHTML = '<img src="'+gebi('src_ajax_circle').value+'" />';
  values = 'action=' + in_act + '&id=' + in_id + '&build_type=' + in_build_type;
  request['search-adv'] = createRequest();
  request['search-adv'].onreadystatechange = function() {updateSearchSelAdv(request['search-adv'], trEl, in_id, in_build_type);};
  var url = "/advertisment/save.php";
  sendRequest(request['search-adv'], url, values);
}

/**
 * Обновляет картинку выбранного объекта и количество отобранных объектов.
 *
 * @param in_req (object): объект запроса.
 * @param in_tr (int): порядковый номер строки результата в таблице.
 * @param in_id (int): айди объявления.
 * @param in_build_type (int): тип недвижимости.
 */
function updateSearchSelAdv(in_req, in_tr, in_id, in_build_type) {
  if (in_req.readyState == 4) {
    if (in_req.status == 200) {
      /*var res = in_req.responseText;
      alert(res);
      return;*/
      var res = in_req.responseXML;
      in_req = null;
      var count = res.getElementsByTagName('count')[0].firstChild.nodeValue;
      var result = res.getElementsByTagName('result')[0].firstChild.nodeValue;
      var img = (result == 1) ? '<img class="iepngfix" src="'+gebi('src_ad_after').value+'" title="Удалить из отобранных объявлений" onclick="saveAdv(this, ' + in_id + ', ' + in_build_type + ', \'del\')" onmouseover="onMouseOverSelAdv(this, \''+gebi('src_ad_after_on').value+'\')" onmouseout="onMouseOutSelAdv(this, \''+gebi('src_ad_after').value+'\')" />' : '<img class="iepngfix" src="'+gebi('src_ad_before').value+'" title="Добавить в отобранные объявления" onclick="saveAdv(this, ' + in_id + ', ' + in_build_type + ', \'add\')" onmouseover="onMouseOverSelAdv(this, \''+gebi('src_ad_before_on').value+'\')" onmouseout="onMouseOutSelAdv(this, \''+gebi('src_ad_before').value+'\')" />';
      in_tr.innerHTML = img;
      if (gebi('menu-adv-count')) gebi('menu-adv-count').innerHTML = count;
      gebi('sel_ad').innerHTML = (count > 0) ? '<a href="/advertisment/">' + gebi("msg_adv_selected").value + ': <span id="sel_ad_count">' + count + '</span></a>' : gebi("msg_adv_selected_no").value;
    }
  }
}

function onMouseOverSelAdv(elem_img, src_img) {
  elem_img.src = src_img;
  //alert(src_img);
}

function onMouseOutSelAdv(elem_img, src_img) {
  elem_img.src = src_img;
}

/**
 * Переход в расширенный поиск с результатов поиска с возможным сохранением айди шаблона.
 */
function goSearchExt() {
  var stem = (gebi('search-template-save') && gebi('search-template-save').value != '') ? '?stem=' + gebi('search-template-save').value : '';
  location.href = '/search/' + stem;
}

/**
 * Сохраняет шаблон поиска в результатах.
 */
function saveTemplateSearch() {
  //gebi('search-save-img').src = gebi('src_ajax_circle').value;
  var values = '';
  for (var i = 0; i < gebi('search-template').childNodes.length; i++) {
    var input = gebi('search-template').childNodes[i];
    if (input.nodeName.toLowerCase() == 'input') {
      var name = input.id.substr(16);
      values += name + '=' + escape(input.value) + '&';
    }
  }
  values = values.replace(/&$/, '');
  request['search-save'] = createRequest();
  request['search-save'].onreadystatechange = function() {updateSearchTemplate(request['search-save']);};
  var url = "/search/savetemplate.php";
  //alert(values);
  sendRequest(request['search-save'], url, values);
}

/**
 * Выводит сообщение о результате сохранения шаблона поиска.
 *
 * @param in_req (object ajax) объект запроса.
 */
function updateSearchTemplate(in_req) {
  var mes = 'Ошибка сохранения шаблона';
  gebi('srch_save_tpl_bg').className = "srch_spec_blue";
  //gebi('srch_save_left_img').src = gebi('src_left_blue').value;
  //gebi('srch_save_right_img').src = gebi('src_right_blue').value;
  if (in_req.readyState == 4) {
    if (in_req.status == 200) {
      var id = in_req.responseText;
      //alert(id);
      in_req = null;
      if (/^[0-9]+|-1$/.test(id) && id != 'false') {
        if (id == -1) {
          mes = 'Вы сохранили <a class="link_white" href="/user/?act=search_template">' + SEARCH_TEMPLATE_MAX + ' шаблонов</a>';
          gebi('srch_save_tpl').innerHTML = mes;
          gebi('search-template-save').value = '';
          return;
        }
        var count = Number(gebi('menu-search-template').innerHTML);
        gebi('menu-search-template').innerHTML = (gebi('search-template-save').value == id) ? count : ++count;
        //mes = (gebi('search-template-save').value == id) ? 'Сохранён редактированный шаблон' : 'Сохранён новый шаблон';
        mes = 'Шаблон поиска сохранён';
        gebi('srch_save_tpl').innerHTML = mes;
        if (gebi('search-template-save')) {
          gebi('search-template-save').value = id;
          document.cookie = "stem=" + id + "; path=/;";
        }
      } else {
        gebi('srch_save_tpl').innerHTML = mes;
        gebi('search-template-save').value = '';
      }
    } else {
      gebi('srch_save_tpl').innerHTML = mes;
    }
  }
}

/**
 * Сохраняет шаблон поиска в расшиернном поиске.
 */
function saveTemplateSearchExt() {
  //gebi('search-save-img').src = gebi('src_ajax_circle').value;
  changeTopTextSearch();
  var values = "ext=1";
  values += "&iwant=" + escape(globalTopText);
  values += (gebi('search-template-save') && gebi('search-template-save').value != '') ?
             "&id=" + escape(gebi('search-template-save').value) : '';
  values += "&userid=" + escape(gebi('search-template-usid').value);
  values += "&deal=" + escape(gebi('search-ext-type').value);
  values += (!gebi('search-ext-realty')) ? "&build=" + escape(gebi('search-ext-build').value) : '';
  values += gebi('search-ext-realty') ? (/[0-9]+/.test(gebi('search-ext-realty').value) ?
              "&build=" + escape(gebi('search-ext-realty').value) : "&build=-1&build_type=2") : '';
  values += (gebi('search-ext-type-result1').style.visibility == 'visible' && gebi('search-ext-srok-ot').value != '') ?
             "&srok_ot=" + escape(gebi('search-ext-srok-ot').value) : '';
  values += (gebi('search-ext-type-result1').style.visibility == 'visible' && gebi('search-ext-srok-do').value != '') ?
             "&srok_do=" + escape(gebi('search-ext-srok-do').value) : '';
  values += (gebi('search-ext-type-result1').style.visibility == 'visible') ? "&srok_type=" + escape(gebi('search-ext-srok_type').value) : '';
  values += "&region=" + escape(gebi('search-ext-region').value);
  values += (gebi('search-ext-price-ot').value != '') ? "&price_ot=" + escape(gebi('search-ext-price-ot').value) : '';
  values += (gebi('search-ext-price-do').value != '') ? "&price_do=" + escape(gebi('search-ext-price-do').value) : '';
  values += "&currency=" + escape(gebi('search-ext-currency').value);
  values += (gebi('search-ext-street').value != '') ? "&street=" + escape(gebi('search-ext-street').value) : '';
  if (gebi('search-ext-metrolist').style.display != 'none') {
    var arr = gebi('search-ext-metro').options;
    var metro = '';
    for (var i = 0; i < arr.length; i++) {
      metro += arr[i].value + ' ';
    }
    values += (metro != '') ? "&metro=" + escape(metro) : '';
    values += (gebi('search-ext-time').value != '') ? "&time=" + escape(gebi('search-ext-time').value) : '';
    values += "&time_type=" + escape(gebi('search-ext-timetype').value);
  }
  if (gebi('search-ext-highwaylist').style.display != 'none') {
    var arr = gebi('search-ext-highway2').options;
    var highway = '';
    for (var i = 0; i < arr.length; i++) {
      highway += arr[i].value + ' ';
    }
    values += (highway != '') ? "&highway=" + escape(highway) : '';
    values += (gebi('search-ext-mkad-ot').value != '') ? "&mkad_ot=" + escape(gebi('search-ext-mkad-ot').value) : '';
    values += (gebi('search-ext-mkad-do').value != '') ? "&mkad_do=" + escape(gebi('search-ext-mkad-do').value) : '';
  }
  if (gebi('search-ext-citylist').style.display != 'none') {
    var arr = gebi('search-ext-city2').options;
    var city = '';
    for (var i = 0; i < arr.length; i++) {
      city += arr[i].value + ' ';
    }
    values += (city != '') ? "&city=" + escape(city) : '';
  }
  /*if (gebi('search-ext-arealist') && gebi('search-ext-arealist').style.display != 'none') {
    var arr = gebi('search-ext-area2').options;
    var area = '';
    for (var i = 0; i < arr.length; i++) {
      area += arr[i].value + ' ';
    }
    values += (area != '') ? "&area=" + escape(area) : '';
  }*/
  if (gebi('search-ext-build-liv').className != 'none' || gebi('search-ext-build-liv').className == 'block') {
    var rooms = '';
    var count = 0;
    for (var i = 1; i <= 5; i++) {
      if (gebi('srch-chbox' + i).checked) {
        count++;
        rooms += (i == 5) ? i + '> ' : i + ' ';
      }
    }
    var area1 = gebi('search-ext-area-ot').value;
    var area2 = gebi('search-ext-area-do').value;
    values += (rooms != '' && count != 5) ? "&rooms=" + escape(rooms) : '';
    values += (gebi('search-ext-areakit-ot').value != '') ? "&areakit_ot=" + escape(gebi('search-ext-areakit-ot').value) : '';
    values += (gebi('search-ext-areakit-do').value != '') ? "&areakit_do=" + escape(gebi('search-ext-areakit-do').value) : '';
    values += (gebi('search-ext-floor1').checked) ? "&floor1=1" : '';
    values += (gebi('search-ext-floor2').checked) ? "&floor2=1" : '';
    values += (_getOptionText('search-ext-wc') != 'неважно') ? "&wc=" + escape(gebi('search-ext-wc').value) : '';
    values += (_getOptionText('search-ext-balcony') != 'неважно') ? "&balcony=" + escape(gebi('search-ext-balcony').value) : '';
    values += (_getOptionText('search-ext-loggia') != 'неважно') ? "&loggia=" + escape(gebi('search-ext-loggia').value) : '';
    values += (_getOptionText('search-ext-garbage') != 'неважно') ? "&garbage=" + escape(gebi('search-ext-garbage').value) : '';
    values += (_getOptionText('search-ext-house_type') != 'неважно') ? "&house_type=" + escape(gebi('search-ext-house_type').value) : '';
    values += (_getOptionText('search-ext-furniture') != 'неважно') ? "&furniture=" + escape(gebi('search-ext-furniture').value) : '';
    values += (_getOptionText('search-ext-phone-liv') != 'неважно') ? "&phone=" + escape(gebi('search-ext-phone-liv').value) : '';
    values += (_getOptionText('search-ext-tv') != 'неважно') ? "&tv=" + escape(gebi('search-ext-tv').value) : '';
    values += (_getOptionText('search-ext-fridge') != 'неважно') ? "&fridge=" + escape(gebi('search-ext-fridge').value) : '';
    values += (_getOptionText('search-ext-housetech') != 'неважно') ? "&housetech=" + escape(gebi('search-ext-housetech').value) : '';
  }
  if (gebi('search-ext-build-cot').className != 'none' || gebi('search-ext-build-cot').className == 'block') {
    var area1 = gebi('search-ext-areahouse-ot').disabled == false ? gebi('search-ext-areahouse-ot').value : '';
    var area2 = gebi('search-ext-areahouse-do').disabled == false ? gebi('search-ext-areahouse-do').value : '';
    values += (gebi('search-ext-areasotok-ot').value != '') ? "&areasotok_ot=" + escape(gebi('search-ext-areasotok-ot').value) : '';
    values += (gebi('search-ext-areasotok-do').value != '') ? "&areasotok_do=" + escape(gebi('search-ext-areasotok-do').value) : '';
    values += (gebi('srch-chbox2-1').checked && gebi('search-ext-cotvillage').style.display != 'none') ? "&cotvillage=1" : '';
    values += (gebi('srch-chbox2-2').checked) ? "&woodlot=1" : '';
    values += (gebi('srch-chbox2-3').checked) ? "&bywater=1" : '';
    values += (gebi('srch-chbox2-4').checked && gebi('search-ext-vipcot').style.display != 'none') ? "&vipcot=1" : '';
    values += (_getOptionText('search-ext-phone-cot') != 'неважно') ? "&phone=" + escape(gebi('search-ext-phone-cot').value) : '';
    values += (_getOptionText('search-ext-electricity') != 'неважно') ? "&electricity=" + escape(gebi('search-ext-electricity').value) : '';
    values += (_getOptionText('search-ext-heating') != 'неважно') ? "&heating=" + escape(gebi('search-ext-heating').value) : '';
    values += (_getOptionText('search-ext-water') != 'неважно') ? "&water=" + escape(gebi('search-ext-water').value) : '';
    values += (_getOptionText('search-ext-sewerage') != 'неважно') ? "&sewerage=" + escape(gebi('search-ext-sewerage').value) : '';
    values += (_getOptionText('search-ext-gas') != 'неважно') ? "&gas=" + escape(gebi('search-ext-gas').value) : '';
    values += (_getOptionText('search-ext-guard') != 'неважно') ? "&guard=" + escape(gebi('search-ext-guard').value) : '';
    values += (_getOptionText('search-ext-parking') != 'неважно') ? "&parking=" + escape(gebi('search-ext-parking').value) : '';
  }
  if (gebi('search-ext-build-com').className != 'none' || gebi('search-ext-build-com').className == 'block') {
    var area1 = gebi('search-ext-area_com-ot').value;
    var area2 = gebi('search-ext-area_com-do').value;
  }
  if (Number(area1) > Number(area2) &&  area1 != '' && area2 != '') {
    buf = area2;
    area2 = area1;
    area1 = buf;
  }
  values += area1 != '' ? '&area_ot='+escape(area1) : '';
  values += area2 != '' ? '&area_do='+escape(area2) : '';
  values += (gebi('search-ext-photo').checked) ? "&photo=1" : '';
  //alert(values);
  request['search-save-ext'] = createRequest();
  request['search-save-ext'].onreadystatechange = function() {updateSearchTemplate(request['search-save-ext']);};
  var url = "/search/savetemplate.php";
  sendRequest(request['search-save-ext'], url, values);
}

function updateIWant(in_req, in_submit) {
  if (in_req.readyState == 4) {
    if (in_req.status == 200) {
      var text = in_req.responseText;
      in_req = null;
      if (globalTopText != text) {
        globalTopText = text;
        gebi('search-exttoptext').value = globalTopText;
        gebi('search-ext-toptxt').innerHTML = "<div>" + text + "</div>";
      }
      if (in_submit == 'submit') {
        gebi('form-search-ext').submit();
      }
    } else alert(gebi('err_browser').value);
  }
}

/**
 * Формирует надпись в верхнем блоке раширенного поиска - "Я хочу...".
 */
function changeTopTextSearch(in_submit) {
  var price1 = gebi('search-ext-price-ot');
  var price2 = gebi('search-ext-price-do');
  var areakit1 = gebi('search-ext-areakit-ot');
  var areakit2 = gebi('search-ext-areakit-do');
  var areasotok1 = gebi('search-ext-areasotok-ot');
  var areasotok2 = gebi('search-ext-areasotok-do');
  var srok1 = gebi('search-ext-srok-ot');
  var srok2 = gebi('search-ext-srok-do');
  var mkad1 = gebi('search-ext-mkad-ot');
  var mkad2 = gebi('search-ext-mkad-do');
  if (Number(price1.value) > Number(price2.value) && price2.value != '' && price1.value != '') {
    buf = price2.value;
    price2.value = price1.value;
    price1.value = buf;
  }
  if (Number(areakit1.value) > Number(areakit2.value) && areakit2.value != '' && areakit1.value != '') {
    buf = areakit2.value;
    areakit2.value = areakit1.value;
    areakit1.value = buf;
  }
  if (Number(areasotok1.value) > Number(areasotok2.value) && areasotok2.value != '' && areasotok1.value != '') {
    buf = areasotok2.value;
    areasotok2.value = areasotok1.value;
    areasotok1.value = buf;
  }
  if (Number(srok1.value) > Number(srok2.value) && srok2.value != '' && srok1.value != '') {
    buf = srok2.value;
    srok2.value = srok1.value;
    srok1.value = buf;
  }
  if (Number(mkad1.value) > Number(mkad2.value) && mkad2.value != '' && mkad1.value != '') {
    buf = mkad2.value;
    mkad2.value = mkad1.value;
    mkad1.value = buf;
  }
  var val = "<?xml version='1.0' encoding='windows-1251'?>";
  val += '<data>';
  val += '<type>'+gebi('search-ext-type').value+'</type>';
  val += '<build>'+gebi('search-ext-build').value+'</build>';
  val += (gebi('search-ext-realty')) ? '<realty>'+((/^[0-9]+$/.test(gebi('search-ext-realty').value)) ? gebi('search-ext-realty').value : '')+'</realty>' : '';
  val += '<currency>'+gebi('search-ext-currency').value+'</currency>';
  val += '<price_ot>'+gebi('search-ext-price-ot').value+'</price_ot>';
  val += '<price_do>'+gebi('search-ext-price-do').value+'</price_do>';
  val += '<srok_ot>'+gebi('search-ext-srok-ot').value+'</srok_ot>';
  val += '<srok_do>'+gebi('search-ext-srok-do').value+'</srok_do>';
  val += '<srok_type>'+gebi('search-ext-srok_type').value+'</srok_type>';
  val += '<region>'+gebi('search-ext-region').value+'</region>';
  val += '<mkad_ot>'+gebi('search-ext-mkad-ot').value+'</mkad_ot>';
  val += '<mkad_do>'+gebi('search-ext-mkad-do').value+'</mkad_do>';
  var arr = gebi('search-ext-highway2').options;
  val += '<highway>';
  for (var i = arr.length - 1; i >= 0; i--) {
    val += '<num id="'+i+'">'+arr[i].id.substr(21)+'</num>';
  }
  val += '</highway>';
  arr = gebi('search-ext-city2').options;
  val += '<city>';
  for (var i = arr.length - 1; i >= 0; i--) {
    val += '<num id="'+i+'">'+arr[i].id.substr(22)+'</num>';
  }
  val += '</city>';
  val += '<time>'+gebi('search-ext-time').value+'</time>';
  val += '<timetype>'+gebi('search-ext-timetype').value+'</timetype>';
  arr = gebi('search-ext-metro').options;
  val += '<metro>';
  for (var i = arr.length - 1; i >= 0; i--) {
    val += '<num id="'+i+'">'+arr[i].id.substr(19)+'</num>';
  }
  val += '</metro>';
  val += '<street>'+escape(gebi('search-ext-street').value)+'</street>';
  if (gebi('search-ext-build-com').className != 'none' || gebi('search-ext-build-com').className == 'block') {
    var area1 = gebi('search-ext-area_com-ot').value;
    var area2 = gebi('search-ext-area_com-do').value;
  }
  if (gebi('search-ext-build-liv').className != 'none' || gebi('search-ext-build-liv').className == 'block') {
    var area1 = gebi('search-ext-area-ot').value;
    var area2 = gebi('search-ext-area-do').value;
    val += '<areakit_ot>'+gebi('search-ext-areakit-ot').value+'</areakit_ot>';
    val += '<areakit_do>'+gebi('search-ext-areakit-do').value+'</areakit_do>';
    val += '<rooms_sel>'+gebi('search-ext-rooms_sel').value+'</rooms_sel>';
    val += '<chbox1>'+Number(gebi('srch-chbox1').checked)+'</chbox1>';
    val += '<chbox2>'+Number(gebi('srch-chbox2').checked)+'</chbox2>';
    val += '<chbox3>'+Number(gebi('srch-chbox3').checked)+'</chbox3>';
    val += '<chbox4>'+Number(gebi('srch-chbox4').checked)+'</chbox4>';
    val += '<chbox5>'+Number(gebi('srch-chbox5').checked)+'</chbox5>';
    val += '<floor1>'+gebi('search-ext-floor1').checked+'</floor1>';
    val += '<floor2>'+gebi('search-ext-floor2').checked+'</floor2>';
    val += '<wc>'+gebi('search-ext-wc').value+'</wc>';
    val += '<balcony>'+gebi('search-ext-balcony').value+'</balcony>';
    val += '<loggia>'+gebi('search-ext-loggia').value+'</loggia>';
    val += '<garbage>'+gebi('search-ext-garbage').value+'</garbage>';
    val += '<house_type>'+gebi('search-ext-house_type').value+'</house_type>';
    val += '<furniture>'+gebi('search-ext-furniture').value+'</furniture>';
    val += '<phone>'+gebi('search-ext-phone-liv').value+'</phone>';
    val += '<enternet>'+gebi('search-ext-enternet').value+'</enternet>';
    //val += '<tv>'+gebi('search-ext-tv').value+'</tv>';
    //val += '<fridge>'+gebi('search-ext-fridge').value+'</fridge>';
    val += '<housetech>'+gebi('search-ext-housetech').value+'</housetech>';
  }
  if (gebi('search-ext-build-cot').className != 'none' || gebi('search-ext-build-cot').className == 'block') {
    var area1 = (gebi('search-ext-areahouse-ot').disabled == false) ? gebi('search-ext-areahouse-ot').value : '';
    var area2 = (gebi('search-ext-areahouse-do').disabled == false) ? gebi('search-ext-areahouse-do').value : '';
    val += '<areasotok_ot>'+gebi('search-ext-areasotok-ot').value+'</areasotok_ot>';
    val += '<areasotok_do>'+gebi('search-ext-areasotok-do').value+'</areasotok_do>';
    val += '<cotvillage>'+Number(gebi('srch-chbox2-1').checked)+'</cotvillage>';
    val += '<woodlot>'+Number(gebi('srch-chbox2-2').checked)+'</woodlot>';
    val += '<bywater>'+Number(gebi('srch-chbox2-3').checked)+'</bywater>';
    val += '<vipcot>'+Number(gebi('srch-chbox2-4').checked)+'</vipcot>';
    val += '<heating>'+gebi('search-ext-heating').value+'</heating>';
    val += '<water>'+gebi('search-ext-water').value+'</water>';
    val += '<electricity>'+gebi('search-ext-electricity').value+'</electricity>';
    val += '<gas>'+gebi('search-ext-gas').value+'</gas>';
    val += '<phone>'+gebi('search-ext-phone-cot').value+'</phone>';
    val += '<sewerage>'+gebi('search-ext-sewerage').value+'</sewerage>';
    val += '<guard>'+gebi('search-ext-guard').value+'</guard>';
    val += '<parking>'+gebi('search-ext-parking').value+'</parking>';
    val += '<house_type>'+gebi('search-ext-house_type').value+'</house_type>';
    val += '<furniture>'+gebi('search-ext-furniture').value+'</furniture>';
    val += '<tv>'+gebi('search-ext-tv').value+'</tv>';
    val += '<fridge>'+gebi('search-ext-fridge').value+'</fridge>';
    val += '<housetech>'+gebi('search-ext-housetech').value+'</housetech>';
  }
  if (Number(area1) > Number(area2) &&  area1 != '' && area2 != '') {
    buf = area2;
    area2 = area1;
    area1 = buf;
  }
  val += '<area_ot>'+area1+'</area_ot>';
  val += '<area_do>'+area2+'</area_do>';
  val += '<photo>'+gebi('search-ext-photo').checked+'</photo>';
  val += '</data>';
  //alert(val);
  val = 'data='+val;
  var req = createRequest();
  req.onreadystatechange = function() {updateIWant(req, in_submit);};
  var url = "/search/request_iwant.php";
  sendRequest(req, url, val);
}

/**
 * Возвращает текст активной опции селекта.
 *
 * in_sel (object): селект.
 */
function _getOptionText(in_sel) {
  if (gebi(in_sel).selectedIndex == -1) return ''; 
  return gebi(in_sel).options[gebi(in_sel).selectedIndex].text;
}

/**
 * Возвращает массив строк из опций селекта.
 *
 * in_sel (object) селект.
 */
function _getOptionsText(in_sel) {
  if (!gebi(in_sel)) return;
  var arr = new Array;
  for (var i = 0; i < gebi(in_sel).options.length; i++) {
    if (gebi(in_sel).options[i].firstChild) arr[i] = gebi(in_sel).options[i].firstChild.nodeValue;
  }
  return arr;
}

/**
 * Показывает или скрывает срок аренды.
 * in_id (int): айди типа из таблицы types.
 */
function changeSearchExtType(in_id) {
  var extra = gebi('idsearch-extra-' + in_id).value;
  var type = gebi('idtypes-value-' + extra).value;
  gebi('search-ext-srok-ot').value = (type == DEAL_TYPE_RENT || type == DEAL_TYPE_LEASE) ? gebi('search-ext-srok-ot').value : '';
  gebi('search-ext-srok-do').value = (type == DEAL_TYPE_RENT || type == DEAL_TYPE_LEASE) ? gebi('search-ext-srok-do').value : '';
  if (type == DEAL_TYPE_RENT || type == DEAL_TYPE_LEASE) {
    $('#search-ext-type-result1').fadeIn('fast');
  } else {
    $('#search-ext-type-result1').fadeOut('fast');
  }
  gebi("search-ext-price-ot").value = "";
  gebi("search-ext-price-do").value = "";
  gebi("search-ext-srok-ot").value = "";
  gebi("search-ext-srok-do").value = "";
  gebi("search-ext-mkad-ot").value = "";
  gebi("search-ext-mkad-do").value = "";
  gebi("search-ext-areahouse-ot").value = "";
  gebi("search-ext-areahouse-do").value = "";
  gebi("search-ext-areasotok-ot").value = "";
  gebi("search-ext-areasotok-do").value = "";
  gebi("search-ext-area-ot").value = "";
  gebi("search-ext-area-do").value = "";
  gebi("search-ext-areakit-ot").value = "";
  gebi("search-ext-areakit-do").value = "";
  gebi("search-ext-area_com-ot").value = "";
  gebi("search-ext-area_com-do").value = "";
  gebi("search-ext-area_com-do").value = "";
  gebi("search-ext-rooms_sel").value = "";
  gebi("srch-chbox1").checked = false;
  gebi("srch-chbox2").checked = false;
  gebi("srch-chbox3").checked = false;
  gebi("srch-chbox4").checked = false;
  gebi("srch-chbox5").checked = false;
  gebi("search-ext-floor1").checked = false;
  gebi("search-ext-floor2").checked = false;
  if (type == DEAL_TYPE_SALE || type == DEAL_TYPE_RENT) {
    setTrigersSearchExtInputText(true);
  } else {
    setTrigersSearchExtInputText(false);
  }
  var class_sale = type == DEAL_TYPE_SALE || type == DEAL_TYPE_RENT ? "inline" : "none";
  var class_buy = type == DEAL_TYPE_BUY || type == DEAL_TYPE_LEASE ? "inline" : "none";
  gebi("srch_ext_price_to").className = class_sale;
  gebi("srch_ext_srok_to").className = class_sale;
  gebi("srch_ext_mkad_to").className = class_sale;
  gebi("srch_ext_areahouse_to").className = class_sale;
  gebi("srch_ext_areasotok_to").className = class_sale;
  gebi("srch_ext_area_to").className = class_sale;
  gebi("srch_ext_areakit_to").className = class_sale;
  gebi("srch_ext_area_com_to").className = class_sale;
  gebi("srch_ext_rooms").className = class_sale;
  gebi("srch_ext_floor").className = class_sale;
  gebi("search-ext-rooms_sel").className = class_buy;
  changeTopTextSearch();
}

function changeSearchType(in_id) {
  var extra = gebi('idsearch-extra-' + in_id).value;
  var type = gebi('idtypes-value-' + extra).value;
  vis = (type == DEAL_TYPE_RENT || type == DEAL_TYPE_LEASE) ? 'inline' : 'none';
  gebi("search-price-ot").value = "";
  gebi("search-price-do").value = "";
  gebi("search-area-ot").value = "";
  gebi("search-area-do").value = "";
  if (type == DEAL_TYPE_SALE || type == DEAL_TYPE_RENT) {
    setTrigersSearchInputText(true);
  } else {
    setTrigersSearchInputText(false);
  }
  var class_sale = type == DEAL_TYPE_SALE || type == DEAL_TYPE_RENT ? "inline" : "none";
  gebi("srch_price_to").className = class_sale;
  gebi("srch_area_to").className = class_sale;
}

/**
 * Показываем верхний блок для расширенного поиска и устанавливаем тригеры для переключения между верхними блоками
 * популярного и расширенного поисков.
 *
 * in_tab (string) тип блока, который надо отобразить.
 */
function changeTabSearch(in_tab) {
  // Меняем верхний блок с популярного поиска на расширенный.
  if (in_tab == 'extended') {
    gebi('srch_tab_1').className = 'srch_tab_noactive';
    gebi('srch_tab_2').className = 'srch_tab_active';
    gebi('srch_tab_1').innerHTML = '<div><a href="javascript: changeTabSearch(\'simple\')">' + gebi('search_popular').value + '</a></div>';
    gebi('srch_tab_2').innerHTML = '<div>' + gebi('search_advanced').value + '</div>';
    gebi('search-back').style.display = 'none';
    gebi('search-request').style.display = 'none';
    gebi('search-ext-top').style.display = 'block';
  } else {
    gebi('srch_tab_1').className = 'srch_tab_active';
    gebi('srch_tab_2').className = 'srch_tab_noactive';
    gebi('srch_tab_1').innerHTML = '<div>' + gebi('search_popular').value + '</div>';
    gebi('srch_tab_2').innerHTML = '<div><a href="javascript: changeTabSearch(\'extended\')">' + gebi('search_advanced').value + '</div></a>';
    gebi('search-ext-top').style.display = 'none';
    gebi('search-back').style.display = 'block';
    gebi('search-request').style.display = 'block';
  }
}

function changeTabSearch2(in_tab) {
  
  if (in_tab == 'extended') {
    
    // Меняем верхний блок с популярного поиска на расширенный.
    gebi('search-tab2').style.background = "url('/_img/srch_tab_2.gif') no-repeat";
    gebi('search-simple-tab2').innerHTML = '<a href="javascript: changeTabSearch2(\'simple\')">Популярный поиск</a>';
    gebi('search-extended-tab2').innerHTML = 'Расширенный поиск';
    gebi('search-back').style.visibility = 'hidden';
    gebi('search-request').style.visibility = 'hidden';
    gebi('search-ext-top2').style.visibility = 'visible';
    
  } else {
    
    // Меняем верхний блок с популярного поиска на расширенный.
    gebi('search-tab2').style.background = "url('/_img/srch_tab_1.gif') no-repeat";
    gebi('search-simple-tab2').innerHTML = 'Популярный поиск';
    gebi('search-extended-tab2').innerHTML = '<a href="javascript: changeTabSearch2(\'extended\')">Расширенный поиск</a>';
    gebi('search-ext-top2').style.visibility = 'hidden';
    gebi('search-back').style.visibility = 'visible';
    gebi('search-request').style.visibility = 'visible';
    
  }
  
}

/**
 * Устанавливает тригеры на заполнение полей логина и пароля блока навигации.
 */
function setTrigersAuthInputText() {
  // Убираем фокус с текстовых полей.
  gebi('pas').blur();
  // Показываем или скрываем надписи в зависимости от того, пустые ли текстовые поля.
  gebi('auth-login-text').style.display = (gebi('log').value == '') ? 'block' : 'none';
  gebi('auth-pass-text').style.display = (gebi('pas').value == '') ? 'block' : 'none';
  // События срабатывающие при щелчке на надписи.
  gebi('auth-login-text').onclick = function() {authInputText('auth-login-text', 'log', 'in');};
  gebi('auth-pass-text').onclick = function() {authInputText('auth-pass-text', 'pas', 'in');};
  // События срабатывающие при вхождении в поле.
  gebi('log').onfocus = function() {authInputText('auth-login-text', 'log', 'in');};
  gebi('pas').onfocus = function() {authInputText('auth-pass-text', 'pas', 'in');};
  // События срабатывающие при покидании поля.
  gebi('log').onblur = function() {authInputText('auth-login-text', 'log', 'out');};
  gebi('pas').onblur = function() {authInputText('auth-pass-text', 'pas', 'out');};
  // Проверка поля с паролем на наличие символов.
  timer['auth-input-text2'] = setInterval(function () {checkPassText('auth-pass-text', 'pas');}, 10);
}

/**
 * Передаёт фокус текстовому полю и скрывает надпись над ним ('логин' или 'пароль'), 
 * или при потере фокуса полем восстанавливает надпись.
 *
 * in_id_text (string) айди поля с надписью.
 * in_id_input (string) айди текстового поля input.
 * in_act (string) out - потеря фокуса текстовым полем input, in - вход в поле (получение полем фокуса).
 */
function authInputText(in_id_text, in_id_input, in_act) {
  if (in_act == 'out') {
    if (in_id_text != null) {
      // Скрываем или показываем надпись над текстовым полем.
      if (gebi(in_id_text)) gebi(in_id_text).style.display = (gebi(in_id_input).value == '') ? 'block' : 'none';   
    }
    // Убираем проверку ввода на корректность из поля.
    clearInterval(timer['auth-input-text']);
    if (in_id_input == 'pas') {
      // Проверка поля с паролем на наличие символов.
      timer['auth-input-text2'] = setInterval(function () {checkPassText(in_id_text, in_id_input);}, 10);
    }
  } else {
    if (in_id_input == 'pas') clearInterval(timer['auth-input-text2']);
    if (in_id_text != null && gebi(in_id_input)) {
      // Скрываем надпись и переводим фокус в текстовое поле.
      gebi(in_id_text).style.display = 'none';
      gebi(in_id_input).focus();
    }
    // Ставим проверку ввода на корректность.
    timer['auth-input-text'] = setInterval(function () {checkInputText(in_id_input, 'login');}, 500);
  }
}

/**
 * Проверяет поле с паролем на наличие символов в нём. Если символов нет, то показывает над ним надпись 'пароль'.
 * 
 * in_id_text (string) айди поля с надписью.
 * in_id_input (string) айди текстового поля input.
 */
function checkPassText(in_id_text, in_id_input) {
  // Скрываем или показываем надпись над текстовым полем.
  gebi(in_id_text).style.display = (gebi(in_id_input).value == '') ? 'inline' : 'none';   
}

/**
 * Устанавливает тиргеры на заполнение полей цены и площади популярного поиска.
 */
function setTrigersSearchInputText(alt) {
  // Убираем фокус с текстовых полей.
  gebi('search-area-ot').blur();
  gebi('search-area-do').blur();
  gebi('search-price-ot').blur();
  gebi('search-price-do').blur();
  // Показываем или скрываем надписи в зависимости от того, пустые ли текстовые поля.
  gebi('search-area-text1').style.display = (gebi('search-area-ot').value == '' && alt) ? 'inline' : 'none';
  gebi('search-area-text2').style.display = (gebi('search-area-do').value == '' && alt) ? 'inline' : 'none';
  gebi('search-price-text1').style.display = (gebi('search-price-ot').value == '' && alt) ? 'inline' : 'none';
  gebi('search-price-text2').style.display = (gebi('search-price-do').value == '' && alt) ? 'inline' : 'none';
  // События срабатывающие при щелчке на надписи 'от' или 'до'.
  gebi('search-area-text1').onclick = function() {searchInputText('search-area-text1', 'search-area-ot', 'in', true, alt);};
  gebi('search-area-text2').onclick = function() {searchInputText('search-area-text2', 'search-area-do', 'in', true, alt);};
  gebi('search-price-text1').onclick = function() {searchInputText('search-price-text1', 'search-price-ot', 'in', false, alt);};
  gebi('search-price-text2').onclick = function() {searchInputText('search-price-text2', 'search-price-do', 'in', false, alt);};
  // События срабатывающие при вхождении в поле.
  gebi('search-area-ot').onfocus = function() {searchInputText('search-area-text1', 'search-area-ot', 'in', true, alt);};
  gebi('search-area-do').onfocus = function() {searchInputText('search-area-text2', 'search-area-do', 'in', true, alt);};
  gebi('search-price-ot').onfocus = function() {searchInputText('search-price-text1', 'search-price-ot', 'in', false, alt);};
  gebi('search-price-do').onfocus = function() {searchInputText('search-price-text2', 'search-price-do', 'in', false, alt);};
  // События срабатывающие при покидании поля.
  gebi('search-area-ot').onblur = function() {searchInputText('search-area-text1', 'search-area-ot', 'out', true, alt);};
  gebi('search-area-do').onblur = function() {searchInputText('search-area-text2', 'search-area-do', 'out', true, alt);};
  gebi('search-price-ot').onblur = function() {searchInputText('search-price-text1', 'search-price-ot', 'out', false, alt);};
  gebi('search-price-do').onblur = function() {searchInputText('search-price-text2', 'search-price-do', 'out', false, alt);};    
}

/**
 * Устанавливает тиргеры на заполнение полей цены, площади, сроков расширеного поиска.
 * alt (bool) - показывать в поле подсказку.
 */
function setTrigersSearchExtInputText(alt) {
  // Убираем фокус с текстовых полей.
  gebi('search-ext-area-ot').blur();
  gebi('search-ext-area-do').blur();
  gebi('search-ext-area_com-ot').blur();
  gebi('search-ext-area_com-do').blur();
  gebi('search-ext-areakit-do').blur();
  gebi('search-ext-areakit-ot').blur();
  gebi('search-ext-areahouse-ot').blur();
  gebi('search-ext-areahouse-do').blur();
  gebi('search-ext-areasotok-ot').blur();
  gebi('search-ext-areasotok-do').blur();
  gebi('search-ext-price-ot').blur();
  gebi('search-ext-price-do').blur();
  gebi('search-ext-srok-ot').blur();
  gebi('search-ext-srok-do').blur();
  if (gebi('search-ext-mkad-ot')) gebi('search-ext-mkad-ot').blur();
  if (gebi('search-ext-mkad-do')) gebi('search-ext-mkad-do').blur();

  // Показываем или скрываем надписи в зависимости от того, пустые ли текстовые поля.
  gebi('search-ext-area-text1').style.display = (gebi('search-ext-area-ot').value == '' && alt) ? 'inline' : 'none';
  gebi('search-ext-area-text2').style.display = (gebi('search-ext-area-do').value == '' && alt) ? 'inline' : 'none';
  gebi('search-ext-area_com-text1').style.display = (gebi('search-ext-area_com-ot').value == '' && alt) ? 'inline' : 'none';
  gebi('search-ext-area_com-text2').style.display = (gebi('search-ext-area_com-do').value == '' && alt) ? 'inline' : 'none';
  gebi('search-ext-areahouse-text1').style.display = (gebi('search-ext-areahouse-ot').value == '' && alt) ? 'inline' : 'none';
  gebi('search-ext-areahouse-text2').style.display = (gebi('search-ext-areahouse-do').value == '' && alt) ? 'inline' : 'none';
  gebi('search-ext-areakit-text1').style.display = (gebi('search-ext-areakit-ot').value == '' && alt) ? 'inline' : 'none';
  gebi('search-ext-areakit-text2').style.display = (gebi('search-ext-areakit-do').value == '' && alt) ? 'inline' : 'none';
  gebi('search-ext-areasotok-text1').style.display = (gebi('search-ext-areasotok-ot').value == '' && alt) ? 'inline' : 'none';
  gebi('search-ext-areasotok-text2').style.display = (gebi('search-ext-areasotok-do').value == '' && alt) ? 'inline' : 'none';
  gebi('search-ext-price-text1').style.display = (gebi('search-ext-price-ot').value == '' && alt) ? 'inline' : 'none';
  gebi('search-ext-price-text2').style.display = (gebi('search-ext-price-do').value == '' && alt) ? 'inline' : 'none';
  gebi('search-ext-srok-text1').style.display = (gebi('search-ext-srok-ot').value == '' && alt) ? 'inline' : 'none';
  gebi('search-ext-srok-text2').style.display = (gebi('search-ext-srok-do').value == '' && alt) ? 'inline' : 'none';
  if (gebi('search-ext-mkad-ot')) gebi('search-ext-mkad-text1').style.display = (gebi('search-ext-mkad-ot').value == '' && alt) ? 'inline' : 'none';
  if (gebi('search-ext-mkad-do')) gebi('search-ext-mkad-text2').style.display = (gebi('search-ext-mkad-do').value == '' && alt) ? 'inline' : 'none';

  // События срабатывающие при щелчке на надписи 'от' или 'до'.
  gebi('search-ext-area-text1').onclick = function() {searchInputText('search-ext-area-text1', 'search-ext-area-ot', 'in', true, alt);};
  gebi('search-ext-area-text2').onclick = function() {searchInputText('search-ext-area-text2', 'search-ext-area-do', 'in', true, alt);};
  gebi('search-ext-area_com-text1').onclick = function() {searchInputText('search-ext-area_com-text1', 'search-ext-area_com-ot', 'in', true, alt);};
  gebi('search-ext-area_com-text2').onclick = function() {searchInputText('search-ext-area_com-text2', 'search-ext-area_com-do', 'in', true, alt);};
  gebi('search-ext-areahouse-text1').onclick = function() {searchInputText('search-ext-areahouse-text1', 'search-ext-areahouse-ot', 'in', true, alt);};
  gebi('search-ext-areahouse-text2').onclick = function() {searchInputText('search-ext-areahouse-text2', 'search-ext-areahouse-do', 'in', true, alt);};
  gebi('search-ext-areakit-text1').onclick = function() {searchInputText('search-ext-areakit-text1', 'search-ext-areakit-ot', 'in', true, alt);};
  gebi('search-ext-areakit-text2').onclick = function() {searchInputText('search-ext-areakit-text2', 'search-ext-areakit-do', 'in', true, alt);};
  gebi('search-ext-areasotok-text1').onclick = function() {searchInputText('search-ext-areasotok-text1', 'search-ext-areasotok-ot', 'in', true, alt);};
  gebi('search-ext-areasotok-text2').onclick = function() {searchInputText('search-ext-areasotok-text2', 'search-ext-areasotok-do', 'in', true, alt);};
  gebi('search-ext-price-text1').onclick = function() {searchInputText('search-ext-price-text1', 'search-ext-price-ot', 'in', false, alt);};
  gebi('search-ext-price-text2').onclick = function() {searchInputText('search-ext-price-text2', 'search-ext-price-do', 'in', false, alt);};
  gebi('search-ext-srok-text1').onclick = function() {searchInputText('search-ext-srok-text1', 'search-ext-srok-ot', 'in', true, alt);};
  gebi('search-ext-srok-text2').onclick = function() {searchInputText('search-ext-srok-text2', 'search-ext-srok-do', 'in', true, alt);};
  if (gebi('search-ext-mkad-ot')) gebi('search-ext-mkad-text1').onclick = function() {searchInputText('search-ext-mkad-text1', 'search-ext-mkad-ot', 'in', true, alt);};
  if (gebi('search-ext-mkad-do')) gebi('search-ext-mkad-text2').onclick = function() {searchInputText('search-ext-mkad-text2', 'search-ext-mkad-do', 'in', true, alt);};

  // События срабатывающие при вхождении в поле.
  gebi('search-ext-area-ot').onfocus = function() {searchInputText('search-ext-area-text1', 'search-ext-area-ot', 'in', true, alt);};
  gebi('search-ext-area-do').onfocus = function() {searchInputText('search-ext-area-text2', 'search-ext-area-do', 'in', true, alt);};
  gebi('search-ext-area_com-ot').onfocus = function() {searchInputText('search-ext-area_com-text1', 'search-ext-area_com-ot', 'in', true, alt);};
  gebi('search-ext-area_com-do').onfocus = function() {searchInputText('search-ext-area_com-text2', 'search-ext-area_com-do', 'in', true, alt);};
  gebi('search-ext-areahouse-ot').onfocus = function() {searchInputText('search-ext-areahouse-text1', 'search-ext-areahouse-ot', 'in', true, alt);};
  gebi('search-ext-areahouse-do').onfocus = function() {searchInputText('search-ext-areahouse-text2', 'search-ext-areahouse-do', 'in', true, alt);};
  gebi('search-ext-areakit-ot').onfocus = function() {searchInputText('search-ext-areakit-text1', 'search-ext-areakit-ot', 'in', true, alt);};
  gebi('search-ext-areakit-do').onfocus = function() {searchInputText('search-ext-areakit-text2', 'search-ext-areakit-do', 'in', true, alt);};
  gebi('search-ext-areasotok-ot').onfocus = function() {searchInputText('search-ext-areasotok-text1', 'search-ext-areasotok-ot', 'in', true, alt);};
  gebi('search-ext-areasotok-do').onfocus = function() {searchInputText('search-ext-areasotok-text2', 'search-ext-areasotok-do', 'in', true, alt);};
  gebi('search-ext-price-ot').onfocus = function() {searchInputText('search-ext-price-text1', 'search-ext-price-ot', 'in', false, alt);};
  gebi('search-ext-price-do').onfocus = function() {searchInputText('search-ext-price-text2', 'search-ext-price-do', 'in', false, alt);};
  gebi('search-ext-srok-ot').onfocus = function() {searchInputText('search-ext-srok-text1', 'search-ext-srok-ot', 'in', true, alt);};
  gebi('search-ext-srok-do').onfocus = function() {searchInputText('search-ext-srok-text2', 'search-ext-srok-do', 'in', true, alt);};
  if (gebi('search-ext-time')) gebi('search-ext-time').onfocus = function() {searchInputText(null, 'search-ext-time', 'in', true, alt);};
  if (gebi('search-ext-mkad-ot')) gebi('search-ext-mkad-ot').onfocus = function() {searchInputText('search-ext-mkad-text1', 'search-ext-mkad-ot', 'in', true, alt);};
  if (gebi('search-ext-mkad-do')) gebi('search-ext-mkad-do').onfocus = function() {searchInputText('search-ext-mkad-text2', 'search-ext-mkad-do', 'in', true, alt);};

  // События срабатывающие при покидании поля.
  gebi('search-ext-area-ot').onblur = function() {searchInputText('search-ext-area-text1', 'search-ext-area-ot', 'out', true, alt);};
  gebi('search-ext-area-do').onblur = function() {searchInputText('search-ext-area-text2', 'search-ext-area-do', 'out', true, alt);};
  gebi('search-ext-area_com-ot').onblur = function() {searchInputText('search-ext-area_com-text1', 'search-ext-area_com-ot', 'out', true, alt);};
  gebi('search-ext-area_com-do').onblur = function() {searchInputText('search-ext-area_com-text2', 'search-ext-area_com-do', 'out', true, alt);};
  gebi('search-ext-areahouse-ot').onblur = function() {searchInputText('search-ext-areahouse-text1', 'search-ext-areahouse-ot', 'out', true, alt);};
  gebi('search-ext-areahouse-do').onblur = function() {searchInputText('search-ext-areahouse-text2', 'search-ext-areahouse-do', 'out', true, alt);};
  gebi('search-ext-areakit-ot').onblur = function() {searchInputText('search-ext-areakit-text1', 'search-ext-areakit-ot', 'out', true, alt);};
  gebi('search-ext-areakit-do').onblur = function() {searchInputText('search-ext-areakit-text2', 'search-ext-areakit-do', 'out', true, alt);};
  gebi('search-ext-areasotok-ot').onblur = function() {searchInputText('search-ext-areasotok-text1', 'search-ext-areasotok-ot', 'out', true, alt);};
  gebi('search-ext-areasotok-do').onblur = function() {searchInputText('search-ext-areasotok-text2', 'search-ext-areasotok-do', 'out', true, alt);};
  gebi('search-ext-price-ot').onblur = function() {searchInputText('search-ext-price-text1', 'search-ext-price-ot', 'out', false, alt);};
  gebi('search-ext-price-do').onblur = function() {searchInputText('search-ext-price-text2', 'search-ext-price-do', 'out', false, alt);};    
  gebi('search-ext-srok-ot').onblur = function() {searchInputText('search-ext-srok-text1', 'search-ext-srok-ot', 'out', true, alt);};
  gebi('search-ext-srok-do').onblur = function() {searchInputText('search-ext-srok-text2', 'search-ext-srok-do', 'out', true, alt);};    
  if (gebi('search-ext-time')) gebi('search-ext-time').onblur = function() {searchInputText(null, 'search-ext-time', 'out', true, alt);};
  if (gebi('search-ext-mkad-ot')) gebi('search-ext-mkad-ot').onblur = function() {searchInputText('search-ext-mkad-text1', 'search-ext-mkad-ot', 'out', true, alt);};
  if (gebi('search-ext-mkad-do')) gebi('search-ext-mkad-do').onblur = function() {searchInputText('search-ext-mkad-text2', 'search-ext-mkad-do', 'out', true, alt);};
}

function setTrigersListInputText(alt) {
  gebi('search-ext-area-text1').style.display = (gebi('search-ext-area-ot').value == '' && alt) ? 'inline' : 'none';
  gebi('search-ext-area-text2').style.display = (gebi('search-ext-area-do').value == '' && alt) ? 'inline' : 'none';
  gebi('search-ext-area_com-text1').style.display = (gebi('search-ext-area_com-ot').value == '' && alt) ? 'inline' : 'none';
  gebi('search-ext-area_com-text2').style.display = (gebi('search-ext-area_com-do').value == '' && alt) ? 'inline' : 'none';
  gebi('search-ext-areahouse-text1').style.display = (gebi('search-ext-areahouse-ot').value == '' && alt) ? 'inline' : 'none';
  gebi('search-ext-areahouse-text2').style.display = (gebi('search-ext-areahouse-do').value == '' && alt) ? 'inline' : 'none';
  gebi('search-ext-areakit-text1').style.display = (gebi('search-ext-areakit-ot').value == '' && alt) ? 'inline' : 'none';
  gebi('search-ext-areakit-text2').style.display = (gebi('search-ext-areakit-do').value == '' && alt) ? 'inline' : 'none';
  gebi('search-ext-areasotok-text1').style.display = (gebi('search-ext-areasotok-ot').value == '' && alt) ? 'inline' : 'none';
  gebi('search-ext-areasotok-text2').style.display = (gebi('search-ext-areasotok-do').value == '' && alt) ? 'inline' : 'none';
  gebi('search-ext-price-text1').style.display = (gebi('search-ext-price-ot').value == '' && alt) ? 'inline' : 'none';
  gebi('search-ext-price-text2').style.display = (gebi('search-ext-price-do').value == '' && alt) ? 'inline' : 'none';
  if (gebi('search-ext-mkad-text1')) gebi('search-ext-mkad-text1').style.display = (gebi('search-ext-mkad-ot').value == '' && alt) ? 'inline' : 'none';
  if (gebi('search-ext-mkad-text1')) gebi('search-ext-mkad-text2').style.display = (gebi('search-ext-mkad-do').value == '' && alt) ? 'inline' : 'none';

  gebi('search-ext-area-text1').onclick = function() {searchInputText('search-ext-area-text1', 'search-ext-area-ot', 'in', true, alt);};
  gebi('search-ext-area-text2').onclick = function() {searchInputText('search-ext-area-text2', 'search-ext-area-do', 'in', true, alt);};
  gebi('search-ext-area_com-text1').onclick = function() {searchInputText('search-ext-area_com-text1', 'search-ext-area_com-ot', 'in', true, alt);};
  gebi('search-ext-area_com-text2').onclick = function() {searchInputText('search-ext-area_com-text2', 'search-ext-area_com-do', 'in', true, alt);};
  gebi('search-ext-areahouse-text1').onclick = function() {searchInputText('search-ext-areahouse-text1', 'search-ext-areahouse-ot', 'in', true, alt);};
  gebi('search-ext-areahouse-text2').onclick = function() {searchInputText('search-ext-areahouse-text2', 'search-ext-areahouse-do', 'in', true, alt);};
  gebi('search-ext-areakit-text1').onclick = function() {searchInputText('search-ext-areakit-text1', 'search-ext-areakit-ot', 'in', true, alt);};
  gebi('search-ext-areakit-text2').onclick = function() {searchInputText('search-ext-areakit-text2', 'search-ext-areakit-do', 'in', true, alt);};
  gebi('search-ext-areasotok-text1').onclick = function() {searchInputText('search-ext-areasotok-text1', 'search-ext-areasotok-ot', 'in', true, alt);};
  gebi('search-ext-areasotok-text2').onclick = function() {searchInputText('search-ext-areasotok-text2', 'search-ext-areasotok-do', 'in', true, alt);};
  gebi('search-ext-price-text1').onclick = function() {searchInputText('search-ext-price-text1', 'search-ext-price-ot', 'in', false, alt);};
  gebi('search-ext-price-text2').onclick = function() {searchInputText('search-ext-price-text2', 'search-ext-price-do', 'in', false, alt);};
  if (gebi('search-ext-mkad-text1')) gebi('search-ext-mkad-text1').onclick = function() {searchInputText('search-ext-mkad-text1', 'search-ext-mkad-ot', 'in', false, alt);};
  if (gebi('search-ext-mkad-text1')) gebi('search-ext-mkad-text2').onclick = function() {searchInputText('search-ext-mkad-text2', 'search-ext-mkad-do', 'in', false, alt);};

  gebi('search-ext-area-ot').onfocus = function() {searchInputText('search-ext-area-text1', 'search-ext-area-ot', 'in', true, alt);};
  gebi('search-ext-area-do').onfocus = function() {searchInputText('search-ext-area-text2', 'search-ext-area-do', 'in', true, alt);};
  gebi('search-ext-area_com-ot').onfocus = function() {searchInputText('search-ext-area_com-text1', 'search-ext-area_com-ot', 'in', true, alt);};
  gebi('search-ext-area_com-do').onfocus = function() {searchInputText('search-ext-area_com-text2', 'search-ext-area_com-do', 'in', true, alt);};
  gebi('search-ext-areahouse-ot').onfocus = function() {searchInputText('search-ext-areahouse-text1', 'search-ext-areahouse-ot', 'in', true, alt);};
  gebi('search-ext-areahouse-do').onfocus = function() {searchInputText('search-ext-areahouse-text2', 'search-ext-areahouse-do', 'in', true, alt);};
  gebi('search-ext-areakit-ot').onfocus = function() {searchInputText('search-ext-areakit-text1', 'search-ext-areakit-ot', 'in', true, alt);};
  gebi('search-ext-areakit-do').onfocus = function() {searchInputText('search-ext-areakit-text2', 'search-ext-areakit-do', 'in', true, alt);};
  gebi('search-ext-areasotok-ot').onfocus = function() {searchInputText('search-ext-areasotok-text1', 'search-ext-areasotok-ot', 'in', true, alt);};
  gebi('search-ext-areasotok-do').onfocus = function() {searchInputText('search-ext-areasotok-text2', 'search-ext-areasotok-do', 'in', true, alt);};
  gebi('search-ext-price-ot').onfocus = function() {searchInputText('search-ext-price-text1', 'search-ext-price-ot', 'in', false, alt);};
  gebi('search-ext-price-do').onfocus = function() {searchInputText('search-ext-price-text2', 'search-ext-price-do', 'in', false, alt);};
  if (gebi('search-ext-mkad-text1')) gebi('search-ext-mkad-ot').onfocus = function() {searchInputText('search-ext-mkad-text1', 'search-ext-mkad-ot', 'in', false, alt);};
  if (gebi('search-ext-mkad-text1')) gebi('search-ext-mkad-do').onfocus = function() {searchInputText('search-ext-mkad-text2', 'search-ext-mkad-do', 'in', false, alt);};

  gebi('search-ext-area-ot').onblur = function() {searchInputText('search-ext-area-text1', 'search-ext-area-ot', 'out', true, alt);};
  gebi('search-ext-area-do').onblur = function() {searchInputText('search-ext-area-text2', 'search-ext-area-do', 'out', true, alt);};
  gebi('search-ext-area_com-ot').onblur = function() {searchInputText('search-ext-area_com-text1', 'search-ext-area_com-ot', 'out', true, alt);};
  gebi('search-ext-area_com-do').onblur = function() {searchInputText('search-ext-area_com-text2', 'search-ext-area_com-do', 'out', true, alt);};
  gebi('search-ext-areahouse-ot').onblur = function() {searchInputText('search-ext-areahouse-text1', 'search-ext-areahouse-ot', 'out', true, alt);};
  gebi('search-ext-areahouse-do').onblur = function() {searchInputText('search-ext-areahouse-text2', 'search-ext-areahouse-do', 'out', true, alt);};
  gebi('search-ext-areakit-ot').onblur = function() {searchInputText('search-ext-areakit-text1', 'search-ext-areakit-ot', 'out', true, alt);};
  gebi('search-ext-areakit-do').onblur = function() {searchInputText('search-ext-areakit-text2', 'search-ext-areakit-do', 'out', true, alt);};
  gebi('search-ext-areasotok-ot').onblur = function() {searchInputText('search-ext-areasotok-text1', 'search-ext-areasotok-ot', 'out', true, alt);};
  gebi('search-ext-areasotok-do').onblur = function() {searchInputText('search-ext-areasotok-text2', 'search-ext-areasotok-do', 'out', true, alt);};
  gebi('search-ext-price-ot').onblur = function() {searchInputText('search-ext-price-text1', 'search-ext-price-ot', 'out', false, alt);};
  gebi('search-ext-price-do').onblur = function() {searchInputText('search-ext-price-text2', 'search-ext-price-do', 'out', false, alt);};    
  if (gebi('search-ext-mkad-text1')) gebi('search-ext-mkad-ot').onblur = function() {searchInputText('search-ext-mkad-text1', 'search-ext-mkad-ot', 'out', false, alt);};
  if (gebi('search-ext-mkad-text1')) gebi('search-ext-mkad-do').onblur = function() {searchInputText('search-ext-mkad-text2', 'search-ext-mkad-do', 'out', false, alt);};    
}

/**
 * Проверяет данные в текстовых поля простого поиска и отправляет форму на сервер. 
 * Если необходимо, то меняет местами значения, чтобы большее соответствовало 'до', а меньшее - 'от'.
 */
function submitSearch() {
  var buf = null;
  // Проверяем введённые данные в текстовые поля на корректность.
  checkInputText('search-area-ot', 'int')
  checkInputText('search-area-do', 'int')
  checkInputText('search-price-ot', 'int')
  checkInputText('search-price-do', 'int')
  // Считываем значения текстовых полей
  var area1 = gebi('search-area-ot');
  var area2 = gebi('search-area-do');
  var price1 = gebi('search-price-ot');
  var price2 = gebi('search-price-do');
  if (Number(area1.value) > Number(area2.value) && area2.value != '' && area1 != '') {
    // Меняем площади местами.
    buf = area2.value;
    area2.value = area1.value;
    area1.value = buf;
  }
  if (Number(price1.value) > Number(price2.value) && price2.value != '' && price1 != '') {
    // Меняем цены местами.
    buf = price2.value;
    price2.value = price1.value;
    price1.value = buf;
  }
  // Обнуление текста 'Я хочу...'.
  if (gebi('search-exttext')) gebi('search-exttext').value = '';
  document.cookie = "stem=-1; path=/;";
  gebi('form-search').submit();
}

function submitSearchFilter() {
  var buf = null;
  // Проверяем введённые данные в текстовые поля на корректность.
  checkInputText('search-ext-area-ot', 'int')
  checkInputText('search-ext-area-do', 'int')
  checkInputText('search-ext-area_com-ot', 'int')
  checkInputText('search-ext-area_com-do', 'int')
  checkInputText('search-ext-areahouse-ot', 'int')
  checkInputText('search-ext-areahouse-do', 'int')
  checkInputText('search-ext-price-ot', 'int')
  checkInputText('search-ext-price-do', 'int')
  checkInputText('search-ext-areakit-ot', 'int')
  checkInputText('search-ext-areakit-do', 'int')
  checkInputText('search-ext-areasotok-ot', 'int')
  checkInputText('search-ext-areasotok-do', 'int')
  // Считываем значения текстовых полей
  var area1 = gebi('search-ext-area-ot').value != '' ? gebi('search-ext-area-ot').value : '';
  var area2 = gebi('search-ext-area-do').value != '' ? gebi('search-ext-area-do').value : '';
  area1 = gebi('search-ext-areahouse-ot').value != '' ? gebi('search-ext-areahouse-ot').value : area1;
  area2 = gebi('search-ext-areahouse-do').value != '' ? gebi('search-ext-areahouse-do').value : area2;
  area1 = gebi('search-ext-area_com-ot').value != '' ? gebi('search-ext-area_com-ot').value : area1;
  area2 = gebi('search-ext-area_com-do').value != '' ? gebi('search-ext-area_com-do').value : area2;
  var price1 = gebi('search-ext-price-ot');
  var price2 = gebi('search-ext-price-do');
  var areakit1 = gebi('search-ext-areakit-ot');
  var areakit2 = gebi('search-ext-areakit-do');
  var areasotok1 = gebi('search-ext-areasotok-ot');
  var areasotok2 = gebi('search-ext-areasotok-do');
  if (Number(area1) > Number(area2) &&  area1 != '' && area2 != '') {
    // Меняем площади местами.
    buf = area2;
    area2 = area1;
    area1 = buf;
  }
  gebi('search-ext-gen_area-ot').value = area1;
  gebi('search-ext-gen_area-do').value = area2;
  if (Number(price1.value) > Number(price2.value) && price2.value != '' && price1.value != '') {
    // Меняем цены местами.
    buf = price2.value;
    price2.value = price1.value;
    price1.value = buf;
  }
  if (Number(areakit1.value) > Number(areakit2.value) && areakit2.value != '' && areakit1.value != '') {
    // Меняем площади кухни местами.
    buf = areakit2.value;
    areakit2.value = areakit1.value;
    areakit1.value = buf;
  }
  if (Number(areasotok1.value) > Number(areasotok2.value) && areasotok2.value != '' && areasotok1.value != '') {
    // Меняем площади участка местами.
    buf = areasotok2.value;
    areasotok2.value = areasotok1.value;
    areasotok1.value = buf;
  }

  // Обнуление текста 'Я хочу...'.
  if (gebi('search-exttext')) gebi('search-exttext').value = '';
  document.cookie = "stem=-1; path=/;";
  gebi('srch_filter').submit();
}

/**
 * Проверяет данные в текстовых поля расширенного поиска и отправляет форму на сервер. 
 * Если необходимо, то меняет местами значения, чтобы большее соответствовало 'до', а меньшее - 'от' и т.п.
 */
function submitSearchExt() {
  var buf = null;
  // Проверяем введённые данные в текстовые поля на корректность.
  checkInputText('search-ext-area-ot', 'int')
  checkInputText('search-ext-area-do', 'int')
  checkInputText('search-ext-area_com-ot', 'int')
  checkInputText('search-ext-area_com-do', 'int')
  checkInputText('search-ext-areahouse-ot', 'int')
  checkInputText('search-ext-areahouse-do', 'int')
  checkInputText('search-ext-price-ot', 'int')
  checkInputText('search-ext-price-do', 'int')
  checkInputText('search-ext-areakit-ot', 'int')
  checkInputText('search-ext-areakit-do', 'int')
  checkInputText('search-ext-areasotok-ot', 'int')
  checkInputText('search-ext-areasotok-do', 'int')
  checkInputText('search-ext-srok-ot', 'int')
  checkInputText('search-ext-srok-do', 'int')
  // Считываем значения текстовых полей
  var area1 = gebi('search-ext-area-ot').value != '' ? gebi('search-ext-area-ot').value : '';
  var area2 = gebi('search-ext-area-do').value != '' ? gebi('search-ext-area-do').value : '';
  area1 = gebi('search-ext-areahouse-ot').value != '' ? gebi('search-ext-areahouse-ot').value : area1;
  area2 = gebi('search-ext-areahouse-do').value != '' ? gebi('search-ext-areahouse-do').value : area2;
  area1 = gebi('search-ext-area_com-ot').value != '' ? gebi('search-ext-area_com-ot').value : area1;
  area2 = gebi('search-ext-area_com-do').value != '' ? gebi('search-ext-area_com-do').value : area2;
  var price1 = gebi('search-ext-price-ot');
  var price2 = gebi('search-ext-price-do');
  var areakit1 = gebi('search-ext-areakit-ot');
  var areakit2 = gebi('search-ext-areakit-do');
  var areasotok1 = gebi('search-ext-areasotok-ot');
  var areasotok2 = gebi('search-ext-areasotok-do');
  var srok1 = gebi('search-ext-srok-ot');
  var srok2 = gebi('search-ext-srok-do');
  if (Number(area1) > Number(area2) &&  area1 != '' && area2 != '') {
    // Меняем площади местами.
    buf = area2;
    area2 = area1;
    area1 = buf;
  }
  gebi('search-ext-gen_area-ot').value = area1;
  gebi('search-ext-gen_area-do').value = area2;
  if (Number(price1.value) > Number(price2.value) && price2.value != '' && price1.value != '') {
    // Меняем цены местами.
    buf = price2.value;
    price2.value = price1.value;
    price1.value = buf;
  }
  if (Number(areakit1.value) > Number(areakit2.value) && areakit2.value != '' && areakit1.value != '') {
    // Меняем площади кухни местами.
    buf = areakit2.value;
    areakit2.value = areakit1.value;
    areakit1.value = buf;
  }
  if (Number(areasotok1.value) > Number(areasotok2.value) && areasotok2.value != '' && areasotok1.value != '') {
    // Меняем площади участка местами.
    buf = areasotok2.value;
    areasotok2.value = areasotok1.value;
    areasotok1.value = buf;
  }
  if (Number(srok1.value) > Number(srok2.value) && srok2.value != '' && srok1.value != '') {
    // Меняем сроки аренды местами.
    buf = srok2.value;
    srok2.value = srok1.value;
    srok1.value = buf;
  }
  // Обнуляем те поля, которые не будут использоваться при поиске.
  if (gebi('search-ext-type-result1').style.visibility == 'hidden') {
    // Обнуляем срок аренды.
    gebi('search-ext-srok-ot').value = '';
    gebi('search-ext-srok-do').value = '';
  }
  // Обнуляем город.
  /*gebi('search-ext-city').selectedIndex = (gebi('search-ext-city').disabled == true) ?
                                           0 : gebi('search-ext-city').selectedIndex;*/
  if (gebi('search-ext-highway') && gebi('search-ext-highway').disabled == true) {
    // Обнуляем шоссе.
    gebi('search-ext-highway').selectedIndex = 0;
  }
  if (gebi('search-ext-build-liv').className == 'none') {
    // Обнуляем скрытые элементы для городской недвижимости.
    gebi('search-ext-area-ot').value = '';
    gebi('search-ext-area-do').value = '';
    gebi('search-ext-areakit-ot').value = '';
    gebi('search-ext-areakit-do').value = '';
    gebi('search-ext-floor1').checked = false;
    gebi('search-ext-floor2').checked = false;
    gebi('search-ext-wc').selectedIndex = 0;
    gebi('search-ext-balcony').selectedIndex = 0;
    gebi('search-ext-loggia').selectedIndex = 0;
    gebi('search-ext-garbage').selectedIndex = 0;
    gebi('search-ext-house_type').selectedIndex = 0;
    gebi('search-ext-furniture').selectedIndex = 0;
    gebi('search-ext-tv').selectedIndex = 0;
    gebi('search-ext-fridge').selectedIndex = 0;
    gebi('search-ext-housetech').selectedIndex = 0;
    // Очищаем чекбоксы количества комнат.
    gebi('srch-chbox1').checked = false;
    gebi('srch-chbox2').checked = false;
    gebi('srch-chbox3').checked = false;
    gebi('srch-chbox4').checked = false;
    gebi('srch-chbox5').checked = false;
    // Очищаем чекбокс "В коттеджном посёлке".
    if (gebi('search-ext-cotvillage').style.display == 'none') gebi('srch-chbox2-1').checked = false;
    // Очищаем чекбокс "Vip-коттедж".
    if (gebi('search-ext-vipcot').style.display == 'none') gebi('srch-chbox2-4').checked = false;
  }
  
  if (gebi('search-ext-build-cot').className == 'none') {
    // Обнуляем скрытые элементы для загородной недвижимости.
    gebi('search-ext-areahouse-ot').value = '';
    gebi('search-ext-areahouse-do').value = '';
    gebi('search-ext-areasotok-ot').value = '';
    gebi('search-ext-areasotok-do').value = '';
    gebi('search-ext-electricity').selectedIndex = 0;
    gebi('search-ext-heating').selectedIndex = 0;
    gebi('search-ext-water').selectedIndex = 0;
    gebi('search-ext-sewerage').selectedIndex = 0;
    gebi('search-ext-gas').selectedIndex = 0;
    gebi('search-ext-guard').selectedIndex = 0;
    gebi('search-ext-parking').selectedIndex = 0;
    // Очищаем чекбоксы.
    gebi('srch-chbox2-1').checked = false;
    gebi('srch-chbox2-2').checked = false;
    gebi('srch-chbox2-3').checked = false;
    gebi('srch-chbox2-4').checked = false;
    // Устанавливаем значение телефона.
    gebi('search-ext-phone-cot').selectedIndex = gebi('search-ext-phone-liv').selectedIndex;
  }

  if (gebi('search-ext-build-com').className == 'none') {
    // Обнуляем скрытые элементы для коммерческой недвижимости.
    gebi('search-ext-area_com-ot').value = '';
    gebi('search-ext-area_com-do').value = '';
  }

  // Заменяем ограничители тегов <> на {}.
  toptext = gebi('search-exttoptext').value;
  toptext = toptext.replace(/</g, "{");
  toptext = toptext.replace(/>/g, "}");
  gebi('search-exttoptext').value = toptext;


  // Делаем активными все опции в правом селекте с метро.
  if (gebi('search-ext-metrolist').style.display != 'none') {
    for (var i = 0; i < gebi('search-ext-metro').options.length; i++) {
      gebi('search-ext-metro').options[i].selected = true;
    }
  }

  if (gebi('search-ext-citylist').style.display != 'none') {
    // Делаем активными все опции в правом селекте с городами и помещаем в value айди городов.
    for (var i = 0; i < gebi('search-ext-city2').options.length; i++) {
      gebi('search-ext-city2').options[i].selected = true;
      gebi('search-ext-city2').options[i].value = gebi('search-ext-city2').options[i].id.substr(22);
    }
  }

  if (gebi('search-ext-highwaylist').style.display != 'none') {
    // Делаем активными все опции в правом селекте с городами и помещаем в value айди городов.
    for (var i = 0; i < gebi('search-ext-highway2').options.length; i++) {
      gebi('search-ext-highway2').options[i].selected = true;
      gebi('search-ext-highway2').options[i].value = gebi('search-ext-highway2').options[i].id.substr(21);
    }
  }
  // Вызываем функцию формирования текста в блоке 'Я хочу'.
  changeTopTextSearch('submit');
}

/**
 * Передаёт фокус текстовому полю и скрывает надпись над ним ('от' или 'до'), 
 * или при потере фокуса полем восстанавливает надпись.
 *
 * in_id_text (string) айди поля с надписью.
 * in_id_input (string) айди текстового поля input.
 * in_act (string) out - потеря фокуса текстовым полем input, in - вход в поле (получение полем фокуса).
 */
function searchInputText(in_id_text, in_id_input, in_act, check, alt) {
  if (in_act == 'out') {
    if (in_id_text != null) {
      // Скрываем или показываем надпись над текстовым полем.
      if (gebi(in_id_text)) {
        gebi(in_id_text).style.display = gebi(in_id_input).value == '' && alt ? 'inline' : 'none';   
      }
    }
    // Убираем проверку ввода на корректность из поля.
    if (check) clearInterval(timer['search-input-text']);
  } else {
    if (in_id_text != null && gebi(in_id_input)) {
      // Скрываем надпись и переводим фокус в текстовое поле.
      gebi(in_id_text).style.display = 'none';
      gebi(in_id_input).focus();
    }
    // Ставим проверку ввода на корректность.
    if (check) timer['search-input-text'] = setInterval(function () {checkInputText(in_id_input, 'int');}, 500);
  }
}

/**
 * Проверяет на корректность введёное значение в текстовое поле и удаляет некорректные символы.
 * Корректность символов зависит от переданного типа. Например, int - позволит вводить только цифры.
 *
 * in_id_input (string) айди текстового поля input.
 * in_type (string) допустимый тип ввоодимого значения в текстовое поле.
 */
function checkInputText(in_id_input, in_type) {
  if(gebi(in_id_input))
  {
	  var val = gebi(in_id_input).value;
	  switch (in_type) {
	    // Корректными считаются только цифры.
	    case 'int':
	      var reg = new RegExp("[^0-9]", "g");
	      break;
	    
	    // Корректными считаются только цифры и точка .
	    case 'float':
	    	var reg = new RegExp("[^0-9.]", "g");
	    break;
	    
	    // Корректными считаются только символы русского алфавита и @-.,_
	    case 'rus_str':
	    	var reg = new RegExp("[^-.,а-яА-ЯёЁ_\\s ]", "g");
	    break;
	    
	    // Корректными считаются только цифры, символы русского алфавита и @-.,_
	    case 'rus_str_num':
	    	var reg = new RegExp("[^-.,а-яА-ЯёЁ_0-9\\s ]", "g");
	    break;
	    
	    // Корректными считаются только цифры, символы латинского алфавита и @-._.
	    case 'login':
	      var reg = new RegExp("[^-.@\\w]", "g");
	      break;
	  }
	  if (reg.test(val)) {
	    // Удаляем некорректные символы.
	    var res = val.replace(reg, '');
	    gebi(in_id_input).value = res;
	  }
  }
}

/**
 * Меняет количество выводимых результатов поиска на страницу.
 * 
 * in_el (object): элемент селект.
 */
function changeRowsPerPage(in_el) {
  location.href = '/list/?rpp=' +  in_el.value;
}

/**
 * Меняет цвет фона строки в таблице с результатами поиска при наведении мышки.
 *
 * @param in_el элемент tr, на котором произошло событие onmouseover или onmouseout.
 * @param in_hover true - произошло наведение, false - мышка была убрана.
 */
function onmouseSearch(in_el, in_hover, parity) {
  if ((in_el.nodeName == null) || (in_el.nodeName != null && in_el.nodeName.toLowerCase() != 'tr')) return;
  switch (in_hover) {
    case true:
      in_el.className = 'search-tr-bgon';
      _setVisibleImg(in_el, 'active');
      break;
    case false:
      if (parity % 2) {
        in_el.className = 'search-tr-bgparity';
        _setVisibleImg(in_el, 'on');
      } else {
        in_el.className = 'search-tr-bgoff';
        _setVisibleImg(in_el, 'off');
      }
      break;      
  }
}

/**
 * Устанавлиает видимость картинки с градиентом, а две другие гасит.
 *
 * @param in_el: элемент tr из таблицы с результатами поиска.
 * @param in_act: принимает три значения: off - должна быть видима картинка с градиентом для нечётной строки, on - для чётной строки,
 * active - для выделенной строки.
 */
function _setVisibleImg(in_el, in_act) {
  // Перебираем потомков tr (нам нужны элементы td).
  for (var i = 0; i < in_el.childNodes.length; i++) {
    if (in_el.childNodes[i].nodeName.toLowerCase() == 'td') {
      // Перебираем потомков в td.
      for (var j = 0; j < in_el.childNodes[i].childNodes.length; j++) {
        // Потомок td.
        var divEl = in_el.childNodes[i].childNodes[j];
        if (divEl.nodeName.toLowerCase() == 'div') {
          var count = 0;
          for (var k = 0; k < divEl.childNodes.length; k++) {
            if (divEl.childNodes[k].nodeName.toLowerCase() == 'img') {
              var imgEl = divEl.childNodes[k];
              count++;
              switch (count) {
                // Показываем или прячем первую картинку (srch_grad1.png)
                case 1:
                  imgEl.style.visibility = (in_act == 'off') ? 'visible' : 'hidden';
                  break;
                  
                // Показываем или прячем вторую картинку (srch_grad2.png)
                case 2:
                  imgEl.style.visibility = (in_act == 'active') ? 'visible' : 'hidden';                  
                  break;
                  
                // Показываем или прячем третью картинку (srch_grad3.png)
                case 3:
                  imgEl.style.visibility = (in_act == 'on') ? 'visible' : 'hidden';                  
                  break;                  
              }
            }
          }
        }
      }
    }
  }
}

var is_spec_last_ad = false;
function onMouseLastAd(in_el, in_hover, parity) {
  switch (in_hover) {
    case true:
      is_spec_last_ad = in_el.className == "div_last_ad bg_last_ad_spec" ? true : false;
      in_el.className = 'div_last_ad bgyellow';
      _setGradLastAd(in_el, 'yellow');
      break;
    case false:
      if (is_spec_last_ad) {
        in_el.className = 'div_last_ad bg_last_ad_spec';
        _setGradLastAd(in_el, 'spec');
      } else if (parity % 2) {
        in_el.className = 'div_last_ad bgwhite';
        _setGradLastAd(in_el, 'white');
      } else {
        in_el.className = 'div_last_ad bggray';
        _setGradLastAd(in_el, 'gray');
      }
      break;      
  }
}

function _setGradLastAd(in_el, in_act) {
  for (var i = 0; i < in_el.childNodes.length; i++) {
    if (in_el.childNodes[i].nodeName.toLowerCase() == 'div') {
      for (var j = 0; j < in_el.childNodes[i].childNodes.length; j++) {
        var divEl = in_el.childNodes[i].childNodes[j];
        if (divEl.nodeName.toLowerCase() == 'div') {
          var count = 0;
          for (var k = 0; k < divEl.childNodes.length; k++) {
            if (divEl.childNodes[k].nodeName.toLowerCase() == 'img') {
              var imgEl = divEl.childNodes[k];
              count++;
              switch (count) {
                // Показываем или прячем первую картинку (srch_grad_white.png)
                case 1:
                  imgEl.style.visibility = (in_act == 'white') ? 'visible' : 'hidden';
                  break;
                // Показываем или прячем вторую картинку (srch_grad_gray.png)
                case 2:
                  imgEl.style.visibility = (in_act == 'gray') ? 'visible' : 'hidden';                  
                  break;
                // Показываем или прячем третью картинку (srch_grad_spec.png)
                case 3:
                  imgEl.style.visibility = (in_act == 'spec') ? 'visible' : 'hidden';                  
                  break;                  
                // Показываем или прячем 4-ю картинку (srch_grad_yellow.png)
                case 4:
                  imgEl.style.visibility = (in_act == 'yellow') ? 'visible' : 'hidden';                  
                  break;                  
              }
            }
          }
        }
      }
    }
  }
}

/**
 * Создаёт объект запроса (ajax).
 *
 * return объект запроса или сообщение об ошибке.
 */
function createRequest() {
	var request = null;
	try {
		request = new XMLHttpRequest;
	} catch(microsoft) {
		try {
			request = new ActiveXObject("Microsoft.XMLHTTP");
		} catch(othermicrosoft) {
			try {
				request = new ActiveXObject("Msxml2.XMLHTTP");
			} catch(error) {
				request = null;
			}
		}
	}
	if(request == null)	{
    alert('К сожалению Ваш браузер не поддерживает некоторых функций.\r\nУбедитесь, что у Вас включен Javascript в настройках Вашего браузера.');
	}	else {
    return request;
	}
}

/**
 * Деактивирует или активирует поля площади дома для Участка.
 */
function disabledAreaFull(alt) {
  var lot = gebi('build_lot').value;
  var build = _getValueType(gebi('search-build'));
  if (build == lot) {
    gebi('search-ext-areahouse-ot').disabled = true;
    gebi('search-ext-areahouse-do').disabled = true;
    gebi('search-ext-areahouse-text1').style.display = 'none';
    gebi('search-ext-areahouse-text2').style.display = 'none';
  } else {
    gebi('search-ext-areahouse-ot').disabled = false;
    gebi('search-ext-areahouse-do').disabled = false;
    gebi('search-ext-areahouse-text1').style.display = gebi('search-ext-areahouse-ot').value == '' && alt ? 'inline' : 'none';
    gebi('search-ext-areahouse-text2').style.display = gebi('search-ext-areahouse-do').value == '' && alt ? 'inline' : 'none';
  }
}

/**
 * Изменяет интерфейс расширенного поиска в зависимости от выбранной недвижимости.
 * 
 * in_el (object) селект с недвижимостью. 
 */
function getSearchExtBuild(in_el) {
  changeTopTextSearch();
  var type = _getTypeBuild(in_el);
  var values = _getValuesSearch('-ext');
  var data = 'req=build&build_type=' + type + values;
  request['search-ext-build'] = createRequest();
  request['search-ext-build'].onreadystatechange = function() {updateSearchExt(request['search-ext-build']);};
  var url = "/search/request_adv.php";
  var extra = gebi('idsearch-extra-' + gebi("search-ext-type").value).value;
  var type_deal = gebi('idtypes-value-' + extra).value;
  var alt_input_ext_srch = type_deal == DEAL_TYPE_RENT || type_deal == DEAL_TYPE_SALE;
  disabledAreaFull(alt_input_ext_srch);
  //alert(alt_input_ext_srch);
  if (type == TYPE_BUILD_AREA) {
    if (gebi('search-ext-realty-span')) {
      // Удаляем селлект с коммерческой недвижимостью.
      $('#search-ext-realty-span').fadeOut('fast', function () {
        gebi('search-ext-realty-span').innerHTML = "";
      });
    }
    //alert(1);
    $('#search-ext-build-liv').fadeOut('slow');
    $('#search-ext-build-cot').fadeIn('slow');
    $('#search-ext-build-com').fadeOut('slow');
    // Получаем айди недвижимости.
    extra_build = gebi('build-' + in_el.value).value;
    id_build = gebi('idtypes-value-' + extra_build).value
    if (id_build == BUILD_HOUSE || id_build == BUILD_COTTAGE || id_build == BUILD_TOWNHOUSE) {
      // Показываем нужные чекбоксы. 
      $('#search-ext-cotvillage').fadeIn('slow');
      $('#search-ext-vipcot').fadeIn('slow');
    }
    if (id_build == BUILD_DACHA) {
      // Скрываем ненужные чекбоксы. 
      $('#search-ext-cotvillage').fadeOut('slow');
      $('#search-ext-vipcot').fadeOut('slow');
      gebi('srch-chbox2-1').checked = false;
      gebi('srch-chbox2-4').checked = false;
    }
    if (id_build == BUILD_LOT) {
      // Скрываем ненужный чекбокс и показываем нужный. 
      $('#search-ext-cotvillage').fadeIn('slow');
      $('#search-ext-vipcot').fadeOut('slow');
      gebi('srch-chbox2-4').checked = false;
    }
    gebi('search-ext-area-ot').value = '';
    gebi('search-ext-area-do').value = '';
    gebi('search-ext-area_com-ot').value = '';
    gebi('search-ext-area_com-do').value = '';
    gebi('search-ext-areakit-ot').value = '';
    gebi('search-ext-areakit-do').value = '';
    gebi("srch_highway_radio").checked = true;
  }
  if (type == TYPE_BUILD_CITY) {
    if (gebi('search-ext-realty-span')) {
      // Удаляем селлект с коммерческой недвижимостью.
      $('#search-ext-realty-span').fadeOut('fast', function () {
        gebi('search-ext-realty-span').innerHTML = "";
      });
    }
    $('#search-ext-build-liv').fadeIn('slow');
    $('#search-ext-build-cot').fadeOut('slow');
    $('#search-ext-build-com').fadeOut('slow');
    gebi('search-ext-area_com-ot').value = '';
    gebi('search-ext-area_com-do').value = '';
    gebi('search-ext-areahouse-ot').value = '';
    gebi('search-ext-areahouse-do').value = '';
    gebi('search-ext-areasotok-ot').value = '';
    gebi('search-ext-areasotok-do').value = '';
    gebi("srch_city_radio").checked = true;
  }
  if (type == TYPE_BUILD_COMMERCIAL) {
    $('#search-ext-build-liv').fadeOut('slow');
    $('#search-ext-build-cot').fadeOut('slow');
    $('#search-ext-build-com').fadeIn('slow');
    gebi('search-ext-areahouse-ot').value = '';
    gebi('search-ext-areahouse-do').value = '';
    gebi('search-ext-areasotok-ot').value = '';
    gebi('search-ext-areasotok-do').value = '';
    gebi('search-ext-area-ot').value = '';
    gebi('search-ext-area-do').value = '';
    gebi('search-ext-areakit-ot').value = '';
    gebi('search-ext-areakit-do').value = '';
  }
  //alert(data);
  sendRequest(request['search-ext-build'], url, data);
  //setTrigersSearchExtInputText();
  _disabledSelects('-ext', true, true);
}

/**
 * Изменяем интерфейс расширенного поиска при смене значения в селекте region.
 * @param in_el (object): селект с регионами в расширенном поиске.
 */
function getSearchExtRegion(in_el) {
  changeTopTextSearch();
  var region_id = gebi('search-ext-region').value;
  if (region_id == REGION_ALL || region_id == REGION_MOSCOW_AND_OBL || region_id == REGION_S_PETER_AND_OBL) {
    $('#srch_radio_metro_city').fadeOut('slow');
    $('#srch_radio_highway_city').fadeOut('slow');
    $('#search-ext-highwaylist').fadeOut('slow');
    $('#search-ext-metrolist').fadeOut('slow');
    $('#search-ext-citylist').fadeOut('slow');
    return;
  }
  if (gebi('search-ext-highwaylist').className == 'block') {
    gebi('search-ext-mkad-ot').value = '';
    gebi('search-ext-mkad-do').value = '';
  }
  if (gebi('search-ext-metrolist').className == 'block') {
    gebi('search-ext-time').value = '';
    gebi('search-ext-timetype').value = '';
  }
  var values = _getValuesSearch('-ext');
  var type = _getTypeBuild(gebi('search-ext-build'));
  var data = 'req=region&build_type=' + type + values;
  //alert(data);
  request['search-ext-region'] = createRequest();
  request['search-ext-region'].onreadystatechange = function() {updateSearchExt(request['search-ext-region']);};
  var url = "/search/request_adv.php";
  sendRequest(request['search-ext-region'], url, data);
  _disabledSelects('-ext', true, false);
}

/**
 * Обновляет интерфейс расширенного поиска в селектах, данными полученными от сервера.
 * in_req объект запроса.
 * return сообщение об ошибке в случае неудачи. 
 */
function updateSearchExt(in_req) {
  if (in_req.readyState == 4) {
    if (in_req.status == 200) {
      _disabledSelects('-ext', false, true);
      gebi("map_region").className = "none";
      gebi("map_metro").className = "none";
      gebi("map_highway").className = "none";
      gebi("only_city").className = "block";
      //alert(in_req.responseText);return;
			var xmlDoc = in_req.responseXML;
			in_req = null;
      var el = xmlDoc.getElementsByTagName('el');
      //alert(el.length);
      for (var i = 0; i < el.length; i++) {
        if (el[i].getAttribute("id") != null) {
          if (el[i].getAttribute("id") == "region-result") {
            var sels = el[i].getElementsByTagName('select');
            var j = 0;
            while (sels.length) {
              if (j >= sels.length && isIE) {
                break;
              }
              index = isIE ? j : 0;
              var childEl = sels[index];
              j++;
              var node = XMLtoDocument(childEl);
              resetSelectMetro(srch_selects_metro);
              resetSelectCity();
              resetSelectHighway(selects_highway);
              gebi('search-ext-mkad-ot').value = '';
              gebi('search-ext-mkad-do').value = '';
              gebi('search-ext-time').value ='';
              switch (childEl.getAttribute("id")) {
                case "search-ext-city1":
                  rc(gebi('city'), gebi('search-ext-city1'), node);
                  gebi('search-ext-city1').ondblclick = function() {
                    changeCitySelect('search-ext-city1', 'search-ext-city2');changeTopTextSearch();
                  };
                  break;
                case "search-ext-highway1":
                  rc(gebi('highway'), gebi('search-ext-highway1'), node);
                  gebi('search-ext-highway1').ondblclick = function() {
                    changeHighwaySelect('search-ext-highway1', 'search-ext-highway2');changeTopTextSearch();
                  };
                  break;
                case "search-ext-metro1":
                  rc(gebi('metro'), gebi('search-ext-metro1'), node);
                  gebi('search-ext-metro1').ondblclick = function() {
                    changeMetroSelect('search-ext-metro1', 'search-ext-metro');changeTopTextSearch();
                  };
                  break;
              }
              var region_id = gebi('search-ext-region').value;
              if (region_id == REGION_ALL || region_id == REGION_MOSCOW_AND_OBL || region_id == REGION_S_PETER_AND_OBL) {
                $('#srch_radio_metro_city').fadeOut('slow');
                $('#srch_radio_highway_city').fadeOut('slow');
                $('#search-ext-metrolist').fadeOut('slow');
                $('#search-ext-citylist').fadeOut('slow');
                $('#search-ext-highwaylist').fadeOut('slow');
                return;
              } else {
                switch (el[i].getAttribute("type")) {
                  case 'metro':
                    $('#search-ext-metrolist').fadeIn('slow');
                    $('#search-ext-citylist').fadeOut(0);
                    $('#search-ext-highwaylist').fadeOut(0);
                    gebi("srch_metro_radio").checked = true;
                    break;
                  case 'city':
                    $('#search-ext-metrolist').fadeOut(0);
                    $('#search-ext-citylist').fadeIn('slow');
                    $('#search-ext-highwaylist').fadeOut(0);
                    gebi("srch_city_radio").checked = true;
                    break;
                  case 'highway':
                    $('#search-ext-metrolist').fadeOut(0);
                    $('#search-ext-citylist').fadeOut(0);
                    $('#search-ext-highwaylist').fadeIn('slow');
                    gebi("srch_highway_radio").checked = true;
                    break;
                  case 'none':
                  default:
                    $('#search-ext-metrolist').fadeOut(0);
                    $('#search-ext-citylist').fadeOut(0);
                    $('#search-ext-highwaylist').fadeOut(0);
                    break;
                }
              }
            }
            setHeightCellCenter();
            //continue;
          } else {
            for (var j = 0; j < el[i].childNodes.length; j++) {
              var childEl = el[i].childNodes[j];
              var arr = ['area', 'has_metro', 'has_highway', 'has_maps', 'is_moscow_obl', 'has_map_region', 'has_map_metro', 'has_map_highway'];
              if (childEl.nodeValue == null || in_array(el[i].getAttribute("id"), arr)) {
                // Преобразуем XML-элемент в HTML.
                var node = XMLtoDocument(childEl);
                switch (el[i].getAttribute("id")) {
                  case 'has_metro':
                    if (Number(node.nodeValue)) {
                      $('#srch_radio_metro_city').fadeIn('slow');
                    } else {
                      $('#srch_radio_metro_city').fadeOut(0);
                    }
                    gebi("srch_metro_radio").disabled =  Number(node.nodeValue) ? false : true;
                    if (Number(node.nodeValue)) {
                      gebi("only_city").className = "none";
                    }
                    break;
                  case 'has_highway':
                    if (Number(node.nodeValue)) {
                      $('#srch_radio_highway_city').fadeIn('slow');
                    } else {
                      $('#srch_radio_highway_city').fadeOut(0);
                    }
                    gebi("srch_highway_radio").disabled = Number(node.nodeValue) ? false : true;
                    if (Number(node.nodeValue)) {
                      gebi("only_city").className = "none";
                    }
                    break;
                  case 'has_map_region':
                    gebi("map_region").className = "inline";
                    break;
                  case 'has_map_metro':
                    var url_data = {
                      url: "/search/request_map_metro.php",
                      data: "region_id=" + gebi('search-ext-region').value,
                      id_container: "metromap_container",
                      id_map_link: "map_metro"
                    }
                    getMapMetro(url_data);
                    break;
                  case 'has_map_highway':
                    //gebi("map_highway").className = "inline";
                    var url_data = {
                      url: "/search/request_map_highway.php",
                      data: "region_id=" + gebi('search-ext-region').value,
                      id_container: "maphighway_container",
                      id_map_link: "map_highway"
                    }
                    getMapHighway(url_data);
                    break;
                  case 'is_moscow_obl':
                    if (Number(node.nodeValue)) {
                      $('#from_mkad').fadeIn('slow');
                    } else {
                      $('#from_mkad').fadeOut('slow');
                    }
                    break;
                  case 'area':
                    gebi('search-ext-areahouse-ot').disabled = (node.nodeValue == 'true') ? true : false;
                    gebi('search-ext-areahouse-do').disabled = (node.nodeValue == 'true') ? true : false;
                    var extra = gebi('idsearch-extra-' + gebi("search-ext-type").value).value;
                    var type_deal = gebi('idtypes-value-' + extra).value;
                    var alt = type_deal == DEAL_TYPE_RENT || type_deal == DEAL_TYPE_SALE;
                    if (node.nodeValue == 'true' || !alt) {
                      $('#search-ext-areahouse-text1').fadeOut('slow');
                      $('#search-ext-areahouse-text2').fadeOut('slow');
                    } else {
                      $('#search-ext-areahouse-text1').fadeIn('slow');
                      $('#search-ext-areahouse-text2').fadeIn('slow');
                    }
                    break;
                  case 'region':
                    rc(gebi('search-ext-region-span'), gebi('search-ext-region'), node);
                    gebi('search-ext-region').onchange = function() {getSearchExtRegion(this);};
                    gebi('search-ext-mkad-ot').value = '';
                    gebi('search-ext-mkad-do').value = '';
                    gebi('search-ext-time').value ='';
                    break;
                  case 'realty':
                    gebi('search-ext-realty-span').innerHTML = "";
                    gebi('search-ext-realty-span').className = "none";
                    gebi('search-ext-realty-span').appendChild(node);
                    $('#search-ext-realty-span').fadeIn('slow');
                    node.onchange = changeTopTextSearch;
                    break;
                }
              }
            }
          }
        }
      }
      changeTopTextSearch();
    } else alert(gebi('err_browser').value);
  }
}

/**
 * Сотки или метры площади.
 */
function mesureAreaFull() {
  var lot = gebi('build_lot').value;
  var build = _getValueType(gebi('search-build'));
  gebi('search-mesure-area').innerHTML = (build == lot) ? gebi('mesure_hundred').value : gebi('mesure_metre').value;
}

/**
 * Изменяет интерфейс поиска при смене значения в селекте с айди build.
 * 
 * in_el элемент. 
 */
function getSearchBuild(in_el) {
  var values = _getValuesSearch('') + '&select=build';
  //alert(values);
  request['search-build'] = createRequest();
  request['search-build'].onreadystatechange = function() {updateSearch(request['search-build']);};
  var url = (gebi('mesure_metre')) ? "/search/request.php" : "/search/getselect.php";
  // Сотки или метры площади.
  mesureAreaFull();
  // Получаем тип недвижимости.
  var extra = _getTypeBuild(in_el);
  // Некомерческая недвижимость.
  if (extra != TYPE_BUILD_COMMERCIAL) {
    // Создаём селект с количеством комнат, если его нет.
    if (gebi('search-rooms') == null) {
      // Деактивируем или активируем его.
      if (extra == TYPE_BUILD_CITY) {
        var disabled = 0;          
      } else {
        var disabled = 1;
      }    
      var data = 'type=rooms&disabled=' + disabled;
      data = data + values;
      // Отправляем запрос серверу.
      sendRequest(request['search-build'], url, values);
      // Блокируем некоторые селекты и кнопку Поиск, пока не получим ответ от сервера.
      _disabledSelects('', true, true);
    } else { 
      //  Деактивируем или активируем селект rooms.
      if (extra == TYPE_BUILD_CITY) {
        gebi('search-rooms').disabled = false;          
      } else {
        gebi('search-rooms').disabled = true;
      }    
      var data = 'type=region&extra=' + extra;
      data = data + values;
      // Отправляем запрос серверу.
      sendRequest(request['search-build'], url, values);
      _disabledSelects('', true, true);
    }
  } else { // Коммерческая.
    data = 'type=realty&extra=' + extra;
    data = data + values;
    sendRequest(request['search-build'], url, values);
    _disabledSelects('', true, true);
  }
}

/**
 * Деактивирует/активирует некоторые селекты в поиске.
 *
 * in_ext
 * (string) префикс для айди селектов.
 *
 * in_disabled
 * (bool) true - деактивирует элемент, false - активирует. 
 *
 * in_region
 * (bool) true - селект region тоже участвует в активации/деактивации, false - не участвует.
 */
function _disabledSelects(in_ext, in_disabled, in_region) {
  if (in_disabled) {
    $('#srch_sel').fadeTo('slow', 0.25);
  } else {
    $('#srch_sel').fadeTo('slow', 1);
  }
  if (gebi('search' + in_ext + '-region') != null && in_region == true) {
    gebi('search' + in_ext + '-region').disabled = in_disabled;
  }
  if (gebi('search' + in_ext + '-metro') != null) {
    gebi('search' + in_ext + '-metro').disabled = in_disabled;
  }
  if (gebi('search' + in_ext + '-metro1') != null) {
    gebi('search' + in_ext + '-metro1').disabled = in_disabled;
  }
  if (gebi('search' + in_ext + '-time') != null) {
    gebi('search' + in_ext + '-time').disabled = in_disabled;
  }
  if (gebi('search' + in_ext + '-timetype') != null) {
    gebi('search' + in_ext + '-timetype').disabled = in_disabled;
  }
  if (gebi('search-city') != null && in_ext != '-ext') {
    gebi('search-city').disabled = in_disabled;
  }
  if (gebi('search' + in_ext + '-city1') != null) {
    gebi('search-ext-city1').disabled = in_disabled;
  }
  if (gebi('search' + in_ext + '-city2') != null) {
    gebi('search-ext-city2').disabled = in_disabled;
  }
  if (gebi('search' + in_ext + '-highway') != null) {
    gebi('search' + in_ext + '-highway').disabled = in_disabled;
  }
  if (gebi('search' + in_ext + '-highway1') != null) {
    gebi('search' + in_ext + '-highway1').disabled = in_disabled;
  }
  if (gebi('search' + in_ext + '-highway2') != null) {
    gebi('search' + in_ext + '-highway2').disabled = in_disabled;
  }
  if (gebi('search-mkad') != null && in_ext != '-ext') {
    gebi('search-mkad').disabled = in_disabled;
  }
  if (gebi('search' + in_ext + '-mkad-ot') != null) {
    gebi('search' + in_ext + '-mkad-ot').disabled = in_disabled;
  }
  if (gebi('search' + in_ext + '-mkad-do') != null) {
    gebi('search' + in_ext + '-mkad-do').disabled = in_disabled;
  }
  gebi('search' + in_ext + '-submit').disabled = in_disabled;
  
}

/**
 * Возвращает строку из выбранных значений в селектах поиска.
 * Массив используется для отправки серверу, чтобы при генерации опций были сохранены выбранные значения пользователя.
 * 
 * in_ext (string) префикс для определения айди элементов поиска.
 * return (string) массив значений, выбранных пользователем в селектах поиска. 
 */
function _getValuesSearch(in_ext) {
  
  var vals = new Array;
  vals['build'] = (gebi('search' + in_ext + '-build') == null)? '' : gebi('search' + in_ext + '-build').value;
  vals['rooms'] = (gebi('search' + in_ext + '-rooms') == null)? '' : gebi('search' + in_ext + '-rooms').value;
  vals['realty'] = (gebi('search' + in_ext + '-realty') == null)? '' : gebi('search' + in_ext + '-realty').value;
  vals['region'] = (gebi('search' + in_ext + '-region') == null)? '' : gebi('search' + in_ext + '-region').value;
  vals['metro'] = (gebi('search' + in_ext + '-metro') == null)? '' : gebi('search' + in_ext + '-metro').value;
  vals['highway'] = (gebi('search' + in_ext + '-highway') == null)? '' : gebi('search' + in_ext + '-highway').value;
  vals['city'] = (gebi('search' + in_ext + '-city') == null)? '' : gebi('search' + in_ext + '-city').value;
//  vals['area'] = (gebi('search' + in_ext + '-area') == null)? '' : gebi('search' + in_ext + '-area').value;
  vals['time'] = (gebi('search' + in_ext + '-time') == null)? '' : gebi('search' + in_ext + '-time').value;
  vals['mkad'] = (gebi('search' + in_ext + '-mkad') == null)? '' : gebi('search' + in_ext + '-mkad').value;
  
  if (gebi('mesure_metre')) {
    var values = '&rooms=' + vals['rooms'];
    values += '&build=' + vals['build'];
    values += '&realty=' + vals['realty'];
    values += '&region=' + vals['region'];
    values += '&metro=' + vals['metro'];
    values += '&highway=' + vals['highway'];
    values += '&city=' + vals['city'];
//    values += '&area=' + vals['area'];
    values += '&time=' + vals['time'];
    values += '&mkad=' + vals['mkad'];
  } else {
    var values = '&val_rooms=' + vals['rooms'];
    values += '&val_realty=' + vals['realty'];
    values += '&val_region=' + vals['region'];
    values += '&val_metro=' + vals['metro'];
    values += '&val_highway=' + vals['highway'];
    values += '&val_city=' + vals['city'];
//    values += '&val_area=' + vals['area'];
    values += '&val_time=' + vals['time'];
    values += '&val_mkad=' + vals['mkad'];
  }
  //alert(values);
  return values;
}

/**
 * Возвращает тип недвижимости.
 *
 * in_el (object) селект с недвижимостью.
 * return (int) тип недвижимости: 0 - загородная, 1 - городская, 2 - коммерческая.
 */
function _getTypeBuild(in_el) {
  var extra = gebi('build-' + in_el.value).value;
  var type = gebi('idtypes-extra-' + extra).value;
  return type;
}

/**
 * Возвращает значение типа из types по айди из search.
 */
function _getValueType(in_el) {
  var extra = gebi('build-' + in_el.value).value;
  var val = gebi('idtypes-value-' + extra).value;
  return val;
}

/**
 * Обновляет интерфейс поиска в селектах данными, полученными от сервера.
 *
 * in_req объект запроса.
 * return ничего в случае успеха или сообщение об ошибке в случае неудачи. 
 */
function updateSearch(in_req) {
  if (in_req.readyState == 4) {
    if (in_req.status == 200) {
      // Активируем кнопку "Поиск".
      _disabledSelects('', false, true);

      //alert(in_req.responseText);
      /*var div = ce('div');
      div.innerHTML = in_req.responseText;
      gebtn('body')[0].appendChild(div);*/
      
			var xmlDoc = in_req.responseXML;
			in_req = null;
			// Просматриваем содержимое XML-элементов <el>.
      var el = xmlDoc.getElementsByTagName('el');
      for (var i = 0; i < el.length; i++) {
        if (el[i].getAttribute("id") != null) {
          for (var j = 0; j < el[i].childNodes.length; j++) {
            var childEl = el[i].childNodes[j];
            if (childEl.nodeValue == null) {
              // Преобразуем XML-элемент в HTML.
              var node = XMLtoDocument(childEl);
              switch (el[i].getAttribute("id")) {
                // Выводим селект для региона.
                case 'region':
                  rc(gebi('search-region-span'), gebi('search-region'),  node);
                  gebi('search-region').onchange = function() {getSearchRegion(this);};
                  break;
                  
                // Выводим селект для метро|шоссе|районов|городов региона.
                case 'region-result':
                  gebi('search-region-result').innerHTML = "";
                  gebi('search-region-result').appendChild(node);
                  if (node.id == "search-area" || node.id == "search-city" || node.id == "search-highway") {
                    gebi('search-time-mkad').innerHTML = "";
                  }
                  gebi("search-city").disabled = in_array(gebi("search-region").value, [REGION_ALL, REGION_MOSCOW_AND_OBL, REGION_S_PETER_AND_OBL]);
                  break;
                  
                // Выводим селект для типов недвижимости.
                case 'realty':
                  gebi('rooms-realty').innerHTML = "";
                  gebi('rooms-realty').appendChild(node);
                  break;
                
                // Выводим количество комнат.
                case 'rooms':
                  gebi('rooms-realty').innerHTML = "";
                  var text = (gebi('rooms')) ? gebi('rooms').value + ' ' : "Количество комнат ";
                  gebi('rooms-realty').appendChild(ctn(text));
                  gebi('rooms-realty').appendChild(node);
                  break;
    
                // Выводим время в пути от метро.
                case 'time':
                  if (gebi('search-time') == null) {
                    gebi('search-time-mkad').innerHTML = (gebi('frommetro')) ? gebi('frommetro').value + ' ' : "&nbsp;От метро ";
                    gebi('search-time-mkad').appendChild(node);
                  }
                  break;
    
                // Выводим расстояние от МКАД.
                case 'distance-mkad':
                  if (gebi('search-mkad') == null) {
                    gebi('search-time-mkad').innerHTML = (gebi('frommkad')) ? gebi('frommkad').value + ' ' : "&nbsp;От МКАД ";
                    gebi('search-time-mkad').appendChild(node);
                  }
                  break;
              }
            }
          }
        }
      }
    } else alert(gebi('err_browser').value);
  }
}

/**
 * Изменяем интерфейс поиска при смене значения в селекте region.
 * 
 * in_el элемент. 
 */
function getSearchRegion(in_el) {
  // Получаем текущие значения из селектов популярного поиска в виде строки.
  var values = _getValuesSearch('') + '&select=region';
  var url = "/search/request.php";
  // Определяем тип недвижимости.
  var extra = _getTypeBuild(gebi('search-build'));
  var data = 'type=region_result&extra=' + extra;
  data += values;
  //alert(data);
  request['search-region'] = createRequest();
  request['search-region'].onreadystatechange = function() {updateSearch(request['search-region']);};
  sendRequest(request['search-region'], url, values);
  _disabledSelects('', true, false);
}

/**
 * Отправляет запрос серверу.
 * 
 * in_req объект запроса.
 * in_url адрес скрипта на сервере, которы обрабатывает наш запрос.
 * in_data данные, передаваемы серверу, чтобы получить нужный нам селект. 
 * in_type Тип данных.
 */
function sendRequest(in_req, in_url, in_data, in_type, method) {
  var method = method ? method : 'POST'
  in_req.open(method, in_url, true);
  type = (!in_type) ? 'application/x-www-form-urlencoded' : in_type;
  in_req.setRequestHeader('Content-type', type+'; charset=windows-1251');
  in_req.send(in_data);
}

// Функция выдаёт объект с указанным
// ей названием.
// Вход:
// myid - название объекта
// Выход: объект.
function getelementbyid(myid)
{
	if (isNS4)
	{
		 objElement = document.layers[myid];
	}
	else if (isIE4)
	{
		objElement = document.all[myid];
	}
	else if (isIE5 || isNS6)
	{
	 objElement = document.getElementById(myid);
	}
	return(objElement);
}

//
function select_option(arr, s_name, obl)
{
	if(!gebi(s_name)) return;
	getelementbyid(s_name).options.length = 0;
	for (i = 0; i < arr.length/3; i++)
	{
		if (arr[3*i] == obl)
		{
			getelementbyid(s_name).options[getelementbyid(s_name).options.length] = new Option(arr[3*i+2], arr[3*i+1]);
		}
	}
}
//смена метро и шоссе
function hide_show(id_el)
{
	var i;
	var id_len = id_el.length;
	
	for (i = 0; i < id_len; i++)
	{
		if (document.getElementById(id_el[i]).style.display == "none")
		{
			document.getElementById(id_el[i]).style.display = "";
		}
		else
		{
			document.getElementById(id_el[i]).style.display = "none";
		} 
	}
	
	return false;
}

// все цифры
function AllDig(t)
{
	var c;
	if (t.Length == 0)
	{
		return false
	}
	
	for (var i = 0; i< t.length; i++)
	{ 
		c = t.charCodeAt(i);
		if ((c < 48) || (c > 57))
		{
			return false
		}
	}
	return true
}

function IsValidEmail (email)
{
	return (/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,4}$/i).test(email);
}

/**
 * проверка на целое число 
 **/
function GoodInteger(t)
{
	if (AllDig(t)) 
	{
		if (isNaN(t))
		{
			return -1;
		}
		else
		{
			return t * 1;
		}
	} 
	else
	{
		return -1;
	}
}

function RepComma(s)
{
	return s.replace(",", ".") 
}

function GoodReal(t)
{
	t = RepComma(t);
	if (isNaN(t))
	{
		return -1
	}
	else
	{
		return t*1
	}
}

function trim(s)
{
	return rtrim(ltrim(s));
}

function ltrim(s)
{
  return s.replace(/^\s+/, ''); 
}

function rtrim(s)
{
  return s.replace(/\s+$/, ''); 
}


function GoodRus(s)
{
	s = trim(s);
	s_len = s.length
	for (var i = 0; i < s_len; i++)
	{ 
		c = s.charCodeAt(i);
		if ((c < 192) && (c != 32))
		{
			return "";
		} 
	}
	return s;
}

function InDiap(t, d1, d2)
{
	rr = ((t >= d1) && (t <= d2));
	return rr;
}

function Eq(t, d)
{
	return (t == d);
}

function IsGoodAddress(s)
{
	s = trim(s);
	for (var i = 0; i< s.length; i++)
	{ 
		c = s.charCodeAt(i);
		r = (c>192)
		  || InDiap(c, 48, 57)
		  || InDiap(c, 32, 33)
		  || Eq(c, 39)
		  || Eq(c, 10)
		  || Eq(c, 13)
		  || InDiap(c, 40, 47)
		  || InDiap(c, 58, 59)
		  || Eq(c, 63)
		  || Eq(c, 95) ;
		if (!r)
		{
			return false;
		}
	}
	return true
}

function IsGoodBldg(s)
{
	s = trim(s);
	var s_len = s.length;
	for (var i = 0; i < s_len; i++)
	{ 
		c = s.charCodeAt(i);
		r = (c > 192) // русские буквы
		  || InDiap(c, 48, 57) // 0-9
		  || Eq(c, 32) // пробел
		  || Eq(c, 44) // запятая
		  || Eq(c, 45) // тире
		  || InDiap(c, 46, 47) // точка, слэш 
		  ;
		if (!r)
		{
			return false;
		}
	}
	return true
}

function IsGoodPassword(s)
{ 
	s = trim(s);
	for (var i = 0; i< s.length; i++)
	{ 
		c = s.charCodeAt(i);
		r = ((c >= 48) && (c <= 57)) 
		|| ((c >= 65) && (c <= 122)) 
		|| (c == 95) 
		|| (c == 45); 
		if (!r)
		{
			return false;
		} 
	}
	return true
}

//разное от Бориса
var curdate = date_arr();// Текущая календарная дата на компьютере
// пользователя
var lastdate = date_arr();// Последняя выбранная дата
var firstdate = new Array(0, 4, 0, 2008);// Крайняя дата - начало отсчёта дат
var spa = '<img src="../_img/spacer.gif">';// Спейсер
var montsn = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);// Число
// дней
// в
// месяцах
var monts = new Array("Январь", "Февраль", "Март", "Апрель", "Мая", "Июнь",
		"Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"); // Названия
// всех
// месяцев
var link_s1 = "/news/news.php?"; // URL
var link_s2 = "day="; // Число
var link_s3 = "&mon="; // Месяц
var link_s4 = "&year="; // Год

// Инициируем массив, в котором будем хранить даты, когда новость есть
var news = new Array(10); // На 10 лет вперёд (если что - поправить надо на
// больше число лет)
for ( var i = 0; i < news.length; i++) {
	news[i] = new Array(12);
	for ( var j = 0; j < news[i].length; j++) {
		news[i][j] = new Array(31);
		for ( var k = 0; k < news[i][j].length; k++) {
			news[i][j][k] = false;
		}
	}
}

var GlassWindow = null;
// Добавляет прозрачность элементу
function opacityuniv(elen, op) {
	with (elen.style) {
		opacity = op / 100;
		moz = "+" + (op / 100); /* для старых браузеров на основе Gecko */
		filter = "alpha(opacity=" + op + ")"; /* Для IE6&7 */
	}
}

function onResizeact() {
	// Изменение размера окна
	var cWidth = document.body.scrollWidth;
	document.getElementById("pabsmetro").style.left = (cWidth / 2 - 300) + 'px';
	document.getElementById("pabsmetro").style.top = '196px';
	if (document.getElementById("pabsmetro").style.display == "") {
		if (GlassWindow == null) {
			// на первом проходе создаем элемент - "полупрозрачный экран"
			GlassWindow = document.createElement('div');
			with (GlassWindow.style) {
				display = 'none';
				position = 'absolute';
				height = 0;
				width = 0;
				zIndex = 999;
				background = '#FFFFFF';
				opacityuniv(GlassWindow, 90);
				width = document.body.scrollWidth;
				height = document.body.scrollHeight;
				top = 0;
				left = 0;
			}
			document.body.appendChild(GlassWindow);
		}
	}
	GlassWindow.style.width = 0;
	GlassWindow.style.height = 0;
	GlassWindow.style.width = document.body.scrollWidth;
	GlassWindow.style.height = document.body.scrollHeight;
	GlassWindow.style.display = 'block';
}

function adddraw(idn) {
var N = 40;
var text = '<table border="0" cellspacing="0" cellpadding="0"><tr>';
for ( var i = 0; i < N; i++) {
text = text
+ "<td style='height:30px;width:1px;margin:0;' id='"
+ idn
+ '_'
+ +i
+ "'><img src='../_img/1px.gif' style='height:30px;width:1px;margin:0;'></td>";
}
document.getElementById(idn).innerHTML = text + "</tr></table>";
// opacityuniv(document.getElementById(idn), 0);

for ( var i = 0; i < N; i++) {
opacityuniv(document.getElementById(idn + '_' + i), i * 100 / (N))
}
}

function alldraw(id, Num) {
	for ( var j = 0; j < Num*2; j++) {
		adddraw(id + j)
	}
}

function isLeap(theYear) {
	// Проверяем высокосность года
	if (theYear % 400 == 0)
		return true;
	if (theYear % 100 == 0)
		return false;
	if (theYear % 4 == 0)
		return true;
	return false;
}

function left_m() {
	// Смещаемся на месяц назад
	lastdate[2]--;
	if (lastdate[2] < 0) {
		lastdate[2] = 11;
		lastdate[3]--;
	}
	gendates();
}

function right_m() {
	// Смещаемся на месяц вперёд
	lastdate[2]++;
	if (lastdate[2] > 11) {
		lastdate[2] = 0;
		lastdate[3]++;
	}
	gendates();
}

function date_arr() {
	// Сохраняем текущую системную дату в массив
	var t = new Date();
	var datac = new Array(t.getDay(), t.getDate(), t.getMonth(), t.getYear());
	if (datac[3] < 1000)
		datac[3] = datac[3] + 1900;
	return datac;
}

function setdate(ndate_arr) {
	// Устанавливаем дату из массива
	var new_date = new Date();
	new_date.setYear(ndate_arr[3]);
	new_date.setMonth(ndate_arr[2]);
	new_date.setDate(ndate_arr[1]);
	return new_date;
}

function free_href(elem) {
	elem.href = "javascript:;";
	elem.style.cursor = "default";
	return elem;
}

function set_href(elem, href) {
	elem.href = href;
	elem.style.cursor = "pointer";
	return elem;
}

function bigdate(d1, d2) {
	// Сравниваем даты, какая старше
	return (d1[1] > d2[1] && d1[2] >= d2[2] && d1[3] >= d2[3])
			|| (d1[2] > d2[2] && d1[3] >= d2[3]) || (d1[3] > d2[3]);
}

function gendates() {
	// Выводим месяц в календарь
	t = setdate(lastdate);
	document.getElementById('ym').innerHTML = monts[lastdate[2]] + " "
			+ lastdate[3];
	document.getElementById('ym').href = linkstr("", lastdate[2], lastdate[3])
	if (isLeap(t.getYear()))
		montsn[1] = 29;
	t.setDate(1);
	var tek = t.getDay();
	if (tek == 0)
		tek = 7;
	ld = lastdate[1];
	lastdate[1] = curdate[1];
	var right_link = document.getElementById('right_link');
	if (bigdate(curdate, lastdate)) {
		document.getElementById('right_but').src = "../_img/butt_right.gif";
		set_href(right_link, "javascript: right_m();");
	} else {
		document.getElementById('right_but').src = "../_img/butt_right_end.gif";
		free_href(right_link);
	}

	fd = firstdate[1];
	firstdate[1] = lastdate[1];
	var left_link = document.getElementById('left_link');
	if (bigdate(lastdate, firstdate)) {
		document.getElementById('left_but').src = "../_img/butt_left.gif";
		set_href(left_link, "javascript: left_m();");
	} else {
		document.getElementById('left_but').src = "../_img/butt_left_end.gif";
		free_href(left_link);
	}
	firstdate[1] = fd;
	for ( var i = 1; i <= 37; i++) {
		ids = 'd' + (i);
		document.getElementById(ids).innerHTML = "";
		document.getElementById(ids).className = "no";

		free_href(document.getElementById(ids));
	}
	for ( var i = 1; i <= montsn[lastdate[2]]; i++) {
		ids = 'd' + (tek + i - 1);
		document.getElementById(ids).innerHTML = spa + i;
		lastdate[1] = i;

		if (bigdate(curdate, lastdate)
				&& get_news(lastdate[1], lastdate[2], lastdate[3])) {

			t.setDate(i);
			dn = t.getDay();

			if (ld == i) {
				document.getElementById(ids).className = (((tek + i) % 7 == 0) || ((tek + i) % 7 == 1)) ? "lvs"
						: "l";
			} else {
				set_href(document.getElementById(ids), linkstr(i, lastdate[2],
						lastdate[3]));

				document.getElementById(ids).className = (((tek + i) % 7 == 0) || ((tek + i) % 7 == 1)) ? "vs"
						: "b";
			}

		} else {
			if (curdate[1] == i && curdate[2] == lastdate[2]
					&& curdate[3] == lastdate[3]) {

				if (ld !== curdate[1]) {
					set_href(document.getElementById(ids), linkstr(i,
							lastdate[2], lastdate[3]));
					document.getElementById(ids).className = "cur";
				} else {
					document.getElementById(ids).className = "cur1";
				}

			} else {
				document.getElementById(ids).className = (((tek + i) % 7 == 0) || ((tek + i) % 7 == 1)) ? "vs1"
						: "no";
			}
		}
	}
	lastdate[1] = ld;

}

function add_news(d, m, y) {
	// Добавляем дату с новостями
	news[y - firstdate[3]][m][d] = true;
}

function get_news(d, m, y) {
	// Проверяем, есть ли новости для даты
	return news[y - firstdate[3]][m][d];
}

function linkstr(d, m, y) {
	// Формируем URL для календаря
	return link_s1 + link_s2 + d + link_s3 + m + link_s4 + y;
}

function set_text_label(id, idl) {
	// Для указанного id станавливаем пропадающий текст в label из idl
	document.getElementById(id).onfocus = function() {
		document.getElementById(idl).className = "sea_labelnv";
	};
	document.getElementById(id).onblur = function() {
		if (document.getElementById(id).value == "") {
			document.getElementById(idl).className = "sea_label";
		}
	};
	document.getElementById(idl).className = "sea_label";
}
function set_text_label2(id, idl) {
	// Для указанного id станавливаем пропадающий текст в label из idl
	document.getElementById(id).onfocus = function() {
		document.getElementById(idl).className = "sea_labelnv";
	};
	document.getElementById(id).onblur = function() {
		if (document.getElementById(id).value == "") {
			document.getElementById(idl).className = "sea_label2";
		}
	};
	document.getElementById(idl).className = "sea_label2";
}
function set_text_label3(id, idl) {
	// Для указанного id станавливаем пропадающий текст в label из idl
	document.getElementById(id).onfocus = function() {
		document.getElementById(idl).className = "sea_labelnv";
	};
	document.getElementById(id).onblur = function() {
		if (document.getElementById(id).value == "") {
			document.getElementById(idl).className = "sea_label3";
		}
	};
	document.getElementById(idl).className = "sea_label3";
}
var GlassWindow = null;
// Добавляет прозрачность элементу
function opacityuniv(elen, op) {
	with (elen.style) {
		opacity = op / 100;
		moz = "+" + (op / 100); /* для старых браузеров на основе Gecko */
		filter = "alpha(opacity=" + op + ")"; /* Для IE6&7 */
	}
}
function onResizeact() {
	// Изменение размера окна
	var cWidth = document.body.scrollWidth;
	document.getElementById("pabsmetro").style.left = (cWidth / 2 - 300) + 'px';
	document.getElementById("pabsmetro").style.top = '196px';
	if (document.getElementById("pabsmetro").style.display == "") {
		if (GlassWindow == null) {
			// на первом проходе создаем элемент - "полупрозрачный экран"
			GlassWindow = document.createElement('div');
			with (GlassWindow.style) {
				display = 'none';
				position = 'absolute';
				height = 0;
				width = 0;
				zIndex = 999;
				background = '#FFFFFF';
				opacityuniv(GlassWindow, 90);
				width = document.body.scrollWidth;
				height = document.body.scrollHeight;
				top = 0;
				left = 0;
			}
			document.body.appendChild(GlassWindow);
		}
	}
	GlassWindow.style.width = 0;
	GlassWindow.style.height = 0;
	GlassWindow.style.width = document.body.scrollWidth;
	GlassWindow.style.height = document.body.scrollHeight;
	GlassWindow.style.display = 'block';
}

function closeact() {
	document.getElementById("pabsmetro").style.display = "none";
	GlassWindow.style.display = "none";
}
function openact() {
	document.getElementById("pabsmetro").style.display = "";
	onResizeact();
}

/**
 * проверка формы при регистрации 
 **/
function check_reg_form()
{
	var err = true;
	var max_len = 256;

	// логин
	if (getelementbyid('login').value == '')
	{ 
		getelementbyid('login_err').innerHTML = '<span class="red">Заполните поле логин</span>';
		err = false;
	}
	else
	{
		if (getelementbyid('login').value.length > max_len)
		{ 
			getelementbyid('login_err').innerHTML = '<span class="red">Длина адреса не должна превышать '+max_len+' символов</span>';
			err = false;
		}
		else
		{
			if (IsValidEmail(getelementbyid('login').value) == false)
			{ 
				getelementbyid('login_err').innerHTML = '<span class="red">e-mail введен неверно</span>';
				err = false;
			}
			else
			{
				getelementbyid('login_err').innerHTML = 'Адрес будет использоваться в качестве логина';
			}
		}
	}
	
	getelementbyid('pass').value = trim(getelementbyid('pass').value);
	
	// пароль\
	var pass_min_len = 6;
	var pass_max_len = 25;
	
	if (getelementbyid('pass').value == '')
	{
		if (err == true)
		{
			getelementbyid('pass_err').innerHTML = '<span class="red">Заполните поле пароля</span>';
		} 
		err = false;	
	}
	else
	{
		if (getelementbyid('pass').value.length < pass_min_len || getelementbyid('pass').value.length > pass_max_len)
		{
			if (err == true)
			{
				getelementbyid('pass_err').innerHTML = '<span class="red">Пароль должен быть не менее '+pass_min_len+' и не более '+pass_max_len+' символов</span>';
			}
			err = false; 
		}
		else
		{
			if (IsGoodPassword(getelementbyid('pass').value) == false)
			{
				getelementbyid('pass_err').innerHTML = '<span class="red">От '+pass_min_len+' до '+pass_max_len+' символов из списка: A-z, 0-9, _-</span>';
				err = false; 
			}
			else
			{
				getelementbyid('pass_err').innerHTML = 'От '+pass_min_len+' до '+pass_max_len+' символов из списка: A-z, 0-9, _-';
			}
		}
		
	}
	
	// подтверждение пароля
	getelementbyid('pass_pr').value = trim(getelementbyid('pass_pr').value);
	
	if (getelementbyid('pass_pr').value == '')
	{
		getelementbyid('pass_pr_err').innerHTML = '<span class="red">Заполните поле повторного пароля</span>';
		err = false;
	}
	else
	{
		getelementbyid('pass_pr_err').innerHTML='';
	}
	
	if (err == true)
	{
		if (getelementbyid('pass').value != getelementbyid('pass_pr').value)
		{
			getelementbyid('pass_err').innerHTML = '<span class="red">Поля должны совпадать</span>';
			getelementbyid('pass_pr_err').innerHTML = '<span class="red">Поля должны совпадать</span>';
			err = false;
		}
	}
	
	// код подтверждения
	if (getelementbyid('img_z').value == '')
	{
		getelementbyid('img_z_err').innerHTML = '<span class="red">Введите контрольные цифры</span>';
		err = false;
	}
	else
	{
		getelementbyid('img_z_err').innerHTML = '';
	}
	
	// пользовательское соглашение
	if (getelementbyid('ac').checked==false)
	{
		getelementbyid('ac_err').innerHTML = 'Прочитайте пользовательское соглашение';
		err = false;
	}
	
	if (err == true) gebi('registration').submit();
}


// проверка при смене мыла
function right_email()
{
	var err = true;
	
	if (getelementbyid('pass').value == '')
	{
		getelementbyid('err_pass').innerHTML = '<span class="red">Заполните поле пароля</span>';
		err = false;
	}
	else if (IsGoodPassword(getelementbyid('pass').value) == false)
	{
		getelementbyid('err_pass').innerHTML = '<span class="red">Пароль введен некорректно</span>';
		err = false;
	}
	else
	{
		getelementbyid('err_pass').innerHTML = '';
	}
		
	if (getelementbyid('new_email').value == '')
	{
		getelementbyid('err_new').innerHTML = '<span class="red">Заполните поле нового E-mail</span>';
		err = false;
	}
	else if (IsValidEmail(getelementbyid('new_email').value) == false)
	{
		getelementbyid('err_new').innerHTML = '<span class="red">E-mail введен некорректно</span>';
		err = false;
	}
	else
	{
		getelementbyid('err_new').innerHTML = 'Адрес будет использоваться в качестве логина';
	}
	
	if (getelementbyid('new_email_w').value == '')
	{
		getelementbyid('err_new_w').innerHTML = '<span class="red">Заполните поле повторения E-mail</span>';
		err = false;
	}
	else
	{
		getelementbyid('err_new_w').innerHTML = '';
	}
	
	if (err == true)
	{
		if (getelementbyid('new_email').value != getelementbyid('new_email_w').value)
		{
			getelementbyid('err_new').innerHTML = '<span class="red">Адреса эл. почты должны совпадать</span>';
			err = false;
		}
	}
	
	if (err == true)
	{
		gebi('form_email').submit();
	}
}

// проверка при смене пароля
function right_pass()
{
	var err = true;
	if (getelementbyid('old_pass').value == '')
	{
		getelementbyid('err_old_pass').innerHTML = '<span class="red">Введите старый пароль</span>';
		err = false;
	}
	else
	{
		getelementbyid('err_old_pass').innerHTML = '';
	}
	
	getelementbyid('new_pass').value = trim(getelementbyid('new_pass').value);
	if (getelementbyid('new_pass').value == '')
	{
		getelementbyid('err_new_pass').innerHTML = '<span class="red">Заполните поле пароля</span>';
		err = false;
	}
	else
	{
		if (getelementbyid('new_pass').value.length < 6)
		{
			getelementbyid('err_new_pass').innerHTML = '<span class="red">Пароль должен быть не менее 6 символов</span>';
			err = false;
		}
		else if (IsGoodPassword(getelementbyid('new_pass').value) == false)
		{
			getelementbyid('err_new_pass').innerHTML = '<span class="red">От 6 до 20 символов из списка: A-z, 0-9, _-</span>';
			err = false;
		}
		else
		{
			getelementbyid('err_new_pass').innerHTML = 'От 6 до 20 символов из списка: A-z, 0-9, _-';
		}
	}
	
	getelementbyid('new_pass_w').value = trim(getelementbyid('new_pass_w').value);
	if (getelementbyid('new_pass_w').value == '')
	{
		getelementbyid('err_new_pass_w').innerHTML = '<span class="red">Заполните поле повторного пароля</span>';
		err = false;
	}
	else
	{
		getelementbyid('err_new_pass_w').innerHTML = 'Пароли должны совпадать';
	}
	
	if (err == true)
	{
		if (getelementbyid('new_pass').value != getelementbyid('new_pass_w').value)
		{
			getelementbyid('err_new_pass').innerHTML = '<span class="red">Пароли должны совпадать</span>';
			getelementbyid('err_new_pass_w').innerHTML = '<span class="red">Пароли должны совпадать</span>';
			err = false;
		}
	}
	
	if (err == true)
	{
		gebi('form_pass').submit();
	}
}



function nextPage(s) {
	df = document.search_form;
	/*for (y=0; y<df["metro12[]"].length; y++) 
	{df["metro12[]"].options[y].selected=true;};
	for (y=0; y<df["citymoin[]"].length; y++) 
	{df["citymoin[]"].options[y].selected=true;};*/	
	df.action=s;
	df.submit();
};

function form_submit(name, act){
df = document[name];
df.action=act;
df.submit();
}



/*******************************************************************
 *              Построение схем метро, районов, шоссе              *
 *******************************************************************/


/**
 * Отмечает районы на карте, которые есть в переданном селекте.
 *
 * @param in_id_sel (string): айди селекта, который проверяется на наличие в нём районов.
 */
function checkMapCity(in_id_sel) {
  for (var i = 0; i < gebi(in_id_sel).options.length; i++) {
    var opt = gebi(in_id_sel).options[i];
    var isArea = opt.text.substr(opt.text.length - 3) == 'р-н' || in_array(opt.text, ['Балашиха', 'Домодедово', 'Химки']);
    if (isArea) gebi('mo' + opt.value).className = 'vid';
  }
}

/**
 * Добавляет в селект города из другого селекта для расширенного поиска.
 *
 * in_id1 (string): айди селекта, из которого необходимо перенести города.
 * in_id2 (string): айди селекта, в который необходимо перенести города. 
 */
function changeCitySelect(in_id1, in_id2) {
  if (gebi(in_id1).selectedIndex == -1 || gebi(in_id1).options.length == 0) return;
  // Выделенная опция.
  var opt = gebi(in_id1).options[gebi(in_id1).selectedIndex];
  // Определяем выбран ли район.
  var isArea = opt.text.substr(opt.text.length - 3) == 'р-н' || in_array(opt.text, ['Балашиха', 'Домодедово', 'Химки']);
  if (isArea && gebi('mo' + opt.value)) {
    // Выделяем район на карте.
    gebi('mo' + opt.value).className = (!gebi(in_id1).multiple) ? 'vid' : 'nevid';
  }
  var i = 0;
  var option_arr = new Array;
  // Определяем выделенные опции или опции принадлежащие выделенному району и переносим их.
  while (i < gebi(in_id1).options.length) {
    if (gebi(in_id1).options[i].selected == true || (isArea && opt.value == gebi(in_id1).options[i].value)) {
      if (gebi(in_id2).options.length > 0) {
        // Делаем вставку.
        _mergeSortCity(gebi(in_id2).options, gebi(in_id1).options[i]);
      } else {
        // Копируем выделенную опцию.
        gebi(in_id2).options.add(new Option(gebi(in_id1).options[i].text, gebi(in_id1).options[i].value));
        gebi(in_id2).options[gebi(in_id2).options.length - 1].id = gebi(in_id1).options[i].id;
      }
      // Удаляем опцию.
      gebi(in_id1).remove(i);
    } else i++;
  }
}

/**
 * Сортировка городов вставкой.
 *
 * @param in_array(array):
 * массив опций, в который необходимо вставить переданную опцию с городом.
 *
 * @param in_opt(object):
 * опция с городом, которую необходимо вставить в список.
 */
function _mergeSortCity(in_array, in_opt) {
 
  var arr = in_array;
  var o = in_opt;
  var len = arr.length;
  var left = 0;
  var right = len - 1;
  
  function _mSort(in_l, in_r) {
    
    var l = in_l;
    var r = in_r;
    var m = Math.ceil((l + r) / 2);
    
    ox_text = arr[m].text;
    ox_value = arr[m].value;
    ox_id = arr[m].id;
    
    //alert([l,r,m,ox_text]);
    
    do {
      
      while (ox_text > o.text && r != l) {
        
        //alert('1: сравниваемый - '+ox_text+', вставляемый - '+o.text+', л - '+l+', п - '+r+', с - '+m);
        r = m;
        m = Math.floor((l + r) / 2); 
        ox_text = arr[m].text;
        ox_value = arr[m].value;
        ox_id = arr[m].id;
        
      }
      
      while (ox_text < o.text && r != l) {
        
        //alert('2: сравниваемый - '+ox_text+', вставляемый - '+o.text+', л - '+l+', п - '+r+', с - '+m);
        l = m;
        m = Math.ceil((l + r) / 2);
        ox_text = arr[m].text;
        ox_value = arr[m].value;
        ox_id = arr[m].id;
        
      }
      
    } while (r - l > 1);
    
    if (arr[l].text > o.text) r = l;
    
    return r;
    
  }
  
  var x = _mSort(left, right);
  
  //alert(x);
  
  arr[len] = new Option('', '');
  arr[len].text = o.text;
  arr[len].value = o.value;
  arr[len].id = o.id;
  
  if (len == 1) {
    
    if (arr[0].text < o.text) {
      
      arr[len].text = o.text;
      arr[len].value = o.value;
      arr[len].id = o.id;
      
    } else {
      
      arr[len].text = arr[0].text;
      arr[len].value = arr[0].value;
      arr[len].id = arr[0].id;
      arr[0].text = o.text;
      arr[0].value = o.value;
      arr[0].id = o.id;
      
    }
    
  } else if (arr[x].text > o.text) {
    
    for (var i = len - 1; i >= x; i--) {
      
      arr[i + 1].text = arr[i].text;
      arr[i + 1].value = arr[i].value;
      arr[i + 1].id = arr[i].id;
  
      //alert(i + 1 + ' - ' + arr[i + 1].text);
      
    }
    
    arr[x].text = o.text;
    arr[x].value = o.value;
    arr[x].id = o.id;
    
    //alert(arr[x].text + ' done!');
    
  }
      
}

/**
 * Сбрасывает селект с отобранными городами в расширенном поиске.
 */
function resetSelectCity() {
  // Выделяем все опции в списке.
  for (var i = 0; i < gebi('search-ext-city2').options.length; i++) {
    gebi('search-ext-city2').options[i].selected = true; 
  }
  // Переносим города в левый список.
  changeCitySelect('search-ext-city2', 'search-ext-city1');
  // Очищаем карту.
  for (var i = 1; i < 40; i++) {
  	var id = 'mo' + i;
  	if (gebi(id)) {
  	 gebi(id).className = 'nevid';
    }
  }
}

/**
 * Добавляет или убирает из списка города, которые принадлежат выбранному району на карте области.
 *
 * in_id (string):
 * айди выбранной области на карте.
 */
function switchAreaMap(in_id) {
  // Убираем выделение с города в левом селекте.
  if (gebi('search-ext-city1').selectedIndex != -1) {
    gebi('search-ext-city1').options[gebi('search-ext-city1').selectedIndex].selected = false;
  }
  // Айди района, в котором находится город.
  var id_area = in_id.substr(2);
  // Айди селекта, из которого будет происходит перенос города.
  var id_sel_from = (gebi(in_id).className == 'nevid') ? 'search-ext-city1' : 'search-ext-city2';
  // Айди селекта, в который будет происходит перенос города.
  var id_sel_in = (gebi(in_id).className == 'nevid') ? 'search-ext-city2' : 'search-ext-city1';
  // Показываем или гасим выбранный район на карте области.
  gebi(in_id).className = (gebi(in_id).className == 'nevid') ? 'vid' : 'nevid';
  for (var i = 0; i < gebi(id_sel_from).options.length; i++) {
    if (gebi(id_sel_from).options[i].value == id_area) {
      // Выделяем опцию города, если он принадлежит выбранному району на карте. 
      gebi(id_sel_from).options[i].selected = true;
    }
  }
  // Переносим выделенные города в противоположный список.
  changeCitySelect(id_sel_from, id_sel_in);
}

/**
 * Начало отображения схемы области - показывает фон.
 */
function mapCity() {
  gebi('form-search-ext').style.visibility = 'hidden';
  topSearch = (gebi('search-back').style.visibility == 'visible') ? true : false;
  if (topSearch) gebi('search-request').style.visibility = 'hidden';
  var divEl = ce('div');
  divEl.setAttribute('id', 'search-citymapbg');
  divEl.className = 'search-ext-mapbg';
  gebtn('body')[0].appendChild(divEl);
  var dxScroll = (window.scrollX != null) ? window.scrollX : document.documentElement.scrollLeft; // для Chrome, IE
  divEl.style.width = gebtn('body')[0].offsetWidth + dxScroll + 'px';
  divEl.style.height = gebtn('body')[0].offsetHeight + 'px';
  var dOp = 10;
  var beginOp = 1;
  var finishOp = 50;
  var interTime = 2;
  var timer = 'search-ext-mapbg';
  var funcArr = {
    name: '_mapCityStep2',
    divbg: divEl,
    timer: timer
  };
  opacityVisible(divEl, dOp, beginOp, finishOp, interTime, timer, funcArr);
  checkMapCity('search-ext-city2');
}

/**
 * Второй шаг схемы области - показывает схему.
 */
function _mapCityStep2(in_array) {
  var divEl = in_array['divbg'];
  gebtn('body')[0].appendChild(gebi('kartamofon'));
  gebtn('body')[0].appendChild(gebi('kartamobg'));
  gebtn('body')[0].appendChild(gebi('kartamobord'));
  gebtn('body')[0].appendChild(gebi('kartamo'));
  gebtn('body')[0].appendChild(gebi('kartamomark'));
  // Показываем карту.
  gebi('kartamobg').className = 'vid';
  gebi('kartamofon').className = 'vid';
  gebi('kartamobord').className = 'vid';
  gebi('kartamo').className = 'vid';
  gebi('kartamomark').className = 'vid';
  // Центруем карту.
  timer_map = setInterval(function () {_setCenterCityMap()}, 1);
  var dOp = 10;
  var beginOp = 50;
  var finishOp = 100;
  var interTime = 2;
  var t = in_array['timer'];
  var funcArr = {
    name: '_mapCityStep3',
    divbg: divEl
  };
  opacityVisible(gebi('kartamofon'), dOp, beginOp, finishOp, interTime, t, funcArr);
}

/**
 * Центрует карту области и её фон.
 */
function _setCenterCityMap() {
  // Размеры большого изображения.
  var imgHeight = gebi('kartamo').offsetHeight;
  var imgWidth = gebi('kartamo').offsetWidth;
  var dyScroll = (window.scrollY != null) ? window.scrollY : document.documentElement.scrollTop; // для Chrome, IE
  var dxScroll = (window.scrollX != null) ? window.scrollX : document.documentElement.scrollLeft; // для Chrome, IE
  var winHeight = document.documentElement.clientHeight;
  var divTop = dyScroll + Math.round(winHeight / 2) - Math.round(imgHeight / 2);
  if (divTop < 0) divTop = 0;
  if (divTop + imgHeight + 50 > gebtn('body')[0].offsetHeight) divTop = gebtn('body')[0].offsetHeight - imgHeight - 50;
  divLeft = getCenterHorizontal(gebi('kartamo')) + dxScroll;
  // Бордюр.
  gebi('kartamobg').style.left = divLeft - 9 + 'px';
  gebi('kartamobg').style.top = divTop + 5 + 'px';
  // Фон карты.
  gebi('kartamofon').style.left = divLeft + 'px';
  gebi('kartamofon').style.top = divTop + 'px';
  // Подсветка районов.
  gebi('kartamobord').style.left = divLeft + 'px';
  gebi('kartamobord').style.top = divTop + 'px';
  // Текст карты.
  gebi('kartamo').style.left = divLeft + 'px';
  gebi('kartamo').style.top = divTop + 'px';
  // Разметка карты.
  gebi('kartamomark').style.left = divLeft + 'px';
  gebi('kartamomark').style.top = divTop + 'px';
  divEl = gebi('search-citymapbg');
  divEl.style.width = gebtn('body')[0].offsetWidth + dxScroll + 'px';
  divEl.style.height = gebtn('body')[0].offsetHeight + 'px';
}

/**
 * Устанавливаем обработчик события по клику не на схеме.
 */
function _mapCityStep3(in_array) {
  var divEl = in_array['divbg'];
  gebi('kartamobg').style.display = 'block';
  gebi('kartamofon').style.display = 'block';
  gebi('kartamobord').style.display = 'block';
  gebi('kartamomark').style.display = 'block';
  divEl.onclick = function () {_closeCityMap(divEl);};
  gebi('search-ext-city1').multiple = true;
}

/**
 * Закрывает карту - начинает процесс.
 */
function _closeCityMap(in_div) {
  gebi('search-ext-city1').multiple = false;
  var dOp = -10;
  var beginOp = 50;
  var finishOp = 1;
  var interTime = 2;
  var timer = (in_div.id == 'search-citymapbg') ? 'search-ext-mapstep' : 'search-ext-mapstep2';
  var funcArr = {
    name: '_closeCityMapStep2'
  };
  opacityVisible(in_div, dOp, beginOp, finishOp, interTime, timer, funcArr);
}

/**
 * Шаг 2. Гасит фон схемы.
 */
function _closeCityMapStep2(in_array) {
  gebi('kartamobg').style.display = 'none';
  gebi('kartamofon').style.display = 'none';
  gebi('kartamobord').style.display = 'none';
  gebi('kartamo').className = 'nevid';
  gebi('kartamomark').style.display = 'none';
  gebi('search-ext-citylist').appendChild(gebi('kartamofon'));
  gebi('search-ext-citylist').appendChild(gebi('kartamobg'));
  gebi('search-ext-citylist').appendChild(gebi('kartamobord'));
  gebi('search-ext-citylist').appendChild(gebi('kartamo'));
  gebi('search-ext-citylist').appendChild(gebi('kartamomark'));
  if (gebi('search-citymapbg')) rn(gebi('search-citymapbg'));
  if (gebi('search-citymapbg2')) rn(gebi('search-citymapbg2'));
  gebi('form-search-ext').style.visibility = 'visible';
  if (topSearch) gebi('search-request').style.visibility = 'visible';
  changeTopTextSearch();
  clearInterval(timer_map);
}

/**
 * Плавно подсвечивает или гасит район на карте области.
 * Для IE подсветка мгновенная без плавных переходов.
 *
 * @param in_id (string):
 * айди района.
 *
 * @param in_act(bool):
 * true - подсвечивает, false - убирает подсветку.
 */
function cityMapBorder(in_id, in_act) {
  if (isIE5) {
    var visi = (in_act) ? 'visible' : 'hidden';
    gebi(in_id).style.visibility = visi;
    return;
  }
  gebi(in_id).style.visibility = 'visible';
  var dOp = (in_act) ? 30 : -30;
  var beginOp = (in_act) ? 1 : 100;
  var finishOp = (in_act) ? 100 : 1;
  var interTime = 1;
  var timer = 'search-ext-mapborder' + in_id + in_act;
  opacityVisible(gebi(in_id), dOp, beginOp, finishOp, interTime, timer);
}

/**************************************************************************/


/**
 * гасит или включает кнопки для управления объявлениями и шаблонами поиска
 **/
function fade_offer_buttons(buttons)
{
	buttons.attr('disabled', 'disabled');
	
	$('table.adv_table input.check_offer, table.adv_table input.select_all_offer').bind('click',
		function()
		{
			var sel_all = $(this).parents('table.adv_table').find('.select_all_offer');
			var what_check = sel_all.val();
			var condition = what_check != 'all' ? '[name="' + what_check + '"]' : '' ;
			var all_checkbox = $('input.check_offer' + condition).length;
			var checked_checkbox = $('input.check_offer' + condition + ':checked').length;
			
			sel_all.attr('checked', (checked_checkbox < all_checkbox) ? false : true);
						
			var checked = $('input.check_offer:checked').length;
			if(checked > 0)
			{
				buttons.removeAttr('disabled');
			}
			else
			{
				buttons.attr('disabled', 'disabled');
			}
		}
	);
}

function check_all()
{
	$('table.adv_table input.select_all_offer').click(function(){
		var checked = $(this).is(':checked') ? true : false;
		var what_check = $(this).val();
		var condition = what_check != 'all' ? '[name="' + what_check + '"]' : '' ;
		$('table.adv_table input.check_offer' + condition).attr('checked', checked);
	});
}

/**
 * Добавляет поле для ввода варианта ответа в опросах 
 **/
function add_poll_field(action, poll_id)
{
	$('#add_answ').click(
		function()
		{
			var button = $(this);
			if(action == 1)
			{
				$.ajax({
					  type : 'POST'
					, url : '/poll/admin_ajax.php'
					, data : {action : 'add_answer', poll_id : poll_id}
					, beforeSend : function()
					{
						button.attr('disabled', true);
					}
					, success : function(last_id)
					{
						$('#vote_answers').append('<input name="poll_vote_answers['+last_id+']" class="poll_vote_answers" /><br />');
						$('#vote_answers input:last').focus();
						button.attr('disabled', false);
					}
				});
			}
			else
			{
				$('#vote_answers').append('<input name="poll_vote_answers[]" class="poll_vote_answers" /><br />');
				$('#vote_answers input:last').focus();
			}
			return false;
		}
	);
}

/**
 * Отправка письма 
 **/
function send_mail_form()
{
	var options = { 
		  beforeSubmit : showRequest  // pre-submit callback 
		, success : showResponse  // post-submit callback \
		, url : 'mail.php'
		, dataType : 'json'
	};
	 
	// устанавливаем обработчик на форму
	$('#message_form').submit(
		function()
		{ 
			// убираем сообщения об ошибках
			$('span.errors').hide();
			$(this).ajaxSubmit(options);
			return false; 
		}
	);
	
	// скрываем индикатор, сообщения и ошибки 
	$('#activity, .message, .errors').hide();
	
	/**
	 * функция вызываемая перед отправкой формы
	 * показывает индикатор 
	 */
	function showRequest()
	{
		//$('h4.message, span.errors').hide();
		$('#activity').fadeIn();
	}
	
	/**
	 * функция вызываемая после отправки формы
	 * выводит результат работы скрипта, скрывает индикатор
	 * @param {Object} responseText результат работы скрипта
	 * @param {Object} statusText статус ответа
	 */
	function showResponse(response, statusText)
	{
		if(statusText == 'success')
		{
			// если есть результат, выводим сообщение
			if(response.sucsess)
			{
				$('#result #'+response.sucsess).slideDown().delay(3000).slideUp().html();
				if(response.sucsess == 'mail_sent')
				{
					$('#message_form').clearForm();
					load_captcha();
				}
			}
			
			// если ошибки выводим сообщения радом с полями
			if(response.error)
			{
				$.each(response.error, function(i, val)
					{
						$('#'+i+' #'+val).fadeIn();
					}
				);
				$('#control_num').val('');
				load_captcha();
			}
		}
		$('#activity').fadeOut('slow');
	}
}

/**
 * сохраняет объект в отобранные 
 **/
function house_save_adv(in_id, in_build_type, in_action)
{
	$(function(){
		$.post(
			  '/advertisment/save.php'
			, {action : in_action, id : in_id, build_type : in_build_type}
			, function(response)
			{
				var resp = $(response);
				var res = resp.find('result').text();
				var count = resp.find('count').text();
				var src = title = action = '';
				
				if(res == 1)
				{
					src = $('#src_adv_saved').val();
					title = 'Удалить из отобранных';
					action = 'del';
				}
				else
				{
					src = $('#src_adv_add').val();
					title = 'Добавить в отобранные';
					action = 'add';
				}
				
				$('#house_save').html('<img src="'+src+'" onclick="house_save_adv('+in_id+', '+in_build_type+', \''+action+'\')" alt="'+title+'" title="'+title+'" />');
				var text = count > 0 ? '<a href="/advertisment/">' + gebi("msg_adv_selected").value + ': <span id="sel_ad_count">' + count + '</span></a>' : gebi("msg_adv_selected_no").value;
				$('#sel_ad').html(text);
			}
		);
	});
}

function highlight_adv()
{
	$(function()
	{
		$('table.adv_table tr:odd').addClass('odd');
		
		$('table.adv_table tr:not(.title)')
		.mouseover(function(){
			$(this).addClass('hover');
		})
		.mouseout(function(){
			$(this).removeClass('hover');
		});
	});
}

$(function(){
	var mailer = {
		
	};
	
	function show_hide_button(show)
	{
		if(show)
		{
			$('#buttons input').show();
			$('#activity').hide();
		}
		else
		{
			$('#buttons input').hide();
			$('#activity').show();
		}
	}
	$('#activity').hide();
	
	var remind_password_options = { 
		  url : '/sendmail/index.php?act=remind_password'
		, beforeSubmit : function(form_data)
		{
			if(form_data[0].name == 'login' && IsValidEmail(form_data[0].value) == false)
			{
				$('#login_err').html('<span class="red">Почтовый адрес указан некорректно</span>');
				return false;
			}
			else
			{
				show_hide_button(false);
				return true;
			}
		}  // pre-submit callback 
		, success : function(response, status)
		{
			show_hide_button(true);
			
			//$('#buttons').append('<br /> - '+status+' -');
			
			
			if(response.error)
			{
				$('#login_err').html('<span class="red">'+response.error+'</span>');
			}
			else
			{
				if(response.sucsess)
				{
					$('#content').html(response.sucsess);
					$('#buttons').hide();
				}
				else
				{
					if(!response)
					{
						$('#content').html('Почтовый сервер не отвечает. Если писмо не пришло, попробуйте ещё раз.');
						$('#buttons').hide();
					}
				}
			}
		}  // post-submit callback
		, dataType : 'json'
		
	};
	
	$("#content").ajaxError(
	function(event, request, settings)
	{
	   show_hide_button(true);
	   
	   $(this).html('Почтовый сервер не отвечает. Если писмо не пришло, попробуйте ещё раз. '+request+' '+event);
	   
	   $(this).append("<ul>event: ");
	   for(i in event)
	   {
			$(this).append("<li>"+i+ ' - ' + event[i] + "</li>");
	   }
	   $(this).append("</ul>");
	   
	   $(this).append("<ul>request:"+ request);
	  /* for(i in request)
	   {
			$(this).append("<li>"+i+ ' - ' + request[i] + "</li>");
	   }*/
	   $(this).append("</ul>");
	   
	   $(this).append("<ul>settings:");
	   for(i in settings)
	   {
			$(this).append("<li>"+i+ ' - ' + settings[i] + "</li>");
	   }
	   $(this).append("</ul>");
	   //append("<li>Error requesting page " + settings.url + "</li>");
	});

	
	$('#remind_password').submit(
		function()
		{
			$(this).ajaxSubmit(remind_password_options);
			
			return false;
		}
	);
});

load_captcha = function()
{
	$.getJSON(
		'/user/load_captcha.php'
		, function(response)
		{
			$('#captcha').attr('src', response.captcha_src);
		}
	);
}

$(function(){
	if(gebi('useful_hint'))
	{
		function Usful_hints()
		{
			var data = {
				hints : []
			};
			
			$('#usful_hints_data input').each(function(i, element)
			{
				data.hints[i] = {};
				data.hints[i].id = $(this).attr('id');
				data.hints[i].content = $(this).val();
			});
			
			this.num = $('#useful_hints_num').val();
			this.curent_num = 0;
			this.hints = data.hints;
		}
		
		var useful_hints = new Usful_hints();
				
		useful_hints.get_next_num = function()
		{
			var next_num = this.curent_num + 1;

			if(next_num > this.num - 1)
			{
				next_num = 0;
			}
			this.curent_num = next_num;
			
			return next_num;
		}
		
		useful_hints.get_hint = function(num)
		{
			if(this.hints[num].content != '')
			{
				useful_hints.show_hint(this.hints[num].content);
			}
			else
			{
				$.ajax({
				    dataType : 'json'
				  , type : 'GET'
				  , url : '/useful_hints/useful_hints.php?action=get_hint'
				  , data : {id : this.hints[num].id}
				  , beforeSend : function()
				  {
						useful_hints.show_hint('<div id="ajax"><img src="/styles/standard/img/ajax_circle.gif" alt="" /></div>');
				  }
				  , success : function(response)
					{
						useful_hints.show_hint(response.hint.content);
						useful_hints.hints[num].content = response.hint.content;
					}
				});
			}
		}
		
		useful_hints.show_hint = function(content)
		{
			$('#useful_hint').html(content);
			$('#useful_hints').fadeIn();
		}
		
		$('#next_hint').bind('click', function()
		{
			useful_hints.get_hint(useful_hints.get_next_num());
		}).hover(
			function()
			{
				$(this).attr('src', '/styles/standard/img/butt_refresh_on.png');
			},
			function()
			{
				$(this).attr('src', '/styles/standard/img/butt_refresh_off.png')
			}
		);

		useful_hints.get_hint(0);
	}
});

function log(str)
{
	if(window.console && console.log)
	{
		console.log(str);
	}
	else
	{
		//alert(str);
	}
}

/** Работаем с ценой и прочими полями, где необходимы разделители */
function getCaretPos(obj) {
	obj.focus();
	if (obj.selectionStart)
		return obj.selectionStart;
	else if (document.selection) {
		var range = 0 - document.selection.createRange().duplicate().moveStart(
				'character', -100000);
		return range;
	}
	return 0;
}

function setCaretPos(obj, Pos) {
	if (obj.setSelectionRange) {
		obj.setSelectionRange(Pos, Pos);
	} else {
		var g = obj.createTextRange();
		g.collapse(true);
		g.moveEnd("character", Pos);
		g.moveStart("character", Pos);
		g.select();
	}
}

function UpdatePrice(LastVal, Element) {
	if (Element.value !== "") {
		var CurrentVal = Element.value;
		if (LastVal || CurrentVal) {
			if (LastVal !== CurrentVal) {
				var CurrentPos = getCaretPos(Element);
				var Counter = 0;
				var NewVal = '';
				for ( var i = CurrentVal.length - 1; i >= 0; i--) {
					if (String("0123456789").indexOf(CurrentVal.substr(i, 1)) >= 0) {
						Counter++;
						if ((Counter > 1) && ((Counter - 1) % 3 == 0)) {
							NewVal = CurrentVal.substr(i, 1) + ' ' + NewVal;
							CurrentPos++;
						} else {
							NewVal = CurrentVal.substr(i, 1) + NewVal;
						}
					} else
						CurrentPos--;
				}
				if (NewVal !== CurrentVal)
					Element.value = NewVal;
				if ((CurrentPos > 0)
						&& (NewVal.substr(CurrentPos - 1, 1) == ' ')) {
					CurrentPos--;
				}
				setCaretPos(Element, CurrentPos);
			}
		}
	}
	return Element.value;
}

function format_price(Element) {
	var LastValGlobal = Element.value;
	setTimeout(function() {
		UpdatePrice(LastValGlobal, Element);
	}, 1);
}

function set_format_price(Element) {
	Element.onkeydown = function(e) {
		format_price(this);
		var keyCode = (document.all)? event.keyCode : e.which;
		if (keyCode == 46) {
			var cp = getCaretPos(this);
			if (this.value.substr(cp, 1) == ' ')
				setCaretPos(this, cp + 1);
		} else if (keyCode == 8) {
			var cp = getCaretPos(this);
			if (this.value.substr(cp - 1, 1) == ' ')
				setCaretPos(this, cp - 1);
		}
	};
	var LastValTimerIE = '23423423423';
	setInterval(function() {
		LastValTimerIE = UpdatePrice(LastValTimerIE, Element);
	}, 100);
}

function show_add_srch() {
  $('#img_arrow').toggleClass("srch_img_down srch_img_up");
  $('.srch_add_div').slideToggle('fast');
}
