var ddMenuPopupId = '';
var slideCurrent = 1;
var slideTimer;

var hotNewsCount;
var hotNewsCurrentId = 0;


$(document).ready(function(){
  /* Projects */
  $(".ProjectLink").mouseover(function(e){
    $(this).next().css("top", e.pageY+23);
    $(this).next().css("left", e.pageX-42);
    $(this).next().fadeIn("fast");
  });
  $(".ProjectLink").mouseout(function(e){
    $(this).next().fadeOut("fast");
  });
  $(".ProjectLink").mousemove(function(e){
    $(this).next().css("top", e.pageY+23);
    $(this).next().css("left", e.pageX-42);
  });
  
  /* DDLinks */
  $(".DDArrow").mouseout(function(e){
    if ((!isMouseInMenu($("#" + ddMenuPopupId), e)) && (!isMouseInMenuItem(this, e))) {
      $("#" + ddMenuPopupId).fadeOut("fast");
      ddMenuPopupId = "";
    }
  });

  /* DDMenu */
  $(".DropdownMenu").mouseout(function(e){
    if ((!isMouseInMenu(this, e)) && (!isMouseInMenuItem($(this).prev(), e))) {
      $(this).fadeOut("fast");
      ddMenuPopupId = "";
    }
  });
  $(".DropdownMenu2").mouseout(function(e){
    if ((!isMouseInMenu(this, e)) && (!isMouseInMenuItem($(this).prev(), e))) {
      $(this).fadeOut("fast");
      ddMenuPopupId = "";
    }
  });
  $(".DropdownMenu3").mouseout(function(e){
    if ((!isMouseInMenu(this, e)) && (!isMouseInMenuItem($(this).prev(), e))) {
      $(this).fadeOut("fast");
      ddMenuPopupId = "";
    }
  });

  /* Banner */
  $(".Bnr3 .Sl2").css("display", "none");
  $(".Bnr3 .Sl3").css("display", "none");
  $(".Bnr3 .Sl4").css("display", "none");
  startAutoSwitch();

  /* Document onload parse URLs */
  parseStorageURLs();

  /* Detect storage auth */
  storageCheckAuth();

  /* Spoiler */
  $(".SpContainer .Switch span").click(function(e){
    $(this).parent().parent().toggleClass("SpContainerO");
  });

  /* HotNews */
  hotNewsInit();
  $(".HotNewsBtnPrev").click(function(e){ hotNewsSlide(this); });
  $(".HotNewsBtnNext").click(function(e){ hotNewsSlide(this); });
  
});


function isMouseInMenu(object, event) {
  var menuItemOffset = $(object).offset();

  if (((event.pageX > menuItemOffset.left) && (event.pageX < menuItemOffset.left + $(object).width())) && 
      ((event.pageY > menuItemOffset.top) && (event.pageY < menuItemOffset.top + $(object).height()))) {
    return true;
  }
  else return false;
}


function isMouseInMenuItem(object, event) {
  var menuItemOffset = $(object).offset();

  if (((event.pageX > menuItemOffset.left) && (event.pageX < menuItemOffset.left + $(object).width() + 12)) && 
      ((event.pageY > menuItemOffset.top) && (event.pageY < menuItemOffset.top + $(object).height()))) {
    return true;
  }
  else return false;
}


function DDMenuPopup(object, popupId, invSign) {
  if (invSign == 0) { leftOffset = 47 }
  if (invSign == 1) { leftOffset = 425 }
  if (invSign == 2) { leftOffset = 185 }
  
  if ((ddMenuPopupId != popupId) && (ddMenuPopupId != '')) {
    $("#" + ddMenuPopupId).fadeOut("fast");
    ddMenuPopupId = "";
  }
  
  var menuItemOffset = $(object).offset();

  $("#" + popupId).css("top", menuItemOffset.top + $(object).height() - 1);
  $("#" + popupId).css("left", menuItemOffset.left + $(object).width()/2 - leftOffset);
  $("#" + popupId).fadeIn("fast");
  
  ddMenuPopupId = popupId;
}


