$(document).ready(function () {
	// Precargar el fondo
	var fondo =new Image; 
	fondo.src= asset_url + 'fondo_principal.jpg';
	
	// Asignar acciones al menú permanente (el de abajo)
	$('#menu_permanente li').each(function(i) {
		var id = $(this).attr('id');
		$('a', this).click(function() { 
			resetMenu('menu_permanente');
			$(this).addClass('selected');
			switch(id)
			{
				case 'boton-galeria':
					if (!Galeria.visible) {
						Videos.ocultar();
						Galeria.mostrar();
					} else {
						Galeria.ocultar();
					}
					break;
					
				case 'boton-videos':
					if (Videos.visible) {
						Videos.ocultar();
					} else {
						Videos.mostrar();
					}
					break;
				
				case 'boton-blog':
					Videos.ocultar();
					Blog.mostrar();
					break;
					
				default: // boton-menu
					if (TopMenu.visible) {
						TopMenu.ocultar();
					} else {
						Blog.ocultar();
						Videos.ocultar();
						TopMenu.mostrar();
					}
			}
			return false;
			
		}); // fin onclick
	});
	
	
	// Asignar funciones al menú (el de arriba)
	$('#menu li').each(function(i) {
		var id = $(this).attr('id');
		$('a',this).click(function() {
			if ($(this).hasClass('selected')) {
				Flotante.ocultar(function(){ resetMenu('menu'); });	
			} else {
				var page = id.replace('boton-','');
				var url = $(this).attr('href');
				loadPage(page, url);
				resetMenu('menu');
				$('#' + id).animate({top: '143px'},300, 'linear');
				$(this).addClass('selected');
			}
			return false;
		});
	});
	
	
	$(window).resize(fondoResize);
	
	tiraInicializada = false; 
	tiraInit();
	tiraFadeTimer = setInterval(tiraFadeInterval,4000);
//	$('#bgholder td').cycle();
	// tiraInit();
	// tiraFadeTimer = setInterval(tiraFadeInterval,4000);
		
}); // fin onready



//
// Flotante
//
var Flotante = {
	mostrar: function(html)
	{
		$('#flotante').removeClass('hidden').animate({opacity:1}, 300);
		if (html)
			$('#flotante').html(html);
	},
	
	ocultar: function(onfinish)
	{
		$('#flotante').animate({opacity:0}, 100, 'linear', function(){ 
			$('#flotante').addClass('hidden'); 
			if (onfinish)
				onfinish();
		});
	}
};


//
// topmenu
//
var TopMenu = {
	id: 'menu',
	visible: false,
	
	mostrar: function()
	{
		if (!this.visible)
		{
			Galeria.ocultar();
			Flotante.ocultar();
			$('#' + this.id).animate({marginTop:0});
			$('#boton-menu a').addClass('selected');
			this.visible = true;
		}
	},
	
	ocultar: function()
	{
		if (this.visible) {
			$('#boton-menu a').removeClass('selected');
			// Ocultar la ventana de datos
			menuid = this.id;
			Flotante.ocultar(function() { resetMenu(menuid); });
			// Ocultar el menú			
			$('#'+this.id).animate({marginTop:'-150px'});
			this.visible = false;
		}
	}
};


//
// Galería
//
var Galeria = {

	visible: false,
	
	mostrar: function()
	{
		if (!this.visible)
		{
			TopMenu.ocultar();
			$('#menu_permanente').animate({marginTop:10+'px'});
			tiraId = 'tira';
			$('#' + tiraId + '').removeClass('hidden').animate({top:45+'px'}, 200, 'linear', function() {
				tiraInicializada = false; 
				tiraInit();
			});
			this.visible = true;
			if (tiraFadeTimer)
				clearInterval(tiraFadeTimer);
			tiraFadeTimer = setInterval(tiraFadeInterval,4000);
		}
	},
	
	ocultar: function()
	{
		if (this.visible) {
			clearInterval(tiraFadeTimer);
			$('#menu_permanente').animate({marginTop:'64px'});
			$('#' + tiraId + '').animate({top:'150px'});
			resetMenu('menu_permanente');
			this.visible = false;
		}
	}
};



