// Redbility Web Site v05
// Kike Valdenebro - 2011.03.21
// 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


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


function isIPad(){
	if (navigator.userAgent.match(/iPad/i) != null) {
		return true;
	} else {
		return false;
	}
}

function isIPhone(){
	if (navigator.userAgent.match(/iPhone/i) != null) {
		return true;
	} else {
		return false;
	}
}

function isIPod(){
	if (navigator.userAgent.match(/iPod/i) != null) {
		return true;
	} else {
		return false;
	}
}

function isIOS(){
	if (isIPad() || isIPhone() || isIPod()) {
		return true;
	} else {
		return false;
	}
}

function isIE(){
	if (navigator.userAgent.match(/iMSIE/i) != null) {
		return true;
	} else {
		return false;
	}
}

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 windowResize() {
	
	// 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-diapositiva-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 = (78*(generalWidth/1024)).toString()+'px';
	var sizeTexdeco3Px = (19.2*(generalWidth/1024)).toString()+'px';
	$('.textdeco1').css('width', generalWidth-216).css('font-size', sizeTexdeco1Px);
	$('.textdeco2').css('width', generalWidth-216).css('font-size', sizeTexdeco2Px);
	$('.textdeco3').css('width', generalWidth-216).css('font-size', sizeTexdeco3Px);
	$('.wide').css('width', generalWidth-216);
	if(generalWidth>1680) {
		$('.layer-text').css('font-size', '1.2em');
	} else {
		$('.layer-text').css('font-size', '1em');
	}
	
	// Tamano del mosaico de paginas hijas
	$('.children-mosaic').css('width', parseInt(generalWidth-108));

	// 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));
	});

	// Capa de video embebido
	$('.layer-video').find('iframe').attr('width',generalWidth).attr('height',generalHeight);
	$('.layer-video').find('object').attr('width',generalWidth).attr('height',generalHeight);
	$('.layer-video').find('embed').attr('width',generalWidth).attr('height',generalHeight).attr('wmode','transparent');
	
	// Mosaico de imagenes
	var layerMosaicImageWidth = $('.layer-mosaic-image:first').width();
	var layerMosaicImageHeight = $('.layer-mosaic-image:first').height();	
	$('.layer-mosaic-image img').load(function(){ 
    	if (!this.complete) {
			return false;
			this.load();
		}
		else if (typeof this.naturalWidth != 'undefined' && this.naturalWidth == 0) {
			return false;
			this.load();
		}
		else {
			var elementWidth = $(this).width();
			var elementHeight = $(this).height();
			if ((elementWidth/elementHeight) > (layerMosaicImageWidth/layerMosaicImageHeight)) {  // Si el elemento es mas horizontal que el visor
				$(this).css('height', layerMosaicImageHeight);
				$(this).css('width', 'auto');
			} else {
				$(this).css('width', layerMosaicImageWidth);
				$(this).css('height', 'auto');
			}
			var elementWidth = $(this).width();
			var elementHeight = $(this).height();
			$(this).css('left',parseInt((layerMosaicImageWidth-elementWidth)/2));
			$(this).css('top',parseInt((layerMosaicImageHeight-elementHeight)/2));
		}
	})
	$('.layer-mosaic-image img').each(function(i){ 
		var elementWidth = $(this).width();
		var elementHeight = $(this).height();
		if ((elementWidth/elementHeight) > (layerMosaicImageWidth/layerMosaicImageHeight)) {  // Si el elemento es mas horizontal que el visor
			$(this).css('height', layerMosaicImageHeight);
			$(this).css('width', 'auto');
		} else {
			$(this).css('width', layerMosaicImageWidth);
			$(this).css('height', 'auto');
		}
		var elementWidth = $(this).width();
		var elementHeight = $(this).height();
		$(this).css('left',parseInt((layerMosaicImageWidth-elementWidth)/2));
		$(this).css('top',parseInt((layerMosaicImageHeight-elementHeight)/2));
	})
	
}

