var speed, intervalo, intervaloTwitter, tweetsY, finalY, num_items_slide, fechaAjuste, url, servidor, paginaVideos;

/* PARCHE PARA EL BANNER DE LA RFEG */
$(window).ready(function (){
  bannerCorregido = $('div[class|=banners] a[href|="http://www.bautismodegolf.es/"]');
  $(bannerCorregido).css({ width: $(bannerCorregido).parent().width()-8+"px", height: $(bannerCorregido).find("img").height()+"px", display: "inline-block", textAlign: "center" })
  $(bannerCorregido).find("img").css({float: "none", margin:"0"})
})


$(document).ready( function () {

	// VARIABLES
	servidor = "http://www.cronicagolf.com";
	url = String(location);
	speed = 600;
	finalY = 0;
	tweetsY = 0;
	jQuery.easing.def = "easeInOutQuint";
	
	// SLIDESHOW
	num_items_slide = $('#slideshow ul li').length;
	$('#slideshow ul').append('<li>'+$('#slideshow ul li:first').html()+'</li>')
	slideshow()
	//lanzaIntervaloSlideshow()

	// EXTERNAL LINKS
	$("a[target='_blank']").addClass("external");
	$("a[href*='mailto:']").removeClass("external");
	$(".listado_enlaces a").attr("target", "_blank");
	$(".banners-A a, .banners-B a, .banners-C a, .banners-D a, .banners-E a, .banners-F a, .banner-AA a, banner_mug_580x60 a").removeClass("external");

	// TWITTER
	$("#twitter-content").getTwitter({	userName: "cronicagolf", numTweets: 10, loaderText: "Cargando tweets...", slideIn:false, showHeading: true, headingText: "&Uacute;ltima hora: Crónica Golf en Twitter", showProfileLink: false, showTimestamp: false  });
	intervaloTwitter = setInterval(tweet, 5500)

	// FUNBOX
	$('.content-funbox:not(:first)').hide();
	$('#funbox h2').click(function (){   if( $(this).next().css("display") =="none" ) {   $('#funbox h2').css({ backgroundPosition: "right top" });   $('.content-funbox').slideUp(speed);   $(this).css({ backgroundPosition: "right bottom" });   $(this).next().slideDown(speed);   }   })
	$('#funbox h2:first').css({ backgroundPosition: "right bottom" })
	$('.content-funbox .verMas').click(cargaFunBox);
	
	// SEARCH
	$('#searchForm #s').focus(function (){  if ($(this).val()=="buscar en..."){ $(this).val(""); } 	})
	$('#buscador').hover( function(){ $('#buscador fieldset').css({ visibility:"visible"}) }, function(){ $('#buscador fieldset').css({ visibility:"hidden"}) })
	$("#searchForm").submit(lanzaBuscador);

	// NOTICIAS
	$(".btn-ver-noticias").click(muestraNoticias);
	$(".btn-ver-titulares").click(muestraTitulares);
	$("#lista-noticias li .titular").click(controlCortina);
	
	if (url.lastIndexOf("noticias/?d=") != -1){
		var pc = url.lastIndexOf("noticias/?d=")+12;
		fechaAjuste = url.substr(pc);
		fechaAjuste = fechaAjuste.substr(0,4)+"-"+fechaAjuste.substr(4,2)+"-"+fechaAjuste.substr(6);
	}else{
		fechaAjuste = new Date();
	}
	
	// CALENDARIO
	if (url.lastIndexOf("noticias") != -1){
		$('#datepicker').datepicker({	firstDay: 1,monthNames: ["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"], dayNamesMin: ['Dom', 'Lun', 'Mar', 'Mie', 'Jue', 'Vie', 'Sab'], dateFormat: 'yymmdd', nextText: '>>', prevText:'<<', defaultDate: new Date(fechaAjuste), onSelect: function(dateText) { location = "/noticias/?d="+dateText } });
	}
	
	// VIDEO PLAYER
	$('#verListadoVideos a').click(verListadoVideos)
	$('#listado-videos a').click(cargaVideo);
	$('#listado-videosAlt a').click(cargaVideoAlt);
	paginaVideos = 1;
	$('.prev-videos').click(listPrevVideos)
	$('.next-videos').click(listNextVideos)
	muestraVideos()

	// IMAGENES
	$('.articulo img').removeAttr("width").removeAttr("height")
	$('.articulo div[id *="attachment"]').removeAttr("style");
	
	// REGISTRO
	$('#form_registro .check_aceptar input[type=checkbox]').change(muestraSubmit);
	
	// LEGAL
	$("#registro #tituloCondiciones a").click( function(){ $("#textoLegal").slideToggle(500); return false; })
	$("#condiciones2 #tituloCondiciones2 a").click( function(){ $("#textoLegal2").slideToggle(500); return false; })

	// LIGHTBOX
	$('.gallery-icon a').fancybox({ titleShow:false });
	$('.modal').fancybox({ 'autoDimensions':false, 'autoScale':false, 'centerOnScroll':true, 'width':800});
	
	// INSTRUCCION
	$(".visorInstruccion .diapo").hide();
	$(".visorInstruccion .diapo:eq(0)").show();
	$(".visorInstruccion .nav a:eq(0)").addClass("navSelected");
	$(".visorInstruccion .nav a").click(function (){
																	indexDiapo = Number($(this).text())-1;
																	$(".visorInstruccion .diapo").hide();
																	$(".visorInstruccion .diapo:eq("+indexDiapo+")").show();
																	$(".visorInstruccion .nav a").removeClass("navSelected");
																	$(this).addClass("navSelected");
																	return false;
															})

	
})

