var req;
var reqTimeout;
var name_is_unic = 1;
var duble_name = '';
var duble_link = '';

function showAddVoteForm() {
    if($("#vote").is(":visible")) 
    {
       $("#vote").hide();
    } 
    else 
    {
       $("#vote").show();
    }
}

function showAddress(name, address) {
      if (geocoder) {
          geocoder.getLatLng(address,
              function(point) {
                if (!point) {
                  //alert(address + " not found");
                } else {
                  map.setCenter(point, 13);
                  var marker = new GMarker(point);
                  map.addOverlay(marker);
                  GEvent.addListener(marker, "click", function() {
                       marker.openInfoWindowHtml(name + '<br />' + address); 
                  });
                }
              }
        );
      }
}

function showMainPhoto() {
    if(photoObj)
    {
        mainPhotoId = $(photoObj).attr("id");
        mainPhotoId = mainPhotoId.replace('thumb_', '');
        $("div.mainphoto").attr("style", "display:none");
        var href = $("div#mainphoto_" + mainPhotoId + ".mainphoto a").attr("href");
        $("div#mainphoto_" + mainPhotoId + ".mainphoto").attr("style", "display:block");
        $("a#zoom").attr("href", href);    
    }
}

    
$(function(){
  
  $(".thumb").hover(function() {
       photoObj = this;
       timeout_id = setTimeout(showMainPhoto, 500);   
  });
  
  $("#mainphoto").hover(function() {
      photoObj = false;
      clearTimeout(timeout_id);      
  }); 
    
  $("a.showAllStreet").click(function() {
      var hidestatus = $("p[style*=none]").text();
      if(hidestatus)
      {
          $("p.showlink a").html("Убрать пустые");
          $("p.nodisplay").attr("style", "display:block");    
      }
      else
      {
          $("p.showlink a").html("Показать все");
          $("p.nodisplay").attr("style", "display:none");
      }
           
      return false;
      
  });
  
    
  $("a[href*=.flv]").flowplayer("/js/flowplayer-3.1.5.swf", {
         clip: { autoPlay: false, autoBuffering: false }, 
         onFinish: function() { pageTracker._trackEvent('Videos', 'Play', location.href); }     
  });
  
  $("a.sort").click(function() {
      
      id = $(this).attr("id");
      
      if(id == 'price')
      {
          name = 'Цена';
          query = 'priceSort';       
          $("a#discount.sort").attr("style", "").html("Скидка");
          $("a#capacity.sort").attr("style", "").html("Вместимость");         
      }
      else if(id == 'discount')
      {
          name = 'Скидка';
          query = 'discountSort';
          $("a#price.sort").attr("style", "").html("Цена");
          $("a#capacity.sort").attr("style", "").html("Вместимость");
      }
      else if(id == 'capacity')
      {
          name = 'Вместимость';
          query = 'capacitySort';
          $("a#price.sort").attr("style", "").html("Цена");
          $("a#discount.sort").attr("style", "").html("Скидка");
      }
      else 
      {
          return false;
      }
      
      $(this).attr("style", "background: #E8E8E8");
      
      rel = $(this).attr("rel");
      
      if(rel == "inc")
      {
          var type = 1;
          $(this).attr("rel", "dec").html(name + " <img border='0' src='/images/inc.png'>");    
      }
      else
      {
          var type = 2;
          $(this).attr("rel", "inc").html(name + " <img border='0' src='/images/dec.png'>");
      }
      
      $.get("/ajax/saunSearch.php", query+'&type='+type, function(data){ 
          $('#result').html(data); 
      });
      
      return false;
      
  });
  
});

hs.graphicsDir = '/js/highslide/graphics/';
hs.align = 'center';
hs.transitions = ['expand', 'crossfade'];
hs.outlineType = 'rounded-white';
hs.fadeInOut = true;
//hs.dimmingOpacity = 0.75;

hs.addSlideshow({
    interval: 5000,
    repeat: true,
    useControls: true,
    fixedControls: 'fit',
    overlayOptions: {
        opacity: .75,
        position: 'bottom center',
        hideOnMouseOut: false
    }
});
hs.outlineType = 'rounded-white';
hs.wrapperClassName = 'draggable-header';

    
$(document).ready(function(){
if ($('#button').size()){

new AjaxUpload('#button', {
  action: '/ajax/ajaxUpload.php',
  name: 'photo',
  autoSubmit: true,
  responseType: false,
  onSubmit: function(file, extension) { $("#status").html('Загружаем ' + file); },
  onComplete: function(file, response) { $("#status").html(''); $("#files").html(response); }
});
}
});