function createStructure() {
	// Creacion dinamica de la estructura de un conjunto de diapositivas 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();
			}
		});
	});
}

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) {
		if (isIE()) {
			$('#control-prev').hide();
		} else {
			$('#control-prev').fadeOut();
		}
	} else {
		if (isIE()) {
			$('#control-prev').show();
		} else {
			$('#control-prev').fadeIn();
		}
	}
	if (index == $('.frame').length-1) {
		if (isIE()) {
			$('#control-next').hide();
		} else {
			$('#control-next').fadeOut();
		}
	} else {
		if (isIE()) {
			$('#control-next').show();
		} 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 initNavigation() {
	// Mejora visual de los elementos de cabecera
	$('#header ul li ul').css('background', 'none').hide();
	$('#header').data('headerEnter', true);
	$('#header ul.menu > li, #header #lang_sel_list ul li').mouseenter(
		function(event) {
			event.preventDefault();
			var timer = 0;
			if ($('#header').data('headerEnter')) {timer = 200};
			$('#header').data('headerEnter', false);
			$('#header ul.sub-menu').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();
			return false;
		}
	);
	$('#header').mouseleave(
		function(event) {
			$('#header').data('headerEnter', true);
			$('#header ul.sub-menu').stop(true,true);
			$('#header ul.sub-menu.visible').fadeOut('fast');
			$('#header ul.sub-menu').removeClass('visible');
			$('#header').stop(true,true).delay(500).animate({
				height: 32
			}, 400, 'swing');
		}
	);
	$(document).click(
		function(event) {
			event.stopPropagation();
			$('#header').data('headerEnter', true);
			$('#header ul.sub-menu').stop(true,true);
			$('#header ul.sub-menu.visible').fadeOut('fast');
			$('#header ul.sub-menu').removeClass('visible');
			$('#header').stop(true,true).delay(500).animate({
				height: 32
			}, 400, 'swing');
		}
	);
	$('#secnav ul#social > li').mouseenter(
		function (e) {
			$(this).siblings().children('span').css('opacity',0.5);	
		}
	);
	$('#secnav ul#social > li').mouseleave(
		function (e) {
			$(this).siblings().children('span').css('opacity',1);	
		}
	);
}

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

	// Reajuste de dimensiones
	windowResize();
	
	// 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();
		
	});
	
	// Navegacion interna de diapositivas
	$('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();
		// Eventos táctiles
		$(document).bind('touchstart',function(e) {
			var touchStartX = e.originalEvent.touches[0].screenX;
			$(window)
				.data("touchStartX", touchStartX);
		}).bind("touchmove", function (e) {
			var touchStartX = $(window).data("touchStartX");
			var touchEndX = e.originalEvent.touches[0].screenX;
			$(window)
				.data("touchEndX", touchEndX);
		}).bind("touchend", function(e) {
			var touchStartX = $(window).data("touchStartX");
			var touchEndX = $(window).data("touchEndX");
			var delta = touchEndX - touchStartX;
			if(!isNaN(delta) && Math.abs(delta) > 50) {
				if(delta<0)
					$("#control-next").click();
				else
					$("#control-prev").click();
			}
			$(window)
				.removeData("touchStartX")
				.removeData("touchEndX");
        });
	} 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 : 83,
		width : 65
	});
	$(".long4 input[type=file]").filestyle({ 
		image: "/wp-content/themes/redbility/_style/_gfx/btn-input-file.gif",
		imageheight : 22,
		imagewidth : 83,
		width : 186
	});

	// Mosaico de proyectos: rollover
	$('.project').mouseenter(function (e) {
		e.preventDefault();
		$(this).children('.project-info').slideDown();
	});
	$('.project').mouseleave(function (e) {
		$(this).children('.project-info').stop(true,true).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');
		$('.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);
		$('.project').stop(true, true).fadeOut(200);
		proyectos.each(function() {
			$(this).delay(200*proyectos.index(this)).fadeIn(1000);
		});
	});
	if ($('body').hasClass('section-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();
		}
	}

	// Mosaico de paginas hijas
	$('.children-mosaic-item').mouseenter(function (e) {
		e.preventDefault();
		$(this).children('.children-mosaic-item-info').slideDown();
	});
	$('.children-mosaic-item').mouseleave(function (e) {
		$(this).children('.children-mosaic-item-info').stop(true,true).slideUp();
	});
	
	// Videos HTML5: JWPlayer
	$('video').each(function(index) {
		var attr_src      = $(this).attr('src');
		var attr_poster   = $(this).attr('poster');
		var attr_width    = $(this).attr('width');
		var attr_height   = $(this).attr('height');
		$(this).wrap('<div class="video-container" />');
		$(this).parent().flash({
			src               : template_url+'/_style/_js/jwplayer/player.swf',
			width             : attr_width,
			height            : attr_height,
			id                : 'video-player-'+index,
			name              : 'video-player-'+index,
			allowfullscreen   : 'true',
			allowscriptaccess : 'always',
			wmode             : 'opaque',
			flashvars         : {
				file       : attr_src,
				image      : attr_poster,
				skin       : template_url+'/_style/_js/jwplayer/glow.zip',				
				autostart  : 'false',
				repeat     : 'none',
				controlbar : 'over'
			}
		},
		{ version: '10' });
	});

	// Audio HTML5: JWPlayer
	$('audio').each(function(index) {
		var attr_src      = $(this).attr('src');
		var attr_width    = 674;
		var attr_height   = 24;
		$(this).wrap('<div class="audio-container" />');
		$(this).parent().flash({
			src               : template_url+'/_style/_js/jwplayer/player.swf',
			width             : attr_width,
			height            : attr_height,
			id                : 'audio-player-'+index,
			name              : 'audio-player-'+index,
			allowfullscreen   : 'true',
			allowscriptaccess : 'always',
			wmode             : 'opaque',
			flashvars         : {
				file       : attr_src,
				autostart  : 'false',
				repeat     : 'none',
				controlbar : 'bottom'
			}
		},
		{ version: '10' });
	});
	
	// Galeria "Fancybox"
	$('.gallery dl.gallery-item dt.gallery-icon a').attr('rel','fancybox').fancybox({
		'transitionIn'	 : 'elastic',
		'transitionOut'	 : 'elastic',
		'speedIn'		 : 600, 
		'speedOut'		 : 600, 
		'autoDimensions' : true,
		'overlayShow'	 : true,
		'overlayColor'   : '#000',
		'titlePosition'  : 'over',
		'centerOnScroll' : true,
		'padding'        : 10
	});
	
	// Si se ha definido slideshow automatico comienza el hilo de ejecucion periodica
	if($('body').hasClass('page-template-page-diapositiva-php') && (slideshow==true)) {
		if(slideShowInterval == 0) {
			clearInterval(slideShowInterval);
			slideShowInterval = setInterval("nextFrame()", slidetime);
		}
	}
	
	// Desocultacion de la navegacion y ocultacion del "cargando" cuando se ha cargado el contenido
	$('#loading').animate({
		opacity: 0.0
	},{
		duration: 400,
		complete: function() {
			$(this).hide();
		},
		queue: false
	});
	
	// Captura de enlaces clase "popup"
	$("a.a_popup").click(function(e) {
		e.preventDefault();
		// Obtener atributo HREF del link
		var url = this.href;
		var ancho = 620;
		var alto = 450; // valores por defecto
		// Si existe el atributo "rel" y esta en el formato "xxxx,xxx,xxx",
		// lo usamos para extraer las dimensiones del popup.
		if(this.rel && this.rel.indexOf(",") > -1){
			parametros = this.rel.split(",");
			ancho = parametros[0];
			alto = parametros[1];
		}
		// Abrir pop up usando atributo HREF y las dimensiones de arriba
		window.open(url, '', 'width='+ancho+',height='+alto+',toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no');
		// Hay que retornar FALSE para anular el comportamiento original del link
		return false;
	});

	
}

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