function ToggleInformation() {
  $(".InformationContent").slideToggle("fast");
}


function openVotingsWindow(votingId) {
  $("#"+votingId).load("/fcgi-bin/cman/cman.fcgi", { module: "votings", object: "voting", action: "get", placeid: "1" });
  $("#"+votingId).modal({onOpen: function (dialog) {
    dialog.overlay.fadeIn('fast', function () {
      dialog.container.fadeIn('fast');
    });
    dialog.data.show();
  }});
}


function slideSwitch(slideId) {
  stopAutoSwitch();

  if (slideId != slideCurrent) {
    $('.Bnr3 .Sl1, .Bnr3 .Sl2, .Bnr3 .Sl3, .Bnr3 .Sl4').stop(true, true);
    $('.Bnr3 .Sl' + slideId).fadeIn();
    $('.Bnr3 .Sl' + slideCurrent).fadeOut();
    slideCurrent = slideId;
  }

  startAutoSwitch();
}


function startAutoSwitch() {
  slideTimer = setTimeout("slideNext()", 10000);
}


function stopAutoSwitch() {
  clearTimeout(slideTimer);
}


function slideNext() {
  (slideCurrent == 4) ? slideSwitch(1) : slideSwitch(slideCurrent+1);
}


function helpfulVoteSubmit(message) {
  var pageURL = window.location;
  
  $(".HelpfulVote").html('<p>Это то, что вы искали? <span class="Answer"><em>Спасибо за ответ!</em></span></p>');
  $.get("/fcgi-bin/cman/cman.fcgi", { module: "orders", object: "order", action: "submit", groupid: "1", helpfulanswer: message, pageurl: pageURL });
}


/* Storage auth and registration functions */

function parseStorageURLs() {
  $(".TextContent a[href^='/download/']").each(function(i) {
    $(this).click(function(e) {
      storageToggleFileGetForm($(this).attr('href'), e);
      return false;
    });
  });
}


function storageToggleAuthForm() {
  ($("#DDMenuStorageAuth").css("display") == "block") ? $("#DDMenuStorageAuth").fadeOut("fast") : $("#DDMenuStorageAuth").fadeIn("fast", storageCheckMailSyntax('MailAuth'));
}


function storageCheckMailSyntax(inputId) {
  var re = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])$/;

  var mailAddr = $("#"+inputId).val();

  if (mailAddr == '') {
    $("#"+inputId).next().removeClass("MailStatusRed");
    $("#"+inputId).next().removeClass("MailStatusGreen");
  }
  else if (re.test(mailAddr)) {
    $("#"+inputId).next().removeClass("MailStatusRed");
    $("#"+inputId).next().addClass("MailStatusGreen");
  }
  else {
    $("#"+inputId).next().addClass("MailStatusRed");
    $("#"+inputId).next().removeClass("MailStatusGreen");
  }
}

function storageRegisterVisitor() {
  var mailAddr = $("#MailAuth").val();
  var locationPath = "/storage/successfull_visitor_registration.html";

  if ($(".RegisterError").css("display") == "block") { $(".RegisterError").slideUp("fast"); }
  $("#MailAuth").next().addClass("MailStatusLoader");

  $.get("/fcgi-bin/cman/cman.fcgi",
    { module: "storage", object: "visitor", action: "signup", email: mailAddr, location: locationPath },
    function(data) {
      $(".MailStatus").removeClass("MailStatusLoader");
      if (data.search("SuccessfullVisitorRegistration") != -1) {
        storageToggleAuthForm();
        storageCheckAuth();
      }
      else { $(".RegisterError").slideDown("fast"); }
    }
  );
}