//
// Vídeos
//
var Videos = {

	visible: false,
	
	mostrar: function()
	{
		if (!this.visible)
		{
			TopMenu.ocultar();
			Flotante.ocultar();
			Galeria.ocultar();
			Flotante.mostrar('<img src="' + asset_url + 'indicator.gif" />');
			// $('#boton-videos').animate({marginTop: '-500px'}, 300, 'linear').addClass('selected');
			$('#boton-videos').addClass('selected');
			$('#tiraVideos').remove();
			loadPage('videos', '/paginas/videos', function(){
								$('#flotante').removeClass('hidden').animate({opacity:1}); 
								pos = $('#flotante').offset();
								wh = $(window).height();
								ir = (wh - pos.top)+20;
								$('#boton-videos').animate({marginTop: '-'+ir+'px'},300, 'linear');
								
								$('#footer').append($('#tiraVideos'));
								tiraId = 'tiraVideos';
	
								$('#menu_permanente').animate({marginTop:10+'px'});
								$('#' + tiraId + '').removeClass('hidden').animate({top:45+'px'}, 200, 'linear', function() { 
									tiraInicializada = false;
									tiraInit(true); 
								});
								
								TopMenu.ocultar();
			});
			this.visible = true;
		}
	},
	
	ocultar: function()
	{
		if (this.visible)
		{
			$('#boton-videos').removeClass('selected');
			$('#tiraVideos').remove();
			// Ocultar la ventana de datos
			Flotante.ocultar();
			$('#menu_permanente').animate({marginTop:'64px'});
			$('#' + tiraId + '').animate({top:'150px'});
			resetMenu('menu_permanente');
			this.visible = false;
		}
	}
};



//
// Blog
//
var Blog = {

	visible: false,
	
	mostrar: function()
	{
		if (!this.visible)
		{
			TopMenu.ocultar();
			Galeria.ocultar();
			$('#boton-blog').animate({marginTop: '-500px'}, 300, 'linear').addClass('selected');
			loadPage('blog', '/blogs/blog', function(){ Flotante.mostrar(); });
			this.visible = true;
		}
	},
	
	ocultar: function()
	{
		if (this.visible)
		{
			Flotante.ocultar(function() {
				resetMenu('menu_permanente');
			});
			this.visible = false;
		}
	}
};



function creaVideo(url, id)
{
	if (id)
	{
		$('.bocadillo .contenido').addClass('hidden');
		$('#videodesc-' + id).removeClass('hidden');
	}
	
	var html = '<object width="560" height="340">\
					<param id="movieparam" name="movie" value="' + url + '"></param>\
					<param name="allowFullScreen" value="true"></param>\
					<param name="allowscriptaccess" value="always"></param>\
					<embed src="' + url + '" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="560" height="340"></embed>\
				</object>';
	return html;
}


function imageResize(image, quitarheight) 
{
	var ww = $(window).width();
	var wh = $(window).height();
	var iw = image.width();
	var ih = image.height();
	var ratio = Math.max(ww/iw,wh/ih);
	if (ww > wh) {
		image.css({width:iw*ratio,height:'auto'});
	} else {
		image.css({width:'auto',height:ih*ratio});
	}
};


function fondoResize()
{
	imageResize($('#bgimage'));
}


/******************************
 * TIRA DE FOTOS / VÍDEOS
 *
 *******************************/

var tiraId = 'tira';
var tiraAnchoVentana = 0;
var tiraElementos = 0
var tiraVisibles = 0;
var tiraCelda = 70;
var tiraMoviendose = false;
var tiraEasing = 'linear'; // 'jswing';
var tiraTime = 800;
var tiraInicializada = false;
var tiraFadeTimer = null;
var tiraFadeCurrent = 0;


function tiraFadeInterval()
{
	tiraFade(0);
}


function tiraFade(k)
{
	if (k > 0)
		var next = parseInt(k);
	else
		var next = (tiraFadeCurrent+1)%tiraElementos;
	if (next == 0) {
			next++;
	}
	var idcur = '#galim-' + tiraFadeCurrent;
	var idnext = '#galim-' + next;
	if (tiraFadeCurrent == 0)
		var idimgcur = '#bgimage';
	else
		var idimgcur = '#bgimage-' + tiraFadeCurrent;
	var idimgnext = '#bgimage-' + next;
	if (tiraFadeCurrent != next)
	{ 
		// Deseleccionar todos y seleccionar este
		$('#' + tiraId + ' li#' + idcur).removeClass('selected');
		$('#' + tiraId + ' li#' + idnext).addClass('selected');
		// Mover la flechita indicadora
		tiraColocaFlechita();
		imageResize($(idimgnext));
		$(idimgcur).animate({opacity:0}, 1200, null, function() {
			$(idimgcur).css('display', 'none');
		});
		$(idimgnext).css('display', '').animate({opacity:1},1200);
		/*
		$(idimgcur).fadeOut().removeClass('current');
		imageResize($(idimgnext).fadeIn().addClass('current'));
		*/
		tiraFadeCurrent = next;
    }
    
}