$(document).ready(function(){	
	if($('body').hasClass('page-template-page-conjunto-php')) {  // Pagina tipo conjunto de diapositivas
		$('body').addClass('page-template-page-diapositiva-php');
		$('#content').append('<div id="loading"><div class="loading-inner"></div></div>');
		// Mejora de los elementos de navegacion en cabecera
		initNavigation();
		// Creacion de la estructura del HTML
		createStructure();
		// Carga dinamica del contenido por Ajax
		loadContent();
	} else {  // Pagina tipo scroll
		// Mejora de los elementos de navegacion en cabecera
		initNavigation();
		// Inicializacion de la pagina
		init();
	}
}); 

$(window).load(function(){
	// Ajusta las dimensiones una vez que se carga todo el contenido, incluyendo las imagenes
	windowResize();	
});

$(window).resize(function() {
	// Ajusta las dimensiones e inicializa
	windowResize();
});

if (isIPhone()||isIPod()||isIPad()) {
	// Elementos "Fixed" en Safari Mobile (iPhone, iPad...)	
	$(window).scroll(function () {
		$('.fixed.top').css({
			'top' : $(window).scrollTop()
		});
		$('.fixed.bottom').css({
			'bottom' : '',
			'top' : $(window).scrollTop()+$(window).height()
		});
	});
}



