// JavaScript Document

// JQuery de portada

$(document).ready( function () {

timer = 8000;
speed = 1000;

// Video overlay
$("#right-column img[rel]").overlay();

// Diapositivas portada
// Setup first
$('div#diapos img.first, div#diapos div.texto.first').addClass('selected');

diapoBox = $('div#diapos');
diapoFondos = $('img.diapo', diapoBox);
diapoTextos = $('div.texto', diapoBox);

// DirectX filter fix for IE6
if ($.browser.msie == true) {
	$('h2, p, div.saber-mas', diapoTextos).css('background-color', 'white');
}

interval = setTimeout('transition("forward", timer)', timer);

programControls();

} );

function transition(dir, time) {
	clearTimeout(interval);
	current = detectar(diapoFondos);
	if (dir == 'forward') {
		destination = detectarSiguiente(diapoFondos, current);
	} else {
		destination = detectarAnterior(diapoFondos, current);
	}

	$('div#controls img', diapoBox).unbind('click');
	
	// Transición diapositivas
	$(diapoFondos[destination]).css({ opacity: 1, zIndex: 14}).addClass('selected');
	$(diapoFondos[current]).removeClass('selected').css({ opacity: 1}).animate({opacity: 0}, speed, function() {  
		$(this).css('z-index', 10);
		$(diapoFondos[destination]).css('z-index', 15);	
		interval = setTimeout('transition("forward", timer)', time);
		programControls();
	});
	// Transición textos
	$(diapoTextos[destination]).addClass('selected').css({zIndex: 200, opacity: 0}).animate({opacity: 0}, speed / 2).animate({opacity: 1}, speed / 2);
	$(diapoTextos[current]).removeClass('selected').css('z-index', 100).animate({opacity: 0}, speed / 2);
}

function detectarAnterior(target, ix) {
	if (ix == 0) {
		return ($(target).length - 1);
	} else {
		return (ix -1);
	}
}

function detectarSiguiente(target, ix) {
	ix++;
	if (ix >= $(target).length) {
		return 0;
	}
	return ix;
}

function detectar(target) {
	var current;
	$(target).each( function (ix) {
		if( $(this).hasClass('selected') == true ) {
			current = ix;
			return false;
		}	
	} );
	return current;
}

function programControls() {
	$('img#control-left', diapoBox).click( function () {
		transition('backwards', timer * 3);
	} );
	$('img#control-right', diapoBox).click( function () {
		transition('forward', timer * 3);
	} );
}