function tiraInit(videos)
{
	if (!tiraInicializada)
	{
		if (videos)
		{
			$('#' + tiraId + ' li').each (function(i) {
				var li = this;
				$('a',this).click(function() {
					$('#' + tiraId + ' ul').stop();
					// Deseleccionar todos y seleccionar este
					$('#' + tiraId + ' li').removeClass('selected');
					$(li).addClass('selected');
					// Mover la flechita indicadora
					tiraColocaFlechita();
					
					creaVideo ($(this).attr('href'));
					return false;
				});		
			});
		} else {
			////////////// PRECARGAR IMÁGENES
			if ($('#' + tiraId + ' li.cargando').get(0)) {
				$('#bgholder td img').each(function(j) { if ($(this).attr('id') != 'bgimage') $(this).remove(); });
			}

			$('#' + tiraId + ' li.cargando').each(function(i) {
				anchor = $('a', this);
				var image   = $(new Image());
				var li = this;
				idimage = $(this).attr('id');
				idimage = idimage.replace('galim-', 'bgimage-');
				image.attr('id', idimage);
				
				image.load(function() {
					$(li).removeClass('cargando');
					var big = $('a',li).attr('href');
					bgidimage = $(this).attr('id');
					$('#bgholder td').append('<img id="' + bgidimage + '" style="z-index:10; position:absolute; display:none" src="' + big + '" alt="" />');
					imageResize($('#'+bgidimage));
					
					$('a', li).click(function(){ 
						$('#' + tiraId + ' ul').stop();
						
						clearInterval(tiraFadeTimer);
						tmp = $(li).attr('id').split('-');
						tiraFade(tmp[1]);
						
						return false; 
					}).attr('title','');
					$(this).remove();
				}).attr('src',anchor.attr('href')); // fin load
				
			});
		}
		///////////////
		
		
		configuraTira(videos);
		$(window).resize(tiraResize);
		
		tiraInicializada = true;
	}
}


function tiraResize()
{
	configuraTira();
	imageResize($('#bgholder td img.current'));
}


// Asignar funciones a la tira de fotos
function configuraTira(videos)
{	
	if (!tiraInicializada)
	{
		var w = $( window ); 
		tiraAnchoVentana = w.width(); // window.innerWidth;
		tiraElementos = $('#' + tiraId + ' li').size();
		$('#' + tiraId + ' li').each(function(i) {
			var li = this;
			$('a', this).click(function() 
			{	
				return false;
			});
			if (!videos)
				$('a',this).attr('title','cargando...');
			
		}); // fin tira li
	
	
		$('#' + tiraId + '').mouseover(function() {
	    	$(this).mousemove(function(e){
	      // var pageCoords = "( " + e.pageX + ", " + e.pageY + " )";
	      // var clientCoords = "( " + e.clientX + ", " + e.clientY + " )";
	      		var trozo = Math.ceil(tiraAnchoVentana/4);
	      		if (e.pageX < trozo) {
	      			tiraRetrocedeMouseOver();
	      		} else if (e.pageX > (trozo*3)) {
	      			tiraAvanzaMouseOver();
	      		} else if (tiraMoviendose) {
	      			tiraMoviendose = false;
	      			$('#tira ul').stop();
	      			tiraColocaFlechita();
	      			
	      		}
		    });
	    });
	    $('#' + tiraId + '').mouseout (function() {
	    	$(this).unbind('mousemove');
	    	// tiraMoviendose = false;
	    	// $('#' + tiraId + ' ul').stop();
	    });
    }
}


function tiraColocaFlechita()
{
	seleccionado = $('#' + tiraId + ' li.selected');
	if (seleccionado)
	{
		var offset = seleccionado.offset();
		var left = offset.left + Math.floor(tiraCelda/2.9);
		$('#' + tiraId + ' .flechita').animate({left: left + 'px', top:'-10px'},150);	
	}
}