function listNextVideos()
{
	paginaVideos++;
	muestraVideos()
	return false;
}
function listPrevVideos()
{
	paginaVideos--;
	muestraVideos()
	return false;
}


function muestraVideos()
{
	var i = 0;
	var finRango = paginaVideos*25;
	var inicioRango = finRango-25;
	$('#listado-videosAlt li').each(function(){
			if (i>=inicioRango && i<finRango){
				$(this).show()
			}else{
				$(this).hide()
			}
			
			i++;
	});
	
	(inicioRango==0) ? $('.prev-videos').hide() : $('.prev-videos').show();
	var videosVisibles = 	$('#listado-videosAlt li:visible').length;
	(videosVisibles<25) ?	$('.next-videos').hide() : $('.next-videos').show();

}







function lanzaIntervaloSlideshow(){
	clearInterval(intervalo)
	intervalo = setInterval(slideshow, 5000)
}

function slideshow(){ 
  if ( finalY > (-num_items_slide*240) ) {
  	finalY-=240;
  } else {
    finalY = -240;
    $('#slideshow ul').css({ marginTop: "0px"});
  }
  $('#slideshow ul').clearQueue().delay(5000).animate({ marginTop: finalY+"px" }, speed, slideshow);
}


function muestraSubmit(){
	if( $(this).attr("checked") ){
		$('#form_registro').attr("action", servidor+"/wp-content/themes/cronicagolf/_inc/proceso_registro.php?accion=registro");
		$('#form_registro fieldset:last').append('<input  type="submit" value="Enviar datos"/>');
		
	}else{
		$('#form_registro').attr("action", "#");
		$('#form_registro input[type=submit]').remove()
	}
}



function lanzaBuscador(){
	var motor = $("#searchForm input:checked").val();
	var cadena = $("#searchForm #s").val(); 
	if ( motor == "noticias" ){
		location = servidor+"/noticias/?buscar="+cadena;
	} else{
		 location = servidor+"/?s="+cadena;
	}
	return false;
}




function verListadoVideos(){
	if ( url.lastIndexOf("video") == -1) {
		if ( $('#vidHolderFront').css("margin-top") == "0px" ) {
			$('#vidHolderFront').stop().animate({ marginTop: "-244px" }, speed);
			$('#verListadoVideos a').css({ backgroundPosition: "right bottom" })
		} else {
			$('#vidHolderFront').stop().animate({ marginTop: "0px" }, speed);
			$('#verListadoVideos a').css({ backgroundPosition: "right top" })
		}
	 }
	return false;
}






