var AjaxBasket = Class.extend({

  basket_page_id: 0,
  amountOfProducts: 0,
  products: new Array(),
  productHtmls: new Array(),
  ul: null,

  pages: new Array(),
  perPage: 3, /* HOW MANY PRODUCT DOES WE WANT TO SHOW IN THE BASKET PER PAGE */
  amountOfPages: 0, /* AMOUNT OF PAGES IN THE BASKET */
  currentAddPage: 0,
  currentPage: 0, /* THE CURRENT BASKET PAGE ID */

  init: function (basket) {
    this.ul = $("ajax_webshop_basket");
    this.basket_page_id = basket;
    var par = this;
    jQuery("#prevBasketPage").bind('click', function(){
      par.prevPage();
    });
    jQuery("#nextBasketPage").bind('click', function(){
      par.nextPage();
    });
  },

  /**
   * Let the user define another button(s), that will take the user to the basket.
   * Just pass the component, then the events will be put on it
   *
  **/
  addbasketOrderListener: function (obj) {
    if (obj) {
      if (jQuery(obj)) {
        var bpid = this.basket_page_id;
        jQuery(obj).bind('click', function () {
          window.setTimeout(function(){
            window.location = '/?id=' + bpid;
          }, 0);
        });
      }
    }
  },

  /**
   * Arguments:
   *
   * id = the product id (WILL NOT GET CHANGED)
   * amount = amount of the product the user wants to add to the basket (CAN BE CHANGED)
   * name = the name of the product (WILL NOT GET CHANGED)
   * price = the price for a single product (WILL NOT GET CHANGED)
   */
  addToBasket: function (id, amount, name, price) {
    id = parseInt(id, 10);
    if (this.products[id] == null || this.products[id] == undefined) {
      this.amountOfProducts++;
      this.products[id] = new Array(0, name, price);
      this.products[id][0] += parseInt(amount, 10) -1;
      this.productHtmls[id] = null;
      this.updateBasket(id);
      this.showCurrentPage();
      this.addOne(id, 1);
    } else {
      this.addOne(id, amount);
    }
  },

  /**
   * Adds the given amount (or 1 if amount is not specified),
   * of the given product
  **/
  addOne: function (id, amount, qty_field) {
    id = parseInt(id, 10);
    if (!amount) {
      amount = 1;
    } else {
      amount = parseInt(amount, 10);
    }

    this.products[id][0] += amount;
    if (qty_field) {
      //qty_field.value = 1;
    }
    this.updateBasket(id);
    return true;
  },

  /**
   * Removes the given amount (or 1 if amount is not specified),
   * of the given product
  **/
  removeOne: function (id, amount, qty_field) {
    id = parseInt(id, 10);
    if (!amount) {
      amount = 1;
    } else {
      amount = parseInt(amount, 10);
    }
    if (this.products[id][0] > 0) {
      this.products[id][0] -= amount;
    }
    if (qty_field) {
      //qty_field.value = -1;
    }
    this.updateBasket(id);
    return true;
  },

  /**
   * Just redirects the user to the basket
   */
  order: function () {
    if (this.basket_page_id === 0) {
      // Handle the error here
    } else {
      window.location.href = '/?id=' + this.basket_page_id;
    }
  },

  /**
   * Updates the HTML basket, so that the price and the amount of products is correct
   *
  **/
  updateBasket: function (id) {
    var product = this.products[id];

    if (this.productHtmls[id] == null || this.productHtmls[id] == undefined) {
      var tmp = jQuery('<li id="li' + id + '"></li>');
      jQuery('#ajax_webshop_basket_price').before(tmp);
      this.productHtmls[id] = jQuery("#li" + id);
      if (!this.pages[this.currentAddPage]) {
        this.pages[this.currentAddPage] = new Array(this.perPage);
      }
      for (var i = 0; i < this.perPage; i++) {
        if (!this.pages[this.currentAddPage][i]) {
          this.pages[this.currentAddPage][i] = 'li' + id;
          break;
        }
      }
      if (i == this.perPage-1) {
        this.currentAddPage++;
      }
    }

    var html = this.productHtmls[id];
    var id_amount = $(id+'_amount');
    if (!id_amount) {

    //html.empty();

      var p = jQuery('<p>' + product[1] + '</p>');
      var dl = jQuery('<dl></dl>');
        var dt = jQuery('<dt id="'+id+'_amount">' + product[0] + ' x</dt>');
        var dd = jQuery('<dd></dd>');

          var frm = jQuery('<form id="webshopform'+webshop_id+'p'+id+'_basket" class="webshop-product-loop" method="post" action="/webshop_basket.php"></form>');
            var hdn1 = jQuery('<input type="hidden" name="p['+id+'][id]" value="'+page_id+'" />');
            var hdn2 = jQuery('<input type="hidden" name="p['+id+'][p'+webshop_id+'id]" value="'+id+'" />');
            var hdn3 = jQuery('<input type="hidden" name="p['+id+'][w]" value="'+webshop_id+'" />');
            var hdn4 = jQuery('<input type="hidden" name="p['+id+'][qty_dontadd]" id="'+id+'_qty2" value="10" />');

            hdn1.appendTo(frm);
            hdn2.appendTo(frm);
            hdn3.appendTo(frm);
            hdn4.appendTo(frm);

          var w = null;
          var span = jQuery('<span>DKK ' + (number_format(product[2], 2, ',', '.')) + '</span>');
          var a1 = jQuery('<a href="javascript:void(0);" class="minus"></a>');
          a1.bind('click', function() {
            if (ab.removeOne(id, null, hdn3)) {
              w.submit($("webshopform" + webshop_id+'p'+id+'_basket'));
            }
          });
          var a2 = jQuery('<a href="javascript:void(0);" class="plus"></a>');
          a2.bind('click', function() {
            if (ab.addOne(id, null, hdn3)) {
              w.submit($("webshopform" + webshop_id+'p'+id+'_basket'));
            }
          });
          a2.appendTo(dd);
          a1.appendTo(dd);
          span.appendTo(dd);
          frm.appendTo(dd);
        dt.appendTo(dl);
        dd.appendTo(dl);
      p.appendTo(html);
      dl.appendTo(html);
      w = new Webshop('webshopform'+webshop_id+'p'+id+'_basket');
    } else {
      id_amount.innerHTML = product[0] + ' x';
      $(id + '_qty2').value = product[0];
    }

    this.updateTotal();
  },

  /**
   * Updates the grandtotal
  **/
  updateTotal: function () {
    var total = 0;
    this.amountOfPages = Math.ceil(this.amountOfProducts / this.perPage);
    if ($('basket_pagin')) {
      $('basket_pagin').innerHTML = 'Viser '+ (this.currentPage+1) +' af ' + this.amountOfPages;
    }
    for (var i in this.products) {
      if (IsNumeric(i)) {
        var p = this.products[i];
        total += p[0] * p[2];
      }
    }
    
    if ($('current_basket_price')) {
      $('current_basket_price').innerHTML = 'DKK ' + (number_format(total, 2, ',', '.'));
    }
  },

  hideAllPages: function () {
    for (var p = 0; p < this.pages.length; p++) {
      var pages = this.pages[p];
      for (var i = 0; i < pages.length; i++) {
        if ($(pages[i])) {
          $(pages[i]).style.display = 'none';
        }
      }
    }
  },

  /**
   * Shows the current LI's as a kind of page
   */
  showCurrentPage: function () {
    this.hideAllPages();
    var pages = this.pages[this.currentPage];
    for (var i = 0; i < pages.length; i++) {
      var page = pages[i];
      if (page && $(page)) {
        $(page).style.display = 'list-item';
      }
    }
    if ($('basket_pagin')) {
      $('basket_pagin').innerHTML = 'Viser ' + (this.currentPage+1) + ' af ' + ( this.amountOfPages );
    }
  },

  nextPage: function () {
    //this.amountOfPages = this.products / this.perPage;

    if (this.currentPage+1 < this.amountOfPages) {
      this.currentPage++;
      this.showCurrentPage();
    }
  },

  prevPage: function () {
    this.currentPage--;
    if (this.currentPage < 0) {
      this.currentPage = 0;
    }
    this.showCurrentPage();
  }

});
