function createRequest() {
  var request;
  try {
    request = new XMLHttpRequest();
  } catch (trymicrosoft) {
    try {
      request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (othermicrosoft) {
      try {
        request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (failed) {
        request = false;
      }
    }
  }
  return request;
}

function addoption(elm, name, value) {
  var opt = new Option(name, value);
  try {
    elm.add(opt);
  } catch (fuckie) {
    elm.add(opt, null);
  }
}

function clearselect(elm, text, disable) {
  for (i=elm.options.length-1; i>=0; i--) elm.options[i] = null;
  if (text != "") {
    addoption(elm, text, 0)
  }
  elm.disabled = disable;
}

function shcity(oid) {
 if (oid == -1) {
   var idcity = document.getElementById("user_id_city");
   var newcity = document.getElementById("f_user_new_city");
 } else if (oid) {
   var idcity = document.getElementById("id_city_o_"+oid);
   var newcity = document.getElementById("f_new_city_o_"+oid);
 } else {
   var idcity = document.getElementById("id_city");
   var newcity = document.getElementById("f_new_city");
 } if (idcity.value != "0")
    newcity.style.display = "none";
  else
    newcity.style.display = "inline";
}

function shproducer() {
 if (document.getElementById("id_producer").value != "0")
    document.getElementById("f_new_producer").style.display = "none";
  else
    document.getElementById("f_new_producer").style.display = "inline";
}

function shproducermodel() {
 if (document.getElementById("id_producer").value != "0")
    document.getElementById("tr_model_str").style.display = "";
  else
    document.getElementById("tr_model_str").style.display = "none";
}

function shpartscat() {
 if (document.getElementById("supercat-e").checked) {
    document.getElementById("partcat1").style.visibility = "hidden";
    document.getElementById("partsubcat1").style.visibility = "hidden";
    document.getElementById("catnum1").style.visibility = "hidden";
    document.getElementById("catnum2").style.visibility = "hidden";
 } else {
    document.getElementById("partcat1").style.visibility = "visible";
    document.getElementById("partsubcat1").style.visibility = "visible";
    document.getElementById("catnum1").style.visibility = "visible";
    document.getElementById("catnum2").style.visibility = "visible";
 }
}

function shpartscat2() {
 if (document.getElementById("supercat-e").checked) {
    document.getElementById("partcat1").style.display = "none";
    document.getElementById("partsubcat1").style.display = "none";
    document.getElementById("catnum1").style.display = "none";
    document.getElementById("partname1").style.display = "none";
    document.getElementById("partpower1").style.display = "none";
    document.getElementById("partpower2").style.display = "none";
    document.getElementById("year1").style.display = "";
 } else {
    document.getElementById("partcat1").style.display = "";
    document.getElementById("partsubcat1").style.display = "";
    document.getElementById("catnum1").style.display = "";
    document.getElementById("partname1").style.display = "";
    document.getElementById("partpower1").style.display = "";
    document.getElementById("partpower2").style.display = "";
    document.getElementById("year1").style.display = "none";
 }
}

function shcountry(def, oid) {
 if (oid == -1) {   var idc = document.getElementById("user_id_country");
   var trr = document.getElementById("tr_user_region");
 } else if (oid) {   var idc = document.getElementById("id_country_o_"+oid);
   var trr = document.getElementById("tr_region_o_"+oid);
 } else {
   var idc = document.getElementById("id_country");
   var trr = document.getElementById("tr_region");
 }
 if (idc.value != "1") {
    trr.style.display = "none";
 } else {
    trr.style.display = "";
 }
 loadcitylist(def, oid);
}

function shcountrymult() {
 try {
   if (!document.getElementById("id_country").options[1].selected) {     document.getElementById("td_region1").style.visibility = "hidden";
     document.getElementById("td_region2").style.visibility = "hidden";
   } else {     document.getElementById("td_region1").style.visibility = "visible";
     document.getElementById("td_region2").style.visibility = "visible";
   }
 } catch (err) {;}
}

function loadcitylist(def, oid) {
 if (oid == -1) {
   var idc = document.getElementById("user_id_country");
   var idr = document.getElementById("user_id_region");
   var idcity = document.getElementById("user_id_city");
   var newcity = document.getElementById("f_user_new_city");
 } else if (oid == -2) {
   var idc = {'value':1};
   var idr = document.getElementById("id_region");
   var idcity = document.getElementById("id_city");
   var newcity = true;
 } else if (oid) {
   var idc = document.getElementById("id_country_o_"+oid);
   var idr = document.getElementById("id_region_o_"+oid);
   var idcity = document.getElementById("id_city_o_"+oid);
   var newcity = document.getElementById("f_new_city_o_"+oid);
 } else {
   var idc = document.getElementById("id_country");
   var idr = document.getElementById("id_region");
   var idcity = document.getElementById("id_city");
   var newcity = document.getElementById("f_new_city");
 }
 if (!newcity) return false;

  if (typeof newcity == 'object') newcity.style.display = "none";
  var i = 0; var opt = false;
  var id_region = idr.value;
  var id_country = idc.value;
  clearselect(idcity, "Загрузка...", true);
  var request = createRequest();
  if (id_country == "1")
     var url = "/include/ajax.php?id_region=" + encodeURIComponent(id_region);
    else
     var url = "/include/ajax.php?id_country=" + encodeURIComponent(id_country);
  request.open("GET", url, true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      if (request.status == 200) {
        var resp = request.responseText;
        var optlist = resp.split("||");
        for (i=0; i < optlist.length; i++) {
          var idname = optlist[i].split("|");
          if (def == idname[0]) {            opt = new Option(idname[1], idname[0], true, true);
          } else {
            opt = new Option(idname[1], idname[0]);
          }
          try {
            idcity.add(opt);
          } catch (fuckie) {
            idcity.add(opt, null);
          }
        }
        idcity.options[0] = null;
        idcity.disabled = false;
        shcity(oid);
      }
    }
  }
  request.send(null);
}

function nicesubmit() { var ms = document.getElementById("mainsubmit");
 var msa = document.getElementById("mainsubmitarea");
 if (ms) {   ms.disabled = true;
   msa.innerHTML = 'Загрузка...';
 }
}

function tacount(textarea, span, maxcount) {
 var curlen = maxcount - textarea.value.length;
 if (curlen < 0) {    textarea.value = textarea.value.substr(0, maxcount);
    curlen = 0;
 }
 span.innerHTML = curlen;
 return true;
}

function disablegroup(elm, strbegin) {
 $("INPUT[id^="+strbegin+"]").attr("disabled", !elm.checked);
}

function tabswitch(id) {
 $("DIV[id^=tab-type-]:visible").hide();
 $("DIV#tab-type-"+id).show();
 $("A[id^=tab-caption-]").attr('class', 'r-inactive');
 $("A#tab-caption-"+id).attr('class', 'r-active');
}

function round2(num) {
 return Math.round(num*100)/100;
}

function onlynum(el){
 var v = el.value;
 var o = "";
 for (i=0; i <= v.length; i++){
   ch = v.charAt(i);
   if ((ch == '0') || (ch == '1') || (ch == '2') || (ch == '3') || (ch == '4') || (ch == '5') || (ch == '6') || (ch == '7') || (ch == '8') || (ch == '9')) o = o + ch;
 }
 el.value = o;
}
function onlyfloat(el){
 var v = el.value;
 var o = "";
 for (i=0; i <= v.length; i++){
   ch = v.charAt(i);
   if ((ch == '0') || (ch == '1') || (ch == '2') || (ch == '3') || (ch == '4') || (ch == '5') || (ch == '6') || (ch == '7') || (ch == '8') || (ch == '9')) o = o + ch;
   if ((ch == '.') || (ch == ',')) o = o + '.';
 }
 el.value = o;
}

function toggle_b(eid, defblock) {
 if (typeof(defblock) == 'undefined') defblock = 'block';
 if (document.getElementById(eid).style.display == 'none') {
   document.getElementById(eid).style.display=defblock;
 } else {
   document.getElementById(eid).style.display='none';
 }
}


function gotoselectsurl() {  var url="/";
  if (document.navform) {     for (var i=0; i <= 10; i++) {       if (document.getElementById("navurl_"+i)) {          var navarr = document.getElementById("navurl_"+i).value.split("|");
          if (typeof(navarr[4]) != 'undefined') url = url + navarr[4];
       }
     }
  }
  window.location = url;
}

function shurl(level, thiselm) {  for (var i=level+1; i <= 10; i++) {
    elm = document.getElementById("navurl_"+i);
    if (elm) {
      for (var j=elm.options.length-1; j>0; j--) elm.options[j] = null;
    }
    if ((i>level+1) && document.getElementById("trcat_"+i)) document.getElementById("trcat_"+i).style.display = "none";
  }
  if ((thiselm.value != "" ) && (document.getElementById("navurl_"+(level+1)))) {
    var chars = thiselm.value.split('|');
    if (chars[0] != "") {
      var request = createRequest();
      var url = "/include/ajax.php?i_id=" + encodeURIComponent(chars[0]) + "&i_left=" + encodeURIComponent(chars[1]) + "&i_right=" + encodeURIComponent(chars[2]) + "&i_level=" + encodeURIComponent(chars[3]);
      request.open("GET", url, true);
      request.onreadystatechange = function() {
        if (request.readyState == 4) {
          if (request.status == 200) {
            var resp = request.responseText;
            var lines = resp.split("\n");
            var options = false;
            for (i=0; i<lines.length; i++) if (lines[i] != "") {
              var items = lines[i].split("|");
              addoption(document.getElementById("navurl_"+(level+1)), items[5], items[0]+"|"+items[1]+"|"+items[2]+"|"+items[3]+"|"+items[4]+"|");
              options = true;
            }
            if (document.getElementById("trcat_"+(level+1))) {              document.getElementById("trcat_"+(level+1)).style.display = (options ? "" : "none");
            }
          }
        }
      }
      request.send(null);
    }
  }
}



$(document).mousemove(function(e){
      window.mouseX = e.pageX;
      window.mouseY = e.pageY;
});


function testPosition(elm) { return testPositionOffset(elm, 0);}

function testPositionOffset(elm, offset) {
 if ((elm.offset().left-offset <= mouseX)
   && (elm.offset().left + elm.outerWidth() + offset >= mouseX)
   && (elm.offset().top-offset <= mouseY)
   && (elm.offset().top + elm.outerHeight() + offset >= mouseY))
      return true; else return false;
}

function shhint(title) {
 var popuphint = $("<div></div>");
 popuphint.appendTo("body");
 popuphint.css({"width":"300px", "position":"absolute", "display":"none", "background":"#FFF", "border":"1px solid #000", "padding":"5px", "text-align":"left", "left": Math.min(mouseX, $(document).width()-315), "top": mouseY+"px"});
 popuphint.html(title);
 popuphint.show(100);
 function hidehint(event) {
   if (!testPosition(popuphint)) {
     popuphint.hide();
     popuphint.remove();
     $(document).unbind("mousedown", hidehint);
   }
 }
 $(document).bind("mousedown", hidehint);
}

function shlargeimage(title, w, h) { var popuphint = $("<div></div>");
 popuphint.appendTo("body");
 popuphint.css({"width":w+"px", "height":h+"px", "position":"absolute", "display":"none", "left":Math.max(Math.round(mouseX-w/2), 0)+"px", "top": Math.round(mouseY-h/2)+"px", "border":"1px solid #000"});
 popuphint.html(title);
 popuphint.fadeIn(200);
 function hidehint(event) {
   if (!testPosition(popuphint)) {
     popuphint.fadeOut(200, function() {popuphint.remove();});
     $(document).unbind("mousemove", hidehint);
   }
 }
 $(document).bind("mousemove", hidehint);
}

function shtexthint(title, w, pos) {
 if ($("#popuptexthint").length > 0) return;
 var popuphint = $("<div id='popuptexthint'></div>");
 popuphint.appendTo("body");
 popuphint.css({"width":w+"px", "position":"absolute", "display":"none", "border":"1px solid #000", "background":"#FFF", "padding":"5px"});
 if (pos == "right") {   popuphint.css({"left":(mouseX-w)+"px", top:mouseY+"px"});
 } else if (pos == "center") {
   popuphint.css({"left":Math.round(mouseX-w/2)+"px", "top":mouseY+"px"});
 } else if (pos == "left") {
   popuphint.css({"left":mouseX+"px", "top":mouseY+"px"});
 }
 popuphint.html(title);
 popuphint.fadeIn(200);
 function hidehint(event) {
   if (!testPositionOffset(popuphint, 15)) {
     popuphint.fadeOut(200, function() {popuphint.remove();});
     $(document).unbind("mousemove", hidehint);
   }
 }
 $(document).bind("mousemove", hidehint);
}


function seteditcomment(id) { var contelm = $("#savedcomment-"+id);
 if (!contelm.hasClass("set_edited")) {
   var text = contelm.text();
   if (text == "нет комментария") text = "";
   var oldtitle = contelm.attr("title");
   contelm.attr("title", "");
   contelm.empty();
   var ta = $("<textarea rows='3' cols='30' style='width:97%'></textarea>");
   ta.val(text);
   ta.appendTo(contelm);
   ta.focus();
   $("<br />").appendTo(contelm);
   var button = $("<input type='button' value='Сохранить' />");
   button.appendTo(contelm);
   contelm.addClass("set_edited");
   function setback() {     contelm.empty();
     if (!text) text = "нет комментария";
     contelm.html("<pre>"+text+"</pre>");
     contelm.attr("title", oldtitle);
     $(document).unbind("click", setback);
     contelm.removeClass("set_edited");
   }
   function clicksetback(event) {     if (!testPosition(contelm)) {
        setback();
     }
   }
   function save_comment() {
     $.post("/include/ajax.php", {"act":"savecomment", "descr":ta.val(), "id":id}, function(resp){         if (resp.substr(0, 2) == 'OK') {           text = ta.val();
           setback();
         } else {           alert(resp);
         }
       }, "text");
   }
   $(document).bind("click", clicksetback);
   button.click(save_comment);
 }
}


function shitem(table, id, status, image) {  var request = createRequest();
  var url = "/include/ajax.php?act=setstatus&table=" + encodeURIComponent(table) + "&status=" + encodeURIComponent(status) + "&id=" + encodeURIComponent(id);
  request.open("GET", url, true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      if (request.status == 200) {
        var resp = request.responseText;
        if (resp.substr(0, 2) == 'OK') {          if (status == 0) {            image.src = '/images/i_hide.gif';
            image.onclick = function(){shitem(table, id, 1, image);};
            image.title = 'Показать';
          } else if (status == 1) {
            image.src = '/images/i_show.gif';
            image.onclick = function(){shitem(table, id, 0, image);};
            image.title = 'Скрыть';
          }
        } else {          alert(resp);
        }
      }
    }
  }
  request.send(null);
}




