// 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); },

  _getCartContent: function(){ this._proxy(this._callback47c04d1f7439b, '_getCartContent', arguments, false); },
  _getCartContent_sync: function(){ return this._proxy(this._callback47c04d1f7439b, '_getCartContent', 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); },

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

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

Object.extend(EcommerceController,
{
    _prices: null,
    _hasVat: false,
	_symbolRight: '&euro;',
	_decimalPoint: ',',
	_currencyValue: 1,
	_cartContentTemplate: null,
	_maxOrderIncrement: 1000,
	_minOrderIncrement:0,
    
    init: function(symbolRight,decimalPoint,trans_Price,trans_Qty)
    {
        this._hasVat = true;
		this._symbolRight = symbolRight;
		this._decimalPoint = decimalPoint;
        this.getCartPrice();
		this._cartContentTemplate = '<tr id="cartContentProd-#{id}">';
        this._cartContentTemplate += '<td>#{name}<br /><span class="cartContentProdPrice">'+trans_Price+' : #{price}</span><br /><span class="cartContentProdQty">'+trans_Qty+' : #{qty}</span></td>';
		this._cartContentTemplate += '</tr>';
    },
    
    initProduct: function(prices, hasVat,currencyValue,symbolRight,decimalPoint)
    {
    	this._prices = prices;
    	this._hasVat = true;
		this._symbolRight = symbolRight;
		this._decimalPoint = decimalPoint;
		this._currencyValue = currencyValue;
    	//this.displayPrice();
    },
    
    displayPrice: function()
    {
        var v = parseInt($F('product-qty'));
        if(isNaN(v) || v<=0)
        {
			
            $('product-qty').setValue(1);
			this.displayPrice();
            return;
        }
		var cp = null;
		var i = 0;
		while(i < this._prices.length && this._prices[i].level <= v)
		  i++;
        if(this._hasVat)
		{
    		cp = this._prices[i-1].price*((this._prices[i-1].vatRate+100)/100);
			cp = Math.round(cp*100)/100;
			cp = Math.round(cp * this._currencyValue*100)/100;
			if($('current-price')) $('current-price').update(this._formatPrice(v*cp));
		}
        else
		{
            cp = this._prices[i-1].price;
			cp = Math.round(cp*1000)/1000;
			cp = Math.round(cp * this._currencyValue*1000)/1000;
			if($('current-price')) $('current-price').update(this._formatPrice(v*cp,3));
		}
        //$('current-salesprice').update(this._formatPrice(cp));
    },
    
    nextIncrement: function(maxOrderIncrement,prodQtyId)
    {
		if (maxOrderIncrement != null)
			this._maxOrderIncrement = maxOrderIncrement;
		var v=0;
		var prodQtyField;
		if(prodQtyId != null)
			prodQtyField = 'product-qty-'+prodQtyId;
        else 
			prodQtyField = 'product-qty';
			
		v = parseInt($F(prodQtyField));
        if(isNaN(v))
        {
            $('current-price').update('NaN');
            return;
        }
        v++;        
        if ( v > this._maxOrderIncrement )
			v = this._maxOrderIncrement; 
        
		$(prodQtyField).value = v;
        /*$('product-qty').setStyle({backgroundColor: ''});*/        
        if (this._prices)
        	this.displayPrice();
		if(prodQtyId != null)
			this.updateCart(prodQtyId, $F(prodQtyField));	
    },
    
    previousIncrement: function(minOrderIncrement,prodQtyId)
    {
		if (minOrderIncrement != null)
			this._minOrderIncrement = minOrderIncrement;
        var v=0;
		var prodQtyField;
		if(prodQtyId != null)
			prodQtyField = 'product-qty-'+prodQtyId;
        else 
			prodQtyField = 'product-qty';
			
		v = parseInt($F(prodQtyField));
        if(isNaN(v))
        {
            $('current-price').update('NaN');
            return;
        }
        v--;
		if ( v < this._minOrderIncrement )
			v = this._minOrderIncrement; 
       
        $(prodQtyField).value = v;
       /* $('product-qty').setStyle({backgroundColor: ''});*/
        if (this._prices)
        	this.displayPrice();
		if(prodQtyId != null)
			this.updateCart(prodQtyId, $F(prodQtyField));
    },
    
    getCartPrice: function()
    {
        this._getCartPrice(this._cartUpdated.bind(this, true));
    },
    
    //** Cart management **
    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));
            }
        }
    },
	add2cartEffect: function(source_id, target_id, callback) {
      
      var source = $( source_id );
      var target = $( target_id );
      
      var shadow = $( source_id + '_shadow');
      if( !shadow ) {
		  
		 var shadow = new Element('img', { 'id': source.getAttribute('id')+'_shadow' });
         shadow.writeAttribute('src',source.getAttribute('src'));
		 $(document.body).insert(shadow);
		 
      }
      
      if( !shadow ) {
          alert('Cannot create the shadow div');
      }
	  
    
      shadow.setStyle({'width':source.getWidth()+'px','height':source.getHeight()+'px','top': source.cumulativeOffset()[1]+'px','left': source.cumulativeOffset()[0]+'px','opacity': 1});
	 	
	 
	  shadow.setStyle({'position': 'absolute','zIndex':1000});
    
	  var toStyle = 'opacity: 0; width: '+target.getWidth()+'px; height: '+target.getHeight()+'px; top: '+target.cumulativeOffset()[1]+'px; left: '+target.cumulativeOffset()[0]+'px;';

      new Effect.Morph(shadow,{ style: toStyle, duration:1.2, transition: Effect.Transitions.sinoidal,afterFinish : this.hideShadow.bind(this)} );
	
        
   },
	hideShadow : function(e)
	{
		e.element.remove();
	}
    ,
    _cartUpdated: function(init, r, j)
    {
		
        if(j && !j.failed)
        { 
			//console.log( j.out);
			if(j.out.hasVat != null) this._hasVat = j.out.hasVat;
            if(j.out.qty == null || j.out.price == null)
                j.out.price = j.out.qty = 0;
            j.out.price = (j.out.price);
			
			this._symbolRight = j.out.currencySymbolRight;
			this._decimalPoint = j.out.currencyDecimalPoint;
			
            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(j.out.qty==1) { $('oneItemText').show(); $('manyItemText').hide(); }
				else { $('oneItemText').hide(); $('manyItemText').show(); }
				if(j.out.qty>0) { $('icon_cart').setAttribute('rel','fix'); changeIconCart('on'); }
			}
            if($('cartPrice'))
                $('cartPrice').update(pp);
			if($('subtotalcartPrice'))
                $('subtotalcartPrice').update(pp);	
			
			var d = 0;
			var dv= 0;
			if(!isNaN(j.out.delivery))
			{
				d = parseFloat(j.out.delivery);
				if(!isNaN(j.out.deliveryVAT)) dv = d*(parseFloat(j.out.deliveryVAT)/100); else dv = d;
			}
			
            if(dv!=0 && $('totalCartDelivery'))
            {
                $('totalCartDelivery').update(this._formatPrice(this._hasVat?dv:d));
            }
			
			if(!isNaN(j.out.reduction))
			{
				if($('totalReduction')) $('totalReduction').update(this._formatPrice(j.out.reduction));
				if($('totalReductionVAT')) $('totalReductionVAT').update(this._formatPrice(j.out.reductionWithVAT));
			}
			
			var p = parseFloat(j.out.price);
			var pv = parseFloat(j.out.priceWithVAT);
			
			
			if($('totalCartPriceVAT')) $('totalCartPriceVAT').update(this._formatPrice(pv));
			if($('totalCartPriceWithDelivery')) $('totalCartPriceWithDelivery').update(this._formatPrice(p+d));
			if($('totalCartPriceWithDeliveryVAT')) $('totalCartPriceWithDeliveryVAT').update(this._formatPrice(pv+dv));
			if($('totalCartVAT')) $('totalCartVAT').update(this._formatPrice(pv+dv-p-d));
			
				
			if($('totalCartContentPriceVAT')) $('totalCartContentPriceVAT').update(this._formatPrice(pv));
          
            if(!init)
            {
                if($('cartAdded'))
                {
                    $('cartAdded').show(true);
                    setTimeout(function(){ if($('cartAdded').visible()){ $('cartAdded').hide(); }}, 2000);
                }
            }
        }
		if($('cartContentContainer'))
			this._getCartContent(this._cartContentUpdated.bind(this, true));
    },
   _cartContentUpdated: function(init, r, j)
    {
		
		tb = $('cartContentContainer');
		tb.update('');
        if(j && !j.failed)
        { 	
			var prod;
			
			for(var i=0; i < j.out.length; i++)
			{
				prod =  j.out[i];
				
				var p = {};
				p.name = prod.data.name;
				p.price = this._formatPrice(prod.price.price);
				p.qty = prod.qty;
				p.id = prod.productKey;
				tb.insert({top:this._cartContentTemplate.interpolate(p)});
			}
			if(i>0 && ($('cartContentBox').getStyle('display')=='none' || ($('cartContentBox').getStyle('display')==null)))
				$('cartContentBox').appear();

		}
	},
    _formatPrice: function(p,deci)
    {
		if(deci==null) deci= 2;
        return (p.toFixed(deci)+'').replace( '.' , this._decimalPoint )+' '+this._symbolRight;
    },
    emptyCart: function()
    {
        this._emptyCart(function(){ window.location.reload(); });
    },
    updateCart: function(productId, qty)
    {
		if($('productTotal'+productId)!=null && $('unitPrice'+productId)!=null) 
		{
			if(!isNaN($F('unitPrice'+productId))) $('productTotal'+productId).update(this._formatPrice($F('unitPrice'+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)
                window.location.reload();
            $('productRow-' + productId).remove();
            this._cartUpdated(true, r, j);
        }
    },
	checkClubTintin: function()
	{
			var o = 
            {
                email: $F('ct_email'),
                passwd: $F('ct_passwd')
            };
			this._checkClubTintin(Object.toJSON(o), function(r, j)
			{
				
								
				if(!j || j.failed)
					return;
					
				if(j.out.isMember==1) {
					if($('displayConfirmCT'))
					{
						$('ct_login_form').hide('normal');
						$('confirm_ct_member').show('normal');	
					}
					else
						window.location.reload();
				}
				else  {
					$('not_ct_member').slideDown('normal');
				}
			}.bind(this));
	}
});