function tiraRetrocedeMouseOver()
{
	
	var ulpos = $('#' + tiraId + ' ul').offset();
	if (ulpos.left < 0) {
		var to = ulpos.left + (tiraCelda*3);
		if (to > 0)
			to = 0;
		if (!tiraMoviendose) {
			tiraMoviendose = true;
			$('#' + tiraId + ' ul').animate({marginLeft:to+'px'},tiraTime,tiraEasing, function(){
				tiraColocaFlechita();
				tiraMoviendose = false;
			});
		}
	}
}


function tiraAvanzaMouseOver()
{	
	// Calcular posición donde mover la tira
	var ulpos = $('#' + tiraId + ' ul').offset();
	var totalx = tiraElementos * tiraCelda;
	var quedax = totalx - (tiraAnchoVentana + Math.abs(ulpos.left));
	var quedanel = Math.ceil(quedax/tiraCelda);
	var mult = (quedanel > 3)? 3:quedanel;
	var to = ulpos.left - (tiraCelda * mult);
	if (!tiraMoviendose) {
		tiraMoviendose = true;
		// ¿hemos llegado al final?
		var lipos = $('#' + tiraId + ' li:last').position();
		if (!(lipos.top == 0 && (lipos.left+tiraCelda) < tiraAnchoVentana))
		{
			$('#' + tiraId + ' ul').animate({marginLeft:to+'px'},tiraTime, tiraEasing, function(){
				tiraColocaFlechita();
				tiraMoviendose = false;
			});
		}
		 
	}
}


/*******************
	FIN TIRA
 *******************/


function resetMenu(id)
{
	$('#' + id + ' a').removeClass('selected');
	if (id == 'menu') {
		$('#menu li').animate({top: '0'},100);
	} else {
		$('#menu_permanente li').animate({marginTop: '0'},100);
	}
}


function loadPage(id, url, onsuccess)
{
	showProgress(true);
	$.ajax({
			   type: "GET",
			   url: url + '?ajax', // '/paginas/' + id,
			   data: null,
			   dataType: 'html',
			   success: function(msg){
			   	$('#flotante').html(msg).removeClass('hidden').css('opacity',1);
			   	$('#flotante #ajax').addClass('page-'+id);
			   	$('body').attr('id','page-'+id);
			   		if (onsuccess)
			   			onsuccess();
			   		
			   		if (id == 'blog') {
			   			$('#blognav .c a, #articlelist .tags a').click (function() {
							loadPage('blog', $(this).attr('href'));
							return false;
						});
						
						$('.comment-form form').each(function(i) {

							url = $(this).attr('action');
							data = $(this).serialize();
							var id = $(this).attr('id');
							
							$(this).submit(function() {
								showProgress(true);
								d  = new Date();
								$.ajax({
										   type: "POST",
										   url: url + '?' + d.getMilliseconds(),
										   data: data,
										   dataType: 'html',
										   success: function(msg){
										   		handle = $('#' + id + ' input[name=handle]').val();
										   		$('#comment-form-' + handle).html(msg);
										   },
										   complete: function (XMLHttpRequest, textStatus) { showProgress(false); }
										 });
								return false;
							});
							
						});
						
			   		}
			   },
			   complete: function (XMLHttpRequest, textStatus) { showProgress(false); }
			 });
}


function loadContent(url, destino, onsuccess)
{
	showProgress(true);
	$.ajax({
			   type: "GET",
			   url: url + '?ajax', // '/paginas/' + id,
			   data: null,
			   dataType: 'html',
			   success: function(msg){
			   	$(destino).html(msg);
			   	if (onsuccess)
			   			onsuccess();
			   },
			   complete: function (XMLHttpRequest, textStatus) { showProgress(false); }
			 });
}


function follow_mouse (e)
{
	$('#minindicator').css({'left': e.pageX, 'top': e.pageY});
}

function showProgress(show)
{
	if (show == false){
		$(document).unbind('mousemove', follow_mouse); 
		$('#minindicator').addClass('hidden');
	} else {
		$('#minindicator').removeClass('hidden');
		$(document).mousemove(follow_mouse);
	}
}


function ampliar_reducir_post (id)
{
	$('#article-' + id + ' .resumido, #article-' + id + ' .ampliado, #botonera-' + id + ' .ampliado, #botonera-' + id + ' .resumido').toggleClass('hidden'); 
	return false;
}