var lasttime = new Date();
var srequest = 0;
var oldval = "";

function showpreviewsearch(forrest) {
  if (typeof forrest == 'undefined') var forrest = false
  var curtime = new Date();
  var t1 = lasttime.getTime();
  var t2 = curtime.getTime();
  if (t2-t1 < 100) {
     hidesearch();
     return;
  }
  lasttime = new Date();
  var val = document.getElementById("sq").value;
  if (val == oldval) {
    return;
  }
  oldval = val;
  if (val.length < 2) {
     hidesearch();
     return;
  }
  if (srequest && srequest.readyState < 4) srequest.abort();
  srequest = createRequest();
  var url = "/include/ajax.php?" + (forrest ? "search_rest=" : "search=") + encodeURIComponent(val);

  var divsearch = document.getElementById("previewsearch");
  divsearch.style.width = (document.getElementById("sq").offsetWidth-4)+"px";

  srequest.open("GET", url, true);
  srequest.onreadystatechange = function() {
    if (srequest.readyState == 4) {
      if (srequest.status == 200) {
        hidesearch();
        var resp = srequest.responseText;
        if (resp == "") return;
        var searches = resp.split("\n");
        var html = '';
        for (var i=0; i < searches.length; i++) if (searches[i]) {
          var elms = searches[i].split("||");
          html += "<a href='#' onmouseover='searchmouseover("+i+");' onclick='document.getElementById(\"sq\").value= \"" + elms[0] + "\"; hidesearch(); return false;' style='display:block;' id='slink-"+i+"'>"+elms[0]+"</a>";
        }
        divsearch.innerHTML = html;
        divsearch.style.display = "block";
        document.getElementById("sq").focus();
        document.getElementById("sq").style.zIndex = 1000;
        document.getElementById("previewsearch").style.zIndex = 100;
        searchpos = -1;
      }
    }
  }
  srequest.send(null);
}

