$(document).ready(function()
{

  orderLoading = new Image();
  orderLoading.src = "/templates/pavlabor/images/order-loading.gif";
  whoisLoading = new Image();
  whoisLoading.src = "/templates/pavlabor/images/whois-loading.gif";
  indicator = new Image();
  indicator.src = "/templates/pavlabor/images/indicator.gif";

  // Аккордеон
  var section = document.URL.split('#');
  $("#accordion h3").each(function()
  {
    var rel = $(this).attr('rel');
    if (typeof rel == 'undefined')
          rel = "none";

    if (rel == section[1])
    {
      $(this).addClass("active");
      $(this).next(".section").css("display", "block");
    }
  });
  $("#accordion h3").click(function()
  {
    $(this).next(".section").slideToggle("fast").
    siblings(".section:visible").slideUp("fast");
    $(this).toggleClass("active");
    $(this).siblings("h3").removeClass("active");
  });

  // Прятать/показывать подсказку ввода адреса
  $("input[@name=domain]").focus(function()
  {
    var hintValue = $(this).val();
                    $(this).val('');
    $(this).blur(function()
    {
      if ($(this).val() == '')
          $(this).val(hintValue);
    });
  });
  

  // Переключатель доменов
  $(".domains-toggler").click(function()
  {
    var domainsPanel = $("#domains-panel");
    if (domainsPanel.css("display") == "none")
    {
      $(".domains-toggler img").attr("src", '/templates/pavlabor/images/minus-mini.gif');
      $(".domains-toggler span").text("Скрыть домены");
      domainsPanel.css("display", "block");
    }
    else
    {
      $(".domains-toggler img").attr("src", '/templates/pavlabor/images/plus-mini.gif');
      $(".domains-toggler span").text("Показать больше доменов?");
      domainsPanel.css("display", "none");
    }
  });

  // Выбрать все домены gTLD
  $("#gtld").click(function()
  {
    if ($("#gtld").val() == "none")
    {
      $("#gtld").val("checked");
      $(".gtld-zone").attr('checked', 'checked');
    }
    else
    {
      $("#gtld").val("none");
      $(".gtld-zone").removeAttr('checked');
    }
  });

  // Выбрать все домены ccTLD
  $("#cctld").click(function()
  {
    if ($("#cctld").val() == "none")
    {
      $("#cctld").val("checked");
      $(".cctld-zone").attr('checked', 'checked');
    }
    else
    {
      $("#cctld").val("none");
      $(".cctld-zone").removeAttr('checked');
    }
  });

  // Выбрать все домены uaTLD
  $("#uatld").click(function()
  {
    if ($("#uatld").val() == "none")
    {
      $("#uatld").val("checked");
      $(".uatld-zone").attr('checked', 'checked');
    }
    else
    {
      $("#uatld").val("none");
      $(".uatld-zone").removeAttr('checked');
    }
  });

  // Проверка доменов
  $("input[@name=whois]").click(function()
  {
    var domain = $("input[@name=domain]").val();

    if (domain == '') {}
    else
    {
      $("#whois").css("display", "block");
      $("#whois").css("padding", "50px 0 50px 0");
      $("#whois").html('<img src="/templates/pavlabor/images/whois-loading.gif" border="0" />');
      $("input[@name=whois]").attr('disabled', 'disabled');
      $("body").css("cursor", "wait");
      $("#domains-panel").css("display", "none");

      var listZones = '';
      $("input[@name=zone][@checked]").each(function(i)
      {
        var zone = this.value;
        listZones = listZones+'zone[]='+zone+'&';
      });

      $.ajax({
        type: "POST",
        url: "/extras/whois.php?"+listZones,
        data: "domain="+domain,
        complete: function(http)
        {
          if (http.readyState == 4 && http.status == 200)
          {
            $("#whois").html('');
            $("#whois").css("padding", "0");
            $("#whois").append(http.responseText);
            $("input[@name=whois]").removeAttr('disabled');
            $("body").css("cursor", "");
            //$("input[@name=domain]").val('');
          }
        }
      });

    }
  });

  // Сетевые утилиты
  $("input[@name=lg]").click(function()
  {
    $("#lg").css("padding", "30px 0 0 200px");
    $("#lg").html('<img src="/templates/pavlabor/images/indicator.gif" border="0" alt="">');
    $("input[@name=lg]").attr('disabled', 'disabled');
    $("body").css("cursor", "wait");

    $("#util").change(function()
    {
      util = $("#util option:selected").val()
    }).change();

    var host = $("input[@name=host]").val();

    $.ajax({
      type: "POST",
      url: "/extras/lg.php",
      data: "util="+util+
            "&host="+host,
      complete: function(http)
      {
        if (http.readyState == 4 && http.status == 200)
        {
          switch (http.responseText)
          {
            case 'noutil': lg_error("Не выбрана утилита!"); break;
            case 'nohost': lg_error("Не указан хост!"); break;
            default: lg_result(http.responseText);
          }

          $("input[@name=lg]").removeAttr('disabled');
          $("body").css("cursor", "");
        }
      }
    });

  });

  // Переход к оформлению заказа доменов
  $("input[@name=domain-order]").livequery(function()
  {
    $(this).click(function()
    {
      var listDomains = '';
      var checkedCount = $("input[@name=available-domain][@checked]").length;
      if (checkedCount > 0)
      {
        $("input[@name=available-domain][@checked]").each(function(i)
        {
          var zone = this.value;
          listDomains = listDomains+zone+',';
        });

        var listDomains = listDomains.substring(0, listDomains.length-1);
        document.location.href = '/order/domain/#'+listDomains;;
      }
    });
  });

  // Установка домена при заказе
  if (location.pathname == '/order/domain/')
  {
    var domain = location.hash.replace('#', '').replace(/,/g, ', ');
    //alert(domain);
    //var domain.replace(',', ', ');
    $("input[@name=domain-register]").attr('checked', 'checked');
    $("input[@name=domain]").val(domain);
    $("#domain").css("display", "table-row");
    $("#nic").css("display", "table-row");
  }

  // Установка домена при выборе вида услуги
  $("#service").change(function()
  {
      service = $("#service option:selected").val();
      if (service == "service-domain")
      {
        $("input[@name=domain-register]").attr('checked', 'checked');
        $("#domain").css("display", "table-row");
        $("#nic").css("display", "table-row");
      }
  }).change();

  // Выбор регистрации домена при заказе
  $("input[@name=domain-register]").click(function()
  {
    var domainRegister = $("input:checked[@name=domain-register]");
    if (domainRegister.val() == "on")
    {
      if (location.pathname == '/order/domain/')
      {
        $("#service option").eq(0).
          attr('selected', 'selected');
      }
      $("#domain").css("display", "table-row");
      $("#nic").css("display", "table-row");
    }
    else
    {
      if (location.pathname == '/order/domain/')
      {
        $("#service option:selected").next().
          attr('selected', 'selected');
      }
      $("#domain").css("display", "none");
      $("#nic").css("display", "none");
    }
  });

  // Отправка заказа
  $("input[@name=order]").click(function()
  {
    $("#order-status").html('');
    $("#order-loading").html('<img src="/templates/pavlabor/images/order-loading.gif" align="left" border="0"><strong>Проверка...</strong>');
    $("body").css("cursor", "wait");

    var service = $("#service option:selected").val();
    var domainRegister = $("input:checked[@name=domain-register]");
    if (domainRegister.val() == "on")
      var domain = $("input[@name=domain]").val();
    else var domain = 'none';
    var withdomain = domainRegister.val();
    if (typeof withdomain == 'undefined')
          var withdomain = "off";
    var firstname = $("input[@name=firstname]").val();
    var lastname = $("input[@name=lastname]").val();
    var nic = $("input[@name=nic]").val();
    var address = $("input[@name=address]").val();
    var city = $("input[@name=city]").val();
    var phone = $("input[@name=phone]").val();
    var email = $("input[@name=email]").val();

    $.ajax({
      type: "POST",
      url: "/extras/order.php",
      data: "service="+service+
            "&domain="+domain+
            "&withdomain="+withdomain+
            "&firstname="+firstname+
            "&lastname="+lastname+
            "&nic="+nic+
            "&address="+address+
            "&city="+city+
            "&phone="+phone+
            "&email="+email,
      complete: function(http)
      {
        if (http.readyState == 4 && http.status == 200)
        {
          switch (http.responseText)
          {
            case 'noservice': order_error("Не выбран вид услуги!"); break;
            case 'nodomain': order_error("Вы должны указать доменное имя!"); break;
            case 'nofirstname': order_error("Вы должны ввести свое имя!"); break;
            case 'noaddress': order_error("Вы должны ввести свой адрес!"); break;
            case 'nocity': order_error("Вы должны ввести название города!"); break;
            case 'nophone': order_error("Введите номер телефона!"); break;
            case 'novalidphone': order_error("Не верный формат номера телефона!"); break;
            case 'noemail': order_error("Вы должны ввести адрес e-mail!"); break;
            case 'novalidemail': order_error("Не верный формат адреса e-mail!"); break;
            default:
            {
              order_result(http.responseText);
            }
          }

          $("#order-loading").html('');
          $("body").css("cursor", "");
        }
      }
    });

  });

  $("#contacts input[@name=send]").click(function()
  {
    var fio = $("input[@name=fio]").val();
    var mailfrom = $("input[@name=mailfrom]").val();
    var message = $("textarea[@name=message]").val();

    $.ajax({
      type: "POST",
      url: "/extras/send.php",
      data: "fio="+fio+
            "&mailfrom="+mailfrom+
            "&message="+message,
      complete: function(http)
      {
        if (http.readyState == 4 && http.status == 200)
        {
          switch (http.responseText)
          {
            case 'nofio': send_error("Вы не указали свои инициалы!"); break;
            case 'nomailfrom': send_error("Вы не указали свой обратный адрес E-mail или телефон!"); break;
            case 'nomessage': send_error("Пустое сообщение!"); break;
            default: send_result();
          }
        }
      }
    });
  });

  function lg_error(message)
  {
    $("#lg").css({padding: "60px 0 0 0", textAlign: "left"});
    $("#lg").html('<span style="color: #FF5600; font: 25px arial">&#9658; '+
                  '<span style="color: #AAA; font: 90% arial">'+message+
                  '</span></span>');
  }

  function lg_result(message)
  {
    $("#lg").css({padding: "0", textAlign: "left"});
    $("#lg").html('<div class="console">'+message+'</div>');
  }

  function order_error(message)
  {
    $("#order-status").html('<span style="color: #CC0000; font: 14px arial"><strong>'+message+'</strong></span>');
  }

  function order_result(message)
  {
    $("#order").html(message);
  }

  function send_error(message)
  {
    $("#contacts-status").css({color: "#EE0000", font: "bold 14px arial"});
    $("#contacts-status").html(message);
  }

  function send_result(message)
  {
    $("#contacts").css({"padding": "100px 0 321px 0", "textAlign": "center"});
    $("#contacts").html("Ваше сообщение отвравлено!");
  }

});