// gestion eventos onload
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function () {
			oldonload();
			func();
		}
	}
}

var menuEvents = function () {
	var showing = 0;
	$("#mnulat ul").hide();
	$(".menu").click(function () {
		var id = $(this).attr("rel");
		if (showing != id) {
			$("#mnulat ul").hide(150);
			$("#sub_"+id).show(250);
			showing = id;
		} else {
			$("#sub_"+id).hide(150);
			showing = 0;
		}
		return false;
	});

}

var submenuEvents = function () {
	var $id_parent = $("#id_parent"),
	url = "/ajax/get_cats.php",
	_data;
	
	$(".submenu").click(function () {
		// oculta todos los sub-submenus
		$(".subsub").remove();
		
		// obtiene la lista de subcategorias
		var id = $(this).attr("rel");
		_data = {"id": id}
		
		$.ajax({
			url : url,
			type: "get",
			dataType: "json",
			data: _data,
			success: function (resp) {
				var cats = resp.cats,
				id_parent = resp.id_parent;
				// append to parent
				if (id_parent !== 0) {
					var lis = "";
					for (var i=0; i<cats.length; i++) {
						lis += "<li><a href=\"./categoria.php?id="+cats[i].id+"\">"+cats[i].txt+"</a></li>";
					}
					$("#cat_"+id_parent).append("<ul class=\"subsub\" style=\"display: none;\">"+lis+"</ul>");
				}
				$("#cat_"+id_parent).find("ul").show(250);
			}	
		});		
		
		return false;
	});
	
	// abre el menu si estamos dentro de una categoria
	if ($id_parent.length > 0) {
		var id = $id_parent.val();
		_data = {"id": id};
		$.ajax({
			url : url,
			type: "get",
			dataType: "json",
			data: _data,
			success: function (resp) {
				var cats = resp.cats,
				id_parent = resp.id_parent;
				// append to parent
				if (id_parent !== 0) {
					var lis = "";
					for (var i=0; i<cats.length; i++) {
						lis += "<li><a href=\"./categoria.php?id="+cats[i].id+"\">"+cats[i].txt+"</a></li>";
					}
					$("#cat_"+id_parent).append("<ul class=\"subsub\" style=\"display: none;\">"+lis+"</ul>");
				}
				$("#cat_"+id_parent).find("ul").show(250);
			}	
		});		
		
		return false;
	}
}

var catalogEvents = function () {
	var $scroll = $(".scrollable").scrollable({
			mousewheel: true, 
			onSeek: function () {
				if (this.getIndex() > 0) {
					window.location.hash = this.getIndex();
				} else {
					window.location.hash = null;
				}
			}
		});
	
	$scroll.navigator();
	if (window.location.hash !== '') {
		var api = $(".scrollable").data("scrollable");
		var index = parseInt(window.location.hash.substring(1));
		api.seekTo(index);
	}
	
	var $list = $(".lst_prods li");
	$list.click(function () {
		var $lnk = $(this).find("A");
		var $url = $lnk.attr("href");
		if ($url != '') {
			document.location = $url;
		}
	});
	
	$list.mouseover(function () {
		if (!$(this).hasClass("agota")) {
			$(this).find("img").addClass("over");
		}
		$(this).find("p").addClass("over");
	});
	
	$list.mouseout(function () {
		$(this).find("img").removeClass("over");
		$(this).find("p").removeClass("over");
	});
}

var registerEvents = function () {
	$("#fReg").submit(function () {
		if (validaForm('formulario', listaCampos, listaEtiquetas, "Por favor, rellene:\n", ",\n")) {
			return true;
		} else {
			return false;
		}
	});
	$("#id_pais").change(function () {
		if(this.value === "63") {
			$("#id_provincia").attr("disabled", false);
			$("#lbl_prov").addClass("required");
		} else {
			$("#id_provincia").attr("disabled", true);
			$("#lbl_prov").removeClass("required");
		}
		validateEvents();
	});
}

var fichaEvents = function () {
	// gestiona la vuelta atrás a la coleccion
	var hash = null,
	href = null;
	
	if (window.location.hash !== '') {
		hash = window.location.hash;
		href = $("#back2cat").attr("href");
		href += hash;
		$("#back2cat").attr("href", href);
	}
}