var searchpos = -1;
function hidesearch() {
  document.getElementById("previewsearch").style.display = "none";
}

function searchkeydown(event) {
  if (document.getElementById("previewsearch").style.display == "block") {
     var e = event || window.event;
     var code = e.keyCode;
     if ((code == 40) || (code == 38)) {
       var as = document.getElementsByTagName("a");
       var slcnt = 0;
       for (i=0; i < as.length; i++)
        if (as[i].id.substr(0, 6) == "slink-") {
          as[i].className = "";
          slcnt++;
        }
     }
     if (code == 40) {
       searchpos = searchpos+1;
       if (slcnt <= searchpos) searchpos = 0;
       document.getElementById("slink-"+searchpos).className = "A_hover";
     }
     if (code == 38) {
       searchpos = searchpos-1;
       if (searchpos<0) searchpos = slcnt-1;
       document.getElementById("slink-"+searchpos).className = "A_hover";
     }
     if (code == 13) {
       document.getElementById("sq").value = document.getElementById("slink-"+searchpos).innerHTML;
       hidesearch();
     }
     if ((code == 40) || (code == 38) || (code == 13)) {
       if (e.preventDefault) e.preventDefault(); else e.returnValue = false;
       return false;
     }
  }
}

function searchmouseover(id) {
       var as = document.getElementsByTagName("a");
       var slcnt = 0;
       for (i=0; i < as.length; i++)
        if (as[i].id.substr(0, 6) == "slink-") {
          as[i].className = "";
          slcnt++;
        }
       document.getElementById("slink-"+id).className = "A_hover";
       searchpos = id;
}

