$(document).mousemove(function(e){
      window.mouseX = e.pageX;
      window.mouseY = e.pageY;
});

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 submitreg() {
  var regform_name = document.getElementById("regform_name");
  var regform_email = document.getElementById("regform_email");
  var regform_pass1 = document.getElementById("regform_pass1");
  var regform_pass2 = document.getElementById("regform_pass2");
  var errstr = '';
  if (regform_pass1.value != regform_pass2.value) errstr = 'Пароли не совпадают';
  if (!regform_pass1.value) errstr = 'Вы не ввели пароль';
  if (!regform_email.value) errstr = 'Вы не ввели e-mail';
  if (!regform_name.value) errstr = 'Вы не ввели ник';
  if (errstr) {    document.getElementById('errstr').innerHTML = errstr;    return false;
  }

  document.getElementById('errstr').innerHTML = "Отправка данных...";


  var request = createRequest();
  var url = "/include/ajax.php?act=reg&sid=" + encodeURIComponent(document.getElementById("session_id").value) + "&name=" + encodeURIComponent(regform_name.value) + "&email=" + encodeURIComponent(regform_email.value) + "&pass=" + encodeURIComponent(regform_pass1.value);


  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') {           var spl = resp.split("||||");
           document.getElementById("strat2_un").innerHTML = spl[1];
           document.getElementById("form1reg").style.display = "block";
           document.getElementById("form1notreg").style.display = "none";
           document.getElementById("form2notreg").style.display = "none";
           regform();
        } else {           document.getElementById('errstr').innerHTML = resp;
        }
      }
    }
  }
  request.send(null);
}

function submitlogin() {
  var loginform_email = document.getElementById("loginform_email");
  var loginform_pass = document.getElementById("loginform_pass");

  var errstr = '';
  if (!loginform_pass.value) errstr = 'Вы не ввели пароль';
  if (!loginform_email.value) errstr = 'Вы не ввели ник или e-mail';
  if (errstr) {
    document.getElementById('login_errstr').innerHTML = errstr;
    return false;
  }

  document.getElementById('login_errstr').innerHTML = "Отправка данных...";


  var request = createRequest();
  var url = "/include/ajax.php?act=login&sid=" + encodeURIComponent(document.getElementById("session_id").value) + "&email=" + encodeURIComponent(loginform_email.value) + "&pass=" + encodeURIComponent(loginform_pass.value);


  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') {
           var spl = resp.split("||||");
           document.getElementById("strat2_un").innerHTML = spl[1];
           document.getElementById("form1reg").style.display = "block";
           document.getElementById("form1notreg").style.display = "none";
           document.getElementById("form2notreg").style.display = "none";
           loginform();
        } else {
           document.getElementById('login_errstr').innerHTML = resp;
        }
      }
    }
  }
  request.send(null);
}

function rememberpass() {
  var loginform_email = document.getElementById("loginform_email");

  var errstr = '';
  if (!loginform_email.value) errstr = 'Введите e-mail, указанный Вами при регистрации';
  if (errstr) {
    document.getElementById('login_errstr').innerHTML = errstr;
    return false;
  }

  document.getElementById('login_errstr').innerHTML = "Отправка данных...";


  var request = createRequest();
  var url = "/include/ajax.php?act=remember&sid=" + encodeURIComponent(document.getElementById("session_id").value) + "&email=" + encodeURIComponent(loginform_email.value);


  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') {
           document.getElementById('rememberlink').style.display = "none"
           document.getElementById('login_errstr').innerHTML = "Новый пароль был выслан на Ваш адрес";
        } else {
           document.getElementById('login_errstr').innerHTML = resp;
        }
      }
    }
  }
  request.send(null);
}

function reglogout() {
  var request = createRequest();
  var url = "/include/ajax.php?act=logout&sid=" + encodeURIComponent(document.getElementById("session_id").value);


  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') {
           var spl = resp.split("||||");
           document.getElementById("form1reg").style.display = "none";
           document.getElementById("form1notreg").style.display = "block";
           document.getElementById("form2notreg").style.display = "block";
           document.getElementById("strat2_un").innerHTML = "";
        } else {
           alert(resp);
        }
      }
    }
  }
  request.send(null);
}


// Показ форм входа и регистрации
function regform() { if (loaded) {
   var d = $("#regform");
   if (d.css('display') == "block") {
     d.fadeOut(200);
   } else {     d.css({'top' : (mouseY+15), 'left' : mouseX});
     d.appendTo("body");
     d.fadeIn(200);
     if ($("#loginform").css('display') == "block") loginform();
     $('#errstr').html("");
   }
 }
}

function loginform() {
 if (loaded) {
   var d = $("#loginform");
   if (d.css('display') == "block") {
     d.fadeOut(200);
   } else {
     d.css({'top' : (mouseY+15), 'left' : mouseX});
     d.appendTo("body");
     d.fadeIn(200);
     if ($("#regform").css('display') == "block") regform();
     $('#login_errstr').html("");
   }
 }
}


