$(document).ready(function(){

	var urlnow = document.location.href;
	if(urlnow == 'http://www.bs-media.ru/cat/104/221/258'){ $('#podbor').text('Подбор панелей по производителю, типу, диагонали, разрешению, цене');}
	if(urlnow == 'http://www.bs-media.ru/cat/104/4/256/'){ $('#podbor').text('Подбор проекторов по производителю, яркости, разрешению, цене');}
	if(urlnow == 'http://www.bs-media.ru/cat/104/318'){ $('#podbor').text('Подбор экранов по производителю, типу, диагонали, материалу экрана, цене');}
	if(urlnow == 'http://www.bs-media.ru/Kommutaciya-i-upravlenie/Usiliteli-raspredeliteli/#apodbor'){ $('#podbor').text('Подбор по производителю, назначению, типу сигнала, количеству входов/выходов, цене');}
	
  $(".sort select").change(function() {
    window.location = $(this).val();
  });
  /*find*/
  $('.find a').click(function() {
    $.cookie('find', '1', {expires: 1, path: '/'});
  });
  if ($.cookie('find') == 1 && $('.filter-catalogue').length) {
    $.cookie('find', '', {expires: 1, path: '/'});
    $('.filter-catalogue').show();
  }
  
  function update_unit_width() {
    var unit_width = 0; 
    $('.unit').each(function() {
      if ($(this).width() > unit_width)
        unit_width = $(this).width();
    });
    if (unit_width)
      $('.unit').width(unit_width);
  }
  update_unit_width();
  if ($(".dragarea").length) {
    var ftimer = 0;
    $(".filter-header select, .filter-header input[type=checkbox]").change(function() {
      var temp = '';
      $('.filter-header input:checked, .filter-header select').each(function () {
        temp = temp + $(this).val();
      });
///   comment it
      var aCbxs = [];
      $('.filter-header input[type="checkbox"], .filter-header select').each(function () {
        aCbxs[$(this).attr("name")] |= $(this).is(':checked');
      });
      for(var i in aCbxs){
        if(!aCbxs[i]){
          temp += '/'+i.replace('[]','')+'/-1/';
        }
      }
///   /comment it
      $('.filter-header input[type=text]').each(function () {
        temp = temp + '/'+$(this).attr('name')+'/'+($(this).attr('_value') ? $(this).attr('_value') : $(this).val());
      });
      $.get($('.filter-header form').attr('action') + (temp ? '~' + temp : ''), function(responseText) {
        $('#total_count').text(responseText);
        if (parseInt(responseText) == 0)
          $('#total_count_0').show();
        else
          $('#total_count_0').hide();
      }); 
    });
    function filter_update () {
      $($('.filter-header select, .filter-header input[type=checkbox]').get(0)).change();
    }
    filter_update();
    $(".filter-header input[type=text]").keypress(function(e) {
      clearTimeout(ftimer); 
      ftimer=setTimeout("filter_update();", 500); 
    });

    $(".filter-header h4, .filter-header .h4repl").click(function() {
      $('.filter-catalogue').slideToggle();
      update_unit_width();
    });

    $(".filter-header input[type=submit]").click(function() {
      var temp = '';
      $('.filter-header input:checked, .filter-header select').each(function () {
        temp = temp + $(this).val()
        });
      $('.filter-header input[type=text], .filter-header input[type=hidden]').each(function () {
        temp = temp + '/'+$(this).attr('name')+'/'+($(this).attr('_value') ? $(this).attr('_value') : $(this).val())
        });
      window.location = $('.filter-header form').attr('action') + (temp ? '~' + temp : '');
      return false;
    });
    /*price slider*/  
    $(".dragarea").slider({
      range: true,
      stop: function(event, ui)   {
        filter_update();
      },      
      slide: function(event, ui)
      {
        if ($(this).attr('_vs')) {
          var vs = $(this).attr('_vs').split('|');
          $("input[name="+$(this).attr('_id')+"_from]").val(vs[ui.values[0]]).attr('_value', ui.values[0]);
          $("input[name="+$(this).attr('_id')+"_to]").val(vs[ui.values[1]]).attr('_value', ui.values[1]);
        }
        else {
          $("input[name="+$(this).attr('_id')+"_from]").val(ui.values[0]);
          $("input[name="+$(this).attr('_id')+"_to]").val(ui.values[1]);
        }
      }
    });
    $(".dragarea").each(function() {
      $(this).slider( "option", "max", parseInt($(this).attr('_max')) );
      $(this).slider( "option", "min", parseInt($(this).attr('_min')) );
      if ($(this).attr('_step')>0)
        $(this).slider( "option", "step", parseInt($(this).attr('_step')) );
      var is = [];
      is[0] = parseInt($("input[name="+$(this).attr('_id')+"_from]").val());
      is[1] = parseInt($("input[name="+$(this).attr('_id')+"_to]").val());
      if ($(this).attr('_vs')) {
        var vs = $(this).attr('_vs').split('|');
        $("input[name="+$(this).attr('_id')+"_from]").val(vs[is[0]]).attr('_value', is[0]);
        $("input[name="+$(this).attr('_id')+"_to]").val(vs[is[1]]).attr('_value', is[1]);
      }
      $(this).slider( "option", "values", is );  
    });
  }
  
/*kamimamita*/

	$("#float-header").scrollFollow( {speed: 700} );
	
    $(".header-spacer").css({height: $("#float-header").height()-4});	

    $("#float-header").css({width: $(".main").width() > $("#float-header table").width() ? $(".main").width() : $("#float-header table").width()});

	$(".compare-text").css({width: $("#float-header").width()});

  var add_handler = function() {
    var t =$(this);
    $.post('/basket/ajaxAdd/', {item_id: t.attr('_id'), catalogue_id: $('#ajax_compare_info').attr('_id')}, function(responseText) {
      $('#ajax_compare_info').html(responseText.basket_info_html ? $('#ajax_compare_info').attr('_name')+responseText.basket_info_html : '');
      t.text('Удалить из сравнения').removeClass('compare').addClass('delete_from_compare').unbind('click').bind('click', remove_handler);
      $('.clear-comparetion2').show();
      if ($('.compare').length)
        $('.add-all-comparetion').css('padding-left', '10px');
      else
        $('.add-all-comparetion').hide();
    }, 'json');
    return false;
  };

  var remove_handler = function() {
    var t = $(this);
    $.post('/basket/ajaxRemove/', {item_id: t.attr('_id'), catalogue_id: $('#ajax_compare_info').attr('_id')}, function(responseText) {
      $('#ajax_compare_info').html(responseText.basket_info_html ? $('#ajax_compare_info').attr('_name')+responseText.basket_info_html : '');
      t.text('Сравнить').removeClass('delete_from_compare').addClass('compare').unbind('click').bind('click', add_handler);
      $('th[_id='+t.attr('_id')+'], td[_id='+t.attr('_id')+']').hide().remove();
      $('.compare_block td[_id]').width(100/$('.table-header').length+'%');
      $("#float-header").css({width: $(".content").width()});
      if ($('.compare').length)
        $('.add-all-comparetion').show();
      if ($('.delete_from_compare').length)
        $('.add-all-comparetion').css('padding-left', '10px');
      else {
        if ($('#ajax_compare_info').text() == '') {
          $('.clear-comparetion2').hide();
          $('.add-all-comparetion').css('padding-left', '0');
        }
      }
      if (!$('.table-header').length) {
        $('.compare_block, .clear-comparetion').remove();
        $('.compare_xml').show();
      }
    }, 'json');
    return false;
  };

  $('.compare').click(add_handler);
  $('.delete_from_compare').click(remove_handler);

  $('.add-all-comparetion').click(function() {
    var t = '';
    $('.compare').each(function() {
     t += ';'+$(this).attr('_id');
    });
    $.post('/basket/ajaxAdd/', {item_id: t, catalogue_id: $('#ajax_compare_info').attr('_id')}, function(responseText) {
      $('.clear-comparetion2').show();
      $('.add-all-comparetion').hide();
      $('.compare').text('Удалить из сравнения').removeClass('compare').addClass('delete_from_compare').unbind('click').bind('click', remove_handler);
      $('#ajax_compare_info').html(responseText.basket_info_html ? $('#ajax_compare_info').attr('_name')+responseText.basket_info_html : '');
    }, 'json');
    return false;
  });

  $('.clear-comparetion2').click(function() {
    $.post('/basket/ajaxClear/', {catalogue_id: $('#ajax_compare_info').attr('_id')}, function(responseText) {
      $('.clear-comparetion2').hide();
      $('.add-all-comparetion').show().css('padding-left', '0');
      $('.delete_from_compare').text('Сравнить').removeClass('delete_from_compare').addClass('compare').unbind('click').bind('click', add_handler);
      $('#ajax_compare_info').html(responseText.basket_info_html ? $('#ajax_compare_info').attr('_name')+responseText.basket_info_html : '');
    }, 'json');
    return false;
  });


  $('.clear-comparetion').click(function() {
    var t = '';
    $('.delete_from_compare').each(function() {
     t += ';'+$(this).attr('_id'); 
    });
    $.post('/basket/ajaxRemove/', {item_id: t}, function(responseText) {
      $('.compare_block, .clear-comparetion').remove();
      $('.compare_xml').show();
    }, 'json');
    return false;
  });
  if ($('#ajax_compare_info').text() == '') {
    $('.clear-comparetion2').hide();
    $('.add-all-comparetion').css('padding-left', '0');
  }
  if ($('.compare').length == 0) {
    $('.add-all-comparetion').hide();
  }
  if ($('.compare_block').length) {
      $('.compare_xml').hide();
      $('.compare_block td[_id]').width(100/$('.table-header').length+'%');
  }


  $('.pagesizes').change(function() {
      window.location.href = $(this).val();
  });  

  $('.rsimage').click(function(){
    $('<img class="bimg" src="'+$(this).attr('_src2')+'"  width="'+$(this).attr('_w')+'" height="'+$(this).attr('_h')+'"/>').insertAfter('.main').ready(function () {
    	$('.bimg').modal({closeClass: "bimg", opacity: 40, maxHeight: $('.bimg').height(), maxWidth: $('.bimg').width(), onClose: function () {$.modal.impl.close();$(".bimg").remove();}});
        $('#simplemodal-overlay').width($(window).width()).bgiframe();
    });
  });

  $('.ajax_buying').click(function() {
      $.post('/basket/ajaxBasket/', {item_id: $(this).attr('_id')}, function(data) {
      $(data).insertAfter('.main').ready(function () {
          $('.order').modal({closeClass: "close", opacity: 40, onClose: function () {$.modal.impl.close();$(".order").remove();}});
          $('#simplemodal-overlay').width($(window).width()).bgiframe();
          $(".captcha").each(function() {
            $(this).attr('src','/si.php?n='+$(this).attr('id')+'&rid=' + Math.random());
          }).click(function(){
            $(this).attr('src','/si.php?n='+$(this).attr('id')+'&rid=' + Math.random());
          });
          $('.submit').click(function () {
              $.post('/basket/ajaxOrder/', $('#order').serializeArray() , function(data) {
                if(data == 'ok') {
                  $('#order .submit, .remove, #order div.e').remove();
                  $('#order b:first').text('Ваш заказ принят');
                  $('#order input[type=text], #order textarea').each(function() {$('<div>' + $(this).text()+ $(this).val() + '</div>').insertAfter($(this));$(this).remove();});
                }
                else{
                  $('#order div.e').remove();
                  $.map(data.errors, function(i){
                    $('<div class="e"/>').text(i.error).insertAfter($('#order *[name=' + i.name + ']'));
                  });
                }
              });
              return false;
          });
        });
      });


      /*
      $("#xs").animate({opacity: "0.4", height: $(".main").height()}, 200);
      $(".order").remove();
      $.post('/basket/ajaxBasket/', {item_id: $(this).attr('_id')}, function(data) {
        $(data).insertAfter('.main').ready(function () {
          $(".order")
                .css({'left' : (($(window).width() - $('.order').width()) / 2) + 'px',
                  'top' : (($(window).height() - $('.order').height()) / 2) + 'px'})
                .animate({opacity: "show"}, 600);
          $(".captcha").each(function() {
            $(this).attr('src','/si.php?n='+$(this).attr('id')+'&rid=' + Math.random());
          }).click(function(){
            $(this).attr('src','/si.php?n='+$(this).attr('id')+'&rid=' + Math.random());
          });
           $('.submit').click(function () {
              $.post('/basket/ajaxOrder/', $('#order').serializeArray() , function(data) {
                if(data == 'ok') {
                  $('#order .submit, .remove, #order div.e').remove();
                  $('#order b:first').text('Ваш заказ принят');
                  $('#order input[type=text], #order textarea').each(function() {$('<div>' + $(this).text()+ $(this).val() + '</div>').insertAfter($(this));$(this).remove();});
                }
                else{
                  $('#order div.e').remove();
                  $.map(data.errors, function(i){
                    $('<div class="e"/>').text(i.error).insertAfter($('#order *[name=' + i.name + ']'));
                  });
                }
              });
              return false;
          });
          $('.close').click(function () {
              $("#xs").animate({opacity:"0.0",height:"0"},200);
              $(".order").animate({opacity:"hide"},600);
              return false;
          });
          }
        );
      });*/
      return false;
    });

$('.feedback_send, .ebug').click(function() {
    var t= $(this);
    $.post('/feedbacks/ajaxFeedback/', null, function(data) {
    $(data).insertAfter('.main').ready(function () {
    	$('.feedback').modal({closeClass: "close", opacity: 40, onClose: function () {$.modal.impl.close();$(".feedback").remove();}});
        $('#simplemodal-overlay').width($(window).width()).bgiframe();
        $(".captcha").each(function() {
          $(this).attr('src','/si.php?n='+$(this).attr('id')+'&rid=' + Math.random());
        }).click(function(){
          $(this).attr('src','/si.php?n='+$(this).attr('id')+'&rid=' + Math.random());
        });
        if (t.hasClass('ebug')) {
          $('input[name="type"]').val(0);
          $('textarea[name="qtext"]').val('на странице товара "'+$('.bread').text().replace('Главная страница > ', '')+'" есть неточность:');
        }
        $('.submit').click(function () {
            $.post('/feedbacks/ajaxFeedback/', $('#feedback').serializeArray() , function(data) {
              if(data == 'ok') {
                $('#feedback .submit, .remove, #feedback div.e').remove();
                $('#feedback b:first').text('Ваша заявка принята');
                $('#feedback input[type=text], #feedback textarea').each(function() {$('<div>' + $(this).text()+ $(this).val() + '</div>').insertAfter($(this));$(this).remove();});
              }
              else{
                $('#feedback div.e').remove();
                $.map(data.errors, function(i){
                  $('<div class="e"/>').text(i.error).insertAfter($('#feedback *[name=' + i.name + ']'));
                });
              }
            });
            return false;
        });
      });
    });
    /*
    $("#xs").animate({opacity: "0.4", height: $(".main").height()}, 200);
    $(".feedback").remove();
    $.post('/feedbacks/ajaxFeedback/', null, function(data) {
      $(data).insertAfter('.main').ready(function () {
        $(".feedback")
              .css({'left' : (($(window).width() - $('.feedback').width()) / 2) + 'px',
                'top' : (($(window).height() - $('.feedback').height()) / 2) + 'px'})
              .animate({opacity: "show"}, 600);
        $(".captcha").each(function() {
          $(this).attr('src','/si.php?n='+$(this).attr('id')+'&rid=' + Math.random());
        }).click(function(){
          $(this).attr('src','/si.php?n='+$(this).attr('id')+'&rid=' + Math.random());
        });
        $('.submit').click(function () {
            $.post('/feedbacks/ajaxFeedback/', $('#feedback').serializeArray() , function(data) {
              if(data == 'ok') {
                $('#feedback .submit, .remove, #feedback div.e').remove();
                $('#feedback b:first').text('Ваша заявка принята');
                $('#feedback input[type=text], #feedback textarea').each(function() {$('<div>' + $(this).text()+ $(this).val() + '</div>').insertAfter($(this));$(this).remove();});
              }
              else{
                $('#feedback div.e').remove();
                $.map(data.errors, function(i){
                  $('<div class="e"/>').text(i.error).insertAfter($('#feedback *[name=' + i.name + ']'));
                });
              }
            });
            return false;
        });
        $('.close').click(function () {
            $("#xs").animate({opacity:"0.0",height:"0"},200);
            $(".feedback").animate({opacity:"hide"},600);
            return false;
        });
        }
      );
    });*/
    return false;
  });

  
  $('.request_send').click(function() {
      $.post('/request/ajaxRequest/', null, function(data) {
      $(data).insertAfter('.main').ready(function () {
          $('.request').modal({closeClass: "close", opacity: 40, onClose: function () {$.modal.impl.close();$(".request").remove();}});
          $('#simplemodal-overlay').width($(window).width()).bgiframe();
          $(".captcha").each(function() {
            $(this).attr('src','/si.php?n='+$(this).attr('id')+'&rid=' + Math.random());
          }).click(function(){
            $(this).attr('src','/si.php?n='+$(this).attr('id')+'&rid=' + Math.random());
          });
          $('.submit').click(function () {
              $.post('/request/ajaxRequest/', $('#request').serializeArray() , function(data) {
                if(data == 'ok') {
                  $('#request .submit, .remove, #request div.e').remove();
                  $('#request b:first').text('Ваш запрос принят');
                  $('#request input[type=text], #request textarea').each(function() {$('<div>' + $(this).text()+ $(this).val() + '</div>').insertAfter($(this));$(this).remove();});
                }
                else{
                  $('#request div.e').remove();
                  $.map(data.errors, function(i){
                    $('<div class="e"/>').text(i.error).insertAfter($('#request *[name=' + i.name + ']'));
                  });
                }
              });
              return false;
          });
        });
      });
      return false;
    });
});