if (document.getElementById("previewsearch")) {
  if(document.addEventListener) {
    document.addEventListener("click", hidesearch, false);
    document.addEventListener("keydown", searchkeydown, false);
  } else if(document.attachEvent) {
    document.attachEvent("onclick", hidesearch);
    document.attachEvent("onkeydown", searchkeydown);
  }
}



function addspecfilef(animate) {
  if (current_spec_files < max_spec_files) {   // var newfile = $("<div style='display:none; padding-bottom:4px;'><input type='file' size='30' name='spec[]' style='width:auto;' /></div>");
    var newfile = $("<tr><td><div style='display:none;'><input type='file' size='30' name='spec["+current_spec_files+"]' style='width:auto;' /></div></td><td style='width:100%;'><div style='display:none;'><input type='text' size='30' name='spectitle["+current_spec_files+"]' style='width:100%;' /></div></td></tr>");
    $("#specfiles TABLE").append(newfile);
    if (animate) newfile.children("TD").children("DIV").slideDown(100); else newfile.children("TD").children("DIV").show();
    current_spec_files++;
  }
  if (current_spec_files >= max_spec_files) $("#addspecfile").fadeOut(100).hide();
}

function delspecfilef(key, elm) { if (confirm("Вы уверены?")) {
   $("#specfile_"+key).slideUp(100);   current_spec_files--;
   if ($("TR[id^=specfile_]:visible").size()==max_spec_files) addspecfilef(true);
   else $("#addspecfile:hidden").fadeIn(100);
   elm.checked = true;
 } else {   elm.checked = false;
 }
}


