$(document).ready(function(){


/* ========================= */
/* = DESTACADOS DE LA HOME   */
/* = movimiento y clickable  */
/* ========================= */

$('ul.emphasized.noscript').removeClass('noscript');
$('ul.emphasized li a.img').addClass('click');

$('ul.emphasized li').hover(function(){
	$(this).find('div').stop().animate({'marginLeft':'-24.8em'},800);
},function(){
	$(this).find('div').stop().animate({'marginLeft':'0em'},800);
}).click(function(){
    window.location = $(this).find("a:first").attr("href");
});


/* ====================== */
/* = MENÚ DE NAVEGACIÓN = */
/* ====================== */

$('#menu').hover(function(){
	$('#menu > li.active').removeClass('active').attr({'rel':'active'});
	},function(){
	$("#menu > li[rel='active']").addClass('active').removeAttr('rel');
});


/* ======================================== */
/* = VALIDACIÓN DE FORMULARIO DE BÚSQUEDA = */
/* ======================================== */

$('form#search').submit(function(e){
	var buscarVal =  $.trim($('#s').val()).length;
	var avisoError = '<strong class="error">Debes introducir al menos 3 caracteres</strong>';
	if( buscarVal < 3)
	{
		e.preventDefault();
		$('#recursive strong.error').remove();
		$(avisoError).prependTo('#recursive');				
	}
	else
	{
		return true;
	}
});


/* ========================= */
/* = MENÚ LATERAL FLOTANTE = */
/* ========================= */

jQuery.easing.def = 'easeInOutExpo';

/* ================================== */
/* = INDICE DE ARTISTAS DESPLEGABLE = */
/* = RESULTADOS DE BÚSQUEDA         = */
/* ================================== */

$('#indice li ul').hide();
$('#indice h2').addClass('closed');

$('#indice h2').hover(function(){
	if ($(this).parent().children('ul').length)
		{
			$(this).addClass('hover');
			}	
		},function(){
			$(this).removeClass('hover');
		} 
);

$('#indice h2').click(function(){
	if ($(this).parent().children('ul').length) {
		$(this).toggleClass('closed');
		$(this).parent().children('ul').slideToggle('slow');
	}
});


/* ============================ */
/* = VISIÓN ANVERSO Y REVERSO = */
/* ============================ */
$('a.reverso').hide();
var eltogle = '<span class="toggleAnverso">Ver reverso</span>';
$(eltogle).insertBefore('a.anverso').click(function(){
	$('a.reverso,a.anverso').slideToggle();
	$(this).toggleText('Ver reverso','Ver anverso')
		   .toggleClass('toggleReverso');	
});


/* ================================================= */
/* = ABRIMOS EN NUEVA VENTANA EL MAPA DE LAS OBRAS = */
/* ================================================= */

$('a.external').click(function(){
	this.target = "_blank";	
});

	
	
/* ================================ */
/* = NAVEGACIÓN INTERNA SUAVIZADA = */
/* ================================ */

$('#fastGo a').click(function(e){
		e.preventDefault();
		var slide = $(this).attr('href');
		partes  = slide.split('#');
		seccion = partes[partes.length-1]; /* Esto podría abreviarse, pero al trabajar con basehref, hay que hacerlo así  */				
		
		var targetOffset = $('#'+seccion).offset().top;
		$('html,body').delay(300)
					  .animate({scrollTop: targetOffset},
					  			1500);
		$('#'+seccion).find('h2').removeClass('closed');
		$('#'+seccion).find('ul').slideDown('slow');
});


/* ======================== */
/* = FUNCIONES UTILIZADAS = */
/* ======================== */

$.fn.fadeToggle = function(speed, easing, callback) {
	return this.animate({opacity: 'toggle'}, speed, easing, callback);
};
$.fn.toggleText = function(a, b) {
	return this.each(function() {
		jQuery(this).text(jQuery(this).text() == a ? b : a);
	});
};

$.fn.recortar = function(limite){
	return this.each(function() {
	var texto = $(this).text();
	var largo = $.trim(texto).length;	
	var later = $.trim(texto).substr(0,limite);
	if (largo > limite) {
		$(this).text(later + '...');
	}
	else {
		return true;
	}
	});
}



/* =================== */
/* = VOTACIÓN DE OBRAS = */
/* =================== */

$('#formVal').addClass('js');

/* le ponemos el puntito oscuro a la que vamos a votar y sus anteriores */

$('#formVal ul li').hover(function(){
	$(this).prevAll('li').addClass('hover');
	},function(){
	$(this).prevAll('#formVal ul li').removeClass('hover');
});

/* le pasamos la votación al pinchar en un puntito y nos devuelve lo que tiene */
		
$('#formVal').submit(function(e){
	e.preventDefault();
});		

$('#formVal input[type=radio]').click(function(){
	var voto = new Array();
		voto.votacion = $(this).val(),
		voto.tipo = $('#formVal #tipo_contenido').val(),
		voto.id = $('#formVal #id_contenido').val();

	$.ajax({
	  url: 'services/relations/votar/'+voto.tipo+'/'+voto.id+'/'+voto.votacion,
	  success: function(data) {
			   $('#formVal').parent('li')
			   				.fadeOut()
							.remove();
			   $('li.valoracion').addClass('val'+data)
			   					 .children('span.thisVal')
								 .text(data+'/5');
	  }
	});

});		

/* ======================================================= */
/* = previsualización de imágenes en el listado de obras = */
/* ======================================================= */

if ($('ul.preview').length) {
	$('#container').addClass('obrasPreview');
	$('ul.preview li > a img').each(function(){
		$mini = $(this);
		var attrSrc = $(this).attr('src'), attrSrc = attrSrc.replace('assets/img/thumb/', '');
        if (attrSrc.search(/no_disponible/i)==-1){
            $('<img />').attr('src', 'assets/img/med/' + attrSrc).load(function(){
                var alto = ($(this).height() / 2) - 60;
                var ancho = ($(this).width() / 2) - 88;
                if (ancho > 0 && alto > 0) {
                    $(this).css({
                        'marginTop': '-' + alto + 'px',
                        'marginLeft': '-' + ancho + 'px'
                    });
                }
            }).addClass('preview').insertBefore($mini);
        }
	});
}
$('#bioListado').addClass('preview');


/* ====================== */
/* = INSERCIÓN DE VÍDEO = */
/* ====================== */

if($(".oembed").length)
{
$(".oembed").oembed(null, 
                {
                embedMethod: "append", 
                maxWidth: 330,
                vimeo: { autoplay: false, maxWidth: 330, color: 'CD0920', title:false, byline:false, portrait:false}                 
                })
			.hide();
}


/* ========================== */
/* = BIOGRAFÍAS COLAPSABLES = */
/* ========================== */


if($('#bio').length){
	$("#bio p").filter(function() {
        			   return $.trim($(this).html()) === "";
        	 }).remove();

	var $p1 = $('#bio p').eq(0);
	var largo = $('#bio').text().length;
	var txt_previo = $('#bio').html();
	
	var view_more = '<span class="view_more">Leer biografía completa</span>';

	if (largo > 100) {
	var un_p = $('#bio p').eq(0).text().slice(0,100);
	var dos_p = $('#bio p').eq(0).text().slice(100,largo);
	
	$('#bio p').remove();
	$('#bio').append('<p>'+un_p+'...'+ view_more+'</p>')
	$('span.view_more').live('click',function(){
		$('#bio').empty().html(txt_previo);
		$(this).remove();
		$('#bioListado,#bio, #listado').addClass('ancho');
	});	
	}
}



/* ====================================================================== */
/* = LIMITAR LONGITUD DE TÍTULOS Y LINKS EN MENÚS IZQUIERDOS Y DERECHOS = */
/* ====================================================================== */

$('#content p.h2, #content h2.h2, #content h3.h2').recortar(40);
$('#bread li a').recortar(15);
$('#bread li span').recortar(28);
$('#sideB li a').recortar(13);
$('ul#indice li h3, #obrasList li h2').recortar(20);
$('#bread li span').recortar(22);
$('#actual_menu li a, #actual_menu li span').recortar(22);

// =======================================================
// = AÑADIR EL UNDERSCORE EN EL MENÚ DE LA HOME PARA IE7 =
// =======================================================
if ($.browser.msie) {
	if (parseInt($.browser.version) < 8) {
    	$('#menu div strong').prepend("_");
    	$('#menu li ul li a').prepend("_");
    	$('ul.tags li a').prepend("_");		
    	$('.rc_menu2 li a').prepend("_");
	}
 }

/* ==================== */
/* = SWFOBJECT Flash  = */
/* ==================== */

if ($('#container').hasClass('microsite'))
{
	var folder = $('#content').attr('title');
	var params = {
			quality: "high",
			scale: "noscale",
			wmode: "window",
			allowfullscreen: "true",	
			allowscriptaccess: "always",
			bgcolor: "#FFFFFF"
		};
	var attributes = {};
	var flashvars = {
			siteXML: "assets/flash/"+folder+"/xml/site.xml",
			url: "assets/flash/"+folder+"/"
		};	
	swfobject.embedSWF("assets/flash/"+folder+"/main.swf", "content", "100%", "100%", "9.0.0","assets/flash/expressInstall.swf", flashvars, params, attributes);
}

/* ********** FIN DE DOCUMENT READY *************** */

});



