function update_cart_price(){
  $("body").data('cart_sum', 0)
  $("span.item_price").each(function(){
    cost = parseInt($(this).text());
    amount = parseInt($(this).parents("div.good").find("input[name='amount[]']").val());
    $("body").data('cart_sum', $("body").data('cart_sum') + cost * amount);

  });
  $("#cart_sum").text($("body").data('cart_sum') + ".00");
}

function trim(str, chars) {
  return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
  chars = chars || "\\s";
  return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
  chars = chars || "\\s";
  return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function validate_message_form(form){
  input = $(form).find("input[name='name']");
  if(input.val() == "Константин Полуэктович Константинопольский" || trim(input.val())==""){
    input.focus();
    input.effect("highlight");
    return false;
  }

  input = $(form).find("textarea[name='text']");
  if(trim(input.val())==""){
    input.focus();
    input.effect("highlight");
    return false;
  }

  return true;
}


function validate_comment_form(form){
  input = $(form).find("input[name='name']");
  if(input.val() == "Константин Полуэктович Константинопольский" || trim(input.val())==""){
    input.focus();
    input.effect("highlight");
    return false;
  }

  input = $(form).find("textarea[name='text']");
  if(trim(input.val())==""){
    input.focus();
    input.effect("highlight");
    return false;
  }

  return true;
}

function validate_cart_form(form){
  input = $(form).find("input[name='name']");
  if(input.val() == "Константин Полуэктович Константинопольский" || trim(input.val())==""){
    input.focus();
    input.effect("highlight");
    return false;
  }

  input = $(form).find("input[name='phone_code']");
  if(input.val().replace(/[^0-9]/g, "")==""){
    input.focus();
    input.effect("highlight");
    return false;
  }

  input = $(form).find("input[name='phone']");
  if(input.val().replace(/[^0-9]/g, "")==""){
    input.focus();
    input.effect("highlight");
    return false;
  }

  return true;
}

function pluralForm($n, $form1, $form2, $form5)
{
  $n = Math.abs($n) % 100;
  $n1 = $n % 10;
  if ($n > 10 && $n < 20) return $form5;
  if ($n1 > 1 && $n1 < 5) return $form2;
  if ($n1 == 1) return $form1;
  return $form5;
}

function updateMiniCart(){
  $.post("ajax.php?id=cart&a=get_status", {}, function (data, textStatus){
    if(textStatus=='success'){
      $("div.basket p a:first").text(data.count + " " + pluralForm(data.count, 'товар', 'товара', 'товаров'));
      $("span#minicart_price").text(data.price);
    }else{
    }

  }, "json");

}

function validate_test_form(){
  if($("form#test_form input[name='answer_id']:checked").val() != undefined) return true;
  else return false;
}

$(function(){

  $(".scrollable").scrollable({circular: true}).autoscroll();

  $("form#test_form input.s-but").click(function(){
    if(validate_test_form()){
      data = $(this).parents("form:first").serialize();
      $("div.s-cur,div#test_form_on_main").text('Пожалйуста, подождите...');
      $.post("?id=test&a=add", data, function(data,textStatus){
        $("div.s-cur,div#test_form_on_main").html('Ваш голос учтен! Спасибо!<br />' + data);
      }, 'text');
    } else {
      alert("Пожалуйста, выбирете один вариант ответа.");
    }


    return false;
  });


 
  $("input.resp,input[value='Добавить свой отзыв']").click(function(){
    window.location.href='?id=otzivi#add_comment_form';
  });

  $('form#add_comment_form').find("input").one('focus',function(){
    $(this).val("");
  });

  $("form#send_message_form div.but").click(function(){
    if(validate_message_form()){
      action = $(this).parents("form:first").attr('action');
      data = $(this).parents("form:first").serialize();
      $("div.form").text('Пожалйуста, подождите...');
      $.post(action, data, function(data,textStatus){
        $("div.form").text('Ваше сообщение отправлено! Спасибо!');
      }, 'text');
    }

    return false;
  });

  $("form#add_comment_form div.but").click(function(){
    if(validate_comment_form($("form#add_comment_form"))){
      data = $(this).parents("form:first").serialize();
      $("div.form").text('Пожалйуста, подождите...');
      $.post("?id=otzivi&a=add", data, function(data,textStatus){
        $("div.form").text('Ваш отзыв отправлен! Спасибо!');
      }, 'text');
    }

    return false;
  });



  $(".fancybox").fancybox();

  tmp=$("div.towel td.t-right a:first");
  if(tmp.length)tmp.fancybox();

  tmp=$("div.towel td.t-right p a");
  if(tmp.length)tmp.fancybox();

  tmp=$("div.awards div.award a.award_picture");
  if(tmp.length)tmp.fancybox();

  tmp=$("div.awards div.award a.award_title");
  if(tmp.length)tmp.fancybox()


  //setInterval("updateMiniCart()", 20000);
  //setTimeout("updateMiniCart()", Math.random() * 5000 + 5000);


  //корзина: подробная информация
  $("a:contains('Оставить более подробную информацию для курьера')").click(function(){
    if(!$(this).data('full')){
      $(this).parents("tr:first").next("tr.hidden:first").show();
      $(this).text('Скрыть подробную информацию');
      $(this).data('full', true)
    } else {
      $(this).parents("tr:first").next("tr.hidden:first").hide();
      $(this).text('Оставить более подробную информацию для курьера');
      $(this).data('full', false)
    }
    return false;
  });


  $("div.categoryes div.category div.name").bind("mouseover", function(){
    $("div.categoryes div.category div.name-open").removeClass("name-open").addClass("name").find("div.menu-open").hide();

    $(this).addClass("name-open")
    .removeClass("name")
    .find("div.menu-open")
    .show();
  });
  $("div.categoryes div.category div.name").bind("mouseout", function(){
//setTimeout(cmd = '$("div#'+$(this).attr('id')+'").removeClass("name-open").addClass("name").find("div.menu-open").hide();', 2000);

  });


  //смена цены при смене варианта товара
  $(".good select").change(function(){
    $(this).parent().next().find("span span:first").html($(this).val().split(";")[1]);
    item_id = $(this).val().split(";")[0];
    $(this).parents("div.good").find("input:hidden[name='item_id[]']").val(item_id);
    update_cart_price();
  });
  
  

  

  $("input[name='amount[]']").change(function(){
    value = parseInt($(this).val());
    if(isNaN(value)) value = 1;
    value = Math.abs(value);
    value = Math.min(value, 99);
    value = Math.max(value, 1);
    $(this).val(value);

    update_cart_price();
  });


  $(document).ajaxError(function(event, XMLHttpRequest, ajaxOptions, thrownError){
    $("body").append(
    "<hr /><p>" + 
    "event.type = " + event.type + "<br />" + 
    "XMLHttpRequest.status: " + XMLHttpRequest.status + "<br />" + 
    "XMLHttpRequest.statusText: " + XMLHttpRequest.statusText + "<br />" + 
    "this.documentURI: " + this.documentURI + "<br />" + 
    "status: " + 3 + "<br />" +
    "</p>"
    );
  });

  $(document).ajaxSuccess(function (event, XMLHttpRequest, ajaxOptions) {
    this; // dom element listening
    
  });

  //$.post('/wefwef', {q:3}, function(data){}, 'json');

  $("table.item div.buy input[type='button']").click(function(){

    var id = $(this).parents("div:first").find("input[name='item_id']").val();

    $.post("/ajax.php?id=cart&a=add", {item_id: id}, function(data){
        window.location.href="?id=cart";
    });

  });


  //добавление в корзину товара - со страницы каталога
  $(".good .buy input").click(function(){

    var select = $(this).parents("form:first").find("select:first");
    var item_id;
    if(select.length){
      item_id = select.val().split(";")[0];
      $(this).parents("form:first").find("input:hidden[name='item_id[]']").val(item_id);

    }else{
      item_id = $(this).parents("form:first").find("input:hidden[name='item_id[]']").val();
    }

    $.post("ajax.php?id=cart&a=add", {item_id: item_id}, function (data, textStatus){
      if(textStatus=='success'){
        window.location.href="?id=cart";
      }else{
        alert('Произошла ошибка при добавлении товара!');
      }

    });

  });
  //удаление из корзины
  $(".good .del input").click(function(){

    var select = $(this).parents("div.good").find("select:first");
    var item_id;
    if(select.length){
      item_id = select.val().split(";")[0];
      $(this).parents("div.good").find("input:hidden[name='item_id[]']").val(item_id);

    }else{
      item_id = $(this).parents("div.good").find("input:hidden[name='item_id[]']").val();
    }

    $.post("ajax.php?id=cart&a=remove", {item_id: item_id}, function (data, textStatus) {
      if(textStatus=='success'){
        update_cart_price();
        $(".good input:hidden[name='item_id[]'][value='"+data.item_id+"']").parents(".good").effect("clip", 2000);
      }else{
        alert('Произошла ошибка при удалени товара!');
      }

    }, 'json');
  });


  cart_form = $("div.form:contains('Оформление заказа')").parents("form:first");

  $(cart_form).find("input[name!='amount[]']").one('focus',function(){
    $(this).val("");
  });

  $.datepicker.setDefaults($.extend({showMonthAfterYear: false}, $.datepicker.regional['ru']));
  $(cart_form).find("input[name='del_date']").datepicker({showOn: 'button', buttonImage: '/img/calend.gif', buttonImageOnly: true});


  $(cart_form).find("div.but").click(function(){
    if(validate_cart_form($(this).parents("form:first"))){
      $(this).parents("form:first").submit();
      //alert("отправлено");
    }

    return false;
  });
});
