var ProductList = Class.extend({

  init: function() {
    this.productControlsVisible = false;
    this.observeProductDoubleClicks();
    this.observeProductEntries();
    this.observeProductDeleteClicks();
    this.observeOutsideClicks();
  },

  hideControls: function() {
    $("a.delete").hide();
    $("#product-list .entry").hide();
    this.productControlsVisible = false;
  },

  showControls: function() {
    $("a.delete").show();
    $("#product-list .entry").show();
    $("#new-product").focus();
    this.productControlsVisible = true;
  },

  observeOutsideClicks: function() {
    var self = this;
    $("body").click(function(event) {
      if ($(event.originalTarget).parents("#product-list").attr("id") != $("#product-list").attr("id")) {
        self.hideControls();
      }
    });
  },

  observeProductDoubleClicks: function() {
    var self = this;
    $("#product-list").dblclick(function() {
      if (!self.productControlsVisible) {
        self.showControls();
      } else {
        self.hideControls();
      }
    });
  },

  observeProductDeleteClicks: function() {
    $("#product-list a.delete").click(function() {
      var productName = $(this).prev(".product-name").html();
      $(this).parent("li").remove();
      $.ajax({
        url: sellerDeleteProductUrl,
        data: {
          "product":productName,
          "seller-slug":$("#slug").html()
        },
        failure: function(data) {
          alert("Update failed.");
        }
      });
      return false;
    });
  },

  observeProductEntries: function() {

    var self = this;

    $("#product-form").submit(function() {

      var cleanProductName = ucwords($("#new-product").val().toLowerCase());
      var productLi = "<li><span class=\"product-name\">"
        + cleanProductName
        + "</span> <a href=\"#\" class=\"delete\">X</a></li>";

      $(this).parent("li").before(productLi);
      $("a.delete").show();
      $("#none-indicator").hide();
      self.observeProductDeleteClicks();

      $.ajax({
        url: sellerAddProductUrl,
        data: {
          "product":$("#new-product").val(),
          "seller-slug":$("#slug").html()
        },
        failure: function(data) {
          alert("Update failed.");
        }
      });

      $("#new-product").val("");

      return false;
    });
  }
});

