(function($) {
	
    $.extend($.fn, {
	
		abre_mensaje: function() {
					$(this).fadeTo(0, 0.9).animate({ top: 0 });		
		},
		
		cierra_mensaje: function() {
					var elem = $(this);
			elem.fadeOut("fast", function() {
							elem.css("top", "-150px");
					});
		}
		
    });

    // Simulación de desplegables
	$.fn.desplegable = function(opciones) {
		var clase = $(this).attr("class");
        var paneles = $(this).find(".panel"),
            z_index = 100,
			eleccion;
		togglePanel = function(select) {
            var panel_seleccionado = select.find(".panel");			
            eleccion = select.find(".eleccion");
            paneles.not(panel_seleccionado).filter(":visible").hide();
            panel_seleccionado.toggle();			
		};		
		$(this).each(function() {   // Para corregir el comportamiento de las pilas de z-index en IE7
			$(this).css("z-index", z_index);
			z_index -= 1;
		});
		$(this).bind("keydown", function(e) {
			if (e.which == 13) {
				e.preventDefault();
				togglePanel($(this));
			} else {
				/*var caracter = String.fromCharCode(e.which).toLowerCase();
				$("#select_tmp").val($("#select_tmp").val() + caracter);
				$(this).find("li").each(function() {
					console.log($(this).text().replace(/ /g, "").toLowerCase() + " " + ($("#select_tmp").val().replace(/ /g, "")));
					if ($(this).text().replace(/ /g, "").toLowerCase().indexOf($("#select_tmp").val().replace(/ /g, "")) === 0) {
						$(this).focus().css("color", "#f00");
					}
				});*/
			}
		});
        $(this).bind("click", function() {
			if (!$(this).hasClass("inactivo")) togglePanel($(this));
        });
        
        $("body").bind("click", function(e) {
            if (!$(e.target).hasClass("eleccion")) {
                paneles.hide();        
            }
        });

		$(paneles).find("li").click(function() {
            var valor = $(this).html();
            eleccion.html(valor);            
			var valor = ($(this).attr('id').split('_'))[1];
			$(this).closest(".select_cont").prev().val(valor).trigger("change");
			if (valor != "") $(this).parents(".panel").next('.content_error').empty();
		})
		
		$(this).focus(function() {
			var aux = $("<input type='hidden' id='select_tmp' />");
			if ($(this).next("#select_tmp").length == 0) $(this).after(aux);			
		});
		$(this).blur(function() {
			$(this).next("#select_tmp").remove();
		})
    };
    
    $(document).ready(function() {

	var t;  // Para el setTimeout
	
	$(".inline").fancybox({
	    padding:0,
	    overlayColor:"#000",
	    autoDimensions: true,
	    onComplete: function() {	// Todo el jQuery que se ejecutará al abrirse el lightbox              

                    $(".buttonAnadir").click(function(e) {
                            e.preventDefault();
							var stock_actual = parseInt($("#stock_actual").html());
							var stock_prevision = parseInt($("#stock_prevision").html());
							var stock = stock_actual + stock_prevision;
							var input_unidades = $("#inputUnidades");
                            if (!isNaN(input_unidades.val()) && parseInt(input_unidades.val()) > 0 && (input_unidades.val().indexOf(".") == -1) && parseInt(input_unidades.val()) <= stock) {
                                    var unidades = parseInt($("#inputUnidades").val());
                                    var id_producto = $("#id_producto").val();
                                    $(".clearAnadir").hide();
									$("#anadir_loading").show();
									if (unidades > stock_actual) {
										var unidades_nostock = unidades - stock_actual;
										unidades = stock_actual;
									} else {
										unidades_nostock = 0;
									}
                                    $.ajax({
                                      url: URL_BASE + 'ajax_anyadir_producto.php',
                                      data: { id_producto: id_producto, unidades: unidades, unidades_nostock: unidades_nostock },
                                      success: function() {
											var caja_mensaje = $("#lightbox-home #mensaje");
											if (!caja_mensaje.is(":visible")) {
												caja_mensaje.abre_mensaje();
												t = setTimeout(function() { caja_mensaje.cierra_mensaje()}, 4000);
											}
                                            $("#total_carrito").html(parseInt($("#total_carrito").html()) + unidades);
											var singular = parseInt($("#total_carrito").html()) == 1;
											$("#link_carrito").attr("title", (parseInt($("#total_carrito").html()) + " " + (singular ? txt_producto : txt_productos) + " " + txt_entucarrito));
											if (parseInt($("#stock_actual").html()) > 0) $("#stock_actual").html(parseInt($("#stock_actual").html()) - unidades);
											if (unidades_nostock > 0) {
												if (parseInt($("#stock_prevision").html()) > 0) $("#stock_prevision").html(parseInt($("#stock_prevision").html()) - unidades_nostock);
											}
											$("#anadir_loading").hide();
											$(".clearAnadir").show();
                                      },
									  error: function() {
											var caja_mensaje = $("#lightbox-home #mensaje_error");
											if (!caja_mensaje.is(":visible")) {
												caja_mensaje.abre_mensaje();
												t = setTimeout(function() { caja_mensaje.cierra_mensaje()}, 4000);
											}					
									  }
                                    });
                                    
                            } else {
								if (parseInt(input_unidades.val()) > stock) {
									var caja_mensaje = $("#lightbox-home #mensaje_stock_error");
									if (!caja_mensaje.is(":visible")) {
										caja_mensaje.abre_mensaje();
										t = setTimeout(function() { caja_mensaje.cierra_mensaje()}, 4000);
									}														
								}
								var color_input = $("#inputUnidades").css("color");
								$("#inputUnidades").css("color", "#f00");
								setTimeout(function() { $("#inputUnidades").css("color", color_input)}, 1000);
							}
                    });
                    
                    $("#lightbox-home #mensaje, #lightbox-home #mensaje_error").click(function(e) {
			e.preventDefault();
			clearTimeout(t);
			$(this).cierra_mensaje();
		    }).mouseenter(function() {
			$(this).find("img").show();
		    }).mouseleave(function() {
			$(this).find("img").hide();
		    });
		    

		    $('#inputUnidades').keypress(function(e) {
			if (e.which == 13) {
				e.preventDefault();
				//$(".buttonAnadir").trigger("click");
			}
		    });	
		    
	    },
	    onClosed: function() {
		window.location.hash = '';
	    }
	});

	$(".hashtag_inline").click(function(e) {
	    var hashtag = $(this).attr("href");
		if (hashtag.indexOf("=") !== -1) {
			var hashtag_parts = hashtag.split("=");
			var id = hashtag_parts[1];
			var archivo = hashtag_parts[0] == "#!producto" ? "ficha-producto.php" : "ficha-fabricante.php";
			$("#lanza_lightbox").attr("href", URL_BASE + archivo + "?id=" + id).click().attr("href", "#");
		} else if (hashtag == "#!pdf") {
			$("#lanza_lightbox").attr("href", URL_BASE + "descargar_pdf.php").click().attr("href", "#");
		}
	});

	var hashtag = window.location.hash;
	if (hashtag.indexOf("#!") == 0) {
	    var hashtag_parts = hashtag.split("=");
	    if (hashtag_parts[0] == "#!producto") {
			var id = hashtag_parts[1];
			$("#lanza_lightbox").attr("href", URL_BASE + "ficha-producto.php?id=" + id).click().attr("href", "#");
	    } else if (hashtag_parts[0] == "#!fabricante") {
			var id = hashtag_parts[1];
			$("#lanza_lightbox").attr("href", URL_BASE + "ficha-fabricante.php?id=" + id).click().attr("href", "#");			
		}
	}	

	$("#productos_asociados, #ofertas_relacionadas").live("click", function() {
	    document.location = $(this).attr("rel");
	});
	
	$("#agrupado_seleccionado").live("change", function() {
        $.ajax({
            type: "POST",
            url: URL_BASE + "ajax_carga_agrupado.php",
			data:{ producto: $(this).val() },
            success: function(datos) {
                var datos_json = $.parseJSON(datos);
				$("#id_producto").val(datos_json.id_producto);
				$("#nombre_producto").html(datos_json.producto);
				$("#uds_en_carrito").val(datos_json.uds_en_carrito);
				$("#codigo_producto").html(datos_json.codigo);
				$("#stock_actual").html(datos_json.stock);
				$("#stock_prevision").html(datos_json.stock_prevision);
				$("#inputUnidades").val("1");
				$(".tarifas").empty();
                var j;
                for (j = 0; j < datos_json.precios.length; j++) {
					$(".tarifas").append('<div class="lb-linea"></div>');
					$(".tarifas").append('<div class="lb-tarifaseuros"><p><strong>' + datos_json.precios[j].precio + '&euro; </strong></p></div>');
					$(".tarifas").append('<p>' + datos_json.precios[j].tarifa + '</p>');
                }
            },
            error: function(request,status,errorThrown) { alert("Error en consulta AJAX: " + errorThrown); }
        });

	});
    });
    
})(jQuery);