function voteModerComment(vote_id)
{
    var qString = $("#ModerComment_"+vote_id).formSerialize();
    $.post("/ajax/saunVote.php", qString, function(data){ $('#moder_comment_'+vote_id).html(data) });        
}

function vote(saun_id) {
    var comment = $("#comment").val();
    var name = $("input[name=name]").val();
    var star1 = $("input[name=star1]:checked").val();
    var star2 = $("input[name=star2]:checked").val();
    var star3 = $("input[name=star3]:checked").val();
    var star4 = $("input[name=star4]:checked").val();

    if(name == '')
    {
        $("#error").html('<b>Укажите имя!</b>');
        return false;        
    }
    else if(comment == '')
    {
        $("#error").html('<b>Заполните поле для комментария!</b>');
        return false;
    }
    else if(comment.length < 10)
    {
        $("#error").html('<b>Комментарий должен быть более 10-ти символов!</b>');
        return false;
    }
    else if(!star1 || !star2 || !star3 || !star4)
    {
        $("#error").html('<b>Проголосуйте за все параметры!</b>');
        return false;
    }
    else
    {
       $("#error").html(''); 
    }
    var qString = $("#voteForm").formSerialize();
    $.post("/ajax/saunVote.php", qString, function(data){ 
        $('#vote').html(data);
        $.get("/ajax/saunVote.php", 'saun='+saun_id, function(data){ $('#votes').html(data) });    
    });
}

function addSpecial()
{
   var qString = $("#specialForm").formSerialize();
   $.get("/ajax/saunSpecial.php", qString, function(data){ $('#result').html(data) }); 
}

function delSpecial(obj_type, obj_id, saun)
{
    $.get("/ajax/saunSpecial.php", 'del&obj_type='+obj_type+'&obj_id='+obj_id+'&saun='+saun, function(data){ $('#spec_'+saun).html(data) });    
}

function delContext(obj_type, obj_id, saun)
{
    $.get("/ajax/saunSpecial.php", 'del&obj_type='+obj_type+'&obj_id='+obj_id+'&saun='+saun, function(data){ $('#cont_'+saun).html(data) });    
}

function delVote(id)
{
   $.get("/ajax/saunVote.php", 'del='+id, function(data){ $('#vote_'+id).html(data) }); 
}

function confirmVote(id)
{
   $.get("/ajax/saunVote.php", 'confirm='+id, function(data){ $('#vote_'+id).html(data) }); 
}

function yesVote(id)
{
   $.get("/ajax/saunVote.php", 'yes='+id, function(data){ $('#voteyn_'+id).html(data) }); 
}

function noVote(id)
{
   $.get("/ajax/saunVote.php", 'no='+id, function(data){ $('#voteyn_'+id).html(data) }); 
}

function loc_href(city)
{
    document.location.href = '/'+city+'/';
}

function select_metro(metro)
{
    document.location.href = '/moskva/metro_'+metro+'/';
}

function select_metro_sbp(metro)
{
    document.location.href = '/sankt-peterburg/metro_'+metro+'/';
}

function getBlogCode()
{
    $("#getBlogCode").show("slow");
}

function getSuggestComment()
{
    $("#getSuggestComment").show("slow");
}

/*
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
*/

function getRayonGA(id) {
    $.get("ajaxGArayon.php", 'rayon='+id, function(data){ $('#rayonga').html(data); });
    return false;
}

function past_date(date) {
    document.forms['saun'].elements['date'].value=date;
}

 /*
try {
var pageTracker = _gat._getTracker("UA-8038466-2");
pageTracker._trackPageview();
} catch(err) {}
*/

function loadXMLDoc(url) {
    req = null;
    if (window.XMLHttpRequest) {
        try {
            req = new XMLHttpRequest();
        } catch (e){}
    } else if (window.ActiveXObject) {
        try {
            req = new ActiveXObject('Msxml2.XMLHTTP');
        } catch (e){
            try {
                req = new ActiveXObject('Microsoft.XMLHTTP');
            } catch (e){}
        }
    }

    if (req) {
        req.onreadystatechange = processReqChange;
        req.open("GET", url, true);
        req.send(null);
        reqTimeout = setTimeout("req.abort();", 5000);
    } else {
    }
}

