//----------------------------
//  Configuración por defecto
//----------------------------
	//Mensajes ocultos por defecto
	$("div.mensajes").hide(); 
 	//Enlaces externos
	$('a.external').click(function(){this.target = "_blank";});	
	
//--------------------------
//	FUNCIONES GENERALES
//--------------------------
	
	/* Inserción de videos flash */
	function insertaFlashVideos (swf)
	{
		var flashvars = {};
		var params = {allowFullScreen: true,wmode: "transparent"};
		var attributes = {};
		attributes.id = "videoCargador";
		swfobject.embedSWF(swf, "videoCargador", "512", "320", "9.0.0", "expressInstall.swf", flashvars, params, attributes);	
	}
	
	/*Convierte en enlace un elemento contenedor, tomando el valor href de un elementos contenido en él*/
	function hazClickable (trigger, target)
	{
		$(trigger).click(function(){		
		  	window.location=$(target, this).attr("href");
		  	return false;
		});
	}
	
	/* Desplegables
	Recibe un objetivo (elemento que contiene el trigger y el target) y busca:
	.trigger ->el elemento que se puede clicar para desplegar
	.target -> el elemento que se esconde y responde al trigger
	*/	
	function hazDesplegable (objetivo, autoShow)
	{
		(autoShow==true)? $(objetivo).find('.target').hide() : $(objetivo).find('.ico').hide();
		$(objetivo).find('.trigger').click(function(){
			$(this).next('.target').slideToggle('fast');
			($(this).find('.ico').text() =='Mostrar') ? $(this).find('.ico').text('Ocultar') : $(this).find('.ico').text('Mostrar');
		});			
	}

//--------------------------
//	COMÚN AUTOEJECUTABLE
//--------------------------
$(document).ready(function() {
	//Mi namespace global
	$.globalConfig = {};
	
	/* Selector de idiomas */
	$(".dropdown dt a").click(function() {
        $(".dropdown dd ul").toggle();
    });                        
    $(".dropdown dd ul li a").click(function() {
        var text = $(this).html();
        $(".dropdown dt a span").html(text);
        $(".dropdown dd ul").hide();
        $("#result").html("Selected value is: " + getSelectedValue("sample"));
    });
                
    function getSelectedValue(id) {
        return $("#" + id).find("dt a span.value").html();
    }

    $(document).bind('click', function(e) {
        var $clicked = $(e.target);
        if (! $clicked.parents().hasClass("dropdown"))
            $(".dropdown dd ul").hide();
    });
	
	//Formulario de buscar
	$("input#textoBuscar").click(function(){		
		if (this.value==this.defaultValue) this.value = "";		
	});
	$("a.ico_lupa").click(function(){
		$("form#fBuscar").submit();			
	});
	
	//Botón "Subir" suave
	$("a.btn_goTop").click(function () {
		var elementClick = $(this).attr("href");
		var destination = $(elementClick).offset().top;
		$("body").animate({ scrollTop: destination}, 500 );
		return false;
	});
	
	//Mensajes y notificaciones
	$("div.mensajes").slideDown(400); // Si hay mensajes, los muestro
	$("div.mensajes  a.pop-cerrar").click(function(){
		$(this).closest("div.mensajes").slideUp(300);
	});
	
	
	
	//Animación menú principal
	$("div#menu ul li a").hover(function(){
		$(this).animate({         
	        paddingTop: "3px"
	      }, 100 );		
	},
	function() {
		$(this).animate({         
	        paddingTop: "0px"
	      }, 150 );
	}
	);
	
	//Animación  del menú lateral izquierda
	$("ul.mLeft li:not(class='selected')").hover(function(){
		$.globalConfig.pt0 = $(this).css("padding-top");
		$.globalConfig.pb0 = $(this).css("padding-bottom");
		$(this).animate({     
	        paddingTop: "+=5px",
	        paddingBottom: "+=5px"
	      }, 150 );
	},
	function() {
		$(this).animate({         
	        paddingTop: $.globalConfig.pt0,
	        paddingBottom: $.globalConfig.pb0
	      }, 150 );
	}
	);
	hazClickable('ul.mLeft li','a'); //Hago clicable todo el li de los menús laterales
	
		
	//Animación de botones verFicha
	$("a.btn_verFicha").hover(function(){
		$(this).animate({     
	        marginLeft: "+=6px"
	      }, 150 );		
	},
	function() {
		$(this).animate({         
	        marginLeft: "0"
	      }, 150 );
	}
	);
	
	//Animación de botones gSeleccion
	$("a.btn_gs").hover(function(){
		$.globalConfig.marginLeftInicial = $(this).css("margin-left");
		$(this).animate({     
	        marginLeft: "+=6px"
	      }, 150 );		
	},
	function() {
		$(this).animate({         
	        marginLeft: $.globalConfig.marginLeftInicial
	      }, 150 );
	}
	);
	
	//Animación del índice de productos
	$("div#familias-thumbs div.item h2").css({paddingLeft: "15px",opacity: "0"});
	
	var items = $("div#familias-thumbs div.item h2").get();
	for (var i = 0; i < items.length; i++) {
		if (i%2==0) {
			$(items[i]).animate({paddingLeft: "0", opacity: "1"},1500);
		}
		else {
			$(items[i]).animate({paddingLeft: "0", opacity: "1"},750);
		}
	};
	//Smoth scroll general
	$('a[href^=#]').click(function() {
		var obj = $(this).attr('href');
		$('html, body').animate({
			scrollTop: $(obj).offset().top
		}, 1000);
	});
	
	//Colorbox en clases modales generales
	$(".videoModal").colorbox({iframe:true, width:"580", height:"420"});
});//$.ready


