jQuery.fn.extend({
    shoppingCart: function(o) {
        return this.each(function() {
            new jQuery.shoppingCart(this, o);
        });
    }             
});               

jQuery.extend({   
  shoppingCart: function(e, o) {
    var publ = this;
    publ.add = function(data,callback) {  return priv.addItem(data,callback); };
    publ.isInCart = function(idx) {  return priv.isInCart(idx); };
    var priv = {
      cFg: {
        onMoveItem: o.onMoveItem,
        noButtons: false
      },

      list: e,
      scope: null,
      size: 0,

      prepare: function()
      {
        var scope = jQuery(priv.list).wrap('<div class="shoppingCart-scope"></div>').parent().get(0);
        priv.scope = scope;
        priv.size = jQuery("li", priv.list).size();

        if (priv.size > 0) {
          var idx = 1;
          jQuery("li", priv.list).each(function() { priv.initItem(this, idx++); });
        }
      },

      initItem: function(item)
      {
        // hide unit price
        $('.priceU',item).hide();

        // Add +/- buttons
        $('.qty',item).append('<a href="#" class="minusCart" title="moins" ><span>Moins</span></a>');
        $('.qty',item).append('<a href="#" class="plusCart" title="plus" ><span>Plus</span></a>');

        var pId  = $('.cartProdId',item).val();
        var pQty = $('.qty input',item).val();

        // set row id = product id
        $(item).attr('id',pId);

        // replace qty input by text
        $('.qty',item).append('<span>x</span><span class="qtyTxt">'+pQty+' </span>');
        $('.qty input',item).remove();

        // bind actions - buttons
        $('a.minusCart',item).bind('click',function(){

          var pQty = parseInt($('.qtyTxt',item).html());

          if( pQty == 1 ) {
            priv.removeItem(pId);
          } else {
            priv.decreaseQty(pId);
          }

          return false;
        });

        // bind actions + buttons
        $('a.plusCart',item).bind('click',function(){
          priv.increaseQty(pId);
          return false;
        });

        // bind actions remove bt
        $('a.cartRemove',item).bind('click',function(){
          priv.removeItem(pId);
          return false;
        });

        // bind actions wishlist bt
        $('a.moveToWishlist',item).bind('click',function(){
          priv.moveToWislist(pId);
          return false;
        });

        $(item).hover(function(){
          $(item).addClass("jHover");

        },function(){
          $(item).removeClass("jHover");
        });
      },

      handler: function(handler,arg) {

        if (priv.cFg[handler] == undefined) {
          return;
        }

        var handler = priv.cFg[handler] ;

        if (typeof handler != 'function') {
          return;
        }

        handler(this,arg);
      },

      format: function()
      {
       $('li:first', priv.list).css("border-top","1px solid #dbdbdb");
       $('li',priv.list).removeClass('even').removeClass('odd');
       $('li:even',priv.list).addClass('even');
       $('li:odd',priv.list).addClass('odd');
      },

      increaseQty: function(idx)
      {
        var url = 'services.php?act=addTtoCart&pId='+idx;
        
        acton = file('services.php?act=testQty&pId='+idx);
        
        if(acton>0)
        {
         $.get(url, function()
         {   
          priv.setItemPrice(idx,1);
          priv.updateTotal();
         });
        }
        else
        {
         alert('Malheureusement, nous n\'avons pas de stock supplémentaire disponible. Nous vous remercions de votre compréhension.');        
        }
      },

      decreaseQty: function(idx)
      {
        var url = 'services.php?act=remQty&pId='+idx;
        $.get(url, function(){
          priv.setItemPrice(idx,-1);
          priv.updateTotal();
        });
      },

      setItemPrice: function(idx,qty)
      {
        var currentQty = parseInt($('#'+idx+' .qtyTxt').text());
        var newQty = currentQty + qty;
        var priceU = parseFloat($('#'+idx+' p.priceU').html());
        var newPrice = roundPrice(priceU * newQty);

        $('#'+idx+' .qtyTxt').text(''+newQty);
        $('#'+idx+' .price').html(newPrice+'&euro;');
      },

      removeItem: function(idx)
      {
        var url = 'services.php?act=removeCartProduct&pId='+idx;

        $.get(url,function(){

          $('#'+idx).slideUp("normal",function(){
            $('#'+idx).remove();
            priv.format();
            priv.updateTotal();
          });
        });
      },

      moveToWislist: function(idx)
      {
        var url = 'services.php?act=addToWishList&pId='+idx;
        var productDatas = {
          item: $('#'+idx),
          id: idx,
          name: $('#'+idx+' .name a',priv.list).html(),
          price: $('#'+idx+' .priceU',priv.list).html()
        };

        $.get(url, function(data) {

          if( data == 0 ) {
            alert("Vous devez vous identifier pour mettre des articles de coté");
            return false;
          } else if ( data == 2 ) {
            alert("Ce produit est déjà mis de coté");
            return false;
          } else {

            priv.removeItem(idx);

            if( priv.cFg.onMoveItem) {
              priv.handler("onMoveItem",productDatas);
            }
          }
        });
      },

      setActionBt: function()
      {
        if( priv.getCartItemNbr() == 0 ) {
          $('.btCartOrder a').attr("class","actionButton-disable").click(function(){return false;});
        } else {
          $('.btCartOrder a').attr("class","actionButton").unbind('click');
        }
      },

      getCartItemNbr: function()
      {
        return $('li',priv.list).size();
      },

      updateTotal: function()
      {
        var itemNumber = priv.getCartItemNbr();

        if( itemNumber > 0 && $('#shoppingCartTotalAmount').size() == 0 ) {
          $("#shoppingCartTotal").html(
          '<p id="shoppingCartTotalTitle">Total <span>(sans frais de port)</span></p>'+
          '<p id="shoppingCartTotalAmount"></p>');
        } else if(itemNumber == 0) {
          $("#shoppingCartTotal").html(
          '<p id="shoppingCartEmpty">Votre panier est vide !</p>');
          priv.setActionBt();
          return;
        }

        var url = 'services.php?act=getCarTotal';
        $("#shoppingCartTotalAmount").load(url);
        priv.setActionBt();
      },

      isInCart: function(idx)
      {
        var item = $('#'+idx,priv.scope);
        if (item.size() == 1) {
          return item;
        } else {
          return false;
        }
      },

      addItem: function(data,callback)
      {
        var prod = {
          id: data.id,
          name: data.name,
          price: data.price
        };

        var prodItem = priv.isInCart(prod.id);

        if ( prodItem == false ) {
          var itemHtml =
          '<li class="cartProductRow" style="display:none;" >'+
          '<p class="priceU">'+prod.price+'</p>'+
          '<p class="name"><a href=product_info.php?products_id='+prod.id+'>'+prod.name+'</a></p>'+
          '<p class="qty">'+
          '<input type="text" name="cart_quantity[]" size="2" value="1" />'+
          '<input type="hidden" name="products_id[]" class="cartProdId" value="'+prod.id+'" />'+
          '</p>'+
          '<p class="price">'+prod.price+'</p>'+
          '<p class="cartActions">'+

          '<a class="moveToWishlist" href="shopping_cart.php?action=moveToWishList&pId='+prod.id+'"></a>'+
          '<a class="cartRemove" href="shopping_cart.php?action=remove_product&products_id='+prod.id+'"></a>'+
          '</p>'+
          '</li>';

          var newItem = $(itemHtml).appendTo(priv.list).DropInDown();
          priv.initItem(newItem);
          priv.format();
        } else {
          var quantity = parseInt($('.qtyTxt',prodItem).text()) + 1;
          $('.qtyTxt',prodItem).html(quantity+'').end().Pulsate(300, 2);

          // calculate price
          var price = parseFloat($('.price', prodItem).html());
          var cartItemPrice = parseFloat($('.price', prodItem).html());

          var newItemtotal = cartItemPrice + price;
          $('.price', prodItem).html(roundPrice(newItemtotal)+'&euro;');
        }

        priv.updateTotal();

        callback = typeof callback == 'function' ? callback : null;
        callback();
      }
    };

    // Initialize the shoppingCart
    priv.prepare(e, o);
    priv.format();
    priv.setActionBt();

    $.fn.CartAddItem = function(data,callback) {
  		return publ.add(data,callback);
  	};

    $.fn.CartIsInCart = function(idx) {
  		return publ.isInCart(idx);
  	};
  }
});

var roundPrice = function (value) {
  return Math.round(value * Math.pow(10, 2)) / Math.pow(10, 2);
}

var formatNr = function(nr)
{
	thousands = parseInt(nr/1000);
	hundreds = parseInt(nr - thousands*1000);
	decimals = parseInt((nr - parseInt(nr)) * 100);
	return (thousands > 0 ? thousands + ' ' : '') +
	       (nr > 1000 & hundreds < 100 ? '0' : '') +
	       (nr > 1000 & hundreds < 10 ? '0' : '') + hundreds +
	       '.' + (decimals > 0 ? decimals : '00');
}

function file(fichier)
{
 if(window.XMLHttpRequest) // FIREFOX
 {
  xhr_object = new XMLHttpRequest();
 }
 else if(window.ActiveXObject) // IE
 {
  xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
 }
 else
 {
  alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
  return;
 }

 xhr_object.open("GET", fichier, false);
 xhr_object.send(null);

 if(xhr_object.readyState == 4)
 {
  return(xhr_object.responseText);
 }
 else
 {
  return(false);
 }
}