var cartEvents = function () {
	// btn
	$("#btncarrito").click(function () {
		var $ref = $("#referencia"),
		amount = $.trim($("#cantidad").val()),
		$data = null,
		$color = 0,
		$indicator = null,
		$cartlink = $("#cart"),
		color_ok = false,
		$radio_colors = $(":radio");
		
		if (amount !== '') {
			if (isNaN(amount)) {
				alert("La cantidad sólo puede contener números");
			} else {
				// color
				if ($radio_colors.length > 0 ) {
					$radio_colors.each(function () {
						if ($(this).attr("checked")) {
							$color = $(this).val();
							color_ok = true;
						}
					});
				} else {
					color_ok = true;
				}
				if (color_ok) {
					$data = ({referencia: $ref.val(), color: $color, cantidad: amount, precio: $("#precio").val()});
					$indicator = $("#indicator").indicator({
						text: "Enviando pedido...",
						image:  "/img/indicator.gif",
						animage: 50
					});
					$.ajax({
						url: "/ajax/add2cart.php",
						method: "get",
						dataType: "json",
						data: $data,
						success: function (resp) {
							if (resp.success !== 1) {
								alert("Ocurrió un error al grabar el pedido.\nPor favor, inténtelo más tarde.");
								$indicator.indicator("hide");
							} else {
								// añade el link si no existe
								if ($cartlink.length === 0) {
									$("#probox").append("<a href=\"./solicit-pedido.php\" id=\"cart\">Ver pedido</a>");
								}
								$indicator.indicator("hide");
								$("#indicator").message("init", {
							        text    : "El artículo se ha añadido al pedido",
							        animate :  250,
							        closeimg: "/img/close-icon.png"
							    });
							    $indicator.message("show");
							}
						}
					});
				} else {
					alert("Por favor, selecciona un color");
				}
			}
		} else {
			alert("Por favor, indica una cantidad");
		}
		
		return false;
	});
}

var orderEvents = function () {
	var $btnupdate = $("#updateorder");
	// $indicator = null,
	// $order = ({items: []});
	
	$("#items_pedido :text").change(function () {
		if ($btnupdate.attr("disabled", true)) {
			$btnupdate.attr("disabled", false)
		}
	});
	
	$("a.del_item").click(function () {
		var ref = ($(this).attr("rel")),
		li = $("#ref_"+ref);
		if (confirm("¿Confirma la eliminación de la referencia '"+ref+"' del pedido?")) {
			var cantidad = li.find("input[name=cantidad]");
			cantidad.val(0);
			updateCart();
		}
	});
	
	$btnupdate.click(function () {
		updateCart();
	});
	
	var $scroll = $(".scrollable").scrollable({
			mousewheel: true, 
			onSeek: function () {
				if (this.getIndex() > 0) {
					window.location.hash = this.getIndex();
				} else {
					window.location.hash = null;
				}
			}
		});
	
	$scroll.navigator();
	if (window.location.hash != '') {
		var api = $(".scrollable").data("scrollable");
		var reHash = new RegExp("/([0-9]*)/");
		if (reHash.test(window.location.hash)) {
			var index = RegExp.$1;
		}
	}
}

var confirmaEvents = function () {
	$(":radio").change(function () {
		if($(this).val() === 'otra_direccion') {
			$(":text").attr("disabled", false);
			$("select").attr("disabled", false);
		} else {
			$(":text").val("");
			$(":text").attr("disabled", true);
			$("select").attr("disabled", true);
		}
	});
	
	$("#confirma_pedido").submit(function () {
		// valida si hay datos empresa
		if($("#otra").attr("checked")) {
			return false;			
		} else {
			return true;
		}
	});
}

var updateCart = function () {
	var $indicator = null,
	$data = null,
	$order = ({items: []});
	
	$indicator = $("#indicator").indicator({
		text: "Actualizando pedido...",
		image:  "/img/indicator.gif",
		animage: 50
	});
	
	// datos
	$("#items_pedido li").each(function () {
		var ref = $(this).find("input[name=referencia]"),
		color = $(this).find("input[name=color]"),
		cantidad = $(this).find("input[name=cantidad]"),
		precio = $(this).find("input[name=precio]"),
		$data = ({referencia: ref.val(), color: color.val(), cantidad: cantidad.val(), precio: precio.val()});
		$order.items.push($data);
	});

	// llamada ajax
	$.ajax({
		url: "/ajax/update_cart.php",
		method: "get",
		dataType: "json",
		data: $order,
		success: function (resp) {
			$indicator.indicator("hide");
			if (resp.success === 1) {
				var txt = 'Pedido actualizado';
				$("#brutoamount").html(resp.bruto);
				$("#numrefs").html(resp.refs);
				$("#itemamout").html(resp.items);
			} else {
				var txt = 'No se pudo actualizar';
			}
			$("#indicator").message("init", {
			 	text    : txt,
			    animate :  250,
				closeimg: "/img/close-icon.png"
			});
			$indicator.message("show");
			$("#updateorder").attr("disabled", true);
			
			var refs = resp.clear_refs;
			if (refs.length > 0) {
				for (var i=0; i< refs.length; i++) {
					var $li = $("#ref_"+refs[i]);
					$li.remove();
				}
			}
		}
	});
}
