// config
var animationSpeed = 300;
var int;

$(function(){
	
	/**
	 * Efecto de fade al cargar y salir de las paginas
	 */
	$('#page-wrapper').fadeIn(500);
	$('a:not([target="_blank"],#details-handle)').click(function(e){
		e.preventDefault();
		var link = this;
		$('#page-wrapper').fadeOut(200, function(){
			document.location = link.href;
		});
	})
	
	/**
	 * Inicialización del fader / slider / carousel
	 */
	$('.fader-container.home').appendTo('#header').fadeIn(1400); // Muevo el slider de la home al header del sitio
	if ($('.fader-container').size() > 0) {
		$('.fader-container').anythingFader({
			autoPlay: false,
			delay: 5000,
			startStopped: true,
			animationTime: 500,
			hashTags: false,
			buildNavigation: true,
			pauseOnHover: true
		});
		$('<span class="hover"></span>').appendTo('.fader-container .arrow');
	}
	if ($('.slider-container').size() > 0) {
		$('.slider-container').anythingSlider({
			autoPlay: false,
			hashTags: false,
			animationTime: 600
		});
	}
	if ($('#carousel').size() > 0) {
		$('#carousel').jcarousel({
			scroll: 1
		});
	}
	// Efecto de hover y selección de los items
	$('.thumbNav a').each(function(){
		$('<span class="hover"></span><span class="active"></span>').appendTo(this);
		if ($(this).hasClass('cur')) {
			$(this).children('.active').stop(true, true).fadeIn(animationSpeed);
		};
	}).hover(function(){
		$(this).children('span.hover').stop(true, true).fadeIn(animationSpeed);
	}, function(){
		$(this).children('span.hover').stop(true, true).fadeOut(animationSpeed);
	});
	$('.fader-container .arrow').hover(function(){
		$(this).children('span.hover').stop(true, true).fadeIn(animationSpeed);
	}, function(){
		$(this).children('span.hover').stop(true, true).fadeOut(animationSpeed);
	});
	$('.fader-container .thumbNav a').click(function(){
		$(this).parent('li').siblings().children('a').children('.active').stop(true, true).fadeOut(animationSpeed);
		$(this).children('.active').stop(true, true).fadeIn(animationSpeed);
	});
	
	$('.anythingSlider .thumbNav a, .anythingSlider .arrow').hover(function (){
		$(this).children('a').stop(true, true).fadeIn();
	}, function () {
		$(this).children('a').stop(true, true).fadeOut();
	});
	$('.anythingSlider .thumbNav a, .anythingSlider .arrow a, .fader-container .arrow').click(function (){
		element = $(this);
		if (element.parent().hasClass('arrow') || element.hasClass('arrow')) {
			int = window.setInterval("setCurrentSliderItem(element)",700);
		} else {
			setCurrentSliderItem(element);
		}
		/*console.log($('.slider-container').data('AnythingSlider').currentPage);
		*/
	});
	
	$('.fader-container.home .thumbNav ul').each(function(){
		$(this).css({'width' : $(this).width(), 'float' : 'none'});
	});
	
	/**
	 * Efecto de fade para los diferentes elementos del sitio
	 */
	$('#socialmedia ul li a, .pagination a, .jcarousel-prev, .jcarousel-next').each(function(){
		$(this).append('<span class="hover"></span>');
	}).hover(function(){
		$(this).children('span.hover').stop(true, true).fadeIn(animationSpeed);
	}, function(){
		$(this).children('span.hover').stop(true, true).fadeOut(animationSpeed);
	});
	$('#navigation li:not(.active) a, #top-link, a.project-launch, input[type=submit], .fader-container.home .fader li > a, #description > a').hover(function(){
		$(this).stop(true, true).addClass('hover', animationSpeed);
	}, function(){
		$(this).stop(true, true).removeClass('hover', animationSpeed);
	});
	
	/**
	 * Efecto de superposición del link en la galeria de proyectos/clientes
	 * @ la primera línea la toma del atributo alt de la imágen
	 * @ la segunda línea la toma del atributo title del link original
	 */
	$('.content-gallery li a.overlay-item, .home-list li a.overlay-item, #carousel li a').each(function(i, item){
		element = $(item);
		parent = element.parent('li');
		elementHeight = element.height();
		elementWidth = element.width();
		string = '<span class="name">' + element.find('img').attr('alt') + '</span>'
		       + '<span class="action">' + element.attr('title') + '</span>';
		htmlOutput = '<span class="overlay content">' + string + '</span>'
		           + '<span class="overlay color"></span>';
		$(htmlOutput).prependTo(element);
		element.children('.overlay').css({ height: elementHeight, width: elementWidth });
	});
	$('.content-gallery li a.overlay-item, .home-list li a.overlay-item, #carousel li a').mouseenter(function(){
		element = $(this);
		element.children('.overlay.color').stop().fadeTo(300, 0.8);
		element.children('.overlay.content').stop().fadeTo(300, 1);
	}).mouseleave(function(){
		$(this).children('.overlay').stop().fadeOut(300);
	});
	
	/**
	 * Script para alinear correctamente el texto que se muestra como titulo y descripción de las secciones
	 */
	if ($('#content-top').size() > 0) {
		heightTitle = $('#content-top dt').height();
		heightDesc = $('#content-top dd').height();
		$('#content-top dd').css('padding-top', (heightTitle - heightDesc) / 2);
	}
	
	/**
	 * Mostrar y ocultar detalles de un proyecto
	 */
	$('#details-handle').click(function(){
		if ($(this).hasClass('expand')) {
			$(this).removeClass('expand').addClass('collapse').attr('title', 'Ocultar Detalles').text('Ocultar Detalles -');
			$('#details').slideDown('slow');
		} else {
			$(this).removeClass('collapse').addClass('expand').attr('title', 'Ver Detalles').text('Ver Detalles +');
			$('#details').slideUp('slow');
		}
	});
	/**
	 * Tooltip de la paginacion de proyectos
	 */
	if ($('.pagination').size() > 0) {
		$('.pagination .prev').tooltip({
			track: true,
			fade: 250,
			showURL: false,
			left: -150,
			top: 20,
			bodyHandler: function() { 
	        	return $("<img/>").attr("src", $(this).attr('rel')); 
	    	}
		});
		$('.pagination .next').tooltip({
			track: true,
			fade: 250,
			showURL: false,
			left: 0,
			top: 20,
			bodyHandler: function() { 
	        	return $("<img/>").attr("src", $(this).attr('rel')); 
	    	}
		})
	}
	/**
	 * Formulario
	 */
	$('#contact-form').submit(function(){
		formElement = $(this);
		// Setup
		if ($('#contact-result').size() < 1) {
			$('<p id="contact-result"></p>').insertBefore(formElement);
		}
		successMessage = 'Los datos fueron enviados correctamente. Muchas Gracias';
		validationErrorMessage = 'Error al validar el fomuarlio. Los siguientes campos tienen errores.';
		errorMessage = 'Error al enviar el formulario. Intente nuevamente.';
		validationFields = '';
		// Validacion
		if (jQuery.trim($('#name').val()) == '') {
			validationFields += 'Nombre. '
		}
		if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(jQuery.trim($('#mail').val()))) {
			validationFields += 'Email. ';
		}
		if (jQuery.trim($('#message').val()) == '') {
			validationFields += 'Consulta. ';
		}
		if (validationFields != '') {
			$('#contact-result').empty().removeClass('success').addClass('error').html(validationErrorMessage + '<br />' + validationFields).slideDown();
		} else {
			$.post(
				'contacto.html',
				{ 'name' : $('#name').val(), 'mail' : $('#mail').val(), 'message' : $('#message').val(), 'contact-form-send' : 'true' },
				function (json) {
					if (json[0] == true) {
						$('#contact-result').empty().removeClass('error').addClass('success').html(successMessage).slideDown();
					} else {
						if (json[1]) {
							message = validationErrorMessage + '<br />' + json[1];
						} else {
							message = errorMessage;
						}
						$('#contact-result').empty().removeClass('success').addClass('error').html(message).slideDown();
					}
					return false;
				},
				'json'
			);
		}
		return false;
	});
});