function add_file(animate) {
  $("#uploadtable .uploadaddicon").hide();
  if (current_image_files < max_image_files) {
    var newnode = $("#uploadclone").clone(true);
    newnode.removeAttr("id");
    newnode.appendTo("#uploadtable");
    newnode.children("TD").wrapInner("<div></div>");
    if (animate)  newnode.children("TD").children("DIV").hide();
    newnode.show();
    if (animate) newnode.children("TD").children("DIV").slideDown(100);
    current_image_files++;
    if (current_image_files < max_image_files) newnode.find(".uploadaddicon").show();
  }
}

function delscreen(id, cat) {
  if (window.confirm("Вы уверены?")) {
    $.get("/include/managescreen.php", {"delete" : id, "cat" : cat}, function(resp) {
        if (resp.substr(0, 2) == 'OK') {
          $("#scr-"+id+" TD").wrapInner("<div></div>");
          $("#scr-"+id+" TD DIV").slideUp(100, function(){$("#scr-"+id).hide();});
          current_image_files--;
          if ($("#uploadtable>TR:visible").size()-1==max_image_files) add_file(true);
        } else {
          alert(resp);
        }
    }, "text");
  }
}

function setslideshow(start, suffix) {
  if (suffix != '') {
    var jsimages = eval('jsimages'+suffix);
  }  slideshow = !slideshow;
  if (slideshow) {
    sliid = start;
    $("#link_slideshow").text('остановить');
    slid = window.setInterval(function(){       setimage(sliid, suffix);
       sliid++;
       if (sliid >= jsimages.length) sliid = 1;
    }, 3000);
  } else {
    $("#link_slideshow").text('слайдшоу');    clearInterval(slid);
  }
}

