// Generated from http://etilux.gb.int/dynamic/ecommerce/ajax.phtml, DO NOT EDIT!
if(typeof(EcommerceController) == 'undefined')
  EcommerceController = new Object();

Object.extend(EcommerceController,
{
  _callback47c04d1f7439b: "/dynamic/ecommerce/ajax.phtml",

  _proxy: function(callbackurl, methodName, args, sync)
  {
    var targs = $H();
    for(var i = 0; i < args.length-1; i++){ targs.set('args[' + i + ']', args[i]); }
    callback = args[args.length-1];
    var ar = new Ajax.Request(callbackurl + '?method=' + methodName,
    {
      method: 'post',
      asynchronous: (!sync),
      parameters: targs,
      onComplete: (sync)?null:callback,
      onException: function(request, e){console.debug(request, e);}
    });
    if(sync)
      return new Ajax.Response(ar);
  },

  _addToCart: function(){ this._proxy(this._callback47c04d1f7439b, '_addToCart', arguments, false); },
  _addToCart_sync: function(){ return this._proxy(this._callback47c04d1f7439b, '_addToCart', arguments, true); },
  
  _addMultipleToCart: function(){ this._proxy(this._callback47c04d1f7439b, '_addMultipleToCart', arguments, false); },
  _addMultipleToCart_sync: function(){ return this._proxy(this._callback47c04d1f7439b, '_addMultipleToCart', arguments, true); },

  _updateCart: function(){ this._proxy(this._callback47c04d1f7439b, '_updateCart', arguments, false); },
  _updateCart_sync: function(){ return this._proxy(this._callback47c04d1f7439b, '_updateCart', arguments, true); },

  _removeFromCart: function(){ this._proxy(this._callback47c04d1f7439b, '_removeFromCart', arguments, false); },
  _removeFromCart_sync: function(){ return this._proxy(this._callback47c04d1f7439b, '_removeFromCart', arguments, true); },

  _emptyCart: function(){ this._proxy(this._callback47c04d1f7439b, '_emptyCart', arguments, false); },
  _emptyCart_sync: function(){ return this._proxy(this._callback47c04d1f7439b, '_emptyCart', arguments, true); },

  _getCartPrice: function(){ this._proxy(this._callback47c04d1f7439b, '_getCartPrice', arguments, false); },
  _getCartPrice_sync: function(){ return this._proxy(this._callback47c04d1f7439b, '_getCartPrice', arguments, true); },

  _addVoucher: function(){ this._proxy(this._callback47c04d1f7439b, '_addVoucher', arguments, false); },
  _addVoucher_sync: function(){ return this._proxy(this._callback47c04d1f7439b, '_addVoucher', arguments, true); },

  _removeVoucher: function(){ this._proxy(this._callback47c04d1f7439b, '_removeVoucher', arguments, false); },
  _removeVoucher_sync: function(){ return this._proxy(this._callback47c04d1f7439b, '_removeVoucher', arguments, true); },

	_getFees: function(){ this._proxy(this._callback47c04d1f7439b, '_getFees', arguments, false); },
	_getFees_sync: function(){ return this._proxy(this._callback47c04d1f7439b, '_getFees', arguments, true); },
	
  _t: ''
});
// End of generated code

if(typeof(EcommerceController) == 'undefined')
    EcommerceController = new Object();

