(function($){
	//funcion que inicializa la galería
	//Redimensiona la imagen al inicio o cuando se refresca
	$.fn.galeriaGoki = function() {
	
		$('#content .proyecto').load('botonera.txt');
		$('#galeria .titulo').hide(); //estos dos campos son útiles pero no deben aparecer en pantalla
		$('#galeria .web').hide();    //estos dos campos son útiles pero no deben aparecer en pantalla
		
		if ( ($.browser.msie && $.browser.version < 7) ) //arreglos en CSS para que la web sea visible en IE6
		{
			$('#galeria .diapo').css('margin-left','230px');
			$('#galeria .diapo').css('margin-bottom','10px');
			$('#galeria .diapo img').css('width','95%');
			$('#galeria').css('margin-top','130px');
			$('#navigation').hide();
			$('#contentframe').hide();
		}

		if ( ($.browser.msie && $.browser.version >= 7) || !$.browser.msie ) //funciona correctamente para el resto de navegadores superiores a IE6
		{
			$.inAnimation = false;
			var options = $.extend($.fn.galeriaGoki.defaults, $.fn.galeriaGoki.options);

			$('#galeria').hide();
			$('#galeria .titulo').hide(); //estos dos campos son útiles pero no deben aparecer en pantalla
			$('#galeria .web').hide();    //estos dos campos son útiles pero no deben aparecer en pantalla
			$('#content').hide();		
					
			$(window).bind("load", function(){
				//inicializamos la visibilidad de los divs
				$('#loading').hide();
				$('#loading').fadeIn('slow');
				$('#content').show();
				//marcamos la foto activa como la primera
				if ($('#slideshow .activeslide').length == 0) $('#galeria .diapo:first').addClass('activeslide');
				//controlamos la visibilidad del cargador 
				if ($.browser.msie){ //el efecto fadeOut no funciona con Gif animados en IE, además el evento LOAD no se detecta bien, por lo que asignamos una duración fija
					$('#loading').fadeOut(1500);
				}
				else{ //en el resto de navegadores sí funciona
					var rutaImagen= $('.activeslide img').attr('src');
					$('<img />').attr('src', rutaImagen).load( function(){ //mientras la imagen no se haya cargado aparecerá el Gif de Cargando
						// ocultamos la precarga y mostramos 
			  			$('#loading').fadeOut('fast');
		     		});
				}

				//la primera pantalla aparece suavemente sobre fundido en blanco
				$('#galeria').fadeIn('slow');

				//Inicializamos ahora la información textual del proyecto que se está mostrando
				//Título
				var $titulo='&nbsp;&nbsp;<img src="img/btgal_hover_i.jpg">&nbsp;<span class="textotitulo">'+$('#galeria .titulo').text()+'<span class="ayuda">&nbsp;(ocultar)</span></span></br>';
				$('#titulo').html($titulo);
				//Subtítulo (campo opcional)
				if ( $('.activeslide').find('img').attr('title') ){
					$('#subtitulo').html( $('.activeslide').find('img').attr('title') );
					$('#subtitulo').fadeIn('slow');
				}
				else $('#subtitulo').hide();
			
				//Descripcion
				var $descripcion=$('.activeslide').find('img').attr('alt');				
				$('#contentframe #descripcion').html($descripcion);
			
				//Web (opcional)
				if ($('#galeria').find('p.web').text()){ //no sé por qué no funciona esto -->$('#galeria').find('p.web')
					$('#contentframe #infoproyecto #website').html('<a href="http://'+$('#galeria').find('p.web').text()+'" title="'+$('#galeria .titulo').text() +'" target="_blank">'+$('#galeria').find('p.web').text()+'</a>');
					$('#contentframe #infoproyecto #website').show();
				}
				else {
					$('#contentframe #infoproyecto #website').hide();
				}
				//Contador de diapositivas
				//Inicializamos el contador de proyectos
				$('#contadorFotos .slidenumber').html(1);				//fotos actual
		    	var $fotosTotales=$("#galeria .diapo").size();			//fotos totales
				$('#contadorFotos .totalslides').html($fotosTotales);	
				$('#navigation a').click(function(){  
   					$(this).blur();  
   					return false;  
   				}); 	
			
			
				//FUNCIONES DE NAVEGACIÓN
				//NAVEGACIÓN POR RATÓN
				$('#nextslide').click(function() {
					if($.inAnimation) return false;
						nextslide();
						return false;
				});
				$('#prevslide').click(function() {
					if($.inAnimation) return false;
						prevslide();
					    return false;
					});
					$('#nextslide img').hover(function() {
						$(this).attr("src", "img/btgal_next.jpg");
						}, function(){
						$(this).attr("src", "img/btgal_hover_next.jpg");
					});
					$('#prevslide img').hover(function() {
						$(this).attr("src", "img/btgal_prev.jpg");
					}, function(){
					$(this).attr("src", "img/btgal_hover_prev.jpg");
				});

				// NAVEGACIÓN POR TECLADO
				//IE no detecta keypress
				$(document).keydown(function(event)
				{
					var key = event.charCode ? event.charCode : event.keyCode ? event.keyCode : 0;
					//también podría ser interesante: event.which pero con estos funciona
				
					switch(key)
					{
					//MOVIMIENTO TRANSVERSAL
					// Al pulsar <--
					case 39:	if($.inAnimation) return false;
								nextslide();
								return false;
								break;	
						
					// Al pulsar -->
					case 37:	if($.inAnimation) return false;
								prevslide();
							    return false;
								break;

					//MOVIMIENTO VERTICAL
					// OJO $('.proyecto a') funciona como un array de 0 a .length-1
					// Al pulsar UP
					case 38:	var nextproyecto=$.fn.galeriaGoki.options.numProyecto;
															
								if ( nextproyecto == 1) 
									window.location.href=$('.proyecto a:last').attr('href');								
								else	
									window.location.href=$('.proyecto a:eq('+(nextproyecto-2)+')').attr('href');							
								break;

					// Al pulsar DOWN
					case 40:	var nextproyecto=$.fn.galeriaGoki.options.numProyecto;
								
								if ( nextproyecto == $('.proyecto a').length ) 
									window.location.href=$('.proyecto a:first').attr('href');								
								else 	
									window.location.href=$('.proyecto a:eq('+nextproyecto+')').attr('href');
								break;
					}
				});
				// Al cambiar de proyecto en la galería, hacemos que desaparezca lentamente //esto puede no funcionar
				$('.proyecto a').click(function(){
					$('#galeria').fadeOut('fast');	
				});
				// Control de visibilidad de la información de cada proyecto
				$('#titulo').toggle(function (){
						var $ayuda='&nbsp;(+info)';
						$('#titulo .ayuda').html($ayuda);
						$('#titulo img').attr("src", "img/btgal_i.jpg");				 
					  	$('#infoproyecto').fadeOut('fast', function () { //INFOPROYECTO contiene descripcion / website / titulo														
						$('#titulo').css('margin-top','60px');										
						});
				}, function(){
						var $ayuda='&nbsp;(ocultar)';
						$('#titulo .ayuda').html($ayuda);
						$('#titulo img').attr("src", "img/btgal_hover_i.jpg");
						$('#titulo').css('margin-top','8px');
						$('#infoproyecto').fadeIn('fast');	//INFOPROYECTO contiene descripcion / website / titulo														
				});
		
			});
				
			$(document).ready(function() {
				$('#galeria').resizenow(); 
			});
		
			$(window).bind("resize", function(){
				$('#galeria').resizenow(); 
			});
		}
		//MARCAMOS LA SECCIÓN ACTUAL COMO ACTIVA
		//$('#content .proyecto a:eq(1)').css('font-weight', 'bold');
	};
	
	//Función para redimensionar 
	//Función saca de la librería SUPERSIZE 2.0
	$.fn.resizenow = function() {
		var options = $.extend($.fn.galeriaGoki.defaults, $.fn.galeriaGoki.options);
	  	return this.each(function() {
	  		
			//Gather browser and current image size
			var imagewidth =options.startwidth;
			var imageheight = options.startheight;
			var browserwidth = $(window).width();
			var browserheight = $(window).height();
			var offset;

			//Resize image to proper ratio
		    $(this).height(options.startheight);
		    $(this).width(options.startwidth);
		    $(this).children().height(options.startheight);
		    $(this).children().width(options.startwidth);

			if (options.vertical_center == 1){
				$(this).children().css('left', (browserwidth - imagewidth)/2);
				$(this).children().css('top', (browserheight - imageheight)/2);
			}
			//controlamos la visibilidad del footer para que no se superponga con nuestra botonera
			if (browserheight<760)
			{
				$("#pie .datoscontacto").fadeOut("normal", function(){
					$("#contentframe").css('margin-left', 267);
				});
			}
			else
			{
				$("#pie .datoscontacto").fadeIn("normal");
				$("#contentframe").css('margin-left', 37);
			}
			return false;
		});
	};
	
	//Valores por defecto de la galería //estos valores deberían ser trasferidos desde el HTML
	$.fn.galeriaGoki.defaults = { 
			startwidth: 4,  		//ancho
			startheight: 3, 		//alto
			vertical_center: 1,
			numProyecto:15			//número de proyecto de la lista
	};
})(jQuery);


	
//Slideshow Next Slide
function nextslide() {
	var $fotosTotales=$("#galeria .diapo").size();

	if($.inAnimation) return false;
	else $.inAnimation = true;
    var options = $.extend($.fn.galeriaGoki.defaults, $.fn.galeriaGoki.options);
    var currentslide = $('#galeria .activeslide');
    currentslide.removeClass('activeslide');
		
    if ( currentslide.length == 0 ) currentslide = $('#galeria .diapo:last');
		
	//Display slide counter
	var slidecount = $('#contadorFotos .slidenumber').html();

	if (slidecount == $fotosTotales){
		slidecount = 1;
		var nextslide=$('#galeria .diapo:first');
		var prevslide=$('#galeria .diapo:last');
	}
	else {	
		slidecount++; 
		var nextslide=currentslide.next();
		var prevslide=nextslide.prev();
	}
	$('#contadorFotos .slidenumber').html(slidecount);
		
	$('.prevslide').removeClass('prevslide');
	prevslide.addClass('prevslide');
	nextslide.hide().addClass('activeslide');
		
	//El DIV Título del proyecto sólo se carga una vez por proyecto
	//var $titulo='&nbsp;&nbsp;<img src="img/btgal_hover_i.jpg">&nbsp;<span class="textotitulo">'+$('#galeria .titulo').text()+'</span></br>';
	//$('#titulo').html($titulo);

	var $descripcion=$('.activeslide').find('img').attr('alt');
	$('#descripcion').html($descripcion);
		
	if ($('.activeslide').find('img').attr('title')){
		var $subtitulo=$('.activeslide').find('img').attr('title');
		$('#subtitulo').html($subtitulo);
		$('#subtitulo').fadeIn('slow');
	}
	else $('#subtitulo').hide(); 

	//El DIV web sólo se actualiza al entrar en el proyecto, así que este código sólo es útil en la inicialización
	//if ($('#galeria .web'))
	//	$('#website').html('<a href="http://'+$('#galeria .web').text()+'">'+$('#galeria .web').text()+'</a>');

	var clearQueue = true;
	var gotoEnd= true; 
	
	var rutaImagen= $('.activeslide img').attr('src');

	if ($.browser.msie){
		nextslide.fadeIn('normal', function(){$.inAnimation = false;});
	}
	else{
		var rutaImagen= $('.activeslide img').attr('src');
		$('<img />').attr('src', rutaImagen).load( function(){ 
			// ocultamos la precarga y mostramos 
		    nextslide.fadeIn('normal', function(){$.inAnimation = false;});
   		});
	}
	$('#galeria').resizenow();//Fix for resize mid-transition
}
	
