// JavaScript Document
var laid;
var usuarioid=0;

jQuery(function($) {
	$("a[rel^='lightbox']").slimbox({/* Put custom options here */}, null, function(el) {
		return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
	});
	ajax_id=$("#ajax_elemento_id").html();
	ajax_clase=$("#ajax_elemento_clase").html();
	ajax_tipo=$("#ajax_elemento_tipo").html();
	ajax_usuario=$("#ajax_elemento_usuario").html();
	$(".caja_form").click(function () {
		if($(this).val()=="buscar")$(this).val('')
	});
	
	$(".searchform-noticias .caja_form_not").click(function () {
		if($(this).val()=="buscar noticias...")$(this).val('')
	});
	cargarpodervotar();
	$("#slider").easySlider({
		auto: true,
		continuous: true 
	});
});

function cargar_pestana(id1,id2,blog){
	if($('#pestana_'+id1).hasClass("tab-on"))return 0;
	if($('#pestanaint_'+id1).html()!=""){
		$('#pestana_'+id1).attr("class","tab-on");
		$('#pestana_'+id2).attr("class","tab-off");
		$('#pestanaint_'+id2).hide("slow")
		$('#pestanaint_'+id1).show("slow")
		
	} else {
		jQuery.post("/ajax/tabsside.php", { tab: id1, tab2: id2, blog: blog},   function(data){
			
			if(data.error!=""){
				alert(data.error);return 0;
			}else{
				id1=data.tab
				id2=data.tab2
				$('#pestanaint_'+id1).html(data.datos)
				$('#pestana_'+id1).attr("class","tab-on");
				$('#pestana_'+id2).attr("class","tab-off");
				$('#pestanaint_'+id2).hide("slow")
				$('#pestanaint_'+id1).show("slow")
			}
		}, "json");
	}
}

function realizarBusqueda(blog){
	busqueda=$('#formBusquedaAjax .caja_form').val();
	if(busqueda.length>2){
		$('#formBusquedaAjax .estado').html("Buscando...");
		jQuery.post("/ajax/busquedajuego.php", { busqueda: busqueda, blog: blog},   function(data){
			if(data.error!=""){
				$('#formBusquedaAjax .estado').html(data.error);
			}else{
				$('#formBusquedaAjax .estado').html(data.resultado+" resultados");
				$('#resultadosBusqueda .frame').html(data.resultados);
				$('#resultadosBusqueda').slideDown('slow',function (){
					$(".barraDesplazamiento").slider({
						orientation: "vertical",
						range: "min",
						min: -($("#resultadosBusquedaAjax .frame").height()-$("#resultadosBusquedaAjax").height()),
						max: 0,
						value: 0,
						slide: function(event, ui) {
							$("#resultadosBusquedaAjax").scrollTop(-ui.value)+$("#resultadosBusquedaAjax").height();
						}
					});
					$("#resultadosBusqueda .cerrar").click(function () {
						$('#resultadosBusqueda').slideUp('slow');
						$('#formBusquedaAjax .estado').html("3 carácteres min");
					});
				});
			}
		}, "json");
	} else $('#formBusquedaAjax .estado').html("3 carácteres min");
}

function mostrar(id){
	if(laid)document.getElementById('link_'+laid).style.display="none";
	
	document.getElementById('link_'+id).style.display="block";
	
	laid=id;	
}
function nomostrar(id){
	if(laid)document.getElementById('link_'+laid).style.display="none";
}
function verComOculto(id){
	$('#com'+id+' .comtxt').slideToggle('slow');

}

function verMiniFichaJugador(id){
	$('.minifichajugador').slideUp('slow');
	$('#fichajugador'+id).slideDown('slow');
}

//SLIMBOX!!!!