function processReqChange() {

    if (req.readyState == 4) {
        clearTimeout(reqTimeout);

        // only if "OK"
        if (req.status == 200) {
            response=req.responseText.split('=>');
            if (response[0] == 'cap')
            {
             if (response[1] == 'bad')
             {
              document.getElementById("cap_error").style.display = "";
              document.getElementById("code_wrong").value = "1";
             }
             else
             {
              document.getElementById("cap_error").style.display = "none";
              document.getElementById("code_wrong").value = "0";

             }
            }
            else if (response[0] == 'city')
            {
             if (response[1] == 'good')
             {
              document.getElementById("saunselect").innerHTML = response[2];
             }
             else
             {
              document.getElementById("saunselect").innerHTML = 'Доступных саун нет. Хотите <a href="/add/">добавить сауну</a>?';
             }
            }
            else if (response[0] == 'name')
            {
             if (response[1] == 'good')
             {
              name_is_unic = '1';
             }
             else
             {
              name_is_unic = '0';
              duble_name = response[2];
              duble_link = response[3];
             }
            }
            else
            {
             alert(response);
            }
        }
    }
}
function enable_comment()
{
 document.getElementById("editor_textarea").disabled=false;
 document.getElementById("code").disabled=false;

}
function change_city(city, order)
{
 document.location = '/' + city + '/' + order + '/';
}
function city_saun(id)
{
 if (id != 0 && id != '-')
 {
  document.getElementById("saunselect").innerHTML = '<img width="300" src="/i/ajax-loader.gif">';
 loadXMLDoc('http://www.hots.ru/ajax_city.php?id='+id);
 }
}


var curphotos = 10;
function morephoto(tmpid)
{
 if (curphotos <= 100)
 {
  var obj = document.getElementById("photo_"+curphotos);
  obj.style.display="";
  var children = obj.childNodes;
  for (var i = 0; i < children.length; i++)
  {
   children[i].src="http://www.hots.ru/upload.php?id="+tmpid;
  }
 }
 curphotos = curphotos + 5;
 return false;
}

function cap_wait()
{
 capsTimeOut = setTimeout("cap_check()", 100);

}
function cap_check()
{
 var str = document.getElementById("code").value;
 if (str.length == 5)
 {
  loadXMLDoc('http://www.hots.ru/cap_check.php?str='+str);
 }
}
function check_name_unic(name)
{
 if (name != '')
 {
  var name = escape(name);
  loadXMLDoc('http://www.hots.ru/ajax_check_name_unic.php?name='+name);
 }
}

function ByName(name)
{
 return  document.getElementsByName(name)[0];
}

function add_saun_check(checkLogin)
{
 var error = '';
 if (checkLogin)
 {
    if (ByName("login").value == '')
    {
        error += '- Укажите ваш логин или <a href="/forum/register.php">зарегистрируйтесь</a><br>';
    }
    if (ByName("password").value == '')
    {
        error += '- Укажите ваш пароль<br>';
    }
    if (ByName("email").value == '')
    {
        error += '- Укажите ваш e-mail<br>';
    }
 }
 if (name_is_unic == '0')
 {
  error += '- Сауна <a target="_blank" href="/'+duble_link+'/">'+duble_name+'</a> уже существует на сайте. Если вы - ее владелец, свяжитесь с администрацией и вам будет открыт доступ к редактированию ее информации.<br>';
 }
 if (ByName("contphone").value == '')
 {
  error += '- Укажите контактный номер телефона <br>';
 }
 if (ByName("contname").value == '')
 {
  error += '- Укажите ваше ФИО <br>';
 }
 if (document.getElementById("name1").value == '')
 {
  error += '- Укажите название сауны <br>';
 }
 if (ByName("phone").value == '')
 {
  error += '- Укажите телефон сауны<br>';
 }
 if (document.getElementById("add_city").value == '0' || document.getElementById("add_city").value == '-')
 {
  error += '- Выберите город <br>';
 }
 if (document.getElementById("add_city").value == 'add' && document.getElementById("newcity").value=='')
 if (ByName("code_wrong").value == '1')
 {
  error += '- Проверочный код не совпадает <br>';
 }
 if (totalzal == 0)
 {
  error += '- Вы должны указать хотя бы один зал<br>';
 }
 if (ByName("cdata").value.length < 20)
 {
  error += '- Заполните описание сауны (минимум 20 символов)<br>';
 }

 if (error != '')
 {
  error = '<b>Во время заполнения формы были допущены ошибки:</b><br><br>' + error;
  document.getElementById("error_box").innerHTML = error;
  document.getElementById("error_box").style.display = '';
  document.location="#";
  return false;
 }
 else
 {
  return true;
 }
}

