window.addEvent('domready',function(){
	var Efects = new newEfect();
	if($('vacio_carrito'))
	{
		Cookie.dispose('carrito');
	}
	var CartIcon = $$('.carrito .cantidad');
	var carritocookie = JSON.decode(Cookie.read('carrito'));
	var carritoiconos = function(){
		carritocookie = JSON.decode(Cookie.read('carrito'));
		if(CartIcon && carritocookie)
		{
			carritocookie=carritocookie.clean();
			if(carritocookie.length>0)
			{
				var cantidad=0;
				Array.each(carritocookie, function(producto, index){
					cantidad=cantidad+producto.cantidad;
				});
				CartIcon.set('text',cantidad+" Productos");
				if(CartIcon.getStyle('color')=='#949495')
				{
					CartIcon.setStyle('color','#a33');
					CartIcon.tween('color','#949495');
				}
				else
					CartIcon.setStyle('color','#949495');
			}
		}
	};carritoiconos();
	
	var confCarrito = function(id,cantidad){
		var carrito=JSON.decode(Cookie.read('carrito'));carrito=carrito.clean();
		Array.each(carrito, function(producto, index){
			if(producto.id==id)
			{
				if(cantidad==0)
					carrito[index]=null;
				else
					producto.cantidad=cantidad;
			}
		});
		Cookie.write('carrito',JSON.encode(carrito));
		carritoiconos();
	};
	var agregaruno = function(id){
		if(Cookie.read('carrito'))
		{
			var nuevo=true;
			var carrito=JSON.decode(Cookie.read('carrito'));carrito=carrito.clean();
			Array.each(carrito, function(producto, index){
				if(producto.id==id)
				{
					producto.cantidad=producto.cantidad+1;
					nuevo=false;
				}
			});
			if(nuevo)
				carrito[carrito.length]={'id': id, 'cantidad': 1};
			Cookie.write('carrito',JSON.encode(carrito));
		}
		else
		{
			var carrito=[];
			carrito[0]={'id': id, 'cantidad': 1};
			Cookie.write('carrito',JSON.encode(carrito), {duration: 5});
		}
	}
	var quitaruno = function(id){
		if(Cookie.read('carrito'))
		{
			var carrito=JSON.decode(Cookie.read('carrito'));carrito=carrito.clean();
			Array.each(carrito, function(producto, index){
				if(producto.id==id)
					producto.cantidad=producto.cantidad-1;
				if(producto.cantidad==0)
					carrito[index]=null;
			});
			carrito=carrito.clean();
			Cookie.write('carrito',JSON.encode(carrito));
		}
	}
	var carritoajax = function(id,cantidad){
		var cotizacion = $('cotizacion');
		confCarrito(id,cantidad);
		if(Cookie.read('carrito'))
		{
			var carrito = JSON.decode(Cookie.read('carrito'));carrito=carrito.clean();
			neewcarrito=[];
			indice=0;
			Array.each(carrito, function(producto, index){
				for(i=0;i<producto.cantidad;i++)
				{
					neewcarrito[indice]=producto.id;
					indice++;
				}
			});
			var query = 'productos='+JSON.encode(neewcarrito);
			
			var carritoRecuest = new Request({
				url: '/carrito/cantidadAjax/',
				onRequest: function(txt){
					cotizacion.getElement('.calculando').setStyle('display', 'block');
					cotizacion.getElement('table.sub.white').setStyle('display', 'none');
					cotizacion.getElement('a').setProperty('href', '#');
				},
				onSuccess: function(txt){
					cotizacion.set('html',txt);
				},
				method: 'post',
				data:query
			});	
			carritoRecuest.send();
		}
		else
			location.href="/carrito";
	};
	var onlyNumbers = function(input){
		input.addEvent('keydown',function(event){
			if (event.key >= '0' && event.key <= '9' || event.key == 'backspace')
			{			}
			else if(event)
				event.stop();
				
		});
	};
	/* /////////////////////////////////// PREVIEW DE CARRITO ///////////////////////////////////////////////  */
	var limpiar = function(){
		$$('.autoclean').each(function(e,i){
			Efects.autoCleanContent(e);
		});
	};
	limpiar();
	var borrar_carrito = function(){
		$$('.vaciar_carrito').each(function(e,i){
			e.addEvent('click',function(event){if(event)event.stop();
				if(Cookie.read('carrito'))
					Cookie.dispose('carrito');
				location.href=e.get('href');
			});
		});
		$$('a.borrar').each(function(e,i){
			e.addEvent('click',function(event){if(event)event.stop();
				var id = e.getElement('.id').get('text').toInt();
				if(id)
					confCarrito(id,0)
				location.href=e.get('href');
			});
		});
	};
	borrar_carrito();
	var autosalvar = function(){
		$$('.cantidad.autosave').each(function(e,i){
			onlyNumbers(e);
			e.store('cantidad',e.get('value'));
			e.addEvent('keyup',function(event){
				if (event.key=='enter')
				{
					e.fireEvent('blur');
					e.setStyle('background-color','#F0F0F0');
				}
			});
			e.addEvent('blur',function(event){ if(event)event.stop();
				var action = this.getParent().getNext('.action').getElement('a.borrar');
				var precio = this.getParent().getNext('.precio');
				var precios = this.getParent().getNext('.precios');
				
				if(action && e.get('value')!='')
				{	
					if(e.get('value').toInt()!=e.retrieve('cantidad').toInt())
					{
						if( precio && precios)
						{
							var chars = precio.get('text').split('$')[1].split('');
							for(c=0;c<chars.length;c++)
								if(chars[c]==',')
									chars[c]='';
							chars=chars.join('');
							chars = chars.toFloat()*e.get('value').toInt();
							chars = chars.formatCurrency().toString().split(' ');
							chars=chars.join('');
							precios.set('text',chars);
						}
						carritoajax( action.getElement('.id').get('text').toInt() , e.get('value').toInt());
					}
					e.store('cantidad',e.get('value').toInt());
				}
				else if(e.get('value')=='')
					e.set('value',e.retrieve('cantidad').toInt());
			});
		});
	};
	
	/* /////////////////////////////////// FORMULARIO DE CARRITO ///////////////////////////////////////////////  */
	
	var CarritoFacturacion = $('CarritoFacturacion');
	var DatosFacturacion = $('DatosFacturacion');
	
	if(CarritoFacturacion && DatosFacturacion)
	{
		DatosFacturacion.setStyles({'overflow':'hidden', 'height':'0px'});
		if(DatosFacturacion.get('checked'))
			DatosFacturacion.setStyle('height','238px');

		CarritoFacturacion.addEvent('change', function(event){
			
			event.stop();

			if(this.get('checked'))
			{
				DatosFacturacion.tween('height','238px');
			}
			else
			{
				DatosFacturacion.tween('height','0');
			}
		});
	}
	
	/*  /////////////////////////////////////////////CARRITO BASICO ///////////////////////////////////////////////  */
	/*  /////////////////////////////////////////////CARRITO BASICO ///////////////////////////////////////////////  */
	/*  /////////////////////////////////////////////CARRITO BASICO ///////////////////////////////////////////////  */
	
	var addProduct = $$('a .button.comprar');
	var addProduct2 = $$('a .button.agregar');
	var Cart = $('productos_carrito');
	var FormularioResumen = $('tabla_resumen');
	var unavez=0;
	
	if(Cart)
	{
		if(Cookie.read('carrito'))
		{
			var carrito = JSON.decode(Cookie.read('carrito'));carrito=carrito.clean();
			neewcarrito=[];
			indice=0;
			Array.each(carrito, function(producto, index){
				for(i=0;i<producto.cantidad;i++)
				{
					neewcarrito[indice]=producto.id;
					indice++;
				}
			});
			var query = 'cual=1&productos='+JSON.encode(neewcarrito);
			var getCarrito = new Request({
				url: '/carrito/carrito/',
				onRequest: function(){
					Cart.getElement('.nohay').set('html','<br/>cargando productos<br/><br/>');
				},
				onSuccess: function(txt){
					Cart.set('html',txt);
					limpiar();
					autosalvar();
					borrar_carrito();
				},
				method: 'post',
				data: query
			});	
			getCarrito.send();
		}
	}
	if(FormularioResumen)
	{
		if(Cookie.read('carrito'))
		{
			var carrito = JSON.decode(Cookie.read('carrito'));carrito=carrito.clean();
			neewcarrito=[];
			indice=0;
			Array.each(carrito, function(producto, index){
				for(i=0;i<producto.cantidad;i++)
				{
					neewcarrito[indice]=producto.id;
					indice++;
				}
			});
			if(neewcarrito.length>0)
			{
				formularioResumen = $('formularioResumen');
				var query = 'cual=0&productos='+JSON.encode(neewcarrito);
				var getResumen = new Request({
					url: '/carrito/carrito/',
					onRequest: function(){
						FormularioResumen.set('html','<div class="calculando" style="margin: 70px 200px 30px 30px;"><img src="/images/preload.gif" /></div>');
					},
					onSuccess: function(txt){
						FormularioResumen.set('html',txt);
						formularioResumen.set('action','/carrito/formulario');
						formularioResumen.getElements('input').removeProperty('disabled');
						formularioResumen.getElement('#productosJson').set('value',JSON.encode(neewcarrito));
					},
					method: 'post',
					data: query
				});	
				getResumen.send();
			}
		}
	}
	if(addProduct)
	{
		addProduct.each(function(e,i){
			e.addEvent('click',function(event){if(event)event.stop();
				var id = e.getElement('.id').get('text').toInt();
				var url = e.getParent('a').get('href');
				if(id)
					agregaruno(id);
				if(url)
					location.href=url;
			});
		});
	}
	if(addProduct2)
	{
		addProduct2.each(function(e,i){
			e.addEvent('click',function(event){if(event)event.stop();
				var id = e.getElement('.id').get('text').toInt();
				if(id)
					agregaruno(id);
				carritoiconos();
			});
		});
	}
});

