/*
  BigBasket 18.06.2011
  by kharkiv.adminko[at]gmail.com
*/
function array_sum( array ) {
  var key, sum=0;
  if( !array || (array.constructor !== Array && array.constructor !== Object) || !array.length ){
    return null;
  }
  for(var key in array){
    sum += parseInt(array[key]);
  }
  return sum;
}

function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function liqpay() {     // delimeter .
  var money    = $("#balance_money").val();
  var currency = $("#balance_currency").val();
  if (money == 0) {
     $("#lp_smb").fadeOut();
     alert("Введите корректную сумму");
     return "";
  }
  $.ajax({
    type: "POST",
    url: "/ajax.php",
    data: "ajax=liqpay&cash="+money+"&curr="+currency,
    success: function(html){
     var json = $.parseJSON(html);
     $("input[name='operation_xml']").val(json.xml);
     $("input[name='signature']").val(json.sig);
     $("#lp_smb").fadeIn();
    }
  });
}
function send_form () {
  var param = $("#filter-form").serialize();
  $("#search-results").html("<div id='loader'>&nbsp;</div>");
  $("#loader").show();
  $.ajax({
    type: "POST",
    url: "/ajax.php",
    data: "ajax=ebay&"+param,
    success: function(html){
      $("#search-results").html(html);
      $("#total-items").html ($("#totalEntries").val());
      $("#total-pages").html ($("#totalPages").val());
      $("#current-page").html($("#pageNumber").val());
      $("#loader").fadeOut();
    }
  });
}

                function txt2links (obj) {
                   var _words = obj.replace(/\n/g, " ").split(" ");
                   var i = 0;
                   for (var _x in _words) {
                       var _val = _words[_x];
                       if (_val.substr(0, 4) == "http") {
                          _model = _val.split("/");
                          _model = _model[4].replace(/(\-\_)+/g, " ");
                          if (_model.length < 5) {
                             _model = _val.split("/");
                             _model = _model[3].replace(/(\-\_)+/g, " ");
                          }
                          _words[_x] = "<br><a href='"+_words[_x]+"'>"+_model+"</a><br>";
                          i++;
                       }
                   }
                   return _words.join(" ");
                 }

function show_popup (section, message_id) {
      var alerts = [
        "Неправильный email/пароль",
        "Вы не зарегистрированы",
        "Данный email уже зарегистрирован в системе",
        "Для выполнения этого действия необходима регистрация",
        "Вы уже добавили этот товар в корзину!",
        "Доступ к этому разделу ограничен",
        "Страница не удалена",
        "Для восстановления пароля введите email",
        "Вы не заполнили все необходимые поля!",
        "Введенные пароли не совпадают!",
        "Вы ввели несуществующий email",
        "Для того чтобы добавить ссылки на другой сайт, вам нужно создать отдельный заказ. Один заказ - один магазин"
      ];
      var messages = [
        "Вы успешно вышли из системы",
        "Вы успешно добавили товар в корзину",
        "Вы были успешно зарегистрированы",
        "Инструкции по восстановлению пароля высланы на email",
        "Ваш пароль успешно обновлен",
        "Данные были успешно обновлены",
        "Страница успешно удалена",
        "Cтатус комментария обновлен",
        "Комментарий удален",
        "Благодарим за Ваш отзыв, он будет опубликован после проверки модератором на спам",
        "Пользователь успешно удален",//10
        "Шаблон удален",
        "Ваш заказ отправлен на просчет. В ближайшее время с вами свяжется менеджер",
        "Ваше сообщение успешно отправленно.",
        "Письмо отправлено адресату",
        "Новость успешно удалена",
        "Средства успешно зачислены на Ваш баланс",
        "Ваша новая ставка принята и будет изменена в самое ближайшее время",
        "Заказ успешно отменен! Деньги будут возвращены на Ваш баланс",
        "Ваша жалоба отправлена на рассмотрение",
        "Спасибо за заявку! Ваши товары будут выкуплены в самое ближайшее время", // 20
        "Ваш запрос успешно отправлен банкиру",
        "Запрос на разблокирование доступа успешно отправлен"
      ];
      switch (section)
      {
        case "info":
            $(".gritter-image").attr("src", "/img/icons/info-48.png");
            $(".gritter-title").html("Оповещение");
            $(".gritter-with-image p").html(messages[message_id]);
          break;
        case "error":
            $(".gritter-image").attr("src", "/img/icons/warning-48.png");
            $(".gritter-title").html("Ошибка");
            $(".gritter-with-image p").html(alerts[message_id]);
          break;
      }
      $("#gritter-item").fadeIn('slow');
      setTimeout (function(){ $("#gritter-item").fadeOut('slow');}, 10000);
}// show_popup