function cargaVideoAlt(){
	var vidFile = $(this).attr("href");
 	$("#video-window h3").text($(this).text())  
  jwplayer('videoContainer').setup({
        flashplayer: '/wp-content/themes/cronicagolf/jwplayer/player.swf',
        file: vidFile,
        //plugins: '/wp-content/themes/cronicagolf/jwplayer/ova.swf',
        //config: '/wp-content/themes/cronicagolf/jwplayer/preroll.php',
        height: 320, width: 582
  });
	return false;
}


function cargaVideo(){
	var vidFile = $(this).attr("href");
 	$(".frontVideoTitle").text($(this).text())  
  jwplayer('videoContainerFront').setup({
        flashplayer: '/wp-content/themes/cronicagolf/jwplayer/player.swf',
        file: vidFile,
        //plugins: '/wp-content/themes/cronicagolf/jwplayer/ova.swf',
        //config: '/wp-content/themes/cronicagolf/jwplayer/preroll.php',
        height: 220, width: 366
  });
  verListadoVideos()
	return false;
}






function tweet(){ $("#twitter-box a").attr('target', '_blank'); (tweetsY>-350) ? tweetsY += -50 : tweetsY = 0 ; $("#twitter-box ul").fadeTo(speed, 0.01).animate({ marginTop: tweetsY+"px"},0).fadeTo(speed,1); }
function cargaFunBox(){ cual = $(this).parent().find('p'); $.post( '/wp-content/themes/cronicagolf/funbox.php?'+Math.random() , { seccion:$(this).attr('href') }, function (data){ $(cual).html(data) } ); return false; }
function muestraNoticias(){ $("#lista-noticias .cortina").slideDown(speed); $("#lista-noticias .titular").css({ backgroundPosition: "545px -35px"}); return false; }
function muestraTitulares(){ $("#lista-noticias .cortina").slideUp(speed);	$("#lista-noticias .titular").css({ backgroundPosition: "545px -5px"});	return false; }
function controlCortina(){ ($(this).next().css('display')=='none') ? $(this).css({ backgroundPosition: "545px -35px"}) : $(this).css({ backgroundPosition: "545px -5px"});	$(this).next().slideToggle(speed); return false; }


function muestraMensaje(){
	var mensaje = $(this).attr("id");
	switch (mensaje) {
		case "msg1":
			alert("El nombre de usuario será el alias o apodo que utilizarás en Crónica Golf para publicar comentarios.");
		break;
		case "msg2":
			alert("Tus datos personales jamás serán publicados ni cedidos. Solo utilizaremos tu nombre y apellidos si tenemos que ponernos en contacto contigo para comunicarte que has sido agraciado con algún premio.");
		break;
		case "msg3":
			alert("Escribe una dirección de correo electrónico válida y operativa.");
		break;
	}
	return false;
}



function chequeaFormRegistro(){
	var mensajeError = false;
	// ALERTA VACIOS
	$("#registroFront form input:text").click( function (){ $(this).css({ background:"#FFF" }); })
	$("#registroFront form input:text").focus( function (){ $(this).css({ background:"#FFF" }); })

	// TODOS COMPLETOS
	$("#registroFront form input:text").each( function (){
			if ($(this).val()==""){
				$(this).css({ background:"#F00" });
				mensajeError = true;
			}
	})
	
	if(mensajeError){
		alert("Todos los campos son obligatorios");
	} else{
		// EMAIL BIEN
		if($("#registroFront form input:text:eq(2)").val() != $("#registroFront form input:text:eq(3)").val()){
			alert("Las direcciones de e-mail que has escrito no coinciden. Revísalas y vuelve a escribirlas.");
		}else{	
			var valorCheck = $("#registroFront form #reg_legal:checked").val();
			if (valorCheck=="acepto"){
				return true;
			} else{
				alert("Debe aceptar las condiciones.");
				return false;
			}
		}
	}
	return false;
}














//