(function(w){var E=w(window),u,g,F=-1,o,x,D,v,y,L,s,n=!window.XMLHttpRequest,e=window.opera&&(document.compatMode=="CSS1Compat")&&(w.browser.version>=9.3),m=document.documentElement,l={},t=new Image(),J=new Image(),H,a,h,q,I,d,G,c,A,K;w(function(){w("body").append(w([H=w('<div id="lbOverlay" />')[0],a=w('<div id="lbCenter" />')[0],G=w('<div id="lbBottomContainer" />')[0]]).css("display","none"));h=w('<div id="lbImage" />').appendTo(a).append(q=w('<div style="position: relative;" />').append([I=w('<a id="lbPrevLink" href="#" />').click(B)[0],d=w('<a id="lbNextLink" href="#" />').click(f)[0]])[0])[0];c=w('<div id="lbBottom" />').appendTo(G).append([w('<a id="lbCloseLink" href="#" />').add(H).click(C)[0],A=w('<div id="lbCaption" />')[0],K=w('<div id="lbNumber" />')[0],w('<div style="clear: both;" />')[0]])[0]});w.slimbox=function(O,N,M){u=w.extend({loop:false,overlayOpacity:0.8,overlayFadeDuration:400,resizeDuration:400,resizeEasing:"swing",initialWidth:250,initialHeight:250,imageFadeDuration:400,captionAnimationDuration:400,counterText:"Imagen {x} de {y}",closeKeys:[27,88,67],previousKeys:[37,80],nextKeys:[39,78]},M);if(typeof O=="string"){O=[[O,N]];N=0}y=E.scrollTop()+((e?m.clientHeight:E.height())/2);L=u.initialWidth;s=u.initialHeight;w(a).css({top:Math.max(0,y-(s/2)),width:L,height:s,marginLeft:-L/2}).show();v=n||(H.currentStyle&&(H.currentStyle.position!="fixed"));if(v){H.style.position="absolute"}w(H).css("opacity",u.overlayOpacity).fadeIn(u.overlayFadeDuration);z();k(1);g=O;u.loop=u.loop&&(g.length>1);return b(N)};w.fn.slimbox=function(M,P,O){P=P||function(Q){return[Q.href,Q.title]};O=O||function(){return true};var N=this;return N.unbind("click").click(function(){var S=this,U=0,T,Q=0,R;T=w.grep(N,function(W,V){return O.call(S,W,V)});for(R=T.length;Q<R;++Q){if(T[Q]==S){U=Q}T[Q]=P(T[Q],Q)}return w.slimbox(T,U,M)})};function z(){var N=E.scrollLeft(),M=e?m.clientWidth:E.width();w([a,G]).css("left",N+(M/2));if(v){w(H).css({left:N,top:E.scrollTop(),width:M,height:E.height()})}}function k(M){w("object").add(n?"select":"embed").each(function(O,P){if(M){w.data(P,"slimbox",P.style.visibility)}P.style.visibility=M?"hidden":w.data(P,"slimbox")});var N=M?"bind":"unbind";E[N]("scroll resize",z);w(document)[N]("keydown",p)}function p(O){var N=O.keyCode,M=w.inArray;return(M(N,u.closeKeys)>=0)?C():(M(N,u.nextKeys)>=0)?f():(M(N,u.previousKeys)>=0)?B():false}function B(){return b(x)}function f(){return b(D)}function b(M){if(M>=0){F=M;o=g[F][0];x=(F||(u.loop?g.length:0))-1;D=((F+1)%g.length)||(u.loop?0:-1);r();a.className="lbLoading";l=new Image();l.onload=j;l.src=o}return false}function j(){a.className="";w(h).css({backgroundImage:"url("+o+")",visibility:"hidden",display:""});w(q).width(l.width);w([q,I,d]).height(l.height);w(A).html(g[F][1]||"");w(K).html((((g.length>1)&&u.counterText)||"").replace(/{x}/,F+1).replace(/{y}/,g.length));if(x>=0){t.src=g[x][0]}if(D>=0){J.src=g[D][0]}L=h.offsetWidth;s=h.offsetHeight;var M=Math.max(0,y-(s/2));if(a.offsetHeight!=s){w(a).animate({height:s,top:M},u.resizeDuration,u.resizeEasing)}if(a.offsetWidth!=L){w(a).animate({width:L,marginLeft:-L/2},u.resizeDuration,u.resizeEasing)}w(a).queue(function(){w(G).css({width:L,top:M+s,marginLeft:-L/2,visibility:"hidden",display:""});w(h).css({display:"none",visibility:"",opacity:""}).fadeIn(u.imageFadeDuration,i)})}function i(){if(x>=0){w(I).show()}if(D>=0){w(d).show()}w(c).css("marginTop",-c.offsetHeight).animate({marginTop:0},u.captionAnimationDuration);G.style.visibility=""}function r(){l.onload=null;l.src=t.src=J.src=o;w([a,h,c]).stop(true);w([I,d,h,G]).hide()}function C(){if(F>=0){r();F=x=D=-1;w(a).hide();w(H).stop().fadeOut(u.overlayFadeDuration,k)}return false}})(jQuery);