function add_saun_check_2()
{
 var error = '';
 if (ByName("contphone").value == '')
 {
  error += '- Укажите контактный номер телефона <br>';
 }
 if (ByName("contname").value == '')
 {
  error += '- Укажите ваше ФИО <br>';
 }
 if (document.getElementById("editname").value == '')
 {
  error += '- Укажите название сауны <br>';
 }
 if (ByName("phone").value == '')
 {
  error += '- Укажите телефон сауны<br>';
 }
 if (document.getElementById("editcity").value == '0' || document.getElementById("editcity").value == '-')
 {
  error += '- Выберите город <br>';
 }

 if (totalzal == 0)
 {
  error += '- Вы должны указать хотя бы один зал<br>';
 }
 if (error != '')
 {
  error = '<b>Во время заполнения формы были допущены ошибки:</b><br><br>' + error;
  document.getElementById("error_box").innerHTML = error;
  document.getElementById("error_box").style.display = '';
  document.location="#";
  return false;
 }
 else
 {
  return true;
 }
}

/* ######## EDITOR FUNCTIONS ######## */

//get position of the carret
function getCaretPos(obj)
{
   //obj = textarea obj.

   obj.focus();
   if(obj.selectionStart)
      return obj.selectionStart;//Gecko
   else if (document.selection)//IE
   {
      var sel = document.selection.createRange();
      var clone = sel.duplicate();
      sel.collapse(true);
      clone.moveToElementText(obj);
      clone.setEndPoint('EndToEnd', sel);
      return specLength(clone.text);
   }
   return 0;
}
function specLength(val)
{
 // Special length function.
 // IE should consider line feed (\r\n) for 1 sign.
 // Mozilla use \n sign for line feed, but in our BBcodes
 // we have an '\r\n' construction, which considered by Moz. for 2 signs.
 // We will use this function instead of 'length' property every time in IE,
 // and some times in Mozilla (when we will need to count length of BBcode whith \r\n)
 return val.replace(/\r\n/g, '_').length;
}
function evalthis(val)
{
 eval(val);
 return false;
}
function doInsertCode(obj,opentag,closetag,type)
{
   //obj = textarea obj.
   //opentag,closetag = [tag] [/tag]
   //replace = text, which will replase selection
   //reptype = around (set tags around of selection)
   //          replace (replace selection whith opentag+closetag)

   obj.focus();

   // REPLACE SELECTED TEXT
   // IE
   if (document.selection)
   {
      var s = document.selection;
      var r = s.createRange();
      if (r.text)
      {
       var replText = r.text;
       var selectionLen = specLength(replText);
       var newText = (type == 'around') ?  opentag+replText+closetag : opentag+closetag ;
       r.text = newText;
       // Select inner text of BBcode
       var selectionOffsetStart = specLength(opentag);
       var selectionOffsetEnd = (type == 'around') ? 0 - specLength(closetag) : 0;
       r = s.createRange();
       r.moveStart("character",selectionOffsetStart);
       r.moveEnd("character",selectionOffsetEnd);
       r.select();
	    }
	    else
	    {
	       var selectionEmpty = 1;
      }
   }
   // GECKO
   else if (typeof(obj.selectionStart)=="number")
   {
      if (obj.selectionStart!=obj.selectionEnd)
      {
         var start = obj.selectionStart;
         var end = obj.selectionEnd;
         var replText = obj.value.substr(start,end-start);
         var newText = (type == 'around') ?  opentag+replText+closetag : opentag+closetag ;
         obj.value = obj.value.substr(0,start)+newText+obj.value.substr(end);

         // Select inner text of BBcode
         var newSelectionStart = start + specLength(opentag);
         var newSelectionEnd = (type == 'around') ? newSelectionStart + replText.length : newSelectionStart;//end + opentag.length;
         obj.setSelectionRange(newSelectionStart,newSelectionEnd);
         obj.focus();
      }
      else
	    {
	       var selectionEmpty = 1;
      }
   }
   // INSERT INTO CARET POS
   if (selectionEmpty == 1)
   {
      var caretPos = getCaretPos(obj);
      var text = opentag + closetag;
      var starttext = obj.value.replace(/\r\n/g, 'џ').substr(0, caretPos).replace(/џ/g, '\r\n'); // this need only for IE
      var endtext = obj.value.replace(/\r\n/g, 'џ').substr(caretPos, specLength(obj.value)).replace(/џ/g, '\r\n'); // this need only for IE
      obj.value = starttext + text + endtext;
      // Set caret betwen TAG's
      var caretOffsetStart = caretPos + specLength(opentag);

      //IE
      if (obj.createTextRange)
      {
         var len = specLength(starttext) + specLength(text) + specLength(endtext);
         var caretOffsetEnd = caretOffsetStart - len;
         s = obj.createTextRange();
         s.moveStart("character",caretOffsetStart);
         s.moveEnd("character",caretOffsetEnd);
         s.select();
      }
      //GECKO
      else
      {
         var caretOffsetEnd = caretOffsetStart;
         obj.setSelectionRange(caretOffsetStart,caretOffsetEnd);
         obj.focus();
      }
   }
}