//-------------------------------------
// Constructor de llamada general
//-------------------------------------

var activar =
{
	tabs:
	{
		init: function() {
			$(".tab_content").hide(); 
			$("ul.tabs li:first").addClass("active").show(); 
			$(".tab_content:first").show(); 
			
			$("ul.tabs li").click(function() {
				$("div.fichaSeleccionada").hide().empty();
				$("ul.tabs li").removeClass("active"); 
				$(this).addClass("active"); 
				$(".tab_content").hide(); 
				var activeTab = $(this).find("a").attr("href"); 
				$(activeTab).fadeIn();
				return false;
			});
		}
	},
	thumbs:
	{
		init: function()
		{
			$(".colorbox").colorbox();
			$("a[rel='galeria']").colorbox();
			
			//Muestra icono de ampliar:hover
			$('div.thumb a').bind('mouseover', function(){
				$(this).append('<span class="ampliar"></span>');
				$(this).find('span').click(function(){
					alert($(this).closest('a').attr("href"));
				});
			});
			$('div.thumb a').bind('mouseout', function(){
				$(this).find('span').animate({opacity:0},500, function(){
					$(this).remove();
				});
			});			
		}	
	},
	animaciones:
	{
		init: function()
		{
			$("a.colorbox").colorbox({width:"560", height:"490", iframe:true});
		}
	},
	filtroDiccionario:
	{
		init: function()
		{
			//Filtrado automático
			var total = $('div.item').get().length;
			$("#filter-count").text(total+' de '+total);
			/*
			jQuery Filter
			Based on Matt Ryall´work | revised by Pablo García
			http://www.mattryall.net/blog/2008/07/jquery-filter-demo
			Licensed under Creative Commons Attribution 3.0.
			http://creativecommons.org/licenses/by/3.0/
			*/ 
			$("#filtro").keyup(function () {
			    var filter = $(this).val(), count = 0;
			    $(".resultados:first .item").each(function () {
			        if ($(this).text().search(new RegExp(filter, "i")) < 0) {
			            $(this).addClass("hidden");
			        } else {
			            $(this).removeClass("hidden");
			            count++;
			        }
			    });
			    (count!=0)? $("#filter-count").text('Mostrando '+count+' de '+total) : $("#filter-count").text('No se encuentran resultados');
			});
		}
	},
	contacto:
	{
		init: function()
		{
			$("#fContacto").validate({
			    errorElement: "em",  
			    rules: {
					nombre: "required",
					apellidos: "required",
					email: {
						required:true,
						email:true
					},
					telefono: "required",
					domicilio: "required",
					cp: "required",
					localidad: "required",
					provincia: "required",
					departamento: "required",
					consulta: "required",
					aceptar: "required"	
			    },
			   	messages: {
			   		nombre: "obligatorio",
					apellidos: "obligatorio",
					email: "escriba un email válido",
					telefono: "obligatorio",
					domicilio: "obligatorio",
					cp: "obligatorio",
					localidad: "obligatorio",
					provincia: "obligatorio",
					departamento: "obligatorio",
					consulta: "obligatorio",
					aceptar: "Debe aceptar las condiciones"
			   	}
			});	
		}
	},
	newsletter:
	{
		init: function()
		{
			$("#form_newsletter").validate({
			    errorElement: "em",  
			    rules: {
					nombre: "required",
					apellidos: "required",
					email: {
						required:true,
						email:true
					},
					provincia: "required",
					profesion: "required",
					pais: "required",
					aceptar: "required"	
			    },
			   	messages: {
			   		nombre: "obligatorio",
					apellidos: "obligatorio",
					email: "escriba un email válido",
					provincia: "obligatorio",
					profesion: "obligatorio",
					pais: "obligatorio",
					aceptar: "Debe aceptar las condiciones"
			   	}
			}); 
		}
	},
	sedes:
	{
		init: function()
		{
			var flashvars = {};
			var params = {allowFullScreen: true,wmode: "transparent"};
			var attributes = {};
			attributes.id = "videoCargador";
			swfobject.embedSWF("../_media/swf/sedes.swf", "videoCargador", "500", "320", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
		}
	},
	documentacion:
	{
		init: function()
		{
			$('div.padre ul').hide();
			$('div.padre h3').click(function(){
				bloque = $(this).attr('rel');
				$("div#"+bloque+" ul").slideToggle();
			});			
			$("a.btn_verCatalogo").colorbox({iframe:true, width:"99%", height:"99%"});
		}
	}
}