function setCurrentSliderItem (element) {
	if (element.closest('.anythingSlider').size() > 0) {
		elementContainer = element.closest('.anythingSlider');
		currentPage = elementContainer.find('.slider-container').data('AnythingSlider').currentPage;
		elementContainer.find('.thumbNav .active').stop(true, true).fadeOut(animationSpeed);
		elementContainer.find('.thumbNav li:eq(' + (currentPage - 1) + ') .active').stop(true, true).fadeIn(animationSpeed);
	} else if (element.closest('.fader-container').size() > 0) {
		elementContainer = element.closest('.fader-container');
		elementSize = elementContainer.find('.thumbNav li').size();
		elementIndex = elementContainer.find('.thumbNav .active:visible').closest('li').index();
		if (elementIndex <= 0 && element.hasClass('back')) {
			currentPage = elementSize;
		} else if (elementIndex + 1 >= elementSize && element.hasClass('forward')) {
			currentPage = -1;
		} else {
			currentPage = elementIndex;
		}
		elementContainer.find('.thumbNav .active').stop(true, true).fadeOut(animationSpeed);
		newCurrentPage = element.hasClass('back') ? currentPage - 1 : currentPage + 1;
		elementContainer.find('.thumbNav li:eq(' + newCurrentPage + ') .active').stop(true, true).fadeIn(animationSpeed);
	}
	int = window.clearInterval(int);
}