function clickButton(id) // editor buttons handler
{

   var opentag;
   var closetag;
   var text;
   //initiaize global var 'editor'. Place textarea id there.
   editor = 'editor_textarea';
   //remember textarea scroll position
   var scrollTopCash = fetch_obj(editor).scrollTop;
   var scrollLeftCash = fetch_obj(editor).scrollLeft;

   var obj = fetch_obj(editor); //document.editor_form.editor_textarea;
   id = id.split('_');
   var rn = (id['2']) ? id['2'] : 0;
   var param = (id['3']) ? id['3'] : 0;
   id = id['1'];

   var textarea = fetch_obj(editor);

   //###################
   // Misc functions
   //###################
   if (id.substring(0,6) == 'scroll')
   {
    resizeTextarea(id);
   }

   //###################
   // BbCodes start here
   //###################
   if (id == 'B' || id == 'I' || id == 'U' || id == 'LEFT' || id == 'RIGHT' || id == 'CENTER' || id == 'LEFTBOX' || id == 'RIGHTBOX' || id == 'H')
   {
      var openRn = (rn == '1' || rn == '3') ? "\r\n" : '';
      var closeRn = (rn == '2' || rn == '3') ? "\r\n" : '';
      opentag = openRn+'['+id+']';
      closetag = '[/'+id+']'+closeRn;
      doInsertCode(obj,opentag,closetag, 'around');
   }
   if (id == 'IMG')
   {
      text = prompt('Введите URL изображения, или ID загруженного изображения:', 'http://');
      if (text)
      {
         opentag = '['+id+'="'+text+'"]';
         closetag = '[/'+id+']';
         doInsertCode(obj,opentag,closetag,'replace');
      }
   }
   if (id == 'URL')
   {
      text = prompt('Введите URL для данной ссылки', 'http://');
      //alert(text);
      if (text)
      {
         opentag = '['+id+'="'+text+'"]';
         closetag = '[/'+id+']';
         doInsertCode(obj,opentag,closetag,'around');
      }
   }
   if (id == 'MAIL')
   {
      text = prompt('Введите EMAIL', '');
      if (text)
      {
         opentag = '['+id+'="'+text+'"]';
         closetag = '[/'+id+']';
         doInsertCode(obj,opentag,closetag,'around');
      }
   }
   if (id == 'SIZE')
   {
      text = fetch_obj('editor_SIZE').value;
      if (text != '0')
      {
         opentag = '['+id+'="'+text+'"]';
         closetag = '[/'+id+']';
         doInsertCode(obj,opentag,closetag,'around');
         fetch_obj('editor_SIZE').value = '0';
      }
   }
   if (id == 'COLOR')
   {
      text = fetch_obj('editor_COLOR').value;
      if (text != '0')
      {
         opentag = '['+id+'="'+text+'"]';
         closetag = '[/'+id+']';
         doInsertCode(obj,opentag,closetag,'around');
         fetch_obj("editor_COLOR").style.background = text;
      }
   }
   if (id == 'BR')
   {
      opentag = '\r\n[BR]';
      closetag = '';
      doInsertCode(obj,opentag,closetag,'replace');
   }
   if (id == 'UpIMG')
   {
      opentag = '[IMG="'+param+'"]';
      closetag = '[/IMG]';
      doInsertCode(obj,opentag,closetag,'replace');
   }
   if (id == 'TABLE')
   {
      var str;
      var cel;
      str = prompt('Введите количество строк', '1');
      if (str)
      {
         cel = prompt('Введите количество столбцов', '1');
      }
      if (str && cel)
      {
         text = '\r\n[TABLE]';
         var x, y;
         for (x=1; x<=str; ++x)
         {
            text += '\r\n   [TR]';
            for (y=1; y<=cel; ++y)
            {
               text += '\r\n      [TD][/TD]';
            }
            text += '\r\n   [/TR]';
         }
         text += '\r\n[/TABLE]\r\n';

         opentag = text;
         closetag = '';
         doInsertCode(obj,opentag,closetag,'replace');
      }
   }
   //return textarea scroll to prev position
   fetch_obj(editor).scrollTop = scrollTopCash;
   fetch_obj(editor).scrollLeft = scrollLeftCash;
   return false;
}
function showHelp()
{
   var display = fetch_obj("helpBox").style.display;
   fetch_obj("helpBox").style.display = (display == 'none') ? '' : 'none';
   fetch_obj("helpLink").innerHTML = (display == 'none') ? 'Убрать помощь...' : 'Помощь...';
   return false;
}
function setHelp(id)
{
   id = id.split('_');
   id = id['1'];

   var helpArray = new Array();
   helpArray = {
   'B' : '<b>[B]</b>Жирный текст<b>[/B]</b><br>Текст, помещенный в этот тэг становится <b>жырным</b>',
   'I' : '<b>[I]</b>Наклонный текст<b>[/I]</b><br>Текст, помещенный в этот тэг становится <i>наклонным</i>',
   'U' : '<b>[U]</b>Подчеркнутый текст<b>[/U]</b><br>Текст, помещенный в этот тэг становится <u>подчеркнутым</u>',
   'H' : '<b>[H]</b>Заголовок<b>[/H]</b><br>Выделяет заголовок страницы',
   'BR' : '<b>[BR]</b><br>Создает перенос текста на следующую строку',
   'LEFT' : '<b>[LEFT]</b>Текст<b>[/LEFT]</b><br>Выравнивает текст помещенный внутрь по левому краю',
   'RIGHT' : '<b>[RIGHT]</b>Текст<b>[/RIGHT]</b><br>Выравнивает текст помещенный внутрь по правому краю',
   'CENTER' : '<b>[CENTER]</b>Текст<b>[/CENTER]</b><br>Выравнивает текст помещенный внутрь по середине',
   'LEFTBOX' : '<b>[LEFTBOX]</b>Текст<b>[/LEFTBOX]</b><br>Выравнивает текст помещенный внутрь по левому краю, при этом текст вне этого блока обеткает его справа',
   'RIGHTBOX' : '<b>[RIGHTBOX]</b>Текст<b>[/RIGHTBOX]</b><br>Выравнивает текст помещенный внутрь по правому краю, при этом текст вне этого блока обеткает его слева',
   'IMG' : '<b>[IMG="http://www.ru"]</b>Описание изображения ;0<b>[/IMG]</b><br>Вставляет в текст изображение со ссылкой, указанной в параметре. <br> Текст, заключенный между откр. и закр. тэгами является описанием изображения. Описание отображается прямо под иозбражением, и добавляется в тэг ALT для поисковиков. Если в конце описания установить параметр <B>;0</b> (точка с запятой и ноль), то описание изображения будет доступно только для поисковиков (не будет отображаться под картинкой).',
   'URL' : '<b>[URL="http://www.ru"]</b>Текст ссылки<b>[/URL]</b><br>Добавляет в текст ссылку. Адрес ссылки указывается в параметре, а текст ссылки между тэгами. Если текст ссылки пуст, то вместо него будет отображаться непосредственный адрес',
   'MAIL' : '<b>[MAIL="http://www.ru"]</b>Текст ссылки<b>[/MAIL]</b><br>Добавляет в текст емейл адрес. Адрес указывается в параметре, а текст адреса ссылки между тэгами. Если текст ссылки пуст, то вместо него будет отображаться непосредственный адрес е-мейл',
   'TABLE' : '<b>[TABLE]<br>&nbsp;[TR]<br>&nbsp;&nbsp;&nbsp;[TD]Строка1, Столбец1[/TD]<br>&nbsp;&nbsp;&nbsp;[TD]Строка1, Столбец2[/TD]<br>&nbsp;[/TR]<br>&nbsp;[TR]<br>&nbsp;&nbsp;&nbsp;[TD]Строка2, Столбец1[/TD]<br>&nbsp;&nbsp;&nbsp;[TD]Строка2, Столбец2[/TD]<br>&nbsp;[/TR]<br>[/TABLE]</b><br>Создает таблицу. Тэг TABLE является совокупностью всех тэгов [TR][/TR], находящихся внутри него, и являющихся строками таблицы. Тэг TR является совокупностью всех тэгов [TD][/TD], находящихся внутри него и являющихся стобцами(ячейками) строки. В таблице может быть неограниченное кол-во строк (TR), в которых может быть неограниченное число стобцов (TD). Весь текст, присутсвующий в таблице, должен раполосогаться ТОЛЬКО внутри тэгов TD.',
   'scrollInc' : 'Увеличить размер поля для ввода информации',
   'scrollDec' : 'Уменьшить размер поля для ввода информации'
   };
   fetch_obj("helpBox").innerHTML = helpArray[id];
   return false;
}