function cargarSlimbox(){
	$("a[rel^='lightbox']").slimbox({/* Put custom options here */}, null, function(el) {
		return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
	});
}

function cargarpestana(tipo, pagina, id, id2, blog, cambiopes){
	jQuery.post("/ajax/tabsfichas.php", { tipo: tipo, pagina: pagina, id: id, id2:id2, blog:blog, pestana:cambiopes},   function(data){
		//alert(data)
		if(data.error!=""){
			alert(data.error);
			return 0;
		}
		if(data.destino==0)$('#contenidopestana').html(data.contenido);
		else{
			$('#contenido-tabs').html(data.minicon);
			$('#pagina-tabs').html(data.paginacion);
		}
		$('.tab-ficha-on').attr("class","tab-ficha-off");
		$('#tab_'+data.modo).attr("class","tab-ficha-on");
		cargarSlimbox();
	}, "json");
}

function vervideotab(idvideo){
	jQuery.post("/ajax/cargarvideo.php", { idvideo: idvideo},   function(data){
		//alert(data)
		if(data.error!=""){
			alert(data.error);
			return 0;
		}
		$('#videoactivotab').html(data.contenido);
	}, "json");
}


/* Funciones para valorar */
var voto=0;
function cargarpodervotar(id){
	if(!id)id='.elegirmivoto';
	else id='#'+id;
	$(id+" .estrellas-off").click(function (e) {
		dato=$(this).parent().get(0).id.split("_")
		if(!usuarioid){alert("Debes estár registrado para valorar"); return 0}
		if(voto==0)return 0;
		jQuery.post("/ajax/votar.php", { ajax_id: dato[1], ajax_clase: dato[3], ajax_tipo:dato[2], voto: voto},   function(data){
			if(data.error!=""){
				alert(data.error);
				return 0;
			}
			$("#"+data.id).html(data.contenido);
			cargarpodervotar(data.id)
		}, "json");
	});


	$(id+" .estrellas-off").mouseleave(function(e){
		$("#"+$(this).parent().get(0).id+" .estrellas-voto").css("width","0%");
	});
    $(id+" .estrellas-off").mousemove(function(e){
    	posicion=$(this).position();
    	posvotar=Math.ceil(posicion.left);
    	ancho=$(this).width();
    	voto=Math.ceil(((e.clientX-posvotar)*10)/ancho)
    	porvoto=voto*10;
    	$("#"+$(this).parent().get(0).id+" .estrellas-voto").css("width",porvoto+"%");
    });
}

/*Funciones para comentar */

function cargarcomentariopost(res){
	var resp
	resp=res
	jQuery.post("/ajax/comentarpost.php", { datos:$('#caja_responder div').attr('id')},   function(data){
		/*$("#caja_responder").slideUp();*/
		$("#caja_responder").html(data);
		if(res)$("#responder .comment").val('@'+res);
		/*$("#caja_responder").slideDown('slow');*/
	});
}

function responder_com(res){
	if($('#caja_responder div').attr('id')) cargarcomentariopost(res);
	else {
		if($("#responder .comment").val()>'')$("#responder .comment").val($("#responder .comment").val()+' @'+res);
		else $("#responder .comment").val('@'+res);
	}
}