function setimage(iid, suffix) {  if (typeof suffix == 'undefined') suffix = '';
  if (suffix != '') {    eval('var jsimages = jsimages'+suffix);
    eval('var jswidth = jswidth'+suffix);
    eval('var jsheight = jsheight'+suffix);
    eval('var jsdescr = jsdescr'+suffix);
  }
  if (typeof jsimages == 'undefined') return false;

  if ($("#fmcont").length > 0) $("#fmcont").remove();

  var cont = $("<div id='fmcont' style='display:none;'><img id='picmain' src='"+jsimages[iid]+"' width='"+jswidth[iid]+"' height='"+jsheight[iid]+"' alt='' />"+(jsdescr[iid].length > 0 ? "<div id='fmtitle'>"+jsdescr[iid]+"</div>" : "")+"<div id='fmnav'>Изображение "+iid+" из "+(jsimages.length-1)+".<span id='fmlinks'></span></div></div>");
  cont.appendTo("body");
  cont.css({"margin-top" : $(document).scrollTop() - Math.round(cont.outerHeight())/2, "margin-left" : -Math.round(cont.outerWidth())/2, "width" : Math.max(jswidth[iid], 350)});

  var showprev = false;
  var shownext = false;
  if (iid > 1) showprev = true;
  if (iid < jsimages.length-1) shownext = true;

  if (jsimages.length > 2) {
    $("<a href='#' onclick='setimage("+(iid > 1 ? iid-1 : jsimages.length-1)+", \""+suffix+"\"); return false;'>&laquo; назад</a>").appendTo($("#fmlinks"));
    $("<span>&nbsp;||&nbsp;</span>").appendTo($("#fmlinks"));
    $("<a href='#' onclick='setimage("+(iid < jsimages.length-1 ? iid+1 : 1)+", \""+suffix+"\"); return false;'>вперед &raquo;</a>").appendTo($("#fmlinks"));
    $("<span>&nbsp;&nbsp;&nbsp;&nbsp;</span><a href='#' id='link_slideshow' onclick='setslideshow("+(iid < jsimages.length-1 ? iid+1 : 1)+", \""+suffix+"\"); return false;'>"+(slideshow ? "остановить" : "слайдшоу")+"</a>").appendTo($("#fmlinks"));  }
  cont.fadeIn(200);

  var closeimage = function() {
    if (slideshow) setslideshow(iid);
    $("#fmcont, #moirdiv").fadeOut(100, function(){$(this).remove();});
  }

  if ($("#moirdiv").length == 0) {
    var moirdiv = $("<div id='moirdiv'></div>");
    moirdiv.css({"position" : "absolute", "top" : 0, "left" : 0, "width" : "100%", "height" : $(document).height(), "opacity" : 0.3, "background-color" : "#000", "z-index" : 15000});
    moirdiv.appendTo("body");
    moirdiv.click(closeimage);
  }

  var dragmove = function() {
    if (allowmove) {
      var curdist = (mouseX-startX)*(mouseX-startX) + (mouseY-startY)*(mouseY-startY);
      if (curdist > distance) distance = curdist;
      cont.css({"left" : mouseX - offsX, "top" : mouseY - offsY, "margin" : 0});
    }
  }

  var startX = 0;
  var startY = 0;
  var offsX = 0;
  var offsY = 0;
  var allowmove = false;
  var distance = 0;
  var button = "LEFT";
  $("#picmain").mousedown(function(event) {
    if (event.which == null) {
        button = (event.button < 2) ? "LEFT" : ((event.button == 4) ? "MIDDLE" : "RIGHT");
    } else {
        button = (event.which < 2) ? "LEFT" : ((event.which == 2) ? "MIDDLE" : "RIGHT");
    }
    if (button == 'LEFT') {
      startX = mouseX;
      startY = mouseY;
      distance = 0;
      offsX = startX - cont.offset().left;
      offsY = startY - cont.offset().top;
      allowmove = true;

      $(document).bind("mousemove", dragmove);
      try {
        this.setCapture();
      } catch(eee) {;}

      event.returnValue = false;
      return false;
    }
  });


  $("#picmain").mouseup(function() {
    allowmove = false;
    var curdist = (mouseX-startX)*(mouseX-startX) + (mouseY-startY)*(mouseY-startY);
    if (curdist > distance) distance = curdist;
    $(document).unbind("mousemove", dragmove);
    try {
      this.releaseCapture();
    } catch(eee) {;}
    if (distance < 10) closeimage();
  });

}