function uploadOk(id, name)
{
   //id = uploaded image ID
   //name = its name. We will display it to user interface.
   fetch_obj("editor_upload").reset();
   var add = ' - '+name+' <a href="#" onClick="insertBB(\'editor_UpIMG_0_'+id+'\'); return false;">(вставить в форму)</a> <a target="_blank" href="attach.php?id='+id+'">(посмотреть)</a><br />';
   if (fetch_obj("uploadedImg").innerHTML == 'Загруженных изображений нет')
   {
      fetch_obj("uploadedImg").innerHTML = add;
   }
   else
   {
      fetch_obj("uploadedImg").innerHTML +=add;
   }
}

function fetch_obj(idname)
{
 return document.getElementById(idname);
}

var temImg = new Image();
var gid;
var to;
var totalzal = 0;

function checkLoad() {
    if (!temImg.complete) {
        to = setTimeout("checkLoad()", 300);
    } else {
        clearTimeout(to);

        fetch_obj("mainphoto").src = temImg.src;
        fetch_obj('loader').style.display="none";
    }
}
function updatezalz(id, name)
{
 if (fetch_obj("zal_"+id))
 {
  fetch_obj("zal_"+id).innerHTML = "<a href=\"#\" onClick=\"childWindow = window.open('/room_edit.php?id="+id+"','new','width=800,height=600,toolbar=0,resizable=1,scrollbars=1,left=100,top=50,location=0'); return false;\">" + name + "</a> <img onClick=\"delete_zal('"+id+"')\" border=\"0\" src=\"/i/delete.gif\" style=\"cursor: pointer;\">";
 }
 else
 {
  if (totalzal > 0)
   fetch_obj("zalz").innerHTML += "<div id='zal_"+id+"'><a href=\"#\" onClick=\"childWindow = window.open('/room_edit.php?id="+id+"','new','width=800,height=600,toolbar=0,resizable=1,scrollbars=1,left=100,top=50,location=0'); return false;\">" + name + "</a>  <img onClick=\"delete_zal('"+id+"')\" border=\"0\" src=\"/i/delete.gif\" style=\"cursor: pointer;\"></div>";
  else
   fetch_obj("zalz").innerHTML = "<div id='zal_"+id+"'><a href=\"#\" onClick=\"childWindow = window.open('/room_edit.php?id="+id+"','new','width=800,height=600,toolbar=0,resizable=1,scrollbars=1,left=100,top=50,location=0'); return false;\">" + name + "</a>  <img onClick=\"delete_zal('"+id+"')\" border=\"0\" src=\"/i/delete.gif\" style=\"cursor: pointer;\"></div>";
  totalzal = totalzal + 1;
  fetch_obj("nextzal").innerHTML = totalzal + 1;
 }

 return false;
}
function showphoto(id) {
    fetch_obj('mainphoto_orign').href="/uploads/"+id+".jpg";
    fetch_obj('loader').style.display="block";
    gid = id;
    temImg.src="/uploads/big/"+id+".jpg";
    to = setTimeout("checkLoad()", 300);
}
function delete_zal(id) {
 if (confirm('Вы уверены что хотите удалить зал и всю информацию о нем?'))
 {
    var saun = fetch_obj("edit_tmpid").value;
    fetch_obj("zal_"+id).innerHTML = '';
    loadXMLDoc('http://www.hots.ru/room.php?delete='+id+'&saun='+saun);
 }
}
function ScreenHeight(){

  if(window.innerHeight){

    height = window.innerHeight;

  }   else if(document.documentElement && document.documentElement.clientHeight){

    height = document.documentElement.clientHeight;

  }   else if(document.body && document.body.clientHeight){

    height = document.body.clientHeight;

  }

  return height;

}