function enviarComentario(){
	comentario=$("#responder .comment").val();
	if(comentario=="")return false;
	$("#caja_responder").slideUp('slow');
	jQuery.post("/ajax/comentar.php", { ajax_id: $("#responder .elemento_id").val(), ajax_clase: $("#responder .elemento_clase").val(), ajax_tipo:$("#responder .elemento_tipo").val(), comentario: comentario, alt: $("#responder .comment_alt").val()},   function(data){
		if(data.error!=""){
			alert(data.error);
			$("#caja_responder").slideDown('slow');
			return 0;
		}
		$("#caja_responder").remove();
		$("#comentarios").html(data.total);
		$("#comments").append(data.contenido);
		$("#comment-"+data.id).slideDown('slow');
	}, "json");
}

/*Fuciones editar gamertags*/

function abrirEditarGamertags(){
	$('#dialog').dialog('open');
}
function editarGamertags(){
	$("#dialog").dialog({
		bgiframe: true,
		autoOpen: false,
		height: 200,
		modal: true
	});
}

/*Funciones de votación*/

function MostrarEncuesta(id){
	$("#encuesta_widget_"+id+"_error").html('');
	jQuery.post("/ajax/verencuesta.php", { id: id},   function(data){
		if(data.error!=""){
			$("#encuesta_widget_"+data.id+"_error").html(data.error);
			return 0;
		}
		$("#encuesta_widget_"+data.id).html(data.contenido);
	}, "json");	
}

function Votar_encuesta(id){
	seleccion=$("input:radio[name=respuestaencuesta_"+id+"]:checked").val();
	$("#encuesta_widget_"+id+"_error").html('');
	if(!seleccion) return 0;
	jQuery.post("/ajax/votarencuesta.php", { id: id, voto: seleccion},   function(data){
		if(data.error!=""){
			$("#encuesta_widget_"+data.id+"_error").html(data.error);
			return 0;
		}
		$("#encuesta_widget_"+data.id).html(data.contenido);
		if(data.extra!="")$("#encuesta_widget_"+data.id+"_error").html(data.extra);
	}, "json");	
}
var recargaonload=1;
function actualizarLogin(texto,id){
	usuarioid=id;
	$("#blogocio_login").html(texto);	
	if(recargaonload){
		if(usuarioid){
			document.location.reload();
		}
	}
}

/*
 * 	Easy Slider 1.7 - jQuery plugin
 *	written by Alen Grakalic	
 *	http://cssglobe.com/post/4004/easy-slider-15-the-easiest-jquery-plugin-for-sliding
 *
 *	Copyright (c) 2009 Alen Grakalic (http://cssglobe.com)
 *	Dual licensed under the MIT (MIT-LICENSE.txt)
 *	and GPL (GPL-LICENSE.txt) licenses.
 *
 *	Built for jQuery library
 *	http://jquery.com
 *
 */