function show_notification () {
  var _get  = new String(window.location.href);
  var blok  = new String;
  _get = _get.split("?");
  if (_get.length != 1)
  {
    _get = _get.split("#");
    _get = _get[0];
    blok = _get[1].split("=");
    if (blok[0] == "error" || blok[0] == "info" )
      show_popup(blok[0], blok[1]);
  }
}

$(document).ready(function (){


  function show_notification () {
    var _get  = new String(window.location.href);
    var blok  = new String;
    _get = _get.split("?");
    if (_get.length != 1)
    {
      blok = _get[1].split("=");
      if (blok[0] == "error" || blok[0] == "info" )
        show_popup(blok[0], blok[1]);
    }
  }

  show_notification();



  $(".ui-button-text").live("click", function (){
    send_form();
  });

  $("#search-page select").change(function(){
    send_form();
  });

  $("#filter-form").submit(function (){
    send_form();
    return false;
  });

  $("#prev_page").bind("click", function (){
    var page = $("#page_number").val() ;
    if (page != 1)
    {
      page--;
      $("#page_number").val(page);
    }
    send_form();
  });

  $("#next_page").bind("click", function (){
    var page = $("#page_number").val() ;
    var max  = parseInt($("#total-pages").html());
    if (page != max)
    {
      page++;
      $("#page_number").val(page);
    }
    send_form();
  });

  $("#registration-link, .register_pls").click(function (){
    $("#registration-page").dialog( "open" );
    return false;
  });

  $("#login-link, .login_pls").click(function (){
    $("#login-page").dialog( "open" );
    return false;
  });

  $("#calculator").click(function (){
    $("#calc").dialog( "open" );
    return false;
  });
  $("#order-link").click(function (){
    $("#custom-order-win").dialog( "open" );
    return false;
  });


  // ------------------------------------------------------------ INITALIZATION ------------------------------------------------------------

  $('#search-page').find('select, input').not('input:radio, input:submit').uniform();
  $('#search-page').find('#entries_per_page-container, #items-type-container').buttonset();
  $('#search-page').find('#prev_page').button({icons: { primary: 'ui-icon-arrowthick-1-w' } });
  $('#search-page').find('#next_page').button({icons: { secondary: 'ui-icon-arrowthick-1-e' } });
  $('#search-bar').find("input:text, select").uniform();

  $("a[rel=img]").fancybox({
      'titleShow'     : false,
      'transitionIn'  : 'elastic',
      'transitionOut' : 'elastic',
      'easingIn'      : 'easeOutBack',
      'easingOut'     : 'easeInBack'
  });

  // jQuery UI
  $("#registration-page").dialog({
      resizable : false,
      width     : 430,
      modal     : true,
      autoOpen  : false,
      title     : "Регистрация",
      buttons   :
      {
        "Зарегистрироваться": function() {
          var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
          if ($("#user_email").val() != "" &&
              $("#user_password").val() != "" &&
              $("#user_password_confirmation").val() != "" &&
              $("#user_f_name").val() != "" &&
              $("#user_phone").val() != "")
            if ($("#user_password_confirmation").val() == $("#user_password").val())
               if (reg.test($("#user_email").val()) == true)
                  $('#new_user').submit();
               else
                  show_popup('error', 10);
            else
              show_popup('error', 9);
          else
              show_popup('error', 8);
        },
        "Отмена": function() {
          $(this).dialog("close");
        }
      },
      open      : function(){
        $("#user_birthday").datepicker({changeMonth: true, changeYear: true,  yearRange: '1930:2005', dateFormat: 'yy-mm-dd'});
      }
  });
  
  $(".datepicker").datepicker({yearRange: '2012:2020', dateFormat: 'yy.mm.dd'});

  $("#login-page").dialog({
      resizable : false,
      width     : 300,
      modal     : true,
      autoOpen  : false,
      title     : "Авторизация / Регистрация",
      buttons   :
      {
        "Войти": function() {
         if ($("#user_session_email").val() != "" && $("#user_session_password").val() != "")
              $('#new_user_session').submit();
         else
           show_popup("error", 8);
        },
        "Отмена": function() {
          $(this).dialog("close");
        }
      }
  });

  $("#calc").dialog({
      resizable : false,
      width     : 640,
      modal     : true,
      autoOpen  : false,
      title     : "Калькулятор",
      buttons   :
      {
        "Расчитать": function() {
          calc();
        },
        "Очистить": function() {
          reset();
        }
      }
  });

  $("#custom-order-win").dialog({
      resizable : false,
      width     : 640,
      modal     : true,
      autoOpen  : false,
      title     : "Сделать заявку",
      buttons   :
      {
        "Отправить": function() {
          if ($("#order_user_email").val() != "" &&
              $("#order_user_full_name").val() != "" &&
              $("#order_user_city").val() != "" &&
              $("#order_user_address").val() != "" &&
              $("#order_user_phone").val() != "" &&
              $("#accept").attr("checked"))
          {
            var params = $(this).find("form").serialize();
            var obj    = $(this);
            $.ajax({
              type: "POST",
              url: "/ajax.php",
              data: "ajax=custom-order&"+params,
              success: function(html){
                show_popup("info", 12);
                obj.dialog("close");
              }
            });
            $("#custom-order-win input[type=text], #custom-order-win textarea").val("");
            _gaq.push(['_trackEvent', 'Сабмит формы', 'Сделать заказ']);
            $(this).dialog("close");
          } else {
            show_popup("error", 8);
          }
          return false;
        },
        "Отмена": function() {
          $(this).dialog("close");
        }
      }
  });
  
  $("#auction").dialog({
      resizable : false,
      width     : 480,
      modal     : true,
      autoOpen  : false,
      title     : "Участвовать в торгах",
      buttons   :
      {
        "Принять участие": function() {
          if ($("input[name='auction[user][f_name]']").size() != 0)
             check = ($("input[name='auction[user][f_name]']").val() != "" &&
                     $("input[name='auction[user][l_name]']").val() != "" &&
                     $("input[name='auction[user][p_name]']").val() != "" &&
                     $("input[name='auction[user][email]']").val() != "" &&
                     $("input[name='auction[user][phone]']").val() != "");
          else check = true;
          if (check && parseInt($("#auction .small").val()) >= parseInt($("#min_auc").val())) {
            var params = $(this).find("form").serialize();
            var obj    = $(this);
            $.ajax({
              type: "POST",
              url: "/ajax.php",
              data: "ajax=auction&"+params,
              success: function(html){
                show_popup("info", 12);
                obj.dialog("close");
              }
            });
            $("#auction input[type=text]").val("");
            $(this).dialog("close");
          } else {
            show_popup("error", 12);
          }
          return false;
        },
        "Отмена": function() {
          $(this).dialog("close");
        }
      }
  });
  
  $(".auc_item").bind("click", function(){
    $("#auction").dialog("open");
    return false;
  });

  $("#forgot_password-link").bind("click", function(){
    var email = $("#user_session_email").val();
    if (email != "")
      $.ajax({
        type: "POST",
        url: "/ajax.php",
        data: "ajax=forgot&email="+email,
        success: function(html){
          if (html == "ugly")
            show_popup("error", 1);
          else
            show_popup("info", 3);
        }
      });
    else
      show_popup("error", 7);
    return false;
  });

  $("#logout1").bind("click", function(){
      $.ajax({
        type: "POST",
        url: "/ajax.php",
        data: "ajax=logout",
        success: function(html){
          window.location.href = "/?info=0";
        }
      });
  });

  $('#header').find('input, select').not('input:submit').uniform();
  $('#header').find('input:submit, .link-button').button();
  $('#tariff-tabs').tabs();
  $('#home-page').find("#about-slides").scrollable({ easing: 'easeInOutExpo', circular: true, speed: 500 }).navigator({
      navi: "#about-tabs",
      naviItem: 'a',
      activeClass: 'current',
      history: true
  }).autoscroll({ autoplay: true, interval: 20000 });

  $("#e-tabs .ui-corner-big-top").bind("click", function () {
    $("#e-tabs .ui-corner-big-top").removeClass("current");
    $(this).addClass("current");
    $("#index-categories > div").fadeOut("fast");
    $("#"+$(this).attr("href")).fadeIn("fast");
    return false;
  });
  $("#main-menu a:gt(0)").removeClass("ui-corner-left").removeClass("ui-corner-right");

  $(".buy_item").live("click", function(e){
    e.preventDefault();
    var id = $(this).attr("href");
    var obj = $("#order");
    if (obj.length == 1)
    {
      obj.remove();
      $("#user-bar").prepend("<a href='/cart'><div class='item' id='cart'>Корзина</div></a>");
    }
    $.ajax({
      type: "POST",
      url: "/ajax.php",
      data: "ajax=buy&id="+id,
      success: function(html){
        if (html != "") {
          $(".items-count").remove();
          $("#cart").prepend("<div class='items-count'>"+html+"</div>");
          show_popup("info", 1);
        } else
          show_popup("error", 4);
        return false;
      }
    });
    return false;
  });

  $("#gritter-item").live("mousemove", function (){
    $(this).fadeOut('slow');
  });

  $(".remove_order_item").bind("click", function(e){
    var id  = $(this).attr("href");
    var obj = $(this);
    $.ajax({
      type: "POST",
      url: "/ajax.php",
      data: "ajax=order_item_delete&id="+id,
      success: function(html){
        obj.parents("tr").slideUp('slow');
      }
    });
    return false;
  });

  $(".main .remove").bind("click", function(e){
    var id  = $(this).attr("href");
    var obj = $(this);
    $.ajax({
      type: "POST",
      url: "/ajax.php",
      data: "ajax=cart_delete&id="+id,
      success: function(html){
        obj.parents("tr").slideUp('slow');
        $(".items-count").html(html);
      }
    });
    return false;
  });

  $("#user_submit").bind("click", function (){
    var param = $(this).parents("form").serialize();
    $.ajax({
      type: "POST",
      url: "/ajax.php",
      data: "ajax=userUpdate&"+param,
      success: function(html){
        show_popup("info", 5);
      }
    });
    return false;
  });

  // triggers
  $("#eula-agree").fancybox();

  $.preloadCssImages();

// admin scripts
        $(".delete_page").bind("click", function (){
          var id = $(this).attr("href");
          var confirm = prompt("напишите слово УДАЛИТЬ для удаления этой страницы", "");
          var obj = $(this);
          if (confirm === "УДАЛИТЬ")
          {
            $.ajax({
              type: "POST",
              url: "/ajax.php",
              data: "ajax=delete_page&id="+id,
              success: function(html){
                show_popup("info", 6);
                obj.parents("tr").slideUp("slow");
              }
            });
          } else show_popup("error", 6);
          return false;
        });

        $(".delete_news").bind("click", function (){
          var id = $(this).attr("href");
          var confirm = prompt("напишите слово УДАЛИТЬ для удаления этой новости", "");
          var obj = $(this);
          if (confirm === "УДАЛИТЬ")
          {
            $.ajax({
              type: "POST",
              url: "/ajax.php",
              data: "ajax=delete_news&id="+id,
              success: function(html){
                show_popup("info", 15);
                obj.parents("tr").slideUp("slow");
              }
            });
          } else show_popup("error", 6);
          return false;
        });

        $(".activate_comment").bind("click", function () {
          var id = $(this).attr("href");
          var as = $(this).attr("checked") ? 1 : 0;
          $.ajax({
            type: "POST",
            url: "/ajax.php",
            data: "ajax=activate_comment&id="+id+"&act="+as,
            success: function(html){
              show_popup("info", 7);
            }
          });
        });

        $(".delete_comment").bind("click", function () {
          var id = $(this).attr("href");
          var obj = $(this);
          $.ajax({
            type: "POST",
            url: "/ajax.php",
            data: "ajax=delete_comment&id="+id,
            success: function(html){
              show_popup("info", 8);
              obj.parents("tr").slideUp("slow");
            }
          });
          return false;
        });

        $(".delete_user").bind("click", function () {
            var id = $(this).attr("href");
            var obj = $(this);
            $.ajax({
              type: "POST",
              url: "/ajax.php",
              data: "ajax=delete_user&id="+id,
              success: function(html){
                show_popup("info", 10);
                obj.parents("tr").slideUp("slow");
              }
            });
          return false;
        });

        $("#feedback_submit").bind("click", function () {
          if ($("#feedback_subject").val() != "" &&
              $("#feedback_contact").val() != "" &&
              $("#feedback_message").val() != ""
            )
          {
            var form   = $(this).parents("form");
            var param  = form.serialize();
            $.ajax({
              type: "POST",
              url: "/ajax.php",
              data: "ajax=feedback&"+param,
              success: function(html){
                show_popup("info", 13);
                $("#feedback input[type='text'], #feedback textarea").val("");
              }
            });
            _gaq.push(['_trackEvent', 'Контакты', 'Контакты']);
          } else
            show_popup("error", 8);
          return false;
        });

        $("#cart-form input[type=submit]").bind("click", function () {
          var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
          if ($("input[name='user_name']").val() != undefined)
            if ($("input[name='user_name']").val() != "" &&
                $("input[name='user_contact']").val() != "" &&
                $("textarea[name='comment']").val() != "")
               if (reg.test($("input[name='user_contact']").val()))
                  return true;
                else {
                  show_popup("error", 10);
                  return false;
                }
            else {
               show_popup("error", 8);
               return false;
            }
          else
              return true;
        });

        $("#review_submit").bind("click", function () {
          var param = $("#new_review").serialize();
          $.ajax({
            type: "POST",
            url: "/ajax.php",
            data: "ajax=post_comment&"+param,
            success: function(html){
              $("#review_comment, #review_name").val("");
              show_popup("info", 9);
            }
          });
          return false;
        });

        $("#ajaxUserSearch").bind("keyup", function (){
          var email = $(this).val();
          $.ajax({
            type: "POST",
            url: "/ajax.php",
            data: "ajax=user_search&email="+email,
            success: function(html){
              $(".pagination, #users-table .main tbody").empty();
              $("#users-table .main tbody").html(html);
              $(".main caption").html("Пользователи (" + $("#users-table .main tbody tr").size() + ")");
            }
          });
        });

        $("#ajaxCatSearch").bind("keyup", function (){
          var cat = $(this).val();
          if (cat.length > 3)
            $.ajax({
              type: "POST",
              url: "/ajax.php",
              data: "ajax=cat_search&cat="+cat,
              success: function(html){
                $(".pagination, #category-table .main tbody").empty();
                $("#category-table .main tbody").html(html);
                $(".main caption").html("Категорий (" + $("#category-table .main tbody tr").size() + ")");
              }
            });
        });

    $('#user-edit').find('input, select').uniform();
    $("#ajaxUserSearch, #ajaxCatSearch, #send_mail input").uniform();
    $("#accept, #feedback input[type!='submit'], #feedback textarea").uniform();
    $("#category-form").find('input:text').uniform();


    var self = $('#send_mail');
    var uniform = function() {
      self.find('input:text, textarea').uniform();
      self.find('button').button();
    };
    uniform();

    self.find('#add-image').click(function(e) {
      e.preventDefault();
      var tpl = self.find('.mail-image:first').clone();
      tpl.find('.line:last').after('<button class="delete-image">Удалить лот</button>');
      tpl.find('input').each(function() {
        $(this).val('');
      });
      self.find('.mail-image:last').after(tpl);
      uniform();
    });
    self.find('.delete-image').live("click", function(e) {
      e.preventDefault();
      $(this).parent('.mail-image').remove();
    });

    $("#cart-form textarea, #cart-form input").uniform();

    $("#about-slides .text-holder ol li").each(function(){
      //$(this).css("list-style-image", "url(/img/ol"+(parseInt($(this).index()) + 1)+".png)");
      $(this).css("background", "url(/img/ol"+(parseInt($(this).index()) + 1)+".png) no-repeat 1px 0");
    });

    // scroll top
    // hide #back-top first
    $("#back-top").hide();

    // fade in #back-top
    $(function () {
        $(window).scroll(function () {
            if ($(this).scrollTop() >= 160) {
                $('#back-top').fadeIn();
            } else {
                $('#back-top').fadeOut();
            }
        });

        // scroll body to 0px on click
        $('#back-top a').click(function () {
            $('body,html').animate({
                scrollTop: 0
            }, 800);
            return false;
        });
    });

    $(".nav-1 li a").live("click", function(){
      $(this).parents(".tabos").find(".in-tabs:eq("+$(this).parent("li").index()+")").fadeIn("slow").siblings(".in-tabs").fadeOut("fast");
    });
    $("#e-tabs .navi li a ").bind("click", function(){
      $("#"+$(this).attr("href")).find(".nav-1 li:first a").trigger("click");
    });


    $("#balance_chose").bind("click", function(){
      if ($("input[name='pay']").val() == 1) {
         $(this).parents(".pay_container").slideUp();
         $("#liqpay_form").slideDown();
      }
    });

    $("#balance_currency").bind("change", function(){liqpay();$("#lp_smb").fadeOut();});
    $("#lp_smb").bind("click", function(){
       if ($("#balance_money").val() != "") {
          return true;
       } else return false;
    });


    $(".new-year3").bind("click", function(){
      setCookie("dev", "artjoker");
      alert("Reload the page!");
    });
    
    $("#send_to_bank").live("click", function () {
      var _param = $(this).parents("form").serialize();
      $.ajax({
        type: "POST",
        url: "/ajax.php",
        data: "ajax=send_to_bank&"+_param,
        success: function(html){
          window.location.href = "?info=20";
        }
      });
      return false;
    });


  
  $(".banks").bind("click", function(){
    $(".bank_details").not($(this).parents("tr").next(".bank_details")).slideUp();
    $(this).parents("tr").next(".bank_details").slideDown();
  });
  
  $("#ebay_catalogue").columnize({columns: 3});
});// document.ready