// Показ-скрытие формы комментов
function toggle_commform(aelm) {
 if (loaded && ($("#whiteline").length == 0)) {
   var wl = $("<div id='whiteline'></div>");
   wl.css({"position":"absolute", "left":$("#commentbutton").offset().left, "top":$("#commentbutton").offset().top+$("#commentbutton").outerHeight()-6, "width":$("#commentbutton").outerWidth()-2, "height":9, "background":"#FFF", "z-index":16000, "border-left":"1px solid #c0c0c0", "font-size":"1px"});
   wl.appendTo("body");
 }
 $("#commentblock").slideToggle(300, function(){
   if (!$(aelm).hasClass("show")) $("#whiteline").remove();
 });
 $(aelm).toggleClass("show");
 if (document.getElementById("othernews")) document.getElementById("othernews").style.marginTop='0';
 if (document.getElementById("latestnews")) document.getElementById("latestnews").style.marginTop='0';
}

function toggle_commform_pu() {
  if (!loaded) return;
  if ($("#fmcont").length > 0) $("#fmcont").remove();
  var cont = $("<div id='fmcont' style='display:none;width:750px;'><div class='fhead' style='margin:0 -5px 5px -5px; position:relative;'><img src='/images/ico_close.gif' alt='Закрыть' title='Закрыть' style='float:right; cursor:pointer; margin: 3px 3px 0 0;' id='link_close' />Добавить комментарий</div></div>");
  cont.appendTo("body");
  $("#commentblock").appendTo(cont).css({"display":"block", "margin-top" : "0", "background" : "transparent", "border" : "0"});
  cont.css({"margin-top" : $(document).scrollTop() - Math.round(cont.outerHeight()/2), "margin-left" : -Math.round(cont.outerWidth()/2)});
  cont.fadeIn(200);

  var closepu = function() {
    $("#fmcont, #moirdiv").fadeOut(100, function(){$("#commentblock").appendTo("body").css({"display":"none"}); $(this).remove();});
    return false;
  }

  $("#link_close").click(closepu);

  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" : 20000});
    moirdiv.appendTo("body");
    moirdiv.click(closepu);
  }
}

// Отправка комментария
function send_comment(id, type, ntype) {
  var closepu = function() {
    $("#fmcont, #moirdiv").fadeOut(100, function(){$("#commentblock").appendTo("body").css({"display":"none"}); $(this).remove();});
    return false;
  }
  $("#msgout").html("");
  $("#submit_status").html("Отправка...");
  document.form_input.submit.disabled = true;
  var name = document.form_input.f_name.value;
  var email = document.form_input.f_email.value;
  var message = document.form_input.f_message.value;
  var code = document.form_input.fsec.value;
  var sid = document.form_input.session_id.value;
  $.post('/include/ajax.php', {"act":"addcomment", "ntype":ntype, "id":id, "f_name":name, "f_email":email, "f_message":message, "fsec":code, "sid":sid, "rnd":Math.random()}, function(resp) {    var lines = resp.split("\n");
    if ($.trim(lines[0]) == 'FAIL') {      $("#msgout").html(lines[1]);
    } else if (($.trim(lines[0]) == 'OK') || ($.trim(lines[0]) == 'DELAY')) {      $("#msgout").html(lines[1]);
      var msg = "";
      for (var i=2; i < lines.length; i++) msg += $.trim(lines[i]);
      if ($.trim(lines[0]) == 'OK') {
        if (type == 'popup') {          setTimeout(closepu, 1000);
          $("#commlist_default .commlist").prepend(msg);
        } else {
          $("#header_comments").css('display', 'block');          $("#commlist_default .commlist").append(msg);
        }
        document.form_input.f_message.value = "";
        if ($("#number_comments").length > 0) {          var curnum = parseInt($("#number_comments").html());
          $("#number_comments").html(curnum+1);
        }
      }
    } else {
      alert(resp);
    }
    $("#submit_status").html("&nbsp;");
    document.form_input.submit.disabled = false;
  }, 'text');
}

// Подгрузка всех комментариев
function load_comments(elm, id, type, ntype) {
  elm.style.display = "none";
  if (type == 'popup') {    $("#commlist_default").append("<div style='padding: 5px; text-align:center;'><img src='/img/loading16.gif' width='16' height='16' /></div>");
  } else {    $("#commlist_default").prepend("<div style='padding: 5px; text-align:center;'><img src='/img/loading16.gif' width='16' height='16' /></div>");
  }
  $.post('/include/ajax.php', {"act":"listcomments", "id":id, "type":type, "ntype":ntype, "rnd":Math.random()}, function(resp) {
    $("#commlist_default").html(resp);
  }, 'text');
}



// Народный рейтинг
function item_rate(id, value, ntype) {
  $('#rating_status').html('Отправка...');  $.post('/include/ajax.php', {"act":"item_rate", "id":id, "value":value, "ntype":ntype, "rnd":Math.random()}, function(resp) {
    var lines = resp.split("\n");
    if ($.trim(lines[0]) == 'OK') {
      var value = parseInt($.trim(lines[1]));
      $('#rating_value_'+id).css('color', (value>0 ? '#53b900' : (value<0 ? '#ca0000' : '#adadad')));      $('#rating_status_'+id).html('Ваш голос учтен.');
      $('#rating_value_'+id).html((value>0 ? '+' : '')+value);
      var aelm = document.getElementById('toggle_comment_link');
      if (aelm) {
        if (aelm.className != 'show') toggle_commform(aelm);
      }
    } else {      $('#rating_status_'+id).html(resp+' ');
    }
  }, 'text');
}