Object.extend(EcommerceController,
{
    init: function()
    {
        if($('cartAdded') != null)
            new Dialog.Box('cartAdded');
        if($('cartPrice') == null)
            return;
        this.getCartPrice();  
    },
    
    getCartPrice: function()
    {
        this._getCartPrice(this._cartUpdated.bind(this, true));
    },
    
    /** Cart management **/
    
    addToCart: function(productId)
    {
        if(productId)
        {
            qty = $F('product-qty');
            if(qty.length <= 0 || !qty.match(/[0-9]+/))
                return;
            this._addToCart(productId, qty, this._cartUpdated.bind(this, false));
        }
        else if($('product-list'))
        {
            var p = $H();
            $A($('product-list').getElementsByTagName('select')).each(function(inp)
            {
                var v = $F(inp);
                inp.selectedIndex = 0;
                if(v.length <= 0 || !v.match(/[0-9]+/))
                    return;
                var pi = inp.id.substr(8);
                p.set(pi, v);
            });
            if(p.size() > 0)
            {
                this._addMultipleToCart(p.toJSON(), this._cartUpdated.bind(this, false));
            }
        }
    },
    
    updateCart: function(productId, qty)
    {
        this._updateCart(productId, qty, this._cartUpdated.bind(this, true));
    },
    
    emptyCart: function(empty)
    {
        if(empty)
        {
            this._emptyCart(function(){ document.location = SiteStrings.homeURL; });
        }
        else
        {
            Modalbox.show(SiteStrings.confirmEmptyCart, {title: SiteStrings.cartEmptyTitle, width: 400, height: 100});
        }
    },
    
    removeFromCart: function(productId)
    {
        this._removeFromCart(productId, this._productRemoved.bind(this, productId));
    },

		updateFees: function(countryId, rate)
		{
			this._getFees(countryId, this._feesGetted.bind(this, rate));
		},
		
		_feesGetted: function(rate, r, j) {
			var fees = j.out.price * rate;
			$('fees').update(this._formatPrice(fees));
			$('delay').update(j.out.averageDeliveryDays);
			
			var p = parseFloat($('totalCartPrice').innerHTML)*100;
			var d = parseFloat($('fees').innerHTML)*100;
			var pd = p+d;
			$('totalCartPriceWithDelivery').update(this._formatPrice(pd));
      if($('totalCartVAT'))
      {
          $('totalCartVAT').update(this._formatPrice(pd*0.21));
          $('totalCartPriceVAT').update(this._formatPrice(pd*1.21));
      }
		},
		
		getSelectedValue: function(element) {
			if (!(element = $(element))) return;
			var index = element.selectedIndex;
			return index >= 0 ? element.options[index].value : 0;
		},
    
    _productRemoved: function(productId, r, j)
    {
        if(j && !j.failed)
        {
            if(j.out.qty == null || j.out.qty == 0)
                document.location = SiteStrings.homeURL;
            $('productRow-' + productId).remove();
            this._cartUpdated(true, r, j);
        }
    },
    
    _cartUpdated: function(init, r, j)
    {
        if(j && !j.failed)
        {
            if(j.out.qty == null || j.out.price == null)
                j.out.price = j.out.qty = 0;
            j.out.price = parseInt(j.out.price);
            var pp = this._formatPrice(j.out.price);
            $('cartArticles').update(j.out.qty);
            $('cartPrice').update(pp);
            if(isNaN(j.out.delivery))
                $('cartDelivery').update(j.out.delivery);
            else
                $('cartDelivery').update(this._formatPrice(j.out.delivery)+EcommerceController._currency);
            
			if (j.out.minimunTarif > 0) {
				$('fraisdePort').show();
				$('fraisPortOffert').update(this._formatPrice(j.out.minimunTarif));
			} else {
				$('fraisdePort').hide();
			}
			
            if($('totalCartPrice'))
            {
                var p = j.out.price / j.out.vat[0];
                $('totalCartPrice').update(this._formatPrice(p));

								this.updateFees(EcommerceController.getSelectedValue($("updateFees")),1);
                var d = parseFloat($('fees').innerHTML)*100;
								
                /*if(isNaN(j.out.delivery))
                    $('totalCartDelivery').update(j.out.delivery);
                else
                {
                    d = j.out.delivery/j.out.vat[0];
                    $('totalCartDelivery').update(this._formatPrice(d)+EcommerceController._currency);
                }*/
                var pd = p+d;
                
                $('totalCartPriceWithDelivery').update(this._formatPrice(pd));
                if($('totalCartVAT'))
                {
                    $('totalCartVAT').update(this._formatPrice(pd*0.21));
                    $('totalCartPriceVAT').update(this._formatPrice(pd*1.21));
                }
            }
            if(!init)
            {
                $('cartAdded').show(true);
                setTimeout(function(){ if($('cartAdded').visible()){ $('cartAdded').hide(); }}, 2000);
            }
        }
    },
    
    _productDropped: function(dragged, dropped, e)
    {
        if(dragged.hasClassName('productPicture'))
        {
            var pid = dragged.id.gsub(/productPicture-/,'');
            this.addToCart(pid);
        }
    },
    
    atShopChanged: function()
    {
    	if($F('atshop'))
    	{
    		$('shopSelect').show();
    		$('prevShippingPrice').value = $('totalCartDelivery').innerHTML;
    	    $('totalCartDelivery').innerHTML ="0";
    	}else{
    		$('shopSelect').hide();
    		$('totalCartDelivery').innerHTML =$F('prevShippingPrice');
    		$('prevShippingPrice').value = "0";
    	    
    	}

    },
    
    /** Vouchers management **/
    
    addVoucher: function()
    {
        this._addVoucher($F('newVoucher'), this._voucherAdded.bind(this));
    },
    
    _voucherAdded: function(r, j)
    {
        if(j && !j.failed)
        {
            if(j.out)
            {
                var str = '<tr id="voucher-' + $F('newVoucher') + '"><td class="first">' + $F('newVoucher')+'</td><td>';
                str += j.out.valueToDeduct + ((j.out.discountType == 'cashDiscount')?EcommerceController._currency:'%');
                str += '</td><td align="center" class="last"><img src="/medias/images/ecommerce/cart_remove.png" onclick="EcommerceController.removeVoucher(\'' + $F('newVoucher') + '\')"/></td></tr>';
                $('voucherList').show();
								$('voucherList').insert(str);
                $('newVoucher').value = '';
            }
            else
                Modalbox.show(SiteStrings.invalidVoucher, {title: SiteStrings.error, width: 400, height: 100});
        }
    },
    
    removeVoucher: function(code)
    {
        this._removeVoucher(code, this._voucherRemoved.bind(this));
    },
    
    _voucherRemoved: function(r, j)
    {
        if(j && !j.failed)
        {
            $('voucher-'+j.out).remove();
        }
    },
    
    updateProductPrice: function(id,prices,meta)
    {
    	var qty = $('qty_' + id).value;
    	var cp = prices[0];
        for (i=1;i< prices.length;i++) 
        {
            if (prices[i].level > qty * meta.displayCoef) 
            {
                break;
            }
            else cp = prices[i];
        }
        $('prix_' + id).update(
          this._formatPrice(((cp.price * meta.displayCoef)/meta.baseToSaleCoef) * EcommerceController._currencyRate)
        );
    },
    
    _formatPrice: function(p)
    {
        p = Math.round(p);
        var pp = (p / 100); 
        if(p%100 == 0)
            pp += '.00';
        else if(p%10 == 0)
            pp += '0';
        return pp;
    }
});

