var Carrito = {
	info: {},
	mini: {},

	initialize: function(){
		if(!this.initialized){
			this.initialized = true;

			var ref = document.id('cartInfo');

			//mini-cart
			this.mini.container = new Element('div').inject(new Element('div',{'id':'miniCartItems','class':'hidden'}).inject(body));
			this.mini.wrapper = new Element('div',{'class':'middle'}).inject(this.mini.container.adopt(new Element('div',{'class':'top'}).adopt(new Element('span',{'class':'close','title':'cerrar'}).addEvent('click',this.hide.bind(this)))));

			var bottom = new Element('p').inject(new Element('div',{'class':'bottom'}).inject(this.mini.container));

			//info
			this.info = ref.getElements('em,strong,a').associate(['counter','amount','link']);

			//links
			this.links = {};
			this.links.close = new Element('a',{'href':'#close','html':'&laquo; Seguir comprando'}).addEvent('click',function(e){new Event(e).stop();this.hide();}.bindWithEvent(this)).inject(bottom);
			this.links.pay = new Element('a',{'href':'#pagar','html':'Realizar pedido'}).inject(bottom);
			this.links.details = this.info.link.clone().inject(bottom);

			//mini cart fx
			if(!this.nofx){
				this._autoHide = 0;
				this.fx = new Fx.Slide(this.mini.container,{transition:Fx.Transitions.Sine.easeOut,duration:400});
				this.mini.container.addEvents({
					'mouseenter': function(){$clear(this._autoHide);}.bind(this),
					'mouseleave': this.autoHide.pass([2000], this)
				});
				this.info.link.addEvents({
					//'mouseenter': this.show.bind(this),
					'click': function(e){new Event(e).stop();this.show();}.bindWithEvent(this),
					'mouseleave': this.autoHide.pass([2000], this)
				});
				this.fx.hide();
			}

			//request
			this.request = new Request({url:BASE.ajax+'carrito.ajax',onSuccess:this.onSynchronize.bind(this),onFailure:onError});

			//addCart buttons
			document.getElements('.addCart').each(function(el){
				if(el.get('tag')=='a'){
					el.addEvent('click',function(e){
						new Event(e).stop();
						Carrito.addItem(this.className.substr(8),1,false,true);
					});
				}else{
					el.addEvent('click',this.addItem.pass([el.className.substr(8),1,false,true], this));
				}
			},this);

			//update info
			this.drawItems();
			this.updateInfo();

			if(this.onInitialize){
				this.onInitialize();
			}

			this.finalized = true;
		}
	},

	addItem: function(id,cantidad,replace,synchronize){
		cantidad = cantidad.toInt();
		if(this.items[id]){
			if(cantidad==0){
				delete(this.items[id]);
			}else if(replace) {
				this.items[id].cantidad = cantidad;
			}else{
				this.items[id].cantidad += cantidad;
			}
		}else if(cantidad>0){
			this.items[id] = {cantidad:cantidad};
		}
		if(synchronize){
			this.synchronize();
		}
	},

	removeItem: function(id,synchronize,noask){
		if(noask || confirm(_jlng.cart.remove_ask)){
			delete(this.items[id]);
			if(synchronize){
				this.synchronize();
			}
		}
	},

	empty: function(){
		if(confirm(_jlng.cart.qempty)){
			this.items = {};
			this.synchronize();
		}
	},

	synchronize: function(){
		Loading.show(_jlng.cart.updating);
		if(this.fx){
			this.fx.cancel().hide();
		}
		var items = {};
		for(var i in this.items){
			items[i] = this.items[i].cantidad;
		}
		this.request.send({data:'lng='+LNG.code+'&action=Synchronize&items='+JSON.encode(items)});
	},

	onSynchronize: function(response){
		try{
			var data = JSON.decode(response);
		}catch(e){
			Loading.set('Error!','error');
			return;
		}

		this.items = data.items;
		this.total = data.total;

		this.drawItems();
		this.updateInfo();

		if(this.onSynchronizeComplete){
			this.onSynchronizeComplete();
		}else{
			Loading.hide();
			(function(){
				this.show();
				this.autoHide(2000);
			}).delay(100,this)
		}
	},

	drawItems: function(){
		var html = '<table>';
		html += '<thead><tr><th>Producto</th><th>Precio</th><th>Cantidad</th><th>Subtotal</th><th>&nbsp;</th></tr></thead>';
		html += '<tfoot><tr><th>&nbsp;</th><th>Total</th><td>'+this.count()+'</td><td class="total">'+moneda(this.amount())+'</td><th>&nbsp;</th></tr></tfoot>';
		html += '<tbody>';

		var counter = 0;
		for(var i in this.items){
			var item = this.items[i];
			html += '<tr'+(counter%2>0?' class="par"':'')+'>';
				html += '<td class="name"><span><img src="'+BASE.www+'img/productos/thumb/'+alt(item.imagen,'none.jpg')+'" /></span> <a href="'+BASE.web+item.text_id+'.html">'+item.nombre+'</a> <em>Cod. '+item.codigo+'</em></td>';
				html += '<td class="cant">'+moneda(item.precioFinal)+'</td>';
				html += '<td class="cant">'+item.cantidad+'</td>';
				html += '<td class="total">'+moneda(item.cantidad*item.precioFinal)+'</td>';
				html += '<td class="delete"><span class="dlink" id="i'+item.id+'">quitar</span></td>';
			html += '</tr>';
			counter++;
		}

		html += '</tbody>';
		html += '</table>';

		this.mini.wrapper.set('html',html);
		this.mini.wrapper.getElements('span.dlink').each(function(el){
			el.addEvent('click',Carrito.removeItem.pass([el.id,true], Carrito));
		});
	},

	updateInfo: function(){
		this.info.counter.set('html',this.count());
		this.info.amount.set('html',moneda(this.total,false));
	},

	count: function(){
		var cant = 0;
		for(var i in this.items){
			cant += this.items[i].cantidad;
		}
		return cant;
	},

	amount: function(){
		var amount = 0;
		for(var i in this.items){
			amount += this.items[i].cantidad * this.items[i].precioFinal;
		}
		return amount;
	},

	autoHide: function(delay){
		if(this.fx){
			$clear(this._autoHide);
			this._autoHide = this.fx.slideOut.delay(delay,this.fx);
		}
	},

	show: function(){
		if(this.fx && this.count()>0){
			window.scrollTo(0,0);
			$clear(this._autoHide);
			this.mini.container.getParent().getParent().removeClass('hidden');
			this.fx.cancel().slideIn();
		}
	},

	hide: function(){
		if(this.fx){
			$clear(this._autoHide);
			this.fx.cancel().slideOut();
		}
	}
};