//Slideshow Previous Slide
function prevslide() {

	var $fotosTotales=$("#galeria .diapo").size();

	if($.inAnimation) return false;
	else $.inAnimation = true;
	var options = $.extend($.fn.galeriaGoki.defaults, $.fn.galeriaGoki.options);
	var currentslide = $('#galeria .activeslide');
	currentslide.removeClass('activeslide');
		
   	//Display slide counter
	if ( currentslide.length == 0 ) currentslide = $('#galeria .diapo:first');  //teóricamente esto no es necesario
	var slidecount = $('#contadorFotos .slidenumber').html();
	if (slidecount == 1){
		slidecount=$fotosTotales;
		var nextslide=$('#galeria .diapo:last');
		var prevslide=$('#galeria .diapo:first');
	}
	else{
		slidecount--; 
		var nextslide=currentslide.prev();
		var prevslide=nextslide.next();
	}	
	$('#contadorFotos .slidenumber').html(slidecount);

	$('.prevslide').removeClass('prevslide');
	prevslide.addClass('prevslide');
	nextslide.hide().addClass('activeslide');
		
	//El DIV Título del proyecto sólo se carga una vez por proyecto
	//var $titulo='&nbsp;&nbsp;<img src="img/btgal_hover_i.jpg">&nbsp;<span class="textotitulo">'+$('#galeria .titulo').text()+'</span></br>';
	//$('#titulo').html($titulo);
		
	var $descripcion=$('.activeslide').find('img').attr('alt');
	$('#descripcion').html($descripcion);

	if ($('.activeslide').find('img').attr('title')){
		var $subtitulo=$('.activeslide').find('img').attr('title');
		$('#subtitulo').html($subtitulo);
		$('#subtitulo').fadeIn('slow');
	}
	else $('#subtitulo').hide(); 
		
	//El DIV web sólo se actualiza una vez por proyecto, así que sólo se muestra en el inicio
	//if ($('#galeria .web'))
	//	$('#website').html('<a href="http://'+$('#galeria .web').text()+'">'+$('#galeria .web').text()+'</a>');

	var clearQueue = true;
	var gotoEnd= true; 

	if ($.browser.msie){
		$('#loading').fadeOut(1500);
		nextslide.fadeIn('normal', function(){$.inAnimation = false;});
	}
	else{
		var rutaImagen= $('.activeslide img').attr('src');
		$('<img />').attr('src', rutaImagen).load( function(){ 
			// ocultamos la precarga y mostramos 
		    nextslide.fadeIn('normal', function(){$.inAnimation = false;});
       	});
	}
	$('#galeria').resizenow();//Fix for resize mid-transition
}
