var $product = $product || {};
$product.selections = {};

(function($) {


  $product.selections.handlers = {
    hide: function() {
      if (this.isVisible()) {
        this.animate({width: "0px", queue: true}, 500);
        if (this.__owner) this.__owner.removeClass("selected");
      }
    },
    show: function() {
      this.animate({width: "300px", queue: true}, 500);
      if (this.__owner) this.__owner.addClass("selected");
    },
    isVisible: function() {
      return this.width() > 10;
    },
    toggle: function() {
      if (this.isVisible()) {
        this.hide();
      } else {
        this.show();
      }
    },
    setOwner: function(owner) {
      this.__owner = $(owner);
    },
    resetSelection: function() {
      $product.selections.carFilter.resetFilter();
      $product.selections.typeFilter.hide().resetFilter();
      $product.selections.modelFilter.hide().resetFilter();
      $(".header-img .header-image-toolbox").hide();
      $(".header-img img.header-image")
              .attr("src", $product.defaultBackground)
              .removeAttr("resource-url")
              .removeAttr("model")
              .removeAttr("visibility");
    }
  };

  $product.selections.updateFilters = function() {
    var $car = $(".filters-goods .filters a.select.car-select");
    var $type = $(".filters-goods .filters a.select.type-select");

    if (!$car.attr("selection-id") || !$type.attr("selection-id")) return;

    $product.model_selection.find(".offsetter").empty();
    $.ajax({
      type: "GET",
      url: "/goods/products/by_car_and_type",
      data: {
        car: $car.attr("selection-id"),
        product_type: $type.attr("selection-id")
      },
      dataType: "json",
      success: function(msg) {
        if (msg.length < 1) {
          $product.model_selection.find(".offsetter").html("<strong>Извините, подходящих<br/> моделей не найдено</strong>");
          return;
        }

        $.each(msg, function(index, model) {
          var $dom = $('<div class="item"></div>');
          var $a = $('<a selection-id="' + model.id + '"></a>');
          $dom.append($a);
          $a.html(model.name);
          $a.attr("href", model.resource_url);
          $product.model_selection.find(".offsetter").append($dom);
        });
      }
    });
  };

  $product.selections.selectorsCache = {};
  $product.selections.selectorFactory = function(target) {
    $product.selections.selectorsCache[target] = $product.selections.selectorsCache[target] || function(event) {
      var $self = $(this);
      var $container = $self.parents(".offsetter");
      $container.find(".item a.selected").removeClass("selected");
      $self.addClass("selected");
      $(".filters-goods .filters a.select." + target + "-select").html($self.html()).attr("selection-id", $self.attr("selection-id"));
      $inplace.event.trigger("/goods-filter/" + target + "/selected", {container: $self, event: event});
    };

    return $product.selections.selectorsCache[target];
  };

  $product.selections.resetFilterExtension = {
    resetFilter: function() {
      this.removeAttr("selection-id")
              .find("a.select")
        //.removeClass("selected")
              .html("нажмите, чтобы указать");
      return this;
    }
  };

  $(function() {

    $product.defaultBackground = $(".header-img img.header-image").attr("src");
    var modalWindow = $('.new-product');
    var linkToCreate = $('.new-product-link');
    if (modalWindow.length > 0 && linkToCreate.length > 0) {
      modalWindow.dialog({
        bgiframe: true,
        modal:true,
        draggable: false,
        buttons:{
          "ok":function() {
            if ($("#product_name").val().length > 0) {
              $('.new-product>form').submit();
            } else {
              //тут обработка косяка с пустым названием
              alert("название не может быть пустым");
            }
          },
          "Сancel":function() {
            $(this).dialog("close");
          }
        },
        closeOnEscape:true,
        resizeble:false
      });
      modalWindow.dialog('close');
      linkToCreate.click(function() {
        modalWindow.dialog('open');
      });
    }


    $product.cars_selection = $(".selection-source.cars-selection");
    $.extend($product.cars_selection, $product.selections.handlers).setOwner($(".filters-goods a.select.car-select"));
    $product.cars_selection.find(".item a").click($product.selections.selectorFactory("car"));

    $product.type_selection = $(".selection-source.type-selection");
    $.extend($product.type_selection, $product.selections.handlers).setOwner($(".filters-goods a.select.type-select"));
    $product.type_selection.find(".item a").click($product.selections.selectorFactory("type"));

    $product.model_selection = $(".selection-source.model-selection");
    $.extend($product.model_selection, $product.selections.handlers).setOwner($(".filters-goods a.select.model-select"));
    $product.model_selection.find(".item a").click($product.selections.selectorFactory("model"));


    $product.selections.carFilter = $(".filters-goods .block.cars");
    $.extend($product.selections.carFilter, $product.selections.resetFilterExtension);
    $product.selections.typeFilter = $(".filters-goods .block.types");
    $.extend($product.selections.typeFilter, $product.selections.resetFilterExtension);
    $product.selections.modelFilter = $(".filters-goods .block.models");
    $.extend($product.selections.modelFilter, $product.selections.resetFilterExtension);

    $inplace.event.bind("/goods-filter/car/selected", function($data) {
      $product.selections.typeFilter.show();
      $product.selections.modelFilter.resetFilter();
    });

    $inplace.event.bind("/goods-filter/car/selected", function($data) {
      var $selector = $data.container;
      var $img = $selector.parents(".header-img").find(".header-image.has-header-image-toolbox");
      $img.attr("src", $selector.attr("big-thumbnail"));
      $img.attr("model", $selector.attr("model"));
      $img.attr("bigname", $selector.attr("bigname"));
      $img.attr("smallname", $selector.attr("smallname"));
      $img.attr("small-thumbnail", $selector.attr("small-thumbnail"));
      $img.attr("resource-url", $selector.attr("resource-url"));
      $img.attr("visibility", $selector.attr("visibility"));
      $vis = $selector.parents(".header-img").find(".tool.visibility");
      $vis.removeClass("invisiblee");
      if($selector.attr("visibility") === "false") $vis.addClass("invisiblee");
    });

    $inplace.event.bind("/goods-filter/car/selected", $product.selections.updateFilters);

    $inplace.event.bind("/goods-filter/type/selected", function($data) {
      $product.selections.modelFilter.show().resetFilter();
    });
    $inplace.event.bind("/goods-filter/type/selected", $product.selections.updateFilters);


    $(".filters-goods a.select.car-select").click(function() {
      $product.type_selection.hide();
      $product.model_selection.hide();
      $product.cars_selection.toggle();
    });

    $(".filters-goods a.select.type-select").click(function() {
      $product.cars_selection.hide();
      $product.model_selection.hide();
      $product.type_selection.toggle();
    });

    $(".filters-goods a.select.model-select").click(function() {
      $product.cars_selection.hide();
      $product.type_selection.hide();
      $product.model_selection.toggle();
    });

    $product.cars_selection.find(".item.car a.selected").click();

//     $('div.product-shield').tooltip({
//             delay: 0,
//            showURL: false,
//            bodyHandler: function() {
//            return $("<img/>").attr("src", this.src);
//    }
//});

  });

})(jQuery);
