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

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(){
		var photo = $('#photo-gallery .photos li img[title]');
		//al li y al div le doy el ancho de la imagen
		photo
			.parent()
			.width(photo.width())
			.height(photo.height());
 			
		var widthCaption = photo.width()-20;
		photo.after('<div class="caption" style="width: '+ widthCaption +'px">' + photo.attr('title') + '</div>');
		
		//para mostrar los textos descriptivos
		this.showCaptions();
	},
	
	//muestro/oculto captions
	showCaptions: function(){
		var photo = $('#photo-gallery .photos li.active img[title]');
		
		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;
		});
	
	}
}

var validaciones = function(){
	if (document.getElementById('contacto')) {
		$("#contacto").validate({
				errorContainer: $('.errors'),
				errorLabelContainer: $("ul", $('.errors')),
				wrapper: 'li',
			});
	}
}