/**
 * @author Eric Bartels
 * @version $Id: cart.js 1331 2010-04-29 03:52:46Z ericbartels $
 */

/**
 * @constructor
 */
EKS.ShopCart = function () {
    this.myDataSource = null;
    this.myDataTable = null;
};

/**
 * Add the selected article to the cart
 *
 * @param {string} artno
 * @param {string} supplierID
 * @param {string} idOfElement
 */
EKS.ShopCart.prototype.add = function (artno, supplierID, idOfElement) {
    /// Get the elements holding the progress and the response
    var progress = $("progress_" + idOfElement);

    /// Add the parameters to the call
    params = "artno=" + artno + "&supplier=" + supplierID +
        "&quantity=" + $('quantity_' + idOfElement).value;
    params = encodeURI (params);

    var req = new Ajax.Updater (
        'response_' + idOfElement,
        EKS.Base + "cart/add",
        {
            method: 'post',
            asynchronous: true,
            parameters: params,
            onComplete: function (req, json) {
                progress.style.display = "none";
            },
            onLoading: function (req, json) {
                $('response_' + idOfElement).style.display = 'none';
                progress.style.display = "block";
            }
        }
    );
};

/**
 * Remove article from cart
 * @param {Object} ID
 */
EKS.ShopCart.prototype.remove = function (ID, rowID) {
    var url = Base + "cart/remove";
    var me = this;

    var req = new Ajax.Request (
        url,
        {
            parameters: 'ID=' + ID,
            asynchronous: true,
            onLoading: function () {
                $('summaryProgress').style.display = 'block';
                $('cartSummary').style.display = 'none';
            },
            onComplete: function (req, json) {
                if (json.Status) {
                    // Get the summary
                    me.updateSummary (ID);

                    /// Remove the old row!
                    me._deleteRow (rowID);

                    /// Update the cart-display
                    if ($('currentCartInfoTotalSum') && json.Total) {
                        $('currentCartInfoTotalSum').innerHTML = json.Total;
                    }
                    if ($('currentCartInfoCount') && json.Total) {
                        $('currentCartInfoCount').innerHTML = json.TotalCount;
                    }
                } else {
                    alert ("Fehler beim Löschen!");
                }
            }
        }
    );
};

/**
 * Update the selected article inside the cart
 * @param {Object} ID
 */
EKS.ShopCart.prototype.update = function (ID) {
    var quantity = $('quantity_' + ID).value;
    var url = Base + 'cart/update';
    var params = 'quantity=' + quantity + '&ID=' + ID;

    var me = this;

    var req = new Ajax.Updater (
        'row_' + ID,
        url,
        {
            parameters: params,
            asynchronous: true,
            method: 'post',
            onLoading: function ()
            {
              // Disable the boxes
              jQuery("select.dropdown.quantity").attr('disabled', 'disabled');
              jQuery("input.cart-add-quantity").attr('disabled', 'disabled');

              $('summaryProgress').style.display = 'block';
              $('cartSummary').style.display = 'none';
            },
            onComplete: function (req, json)
            {
              // Disable the boxes
              jQuery("select.dropdown.quantity").attr('disabled', 'disabled');
              jQuery("input.cart-add-quantity").attr('disabled', 'disabled');

              // Update the cart-display
              if ($('currentCartInfoTotalSum') && json.Total) {
                  $('currentCartInfoTotalSum').innerHTML = json.Total;
              }
              if ($('currentCartInfoCount') && json.Total) {
                  $('currentCartInfoCount').innerHTML = json.TotalCount;
              }

              if (!json.Status)
              {
                me.initQuantityChanging();
                jQuery("select.dropdown.quantity").removeAttr('disabled');
                jQuery("input.cart-add-quantity").removeAttr('disabled');
                alert ('Fehler: ' + json.StatusText);
              }
              else
              {
                me.updateSummary (ID);
              }
            }
        }
    );
};

EKS.ShopCart.prototype.updateSummary = function (ID) {
  var url = Base + 'cart/summaryFooter';
  var me = this;

    // Get the data
    var request = new Ajax.Updater (
        'cartSummary',
        url,
        {
            method: 'post',
            onComplete: function (req, json) {
              jQuery("select.dropdown.quantity").removeAttr('disabled');
              jQuery("input.cart-add-quantity").removeAttr('disabled');
              me.initQuantityChanging();
              
              $('cartSummary').style.display = 'block';

                // Hide the loading stuff and animate
                // the result row
                $('summaryProgress').style.display = 'none';

                if (json.Status) {
                    
                } else {
                    alert (json.StatusText);
                }
            }
        }
    )
};

/**
 *
 * @param {Object} e
 */
EKS.ShopCart.prototype.init = function (e) {
  if (!$('cartContent')) {
      return;
  }

  var me = this;

  me.initQuantityChanging();
};

/**
 * Initialize the event-listening for changing the quantity of an item
 */
EKS.ShopCart.prototype.initQuantityChanging = function()
{
  var me = this;

  var addFunc = function(e) {
    var obj = jQuery(e.target);
    var qty = obj.val();

    if(!qty.match(/^[0-9]{1,3}$/))
    {
      alert("Bitte geben Sie eine Zahl zwischen 1 und 999 ein.");
      return;
    }

    var id = obj.attr('id').replace(/quantity_/, "");
    me.update(id);
  };

  // Listen to changes of the dropdowns
  jQuery("select.dropdown.quantity").change(function(e) {
    addFunc(e);
  });

  // If its the textbox
  jQuery("input.cart-add-quantity").keyup(function(e) {
    addFunc(e);
  })
};

/**
 * User pressed keys inside an input box of the quantity
 * @param {Object} e
 */
EKS.ShopCart.prototype.changeQuantity = function (e) {
    var target = e.target || e.srcElement;

    /// Get the id of the link for updating the field and show it
    var id = target.id.replace (/quantity_/, '');
    $('updateCmd_' + id).style.display = "block";
};

/**
 * Redraw the grid and apply alternating colors
 */
EKS.ShopCart.prototype._redrawGrid = function () {
    var rows = $('cartContent').getElementsByTagName ('tr');
    var len = rows.length;

    for (var i = 0; i < len; ++i) {
        rows[i].className = 'product row' + (i % 2);
    } // end foreach
};

/**
 * Remove the given row from the table
 * @param {string} rowID
 */
EKS.ShopCart.prototype._deleteRow = function (rowID) {
    var rows = $$('#cartContent tr.product');
    var len = rows.length;

    for (var i = 0; i < len; ++i) {
        if (rows[i].id == rowID) {
            var parent = rows[i].parentNode;
            parent.removeChild (rows[i]);
            break;
        }
    } // end foreach

    if (0 == $$('#cartContent tr.product').length) {
        $('cartContentValid').style.display = 'none';
        $('cartContentInvalid').style.display = 'block';
    }

    this._redrawGrid ();
};

EKS.Cart = new EKS.ShopCart ();
jQuery(function() {
  EKS.Cart.init ();
});