function showmetros(val)
{
if (val == '8')
 {
  document.getElementById("inp_metro").style.display = "none";
  document.getElementById("sel_metro_16").style.display = "none";
  document.getElementById("inp_metro_1").name = "inp_metro";
  document.getElementById("sel_metro_16_1").name = "sel_metro_16";


  document.getElementById("sel_metro_8").style.display = "";
  document.getElementById("sel_metro_8_1").name = "metro";
 }
 else if (val == '16')
 {
  document.getElementById("inp_metro").style.display = "none";
  document.getElementById("sel_metro_8").style.display = "none";
  document.getElementById("inp_metro_1").name = "inp_metro";
  document.getElementById("sel_metro_8_1").name = "sel_metro_8";

  document.getElementById("sel_metro_16").style.display = "";
  document.getElementById("sel_metro_16_1").name = "metro";
 }
 else
 {
  document.getElementById("inp_metro").style.display = "";

  document.getElementById("inp_metro_1").name = "metro";
  document.getElementById("sel_metro_8_1").name = "sel_metro_8";
  document.getElementById("sel_metro_16_1").name = "sel_metro_16";
  document.getElementById("sel_metro_8").style.display = "none";
  document.getElementById("sel_metro_16").style.display = "none";
 }
}

function readmore(obj, type)
{
 if (type == 'desc')
 {
  text1 = 'раскрыть описание сауны';
  text2 = 'скрыть описание сауны';
 }
 if (type == 'rooms')
 {
  text1 = 'раскрыть информацию по залам';
  text2 = 'скрыть информацию по залам';
 }

 var hidden = obj.parentNode.childNodes[3].style;
 tmp=(hidden.display!='block') ? 'block' : 'none';
 if (tmp == 'block')
 {
  obj.parentNode.childNodes[0].src= "/i/collapse.gif";
  obj.innerHTML = text2;
 }
 else
 {
  obj.parentNode.childNodes[0].src= "/i/collapsed.gif";
  obj.innerHTML = text1;
 }
 hidden.display=tmp;
 return false;
}