function mainscreen(id, main_id, cat) {
  $.get("/include/managescreen.php", {"setmain" : id, "id_main" : main_id, "cat" : cat}, function(resp) {
      if (resp.substr(0, 2) == 'OK') {
        $("SPAN[id^=makemain]").css('display', 'inline');
        $("SPAN[id^=makenomain]").css('display', 'none');
        $("#makemain-"+id).css('display', 'none');
        $("#makenomain-"+id).css('display', 'inline');
      } else {
        alert(resp);
      }
  }, "text");
}

function nomainscreen(id, main_id, cat) {
  $.get("/include/managescreen.php", {"setnomain" : id, "id_main" : main_id, "cat" : cat}, function(resp) {
      if (resp.substr(0, 2) == 'OK') {
        $("SPAN[id^=makemain]").css('display', 'inline');
        $("#makenomain-"+id).css('display', 'none');
      } else {
        alert(resp);
      }
  }, "text");
}

// Подгрузка подкатегорий для услуг и вакансий
function load_serv_subtypes(marketurl, id) {  var id_type = document.form_input.boatmaintype.value;
  if (id_type == "0") {     $("#serv_subtype_tr").hide();
     $("#serv_subtype_div").empty();
     return;
  }
  $("#serv_subtype_tr").show();
  $("#serv_subtype_div").html("Загрузка...");
  $.get("/include/ajax.php", {"act" : "serv_subtypes", "id" : id, "id_type" : id_type, "marketurl" : marketurl, "rnd":Math.random()}, function(resp) {     if (resp == "") {
       $("#serv_subtype_tr").hide();       $("#serv_subtype_div").html('<input type="hidden" name="id_boattypes['+id_type+']" value="1" />');
     } else {
       $("#serv_subtype_div").html(resp);
     }
  }, "text");
}


