// Redbility Web Site v05
// Kike Valdenebro - 18.02.2010
// Redbility
//
// Libreria basica de funciones para la dinamica de interfaz.
// Requiere:
// - jquery-1.4.min.js
// - jquery.flash.js
// - jquery.filestyle.js
// - jquery.cookie.js

var generalWidth = 0;            // Ancho de la capa #general
var generalHeight = 0;           // Alto de la capa #general
var generalMinWidth = 1003;      // Ancho minimo de la capa #general
var generalMinHeight = 588;      // Alto minimo de la capa #general
var contentMinHeight = 320;      // Alto minimo de la capa #content
var frameAnimateTime = 1000;     // Duracion de la animacion del cambio de pagina
var totalFrames = 0;             // Total de paginas en el proyecto
var loadedFrames = 0;            // Paginas ya cargadas
var slideShowInterval = 0;       // ID interval para slideshow automatico
var slideTime = 8000;			 // Periodo para el slideshow automatico


// Funciones globales
// -----------------------------------------------------------------------------------------------

jQuery.fn.sFadeOut = function() {
	// Metodo fadeOut simultaneo
	return this.animate({opacity: 0.0}, {queue: false});
};

jQuery.fn.sFadeIn = function() {
	// Metodo fadeIn simultaneo
	return this.animate({opacity: 1.0}, {queue: false});
};

function resize() {
	
	// Reajuste de dimensiones

	// Recalcula las dimensiones de las capas #general y #content
	if ($(window).width()>generalMinWidth) {
		$('#general').width($(window).width());
	} else {
		$('#general').width(generalMinWidth);
	}
	if ($(window).height()>generalMinHeight) {
		$('#general').height($(window).height());
	} else {
		$('#general').height(generalMinHeight);
	}
	if ($('#content').height()<contentMinHeight) {
		$('#content').height(contentMinHeight);
	}
	

	// Dimensiones de la capa #general
	generalWidth = $('#general').width();
	generalHeight = $('#general').height();
	
	// Si estamos en un proyecto reescalar los elementos estructurales de la pagina
	if($('body').hasClass('page-template-page-proyecto-php')) {
		var frameWidth = generalWidth;
		if (generalWidth<=1680) {  // Para pantallas inferiores a 1680px se utiliza el parametro "adaptPages"
			if (frameAdapt) {
				frameWidth = generalWidth;
			} else {
				frameWidth = 1680;
			}
		} else {  // Para pantallas superiores a 1680px la pagina siempre se adapta a la pantalla
			frameWidth = generalWidth;
		}
		$('.frame').width(frameWidth);
		$('.frame').height(generalHeight);
		
		$('#content').css('width', generalWidth).css('height', generalHeight).css('overflow','hidden');
		$('#viewer').css('width', parseInt(1.1*framesPerRow*frameWidth)).css('height', 'auto');
		
		// Ir a la pagina actual
		$('#viewer').stop();
		if ($('#framenav').data('currentFrame')==undefined) {
			$('#framenav').data('currentFrame',0)
		};
		moveToFrame($('#framenav').data('currentFrame'));
	}
	
	// Tamano de los elementos autoescalables al 100% (class=".resize", etc)
	$('.resize').each(function(i) {
		var elementWidth = $(this).width();
		var elementHeight = $(this).height();
		if ((elementWidth/elementHeight) >= (generalWidth/generalHeight)) {  // Si el elemento es mas panoramico que el visor
			$(this).css('height', generalHeight);
			$(this).css('width', 'auto');
		} else {
			$(this).css('width', generalWidth);
			$(this).css('height', 'auto');
		}
	});

	// Capa de texto reescalable
	var sizeTexdeco1Px = (162*(generalWidth/1024)).toString()+'px';
	var sizeTexdeco2Px = (84*(generalWidth/1024)).toString()+'px';
	$('.textdeco1').css('width', generalWidth-108).css('font-size', sizeTexdeco1Px);
	$('.textdeco2').css('width', generalWidth-108).css('font-size', sizeTexdeco2Px);;
	if(generalWidth>1680) {
		$('.layer-text').css('font-size', '1.2em');
	} else {
		$('.layer-text').css('font-size', '1em');
	}

	// Posicion de las imagenes de contenido
	$('.top').css('top', 0);
	$('.bottom').css('bottom', 0);
	$('.left').css('left', 0);
	$('.right').css('right', 0);
	$('.center').each(function(i) {
		$(this).css('left', parseInt((generalWidth-$(this).width())/2));
	});
	$('.middle').each(function(i) {
		$(this).css('top', parseInt((generalHeight-$(this).height())/2));
	});

}

function createStructure() {
	// Creacion dinamica de la estructura del proyecto a partir de la navegacion interna
	totalFrames = 0;
	$('.frame').remove();
	$('ul#framenav-frames > li.page_item').each(function (i) {
		target = $(this).children('a').attr('href');
		appendHtml = '<div class="frame" href="'+target+'"></div>';
		$('#viewer').append(appendHtml);
		totalFrames += 1;
	});
}