function selectSauns() {
	   $('sauncontainer').innerHTML = "<b>Загружается список саун...</b>";
       var url    = '/ajax_saun.php';
       var params = 'price=' + $F('price') + '&metro=' + $F('metro') + '&city=' + $F['city'];
       var ajax   = new Ajax.Updater(
                                       {success: 'sauncontainer'},
                                        url,
                                       {method: 'post',
                                        parameters: params,
                                        onFailure: reportError}
                                     );
}


function reportError(request) {
     $('sauncontainer').innerHTML = "Ошибка сервера.";
}



function compare(id) {
     
     $.get("/compare_control.php", 'id='+id, function(data){ $('#comparediv').html(data) });
     var value = $('#compare_label_' + id).text();
     if(value == 'добавить к сравнению')
     {
         $('#compare_label_' + id).text('убрать из сравнения');    
     }
     else
     {
         $('#compare_label_' + id).text('добавить к сравнению');
     } 
}

function compare_clean() {
	$.get("/compare_control.php", 'clean', function(data){ $('#comparediv').html(data) });
}

function loadstreets() {
       $('ul-street').innerHTML = "обновляется список улиц...";
       var url    = '/ajax_street.php';
       var params = 'street=' + $F('street'); 
       var ajax   = new Ajax.Updater(
                                       {success: 'ul-street'},
                                        url,
                                       {method: 'get',
                                        parameters: params,
                                        onFailure: $('ul-street').innerHTML = ''}
                                     );

       $('ul-street').style.display='block';
}

