// 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); },

  _t: ''
});
// End of generated code

if(typeof(EcommerceController) == 'undefined')
    EcommerceController = new Object();

Object.extend(EcommerceController,
{
    _prices: null,
    _hasVat: false,
    
    init: function(hasVat)
    {
        this._hasVat = hasVat;
        this.getCartPrice();
    },
    
    toggleDelivery: function()
    {
    	if($('invoiceToDelivery').checked || $('atshop').checked)
    	{
    		if($('delivery').visible())
    		{
    			$('delivery').hide();
    			
    			FormValidate.Validators.each(function(v) {
					if(v.element.id.substr(0, 15) == 'deliveryAddress')
						v.unregister();
				});
    		}
    	}
    	else
    	{
    		$('delivery').show();
    		FormValidate.buildValidators('contactForm');
    	}
    },
    
    /*initProduct: function(prices, hasVat)
    {
    	this._prices = prices;
    	this._hasVat = hasVat;
    	this.displayPrice();
    },*/
    
    displayPrice: function()
    {
        var v = parseInt($F('product-qty'));
        if(v == NaN)
        {
            $('current-price').update('NaN');
            return;
        }
		var cp = null;
		var i = 0;
		while(i < this._prices.length && this._prices[i].level <= v)
		  i++;
        if(this._hasVat)
    		cp = Math.round(this._prices[i-1].price*(this._prices[i-1].vatRate/100));
        else
            cp = Math.round(this._prices[i-1].price);
		
		$('current-price').update(this._formatPrice(v*cp));
		
        $('current-salesprice').update(this._formatPrice(cp));
    },
    
    /*nextIncrement: function(maxOrderIncrement)
    {
		if (maxOrderIncrement != null)
			this._maxOrderIncrement = maxOrderIncrement;
        var v = parseInt($F('product-qty'));
        if(v == NaN)
        {
            $('current-price').update('NaN');
            return;
        }
        v++;        
        if ( v > this._maxOrderIncrement )
			v = this._maxOrderIncrement; 
        
		$('product-qty').value = v;
        $('product-qty').setStyle({backgroundColor: ''});        
        if (this._prices)
        	this.displayPrice();
    },
    
    previousIncrement: function(minOrderIncrement)
    {
		if (minOrderIncrement != null)
			this._minOrderIncrement = minOrderIncrement;
        var v = parseInt($F('product-qty'));
        if(v == NaN )
        {
            $('current-price').update('NaN');
            return;
        }
        v--;
		if ( v < this._minOrderIncrement )
			v = this._minOrderIncrement; 
       
        $('product-qty').value = v;
        $('product-qty').setStyle({backgroundColor: ''});
        if (this._prices)
        	this.displayPrice();
    },*/
    
    getCartPrice: function()
    {
        this._getCartPrice(this._cartUpdated.bind(this, true));
    },
    
    checkValue: function()
    {
        if(this._timer)
            clearTimeout(this._timer);
        this._timer = setTimeout(this._checkValue.bind(this), 125);
    },
    
    _checkValue: function()
    {
        var v = parseInt($F('product-qty'));
        if(v == NaN)
        {
            $('current-price').update('NaN');
            return false;
        }
        else
        {
            this.displayPrice();
        	return true;
        }
    },
    
    addToCart: function(productId, quantity)
    {
    	if(productId)
        {
            qty = quantity ? quantity : $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));
            }
        }
    },
    
    _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 = (j.out.price);
            if(this._hasVat)
                var pp = this._formatPrice(j.out.priceWithVAT);
            else
                var pp = this._formatPrice(j.out.price);
            if($('cartArticles'))
                $('cartArticles').update(j.out.qty);
            if($('cartPrice'))
                $('cartPrice').update(pp);
            if($('cartDelivery'))
            {
                if(isNaN(j.out.delivery))
                    $('cartDelivery').update(j.out.delivery);
                else
                    $('cartDelivery').update(this._formatPrice(j.out.delivery)+'&euro;');
            }
			
            if($('totalCartPrice'))
            {
                
                $('totalCartPrice').update(this._formatPrice(j.out.price));
                var d = 0;
                if(isNaN(j.out.delivery))
                    $('totalCartDelivery').update(j.out.delivery);
                else
                {
                    d = j.out.delivery;
                    $('totalCartDelivery').update(this._formatPrice(j.out.delivery)+'&euro;');
                }
                var pd = parseInt(j.out.price)+d;

                $('totalCartPriceWithDelivery').update(this._formatPrice(pd));
                if($('totalCartVAT'))
                {
                    $('totalCartVAT').update(this._formatPrice(pd*0.21));
                    $('totalCartPriceVAT').update(this._formatPrice(pd*1.21));
                }
            }
            if(!init)
            {
                if($('cartAdded'))
                {
                    $('cartAdded').show(true);
                    setTimeout(function(){ if($('cartAdded').visible()){ $('cartAdded').hide(); }}, 2000);
                }
            }
        }
    },
    
    _formatPrice: function(p)
    {
        p = Math.round(p);
        var v = (p/100).toString();
        if(p%100 == 0)
            v += '.00';
        else if(p%10 == 0)
            v += '0';
        return v;
    },
    
    emptyCart: function()
    {
        this._emptyCart(function(){ document.location = '/'; });
    },
    
    updateCart: function(productId, qty)
    {
        this._updateCart(productId, qty, this._cartUpdated.bind(this, true));
    },
    
    removeFromCart: function(productId)
    {
        this._removeFromCart(productId, this._productRemoved.bind(this, productId));
    },
    
    _productRemoved: function(productId, r, j)
    {
        if(j && !j.failed)
        {
            if(j.out.qty == null || j.out.qty == 0)
                document.location = '/';
            $('productRow-' + productId).remove();
            this._cartUpdated(true, r, j);
        }
    },
    
    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>' + $F('newVoucher')+'</td><td>';
                str += j.out.valueToDeduct + ((j.out.discountType == 'cashDiscount')?'€':'%');
                str += '</td><td><img src="/images/commun/delete.png" onclick="EcommerceController.removeVoucher(\'' + $F('newVoucher') + '\')"/></td></tr>';
                $('voucherList').insert(str);
                $('newVoucher').value = '';
                $('voucherFoot').hide();
                
                showGlobuleError('Coupon validé.', 'E_USER_NOTICE');
            }
            else
            	showGlobuleError('Code de coupon incorrect.', 'E_USER_ERROR');
        }
    },
    
    removeVoucher: function(code)
    {
        this._removeVoucher(code, this._voucherRemoved.bind(this));
    },
    
    _voucherRemoved: function(r, j)
    {
        if(j && !j.failed)
        {
            $('voucher-'+j.out).remove();
            $('voucherFoot').show();
        }
    }

});