function loadContent() {
	// Carga del contenido por Ajax
	loadedFrames = 0;
	var fileName = "";
	$('.frame').each(function(i) {												  
		fileName = $(this).attr('href');
		$(this).load(fileName+' .frame-inner', {async:true, type:"GET"}, function(responseText, textStatus, XMLHttpRequest) {
			loadedFrames += 1;
			if(loadedFrames == totalFrames) {
				// Inicializa la pagina
				init();
				ready = true;
			}
		});
	});
}

function moveToFrame(index) {
	// Mueve el visor hasta el frame de indice i (siendo "0" el primer frame)
	var frame = $('.frame:eq('+index+')');
	var framePosition = frame.position();
	if (index == 0) {
		$('#control-prev').fadeOut();
	} else {
		$('#control-prev').fadeIn();
	}
	if (index == $('.frame').length-1) {
		$('#control-next').fadeOut();
	} else {
		$('#control-next').fadeIn();
	}
	$('#viewer').animate ({
		left: -framePosition.left,
		top: -framePosition.top
	}, frameAnimateTime, function(){
		$('#framenav-frames li.page_item').removeClass('current_page_item');
		$('#framenav-frames li.page_item').eq(index).addClass('current_page_item');
		$('#framenav').data('currentFrame',index);
	});	
}

function nextFrame() {
	// Avanza un frame
	var index = $('#framenav').data('currentFrame')+1;
	if (index >= $('.frame').length) {
		index = 0;
	}
	moveToFrame(index);
}

function prevFrame() {
	// Retrocede un frame
	var index = $('#framenav').data('currentFrame')-1;
	if (index  < 0) {
		index = $('.frame').length-1;
	}
	moveToFrame(index);
}

