$(function(){
	//inicializamos carrusel
	$('#mycarousel').jcarousel({
		scroll: 1
    });
	
	//inicializamos galeria de fotos
	gallery.init();
});

var gallery = {
	//mostramos foto
	show: function(index){
		//le doy al ul la altura de la imagen, oculto la foto actual y muestro la del orden "index"
		$('#photo-gallery .photos li.active')
			.parent()
			.height( $('#photo-gallery .photos li.active img').height() )
			.children('.active')
			.removeClass('active')
			.css('display','none')
			.parent()
			.find('li:eq('+index+')')
			.addClass('active')
			.fadeIn(1000);
			
		//Marco el thumbnail activo
		$('#photo-gallery .thumbs li:eq('+index+')').addClass('active').siblings('.active').removeClass('active');
	},
	
	//las fotos van pasando de manera automatica
	auto: function(){
		$(document).everyTime(4000,'play',function(){
			//consigo el siguiente index
			var current = $('#photo-gallery .photos li').index( $('#photo-gallery .photos li.active') );
			var next = ( current+1 == $('#photo-gallery .photos li').length ) ? 0 : current+1;
			gallery.show(next);
		});
	},
	
	//creo los captions
	addCaptions: function(){
		
		$('#photo-gallery .photos li img[alt]').each(function(){
			$$ = $(this);
			
			//ponemos el height para forzar altura de todos los li's
			if ($$.height() > 0) $('#photo-gallery .photos li').height( $$.height() );
			
			//width para cada imagen
			$$.parent().width(parseInt($$.attr('rel')));
			
			
			var widthCaption = parseInt($$.attr('rel'))-20;
			$$.after('<div class="caption" style="width: '+ widthCaption +'px">' + $$.attr('alt') + '</div>');
		});
		
		//para mostrar los textos descriptivos
		this.showCaptions();
	},
	
	//muestro/oculto captions
	showCaptions: function(){
		var photo = $('#photo-gallery .photos li.active img[alt]');
		
		if ( photo[0] ) {	
			$('#photo-gallery .photos li img').hover(function(){
				$(document).stopTime();
				$('#photo-gallery .photos li:visible div.caption').fadeIn();
			},function(){
				$(document).oneTime(2000,'hideCaption',function(){
					$('#photo-gallery .photos li:visible div.caption').fadeOut('fast');
					gallery.auto();
				});
			});
		}
	},
	
	init: function(){
		//alert('sss')
		if ( !$('#photo-gallery')[0] ) return; //limitamos alcance
		
		//escondemos todas las fotos menos la primera
		$('#photo-gallery .photos li:first').addClass('active').fadeIn();
		
		//autoplay
		this.auto();
		
		//para aņadir dinamicamente los textos descriptivos
		this.addCaptions();
		
		//al clickar al thumb mostramos la foto y paramos el autoplay
		var thumb = $('#photo-gallery .thumbs a');
		thumb.click(function(){ 
			$(document).stopTime('play');
			gallery.show( thumb.index(this) ); 
			return false;
		});
	
	}
}
