(function() {
  $(document).ready(function() {
    var true_slider_values_price = [0, 50, 75, 100, 125, 150, 175, 200, 225, 250, 275, 300, 325, 350, 375, 400, 425, 450, 475, 500, 600, 700, 800, 900, 1000, 1200, 1400, 1600, 1800, 2000, 2200, 2400, 2600, 2800, 3000, 3300, 3600, 3900, 4200, 4500, 4800, 5100, 5400, 5700, 6000, '- -'];
    var values =     [0, 2,   3,   4,   5,   6,   7,   8,   9,   10,   11, 12, 13, 14,  15, 16,  17, 18, 19,  20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40,  42,  44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 67, 68, 70];

    var true_slider_values_cap = [0, 0.125, 0.25, 0.5, 0.75, 1.00, 1.25, 1.5, 2.00, 2.25, 2.5, 2.75, 3.00, 4.00, 5.00, 7.00, '- -'];
    var valuesCap =     [0, 1,     2,    3,   4,    5,    6,    7,   8,    9,    10,  11,   12,   13,   14,   15,   16];
    
    var Search = {
      init: function() {
        var that = this;
        var change_act;
        $(".submit_form").click(function() {
          that.submitForm();
          return false;
        })
        show_overlay();
        if ($( "#slider-range" ).length || $( "#slider-range-cap" ).length) {
          show_slider();
        }
        that.clickHandler(that);
      },

      clickHandler: function(that) {
        $(".search_menu a").click(function() {
          that.searchMenuClick($(this));
          return false;
        })
        $(".type_menu li:not(.simple_link) a").click(function() {
          if ($(this).closest("ul").hasClass("type")) {
            change_act = that.changeAct($(this));
            //$("#catalog_type").val($(this).attr("rel"));
            if (change_act == 1) {
              $("#catalog_type").val('');
            } else {
              $("#catalog_type").val($(this).text());
            }
          } else if ($(this).closest("ul").hasClass("color")) {
            change_act = that.addAct($(this));
            var color_val = '';
            $("ul.color li").each(function() {
              if ($(this).hasClass("act")) color_val += $(this).find("a:first").attr("rel") + ',';
            })
            $("#catalog_color").val(color_val);
          } else if ($(this).closest("ul").hasClass("subgr")) {
            change_act = that.addAct($(this));
            var subgr_val = '';
            $("ul.subgr li").each(function() {
              if ($(this).hasClass("act")) subgr_val += $(this).find("a:first").attr("rel") + ',';
            })
            $("#catalog_subgr").val(subgr_val);
          }
          that.submitForm();
          return false;
        })
        $(".country_list ul a").click(function() {
          change_act = that.changeAct($(this));
          if (change_act == 1) {
            $("#catalog_country").val('');
          } else {
            $("#catalog_country").val($(this).find("span").text());
          }
          that.submitForm();
          return false;
        })
        $("#CatalogPaginator a").live("click", function() {
          $("#catalog_page").val($(this).text());
          that.submitForm();
          return false;
        })
        $("select.page").change(function(){
          $("#catalog_items").val($(this).val());
          that.submitForm();
          return false;
        })
        $(".catalog_page").click(function() {
          $("#catalog_page").val($(this).find("a").attr("rel"));
          that.submitForm();
          return false;
        })

        $(".item1 a").live("click", function() {
            
        })
      },

      submitForm: function() {
         $.ajax({
           method: "post",
           beforeSend: function() {
             $(".ajax_load").show();
           },
           url: $("#searchForm").attr("action") + "?" + $("#searchForm").serialize(),
           success: function(json) {
             var obj = $.parseJSON(json); 
             if (obj) {
               $("#product_catalog").html(obj.content);
               $("#paginator_wrap").html(obj.paginator);
                           
               if (obj.prev_page) {
                 $(".prev_page").show();
                 $(".prev_page a").attr("rel", obj.prev_page);
               } else {
                 $(".prev_page").hide();
               }
               if (obj.next_page) {
                 $(".next_page").show();
                 $(".next_page a").attr("rel", obj.next_page);
               } else {
                 $(".next_page").hide();
               }
               if (obj.next_page || obj.prev_page) {
                 var catalog_height = $(".assortiment").height();
                 $(".catalog_page").css("height", catalog_height);
                 $(".catalog_page a").each(function() {
                   $(this).css("height", parseInt(parseInt(catalog_height)/2));
                   $(this).css("padding-top", parseInt(parseInt(catalog_height)/2)-14);
                 })
               }
             }
             $(".ajax_load").hide();
             show_overlay();

           }

         })
      },

      searchMenuClick: function(el) {
        $(".search_menu a").removeClass("act");
        el.addClass("act");
        $("#catalog_price").val(el.attr("rel"));
      },
      
      changeAct: function(el) {
        if (el.closest("ul")) {
          if (el.closest("li").hasClass("act")) {
            el.closest("li").removeClass("act");
            el.closest("li").find(".act_menu_helper").remove();
            return 1;
          }
          var current = el.closest("ul").find("li.act");
          current.find(".act_menu_helper").remove();
          current.removeClass("act");
          el.parent().addClass("act");
          el.parent().append("<div class='act_menu_helper'></div>")
          $("#catalog_page").val(1);

          return 0;
        }
      },
      addAct: function(el) {
        if (el.closest("ul")) {
          if (el.closest("li").hasClass("act")) {
            el.closest("li").removeClass("act");
            el.closest("li").find(".act_menu_helper").remove();
            return 1;
          }
          el.parent().addClass("act");
          el.parent().append("<div class='act_menu_helper'></div>")
          $("#catalog_page").val(1);
        }
      }
    }

    Search.init();

    function show_overlay() {
      $(".item1 a[rel]").overlay({

        //mask: '#CCC',
        //effect: 'apple',
	//effect: 'drop',
	//mask: '#789',
	mask: {

		// you might also consider a "transparent" color for the mask
		color: '#fff',

		// load mask a little faster
		loadSpeed: 200,

		// very transparent
		opacity: 0.5
	},

        onBeforeLoad: function() {

          // grab wrapper element inside content
          var wrap = this.getOverlay().find(".contentWrap");

          // load the page specified in the trigger
          wrap.load(this.getTrigger().attr("href"));
        }

      });
    }


   function show_slider() {
      var min_value, max_value;
      var slider_price = $( "#slider-range" ).slider({
        range: true,
        min: 0,
        max: 70,
        values: [ 0, 70 ],
        slide: function(event, ui) {
          var includeLeft = event.keyCode != $.ui.keyCode.RIGHT;
          var includeRight = event.keyCode != $.ui.keyCode.LEFT;
          var value = findNearest(includeLeft, includeRight, ui.value, 'price');
          if (ui.value == ui.values[0]) {
              slider_price.slider('values', 0, value);
          }
          else {
              slider_price.slider('values', 1, value);
          }

          $( "#price_1" ).val( getRealValue(slider_price.slider('values', 0), 'price'));
          $( "#price_2" ).val( getRealValue(slider_price.slider('values', 1), 'price') );
          return false;
        },
        stop: function(event, ui) {
          $("#catalog_price_min").val(getRealValue(ui.values[0], 'price'));
          $("#catalog_price_max").val(getRealValue(ui.values[1], 'price'));
          
          Search.submitForm();
        }
      });
      $("#price_1").val(values[$( "#slider-range" ).slider( "values", 0 )]);
      $("#price_2").val('- -');
      
      var slider_cap = $( "#slider-range-cap" ).slider({
        range: true,
        min: 0,
        max: 16,
        values: [ 0, 16 ],
        slide: function(event, ui) {
          var includeLeft = event.keyCode != $.ui.keyCode.RIGHT;
          var includeRight = event.keyCode != $.ui.keyCode.LEFT;
          var value = findNearest(includeLeft, includeRight, ui.value, 'cap');
          if (ui.value == ui.values[0]) {
              slider_cap.slider('values', 0, value);
          }
          else {
              slider_cap.slider('values', 1, value);
          }

          $( "#capacity_1" ).val( getRealValue(slider_cap.slider('values', 0), 'cap') );
          $( "#capacity_2" ).val( getRealValue(slider_cap.slider('values', 1), 'cap') );
          return false;
        },
        stop: function(event, ui) {
          $("#catalog_capacity_min").val(getRealValue(ui.values[0], 'cap'));
          $("#catalog_capacity_max").val(getRealValue(ui.values[1], 'cap'));
          Search.submitForm();
        }
      });
      $("#capacity_1").val(0);
      $("#capacity_2").val("- -");
    }

    function findNearest(includeLeft, includeRight, value, type) {
      var values_inner;

      if (type == 'price') values_inner = values;
        else if (type == 'cap') values_inner = valuesCap;
      var nearest = null;
      var diff = null;
      for (var i = 0; i < values_inner.length; i++) {
          if ((includeLeft && values_inner[i] <= value) || (includeRight && values_inner[i] >= value)) {
              var newDiff = Math.abs(value - values_inner[i]);
              if (diff == null || newDiff < diff) {
                  nearest = values_inner[i];
                  diff = newDiff;
              }
          }
      }
      return nearest;
    }
    
    function getRealValue(sliderValue, type) {
        var values_inner;
        if (type == 'price') values_inner = values;
          else if (type == 'cap') values_inner = valuesCap;

        for (var i = 0; i < values_inner.length; i++) {
            if (values_inner[i] >= sliderValue) {
              if (type == 'price') return true_slider_values_price[i];
                else if (type == 'cap') return true_slider_values_cap[i];
            }
        }
        return 0;
    }

    
  })
})(jQuery);