function init() {
	
	// Inicializa los elementos DESPUES de la carga
	
	// Ajuste de jerarquia en titulares
	var p = $('h1:not(:first)');
	p.each(function(i) {
		var a = '<h2>'+$(this).text()+'</h2>';
		$(this).replaceWith(a);
	});
	
	// Ajuste de constantes
	if($('body').hasClass('page-template-page-proyecto-php') && frameAnimate==false) {
		frameAnimateTime = 0;
	}

	// Reajuste de dimensiones
	resize();
	
	// Carga los Flash
	var flash_src;
	var flash_align;
	var flash_scale;
	var flash_wmode;
	$('.layer-flash').each(function(i) {
		flash_src = $(this).children('object').children('param[name="src"]').attr('value');
		flash_align = $(this).children('object').children('param[name="align"]').attr('value');
		flash_scale = $(this).children('object').children('param[name="scale"]').attr('value');
		flash_wmode = $(this).children('object').children('param[name="wmode"]').attr('value');
		$(this).flash(
			{ 
			  src: flash_src,
			  menu: 'false',
			  width: '100%',
			  height: '100%',
			  scale: flash_scale,
			  wmode: flash_wmode,
			  align: flash_align,
			  salign: flash_align
			},
			{ update: false }
		);
		$(this).children('.alt').remove();
		
	});
	
	// Mejora visual de los elementos de cabecera
	$('#header ul li ul').css('background', 'none').hide();
	$('#header').data('headerEnter', true);
	$('#header > div > ul > li, #header #lang_sel_list ul li').mouseenter(
		function (e) {
			var timer = 0;
			if ($('#header').data('headerEnter')) {timer = 500};
			$('#header').data('headerEnter', false);
			$('#header > div > ul > li > ul').removeClass('visible').stop(true,true).fadeOut('fast');
			var menu = $(this).children('ul:first').addClass('visible');
			var menuHeight = menu.outerHeight();
			if (!menuHeight) {menuHeight=-18};
			$('#header').stop(true,true).delay(timer).animate({
				height: (menuHeight+50)
			}, 400, 'swing');
			menu.stop(true,true).delay(timer).fadeIn();
		}
	);
	$('#header').mouseleave(
		function (e) {
			$('#header').data('headerEnter', true);
			$('#header > div > ul > li > ul').stop(true,true);
			$('#header > div > ul > li > ul.visible').fadeOut('fast');
			$('#header > div > ul > li > ul').removeClass('visible');
			$('#header').stop(true,true).delay(500).animate({
				height: 32
			}, 400, 'swing');
		}
	);
	$(document).click(
		function(e) {
			e.stopPropagation();
			$('#header').data('headerEnter', true);
			$('#header > div > ul > li > ul').stop(true,true);
			$('#header > div > ul > li > ul.visible').fadeOut('fast');
			$('#header > div > ul > li > ul').removeClass('visible');
			$('#header').stop(true,true).delay(500).animate({
				height: 32
			}, 400, 'swing');
		}
	);
	$('ul#secnav-social li').mouseenter(
		function (e) {
			$(this).siblings().children('span').css('opacity',0.5);	
		}
	);
	$('ul#secnav-social li').mouseleave(
		function (e) {
			$(this).siblings().children('span').css('opacity',1);	
		}
	);
	
	// Navegacion interna de proyecto
	$('ul#framenav-frames > li.page_item').removeClass('current_page_item');
	$('ul#framenav-frames > li.page_item').first().addClass('current_page_item');
	$('ul#framenav-frames li.page_item a').live("click", function (e) {
		e.preventDefault();
		clearInterval(slideShowInterval);
		var index = $('#framenav-frames li.page_item').index($(this).parent());
		moveToFrame (index);
	});
	
	if ($('.frame').length > 1) {
		$('#framenav').append('<ul id="framenav-controls"></ul>');
		$('#framenav-controls').prepend('<li id="control-prev"></li>');
		$('#framenav-controls').prepend('<li id="control-next"></li>');
		$('#control-prev').hide().live("click", function (e) {
			clearInterval(slideShowInterval);
			prevFrame();
		});
		$('#control-next').hide().live("click", function (e) {
			clearInterval(slideShowInterval);
			nextFrame();
		});
		$('#control-next').fadeIn();
	} else {
		$('ul#framenav-frames > li.page_item').first().hide();
	}
	
	// Captura de pulsaciones de teclado
	$(document).bind('keydown', function(e){
    	if ((e.keyCode == 33) || ((e.keyCode == 32) && (e.shiftKey == true)))  {  // PgUp o Sft+Spc
			clearInterval(slideShowInterval);
			prevFrame();
		} else if ((e.keyCode == 34) || ((e.keyCode == 32) && (e.shiftKey == false))) {  //PgDown o Spc
			clearInterval(slideShowInterval);
			nextFrame();
		}
	});
	
	// Restyling de los elementos input[type=file]
	$(".long2 input[type=file]").filestyle({ 
		image: "/wp-content/themes/redbility/_style/_gfx/btn-input-file.gif",
		imageheight : 22,
		imagewidth : 75,
		width : 72
	});
	$(".long4 input[type=file]").filestyle({ 
		image: "/wp-content/themes/redbility/_style/_gfx/btn-input-file.gif",
		imageheight : 22,
		imagewidth : 75,
		width : 193
	});

	// Mosaico de proyectos: rollover
	$('.project').mouseenter(function (e) {
		e.preventDefault();
		$(this).children('.project-info').slideDown();
	});
	$('.project').mouseleave(function (e) {
		$(this).children('.project-info').slideUp();
	});
	
	// Mosaico de proyectos: filtros
	var cookie_options = { path: '/', expires: 10 };
	$('ul#framenav-frames li.filter_all').addClass('filter_active');
	$('ul#framenav-frames li.filter_all span').live("click", function (e) {
		$.cookie('project_filter', null, cookie_options);
		e.preventDefault();
		$(this).parent().siblings().removeClass('filter_active');
		$(this).parent().addClass('filter_active');
		var proyectos =	$('.project');
		$('.footer').stop(true, true).fadeOut(200).delay(200*(proyectos.length)).fadeIn();;
		$('.project').stop(true, true).fadeOut(200);
		proyectos.each(function() {
			$(this).delay(200*proyectos.index(this)).fadeIn(1000);
		});
	});
	$('ul#framenav-frames li.filter_item span').live("click", function (e) {
		e.preventDefault();
		var tag_class = $(this).parent().attr("class").split(' ')[1];
		$.cookie('project_filter', tag_class, cookie_options);
		$(this).parent().siblings().removeClass('filter_active');
		$(this).parent().addClass('filter_active');
		var proyectos = $('.project.'+tag_class);
		$('.footer').stop(true, true).fadeOut(200).delay(200*(proyectos.length)).fadeIn();
		$('.project').stop(true, true).fadeOut(200);
		proyectos.each(function() {
			$(this).delay(200*proyectos.index(this)).fadeIn(1000);
		});
	});
	if ($('body').hasClass('proyectos')!==true) {
		$.cookie('project_filter', null, cookie_options);
	} else {
		var project_filter = $.cookie('project_filter');
		if(project_filter) {
			// $('ul#framenav-frames li.filter_item.'+project_filter+' span').trigger('click');
			$('ul#framenav-frames li').removeClass('filter_active');
			$('ul#framenav-frames li.'+project_filter).addClass('filter_active');
			$('.project').hide();
			$('.project.'+project_filter).show();
		}
	}
	
	// Si se ha definido slideshow automatico comienza el hilo de ejecucion periodica
	if($('body').hasClass('page-template-page-proyecto-php') && (slideshow==true)) {
		if(slideShowInterval == 0) {
			clearInterval(slideShowInterval);
			slideShowInterval = setInterval("nextFrame()", slideTime);
		}
	}

}

// DOM Ready -------------------------------------------------------------------------------------

$(document).ready(function(){
	
	// Ajusta las dimensiones
	resize();
	
	// Si la pagina es un proyecto, montar por Ajax todas las paginas
	if($('body').hasClass('page-template-page-proyecto-php')) {
		// Creacion de la estructura del HTML
		createStructure();
		// Carga dinamica del contenido por Ajax
		loadContent();
	} else {
		init();
		ready = true;
	}

	$(window).resize(function() {
		// Ajusta las dimensiones e inicializa
		resize();
	});
	
	$('img:last').load(function(){
		// Ajusta las dimensiones una vez que se carga la ultima imagen.
		resize();
	});

}); 