function setenableoptionbutton() {
 $("input[name=save][type=submit]").attr('disabled', ($(".r_right input[type=checkbox][checked!='']").length > 0 ? false : true));
}


function savevote(id, num) {
  document.getElementById('yourvote'+id).innerHTML = 'Сохранение...';
  document.getElementById('ratestars'+id).style.visibility = 'hidden';
  var errstr = '&nbsp;';
  var request = createRequest();
  var url = "/include/ajax-ratings.php?rate=1&id=" + id + "&value=" + num;
  request.open("GET", url, true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      if (request.status == 200) {
        var response = request.responseText;
        if (response.substr(0, 2) == 'OK') {
          $('#yourvote'+id).html('Ваша оценка: '+num+'/5');
          var valarr = response.split(' ');
          $('#numvotes'+id).html(valarr[1]);
          $('#currrating'+id).html(Math.round(valarr[2]*10) / 10);
          var i;
          for (i=1; i <= 5; i++){
            document.getElementById('rateimg'+i+"-"+id).className='star' + ((i <= Math.round(valarr[2])) ? '1' : '2') + '';
            document.getElementById('rateimg'+i+"-"+id).onmouseover = null;
            document.getElementById('rateimg'+i+"-"+id).onmouseout = null;
            document.getElementById('rateimg'+i+"-"+id).onclick = null;
          }
        } else {
          document.getElementById('yourvote'+id).innerHTML = response;
        }
        document.getElementById('ratestars'+id).style.visibility = 'visible';
      } else {
        errstr = 'Ошибка';
      }
    }
  }
  request.send(null);
}

function selectrate(num, ansid, cr) {
  var i;
  for (i=1; i <= 5; i++) {
     if (i <= num) document.getElementById('rateimg'+i+"-"+ansid).className='star0';
     else if (i <= cr) document.getElementById('rateimg'+i+"-"+ansid).className='star1';
     else document.getElementById('rateimg'+i+"-"+ansid).className='star2';
  }
  if (num > 0) document.getElementById('yourvote'+ansid).innerHTML = 'Ваша оценка: '+num+'/5';
      else document.getElementById('yourvote'+ansid).innerHTML = '&nbsp;';
}

// вставка смайликов в тинимсе
function insertAtCursor(myFieldName, myValue) {
  var myField = document.getElementById(myFieldName);
  //IE support
  if (document.selection) {
    myField.focus();
    sel = document.selection.createRange();
    sel.text = myValue;
  }

  //Mozilla/Firefox/Netscape 7+ support
  else if (myField.selectionStart || myField.selectionStart == '0') {
    var startPos = myField.selectionStart;
    var endPos = myField.selectionEnd;
    myField.value = myField.value.substring(0, startPos)+ myValue+ myField.value.substring(endPos, myField.value.length);
  } else {
    myField.value += myValue;
  }
  myField.focus();
}

function tinyMCEinsert(myFieldName, myValue) {
  var ed = tinyMCE.get(myFieldName);
  ed.execCommand('mceInsertContent', false, myValue);
}

// сохранить разворачивалку в личном кабинете в куках
function save_cookie_lists() {  $('[id^=tb_]').each(function(){
    var murl = this.id.replace('tb_', '');    $.cookie('expand_'+murl, this.style.display=='none' ? null : '1');
  });
}

function load_rest_comments(id) {  $("#rest_comments").append("<div style='padding: 5px; text-align:center;'><img src='/images/loading16.gif' width='16' height='16' /></div>");
  $.post('/include/ajax.php', {"act":"rest_comments", "id":id, "rnd":Math.random()}, function(resp) {
    $("#rest_comments").html(resp);
  }, 'text');
}