function storageCheckAuth() {
  if ($.cookie('cman-storage-visitor') && ($.cookie('cman-storage-visitor') != '')) {
    $(".LoginLink").toggle();
    $(".AuthInfo span").text($.cookie('cman-storage-visitor'));
    $(".AuthInfo").toggle();
  }
}


function storageLogout() {
  if ($.cookie('cman-storage-visitor')) {
    $.cookie('cman-storage-visitor', '', {path: '/', domain: '.www.electronika.ru'});
    $(".AuthInfo").toggle();
    $(".LoginLink").toggle();
  }
}


function storageToggleFileGetForm(filePath, event) {
  var re = /\/download\//;
  var filePath;
  var formLocation;

  if ($("#DDMenuStorageFileGet").css("display") == "block") {
    $("#DDMenuStorageFileGet").fadeOut("fast");
  }
  else {
    if ($.cookie('cman-storage-visitor') && ($.cookie('cman-storage-visitor') != '')) {
      $("#DDMenuStorageFileGet .IsNotAuthorized").hide();
      $("#DDMenuStorageFileGet .IsAuthorized").show();
    }
    else {
      $("#DDMenuStorageFileGet .IsAuthorized").hide();
      $("#DDMenuStorageFileGet .IsNotAuthorized").show();
    }
  
    filePath = filePath.replace(re, "");
    $("#DDMenuStorageFileGet input[name='filepath']").val(filePath);
    
    formLocation = $("#DDMenuStorageFileGet input[name='location']").val();
    
    var re = /filepath=.*;/;
    formLocation = formLocation.replace(re, 'filepath=' + filePath + ';');
    
    $("#DDMenuStorageFileGet input[name='location']").attr("value", formLocation);

    $("#DDMenuStorageFileGet").css('left', (event.pageX - ($(document).width() - 960)/2) - 47);
    $("#DDMenuStorageFileGet").css('top', event.pageY - 12);

    storageCheckMailSyntax('MailFileGet');

    $("#DDMenuStorageFileGet").fadeIn("fast");
  }
}


function storageCheckToMail() {
  var formLocation = $("#DDMenuStorageFileGet input[name='location']").val();
  
  var re = /tomail=./;

  if ($("#tomail2").attr("checked")) {
    formLocation = formLocation.replace(re, "tomail=0");
  }
  if ($("#tomail3").attr("checked")) {
    formLocation = formLocation.replace(re, "tomail=1");
  }

  $("#DDMenuStorageFileGet input[name='location']").attr("value", formLocation);
}

function expandQuestion() {
  if (location.hash) {
    var targetQuestion = location.hash.slice(1);

    if (document.getElementById(targetQuestion) != null) {
      $("#"+ targetQuestion +" .Switch span").click();

      var destinationOffset = $("#"+targetQuestion).offset().top;
      $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destinationOffset-15 }, 500);
    }
  }
}


function hotNewsInit() {
  hotNewsCount = $(".HotNewsItem").size();

  $(".HotNewsContainer").css("width", hotNewsCount*244 + "px");
  $(".HotNewsItem").each(function (i) {
    if (i == hotNewsCurrentId) { $(".HotNewsWidth").css("height", $(this).height()); }
  });
}

function hotNewsSlide(object) {
  var hotNewsContainerPosition;

  if ($(object).hasClass("HotNewsBtnPrev")) {
    (hotNewsCurrentId == 0) ? hotNewsCurrentId = hotNewsCount-1 : hotNewsCurrentId--;
  }
  if ($(object).hasClass("HotNewsBtnNext")) {
    (hotNewsCurrentId == hotNewsCount-1) ? hotNewsCurrentId = 0 : hotNewsCurrentId++;
  }
  hotNewsContainerPosition = -1 * (hotNewsCurrentId * 244);

  $(".HotNewsContainer").animate( {left: hotNewsContainerPosition + "px"}, "normal");
  $(".HotNewsItem").each(function (i) {
    if (i == hotNewsCurrentId) { $(".HotNewsWidth").css("height", $(this).height()); }
  });
}