(function($) {

	$.fn.easySlider = function(options){
	  
		// default configuration properties
		var defaults = {			
			prevId: 		'prevBtn',
			prevText: 		'Previous',
			nextId: 		'nextBtn',	
			nextText: 		'Next',
			controlsShow:	false,
			controlsBefore:	'',
			controlsAfter:	'',	
			controlsFade:	true,
			firstId: 		'firstBtn',
			firstText: 		'First',
			firstShow:		false,
			lastId: 		'lastBtn',	
			lastText: 		'Last',
			lastShow:		false,				
			vertical:		false,
			speed: 			2000,
			auto:			false,
			pause:			4000,
			continuous:		false, 
			numeric: 		false,
			numericId: 		'controls'
		}; 
		
		var options = $.extend(defaults, options);  
				
		this.each(function() {  
			var obj = $(this); 				
			var s = $("li", obj).length;
			var w = $("li", obj).width(); 
			var h = $("li", obj).height(); 
			var clickable = true;
			obj.width(w); 
			obj.height(h); 
			obj.css("overflow","hidden");
			var ts = s-1;
			var t = 0;
			$("ul", obj).css('width',s*w);			
			
			if(options.continuous){
				$("ul", obj).prepend($("ul li:last-child", obj).clone().css("margin-left","-"+ w +"px"));
				$("ul", obj).append($("ul li:nth-child(2)", obj).clone());
				$("ul", obj).css('width',(s+1)*w);
			};				
			
			if(!options.vertical) $("li", obj).css('float','left');
								
			if(options.controlsShow){
				var html = options.controlsBefore;				
				if(options.numeric){
					html += '<ol id="'+ options.numericId +'"></ol>';
				} else {
					if(options.firstShow) html += '<span id="'+ options.firstId +'"><a href=\"javascript:void(0);\">'+ options.firstText +'</a></span>';
					html += ' <span id="'+ options.prevId +'"><a href=\"javascript:void(0);\">'+ options.prevText +'</a></span>';
					html += ' <span id="'+ options.nextId +'"><a href=\"javascript:void(0);\">'+ options.nextText +'</a></span>';
					if(options.lastShow) html += ' <span id="'+ options.lastId +'"><a href=\"javascript:void(0);\">'+ options.lastText +'</a></span>';				
				};
				
				html += options.controlsAfter;						
				$(obj).after(html);										
			};
			
			if(options.numeric){									
				for(var i=0;i<s;i++){						
					$(document.createElement("li"))
						.attr('id',options.numericId + (i+1))
						.html('<a rel='+ i +' href=\"javascript:void(0);\">'+ (i+1) +'</a>')
						.appendTo($("#"+ options.numericId))
						.click(function(){							
							animate($("a",$(this)).attr('rel'),true);
						}); 												
				};							
			} else {
				$("a","#"+options.nextId).click(function(){		
					animate("next",true);
				});
				$("a","#"+options.prevId).click(function(){		
					animate("prev",true);				
				});	
				$("a","#"+options.firstId).click(function(){		
					animate("first",true);
				});				
				$("a","#"+options.lastId).click(function(){		
					animate("last",true);				
				});				
			};
			
			function setCurrent(i){
				i = parseInt(i)+1;
				$("li", "#" + options.numericId).removeClass("current");
				$("li#" + options.numericId + i).addClass("current");
			};
			
			function adjust(){
				if(t>ts) t=0;		
				if(t<0) t=ts;	
				if(!options.vertical) {
					$("ul",obj).css("margin-left",(t*w*-1));
				} else {
					$("ul",obj).css("margin-left",(t*h*-1));
				}
				clickable = true;
				if(options.numeric) setCurrent(t);
			};
			
			function animate(dir,clicked){
				if (clickable){
					clickable = false;
					var ot = t;				
					switch(dir){
						case "next":
							t = (ot>=ts) ? (options.continuous ? t+1 : ts) : t+1;						
							break; 
						case "prev":
							t = (t<=0) ? (options.continuous ? t-1 : 0) : t-1;
							break; 
						case "first":
							t = 0;
							break; 
						case "last":
							t = ts;
							break; 
						default:
							t = dir;
							break; 
					};	
					var diff = Math.abs(ot-t);
					var speed = diff*options.speed;						
					if(!options.vertical) {
						p = (t*w*-1);
						$("ul",obj).animate(
							{ marginLeft: p }, 
							{ queue:false, duration:speed, complete:adjust }
						);				
					} else {
						p = (t*h*-1);
						$("ul",obj).animate(
							{ marginTop: p }, 
							{ queue:false, duration:speed, complete:adjust }
						);					
					};
					
					if(!options.continuous && options.controlsFade){					
						if(t==ts){
							$("a","#"+options.nextId).hide();
							$("a","#"+options.lastId).hide();
						} else {
							$("a","#"+options.nextId).show();
							$("a","#"+options.lastId).show();					
						};
						if(t==0){
							$("a","#"+options.prevId).hide();
							$("a","#"+options.firstId).hide();
						} else {
							$("a","#"+options.prevId).show();
							$("a","#"+options.firstId).show();
						};					
					};				
					
					if(clicked) clearTimeout(timeout);
					if(options.auto && dir=="next" && !clicked){;
						timeout = setTimeout(function(){
							animate("next",false);
						},diff*options.speed+options.pause);
					};
			
				};
				
			};
			// init
			var timeout;
			if(options.auto){;
				timeout = setTimeout(function(){
					animate("next",false);
				},options.pause);
			};		
			
			if(options.numeric) setCurrent(0);
		
			if(!options.continuous && options.controlsFade){					
				$("a","#"+options.prevId).hide();
				$("a","#"+options.firstId).hide();				
			};				
			
		});
	  
	};

})(jQuery);