/* ==================== */
/* = SWFOBJECT Flash  = */
/* ==================== */

if ($('#flashContent'))
{
	var flashvars = {};
	var params = {wmode:"transparent"};
	var attributes = {};
	
	swfobject.embedSWF("assets/flash/home.swf", "flashContent", "100%", "533", "9.0.0","assets/flash/expressInstall.swf", flashvars, params, attributes);
}


/* EVENTOS EN WINDOW LOAD */
$(window).load(function(){

/* ==================== */
/* = SIDEBAR FLOTANTE = */
/* ==================== */

if(($(window).height() > $('#sideB').outerHeight()) && $('#sideB').length)
{
	var dearriba = parseInt($('#sideB').offset().top);

	$(window).scroll(function() {
		var altodoc = parseInt($(document).height()),		
			altoheader = parseInt($('#header').outerHeight()),
			altosideb = parseInt($('#sideB').outerHeight()),
			offsetfooter = parseInt($('#footer').offset().top),
			scroll = $(document).scrollTop(),
		 	maxtop = offsetfooter - altosideb - dearriba - 20;
			
			if (scroll > (dearriba - 20)) {
				if (maxtop > (scroll - altoheader)) {
					$('#sideB').stop().animate({
						'top': scroll - altoheader
					},{
						duration: 1000,
						queue: false
					});
				}
				else {
					$('#sideB').stop().animate({
						'top': maxtop
					},{
					duration: 1000,
					queue: false
				});
				}
			}
			else {
					$('#sideB').stop().animate({
						'top': 0
					},{
					duration: 1000,
					queue: false
				});				
			}
	}); 
}

});