/* Картинки */
function setimage(iid) {  if (!loaded) return;
  if ($("#fmcont").length > 0) $("#fmcont").remove();

  var cont = $("<div id='fmcont' style='display:none;'><div class='fhead' style='margin:0 -5px 5px -5px; cursor:move; position:relative;'><img src='/images/ico_close.gif' alt='Закрыть' title='Закрыть' style='float:right; cursor:pointer; margin: 3px 3px 0 0;' id='link_close' />Изображение "+iid+" из "+(jsimages.length-1)+"</div><div style='position:relative;'>"+jsimages[iid]+"</div><div id='fmnav'><span id='fmlinks'></span></div>"+(jsdescr[iid].length > 0 ? "<div id='fmtitle'>"+jsdescr[iid]+"</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], 300)});

  if (jsimages.length > 2) {
    var tidivcont = $("<div></div>");
    var tidiv = $("<div class='thumbimgdiv'></div>");
    var ribbonwidth = new Array();
    ribbonwidth[0] = 0;
    tidivcont.append(tidiv);
    tidivcont.css({"position":"absolute", "left":0, "top":25, "width":cont.outerWidth()-4, "overflow":"auto", "overflow-x":"auto", "overflow-y":"hidden", "padding-bottom":"0"});
    for(var i=1; i < jsimages.length; i++) {
      tidiv.append($("<div style='width:"+jsthumbwidth[i]+"px; height:"+maxth+"px; margin-bottom:0;'"+(iid == i ? " class='active'" : "")+"><a href='#' onclick='setimage("+i+"); return false;'><img src='"+jsthumbimages[i]+"' width='"+jsthumbwidth[i]+"' height='"+jsthumbheight[i]+"' alt='' title='"+jsshortdescr[i]+"' style='margin-top:"+Math.round((maxth-jsthumbheight[i])/2)+"px;' /></a></div>"));
      ribbonwidth[i] = ribbonwidth[i-1] + jsthumbwidth[i] + 22;
    }
    tidiv.append($("<div class='clear' style='margin:0; padding:0; border:0; background:transparent;'></div>"));
    tidiv.css({'width':1+ribbonwidth[ribbonwidth.length-1], "margin":"5px", "height":maxth+12});
    if ((navigator.appName == "Microsoft Internet Explorer") && ($.browser.version <= 7.0)) {
      tidiv.css({"height":maxth+28});
    }
  }

  var showprev = false;
  var shownext = false;
  if (iid > 1) showprev = true;
  if (iid < jsimages.length-1) shownext = true;

  if (showprev) $("<a href='#' onclick='setimage("+(iid-1)+"); return false;' style='float:left;'>&laquo; предыдущая</a>").appendTo($("#fmlinks"));
  if (shownext) $("<a href='#' onclick='setimage("+(iid+1)+"); return false;' style='float:right'>следующая &raquo;</a>").appendTo($("#fmlinks"));
  if (jsfullsizes[iid] != '') $("<span>&nbsp;&nbsp;<strong>"+jsfullsizes[iid]+"</strong>&nbsp;&nbsp;</span>").appendTo($("#fmlinks"));
  $("<div class='clear'></div>").appendTo($("#fmlinks"));

  if (typeof(tidivcont) != 'undefined') {
    tidivcont.prependTo(cont);
  }
  cont.fadeIn(200, function() {
    if (typeof(tidivcont) != 'undefined') {
      tidivcont.scrollLeft(ribbonwidth[iid-1] - Math.round((cont.outerWidth()-jsthumbwidth[iid]-22)/2));
    }
  });
  if (typeof(tidivcont) != 'undefined') {
    $("#fmcont .fhead").css("margin-bottom", 10+tidivcont.outerHeight(true));
  }
  cont.css({"margin-top" : $(document).scrollTop() - Math.round(cont.outerHeight()/2)});

  var closeimage = function() {
    $("#fmcont, #moirdiv").fadeOut(100, function(){$(this).remove();});
    return false;
  }

  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" : 20000});
    moirdiv.appendTo("body");
    moirdiv.click(closeimage);
  }

  $("#link_close").click(closeimage);

  var dragmove = function() {
    if (allowmove) {
      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";
  $("#fmcont .fhead").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;
    }
  });


  $("#fmcont .fhead").mouseup(function() {
    if (allowmove) {
      allowmove = false;
      $(document).unbind("mousemove", dragmove);
      try {
        this.releaseCapture();
      } catch(eee) {;}
    }
  });

}

var loaded = !((navigator.appName == "Microsoft Internet Explorer") && ($.browser.version <= 7.0));
$(document).ready(function () {
  loaded = true;
});