// ----------------------
// Barullo
// ----------------------
// Carrito
// ----------------------

$(document).ready(function() {
	
	// cambio de cantidad en la cesta de la compra
	// los input de cantidad sólo aceptan números
	/*var changingQuantity = false;
	var changingNotAllowed = false;
	$("input.input_cantidad").keypress(function (e){
		if ($(this).val().length == 1 && (e.which==8)){
			changingNotAllowed = true;
			return false;
		} else {
			changingNotAllowed = false;
		}
	});
	
	$("input.input_cantidad").keyup(function (e){
		if (!changingNotAllowed) {
		
			if (changingQuantity && (e.which != 37 && e.which != 39 && e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57))) {
				// no es un número válido (o estamos procesando ya)
				var oldVal = $(this).val();
				var newVal = oldVal.substr(0, oldVal.length - 1);
				$(this).val(newVal);
				return false;
			} else {
				if (e.which == 0 || e.which == 8 || (e.which >= 48 && e.which <= 57)) {
					changingQuantity = true;
					// si es un número, queremos cambiar el valor
					var idQuantity = parseInt(this.id.split("cantidad_")[1]);
					var quantity = $(this).val(); //parseInt($(this).val()+""+(e.which-48)+"");
					//$(this).val(quantity);
					
					if (quantity == 0) 
						deleteFromCart(this, idQuantity);
					else 
						changeQuantityFromCart(this, idQuantity, quantity);
				}
			}
			
		}
	});*/
	
	$("input.input_cantidad").keypress(function (e){
		if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)){
			var oldVal = $(this).val();
			var newVal = oldVal.substr(0, oldVal.length);
			$(this).val(newVal);
					
			if (e.which==13){
				// hacemos submit
				$(this).parent().find("a.cambiar").click();
			}
			
			return false;
		}
	});
	
	$("#ficha a.cambiar").click(function() {
		var idChange = parseInt(this.id.split("cambiar_")[1]);
		var quantity = $(this).parent().find("input.input_cantidad").val();
		if (quantity=='') alert("introduce una cantidad válida");
		if (quantity==0) deleteFromCart(this, idChange);
		else changeQuantityFromCart(this, idChange, quantity);
		
		return false;
	});
	
	
	function changeQuantityFromCart(item, idValue, quantity){
		// recogemos los valores
		var ajaxUrl = "ajax/update_from_cart.php";
		var ajaxData = "id=" + idValue + "&quantity="+quantity;
		
		// los enviamos por POST
		$(item).hide();
		$(item).parent().find(".borrar_preload").fadeIn("fast", function(){
			$.ajax({
				type: "POST",
				url: ajaxUrl,
				data: ajaxData,
				success: function(data){
					$(item).parent().find(".borrar_preload").fadeIn("slow", function(){

						envioOk = data.indexOf("OK-") != -1;
						data = (envioOk) ? data.split("OK-")[1] : data.split("ERROR-")[1];
						errorCampos = data.indexOf("|") != -1;
						
						if (envioOk) {
							// mostramos otra vez el campo
							$(item).parent().find(".borrar_preload").hide();
							$(item).show();
							// hay que poner el precio nuevo en todos los sitios
							$("#header #user_navigation #shop_price").hide().html("("+data+" €)").fadeIn("slow");
							$("#ficha #total .subtotal").hide().html(data+"€").fadeIn("slow");
							var unitPrice = ($(item).parent().parent().find('td.td_price').html().split(" €")[0]);
							var totalPrice = (quantity*unitPrice);
							$(item).parent().parent().find('td.td_subtotal').html(totalPrice.toFixed(2)+" €");													
						} else {
							// mostramos el error
							if (!errorCampos) {
								alert("ha ocurrido un error");
							}
						}
						
						changingQuantity = false;
						
					});
				}
			});
		});
	}
	
	// borrar algo de la cesta de la compra
	$("#ficha a.borrar").click(function() {
		var idDelete = parseInt(this.id.split("borrar_")[1]);
		
		deleteFromCart(this, idDelete);
		return false;
	});
	
	function deleteFromCart(item, idValue){
		// recogemos los valores
		var ajaxUrl = "ajax/update_from_cart.php";
		var ajaxData = "id=" + idValue + "&quantity=0";
		
		// los enviamos por POST
		$(item).hide();
		$(item).parent().find(".borrar_preload").fadeIn("fast", function(){
			$.ajax({
				type: "POST",
				url: ajaxUrl,
				data: ajaxData,
				success: function(data){
					$(item).parent().find(".borrar_preload").fadeIn("slow", function(){

						envioOk = data.indexOf("OK-") != -1;
						data = (envioOk) ? data.split("OK-")[1] : data.split("ERROR-")[1];
						errorCampos = data.indexOf("|") != -1;
						
						if (envioOk) {
							// aquí en realidad hay que volver a generar la tabla de la compra...
							// como sabemos el que se ha borrado lo podemos quitar y ya está...
							var tr = $(item).parent().parent().fadeOut("slow", function(){
								$(this).remove();
							});
							// y también hay que poner el precio nuevo en todos los sitios
							$("#header #user_navigation #shop_price").hide().html("("+data+" €)").fadeIn("slow");
							$("#ficha #total .subtotal").hide().html(data+"€").fadeIn("slow");
							// si el precio es 0.00 avisamos de que no hay nada en la cesta
							if (data == "0.00"){
								$("#content_center #ficha table tbody").html('<tr><td colspan="8">&nbsp;</td></tr><tr><td colspan="8">Aún no hay ningún producto añadido en el carrito de la compra</td></tr><tr><td colspan="8">&nbsp;</td></tr>');
								// y quitamos el botón de comprar
								$("#content_center #ficha .acciones .confirmar_pedido").fadeOut("normal");
							}							
						} else {
							// mostramos el error
							if (!errorCampos) {
								alert("ha ocurrido un error");
							}
						}
						
					});
				}
			});
		});
	}
	
	// aplicar un descuento a la cesta de la compra
	
	$("#content_center #ficha a.do_discount").click(function(e) {
		var idDiscount = $(this).parent().parent().find("input#codigo_descuento").val();
		if (idDiscount=='') alert("No has introducido ningún código de descuento.");
		else doDiscount($(this), idDiscount);
		return false;
	});
	
	// también se puede haciendo enter sobre el campo...
	$("#content_center #ficha input#codigo_descuento").keypress(function (e){
		if (e.which==13){
			var idDiscount = $(this).val();
			
			if (idDiscount=='') alert("No has introducido ningún código de descuento.");
			else doDiscount($("#content_center #ficha a.do_discount"), idDiscount);
		}
	});
	
	function doDiscount(item, idDiscount){// recogemos los valores
		var ajaxUrl = "ajax/do_discount.php";
		var ajaxData = "id=" + idDiscount;
		
		// los enviamos por POST
		$(item).fadeTo("fast", 0.5, function(){
			$.ajax({
				type: "POST",
				url: ajaxUrl,
				data: ajaxData,
				success: function(data){
					$(item).fadeTo("slow", 1, function(){

						envioOk = data.indexOf("OK-") != -1;
						data = (envioOk) ? data.split("OK-")[1] : data.split("ERROR-")[1];
						errorCampos = data.indexOf("|") != -1;
						
						//if (envioOk) {
							var subtotal = data.split("+++")[0];
							var descuento = data.split("+++")[1];
							var total = subtotal - descuento
							
							if (total<0) total = 0;
							total = (total).toFixed(2);
							
							if (descuento == 0) descuento = "0.00";
							
							// hay que poner el precio nuevo en todos los sitios
							$("#header #user_navigation #shop_price").hide().html("("+total+" €)").fadeIn("slow");
							$("#ficha #total .subtotal").hide().html(total+"€").fadeIn("slow");
							$("#ficha #total .descuento").hide().html(descuento+"€").fadeIn("slow");
							
							
							if (!envioOk && !errorCampos) alert("Código de descuento no válido");
														
						//} else {
							// mostramos el error
						//	if (!errorCampos) {
						//		alert(data);
						//	}
						//}
						
					});
				}
			});
		});
	}
	
	// submit del carrito
	$("#content_center #ficha .acciones .confirmar_pedido").click(function(e){
		var f = document.forms["form_carrito"];
			f.submit();
		return false;
	});
	
	
});	
