$(document).ready(function(){
	




	
	$("a[rel^='lightbox']").slimbox({/* Put custom options here */}, null, function(el) {
		return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
	});
	
	
	$("#q").blur(function () {$('#q').val();});
		
	$("#anadirTag").click(function () {anadirTag();});
	
	cargarpodervotar();
	
	$("#cambiarKaptcha").click(function () {
		$.post("/ajax/kaptcha.php", {}, function(dataKaptcha){$('#strKaptcha').html(dataKaptcha);});
	});
	
	

		
	
	$("#anadirComentario").click(function () {		
		var txtNick="";	
		var txtEmail="";
		var txtComentario="";
		var idElemento=0;
		var apartadoComentario="";
		var respuesta="";
		var kaptcha="";
		var strKaptcha=""; 
		
		txtComentario = trim($('#txtcomentario').val());
		idElemento = $('#idElemento').val();
		apartadoComentario = trim($('#apartadoComentario').val());
		jKaptcha = $('#kaptcha').val();
		jStrKaptcha = $('#strKaptcha').html();
		
		if ($('#nick').length > 0) {txtNick=trim($('#nick').val());}
		if ($('#email').length > 0) {txtEmail=trim($('#email').val());}
		var strAcepto=$('#acepto').attr("checked");
		
		if (txtComentario!="" && idElemento!="" && apartadoComentario!=""){
			$.post("/ajax/comentarCliente.php", { relacion_tablas: idElemento
												, tipotabla: apartadoComentario
												, comentario: txtComentario
												, nick: txtNick
												, email: txtEmail
												, acepto:strAcepto, kaptcha:jKaptcha, strKaptcha:jStrKaptcha}, function(data){
				$.post("/ajax/kaptcha.php", {}, function(dataKaptcha){$('#strKaptcha').html(dataKaptcha);});
				
				var error = $('error', data).text();
				error = error.replace("<![CDATA[", "");
				error = error.replace("]]>", "");
				
				if(error!=""){					
					$('#errorcomentario').html($('error', data).text());
					return 0;
				}else{					
					var contenido = $('contenido', data).text();
					contenido = contenido.replace("<![CDATA[", "");
					contenido = contenido.replace("]]>", "");
					
					if(contenido!=""){
						if ($('#listComentarios').html()==no_se_ha_introducido_ningun_comentario_por_ahora){
							$('#listComentarios').html($('contenido', data).text());
						}else{
							$('#listComentarios').html($('#listComentarios').html() + $('contenido', data).text());
						}
						var x;
						x=$("li[name^='comentario']");
						var cantidad=x.length;
						x=x.eq(cantidad-1);
						x.slideDown('1000');
					}
					
					$('#nick').val("");
					$('#email').val("");					
					$('#txtcomentario').val("");
					$('#kaptcha').val("");
					$('#acepto').attr("checked",0);
					$('#errorcomentario').html("");
				}
			});
		}
	});
	
	
	$('a[id*="PagComentario"]').click(function(){
		idPag = "#"+this.id;
		nPagina=this.id;
		nPagina=nPagina.substring(13);	
		$('a[id*="PagComentario"]').removeClass("num-activo");
		$('a[id*="PagComentario"]').addClass("num");
		$(idPag).removeClass("num");
		$(idPag).addClass("num-activo");
		
		idElemento = $("#idElemento").val();
		apartadoComentario = $("#apartadoComentario").val();
				
		$.post("/ajax/paginarComentarCliente.php", {pagina:nPagina, elemento:idElemento, apartado:apartadoComentario}, function(data){
			if (data.length>0){
				$('#listComentarios').html(data);				
			}
		});
	});
	
	$('#botonLoginCabecera').click(function(){
		$('.logincabeceraoculto').slideToggle('slow');
		$('#botonLoginCabecera a').toggle();
	});
	
	$("#anadirValor1").click(function () {votar(2);});
	$("#anadirValor2").click(function () {votar(4);});
	$("#anadirValor3").click(function () {votar(6);});
	$("#anadirValor4").click(function () {votar(8);});
	$("#anadirValor5").click(function () {votar(10);});
	
	$('[id*="anadirValor"]').hover(
		function(){
			var estrella=this.id;
			idEstrella = estrella.substring(11);		
			$('[id*="anadirValor"]').attr('src','images/'+valoridioma+'/estrella_negra.png');	
			for (i=1; i<=idEstrella; i++){$("#anadirValor"+i).attr('src','images/'+valoridioma+'/estrella_amarilla.png');}
		},function(){		
			$('[id*="anadirValor"]').attr('src','images/'+valoridioma+'/estrella_negra.png');		
		}
	);
	
	$("#cerrarVentanaModal").click(function(){		
		$('#mask').hide();
		$('.window').hide();
	});
	
});

function mostrarcargando(){


	//Get the screen height and width
		var maskHeight = $(document).height();
		var maskWidth = $(window).width();
	
		//Set heigth and width to mask to fill up the whole screen
		$('#mask2').css({'width':maskWidth,'height':maskHeight});
		
		$('#cargando').css('background-image','url(images/'+valoridioma+'/definde-loading2.gif)').fadeIn('fast');
	
		
		//transition effect	
		$('#mask2').fadeTo("fast",0.4);	
	
		var anchoDialog=parseInt($('#cargando').css('width'));				
		anchoDialog=anchoDialog/2;
		var altoDialog=parseInt($('#cargando').css('height'));				
		altoDialog=altoDialog/2;
		
		//Altura de la cabecera
		var alturaCabecera=parseInt($('#cabecera100').height());
		
		var top = getPageScroll()[1] + (getPageHeight() / 10);
		var left = 385.5;
		$("#cargando").css('top',  top);
		$("#cargando").css('left', left);	
	
		//transition effect
		$("#cargando").fadeIn(300);

	
}

function ocultarcargando(){
	
	$('#mask2').hide();
	$("#cargando").fadeOut(300);
	$('.window2').hide();
}

function abrirVentanaModal(strTitulo, strMensaje, html){
	//alert("Titulo: "+strTitulo+ " -- Mensaje: "+strMensaje);
	
	$.post("/ajax/ventanaModal.php", {titulo:strTitulo, mensaje:strMensaje, ishtml:html}, function(data){
		if (data.length>0 && data!=0){
			$("#dialogInvitar").html(data);

			id = "#dialogInvitar";
			//Get the screen height and width
			var maskHeight = $(document).height();
			var maskWidth = $(window).width();
		
			//Set heigth and width to mask to fill up the whole screen
			$('#mask').css({'width':maskWidth,'height':maskHeight});
			
			//transition effect	
			$('#mask').fadeTo("fast",0.4);	
		
			var anchoDialog=parseInt($('#dialogInvitar').css('width'));				
			anchoDialog=anchoDialog/2;
			var altoDialog=parseInt($('#dialogInvitar').css('height'));				
			altoDialog=altoDialog/2;
			
			//Altura de la cabecera
			var alturaCabecera=parseInt($('#cabecera100').height());		
			
			//var top=200;
			//var left=300;
			
			var top = getPageScroll()[1] + (getPageHeight() / 10);
    		var left = 385.5;
			$("#dialogInvitar").css('top',  top);
			$("#dialogInvitar").css('left', left);	
			
			$(id).css('top',  top);
			$(id).css('left', left);
		
			//transition effect
			$(id).fadeIn(300);
		}
	}, "html"
	);
	
	/*$("#cerrarsesion").click(function(){cerrarsesion();});*/
	/*$("#loginUser").click(function(){loginuser()});*/
}

/******************************/
  function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;	
    }
    return new Array(xScroll,yScroll) 
  }
  
  function getPageHeight() {
    var windowHeight
    if (self.innerHeight) {	// all except Explorer
      windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
      windowHeight = document.body.clientHeight;
    }	
    return windowHeight
  }
/******************************/

function loginuser(){
	var url=document.location.href;
	var strUsuario= $("#Usuario").val();
	var strPass= $("#Pass").val();
	
	//A la url hay que quitarle lo que viene a continuacion de #
	url=url.split("#");
	
	$.post("/ajax/abrirSesion.php", {Usuario:strUsuario, Pass:strPass}, function(data){		
		if(data==3){
			abrirVentanaModal(login_incorrecto, esta_cuenta_tiene_pendiente_la_confirmacion_de_email_pulsa+" <a onclick='enviarConfirmacion("+'"'+strUsuario+'"'+")' >"+aqui+"</a> "+para_mandarte_de_nuevo_el_email_de_activacion,1);
		}else if (data>=0 && data!=""){
			abrirVentanaModal(login_incorrecto, el_login_que_ha_introducido_es_incorrecto+"|"+vuelva_a_intentarlo);
		}else{
			document.location.href='http://'+document.domain+'/miguia/';
		}
		

	});
}

function enviarConfirmacion(Usuario){
	$.post("/ajax/registro.php", {Usuario:Usuario, ConfirmarCorreo2:1}, function(data){
		if(data=="1") abrirVentanaModal(enviar_confirmacion,se_ha_enviado_el_correo_de_confirmacion);
		else abrirVentanaModal(enviar_confirmacion,data);
	});
	
}

function buscadorgeneral(){
	var strUrl= $("#PaginaBuscador").val();

}

function loginuserVM(){
	var url=document.location.href;
	var strUsuario= $("#UsuarioVM").val();
	var strPass= $("#PassVM").val();
	
	$.post("/ajax/abrirSesion.php", {Usuario:strUsuario, Pass:strPass}, function(data){
		if (data!=""){abrirVentanaModal(login_incorrecto, el_login_que_ha_introducido_es_incorrecto+"<br/>"+vuelva_a_intentarlo);}
		else{document.location.href=url;}		
	});
}

function cerrarsesion(){
	$.post("/ajax/cerrarSesion.php", "", function(data){				

		if (data!=""){
			document.location.href=data;
		}else{
			var url=document.location.href;	
			url=url.split("/");
			document.location.href="http://"+url[2];
		}
	});
}

/* Funciones para valorar */
var voto=0; var idvoto="";
function cargarpodervotar(id){
	if(!id)id='.elegirmivoto';
	else id='#'+id;
	$(id+" .estrellas-off").click(function (e) {
		dato=$(this).parent().get(0).id.split("_")
		if(dato[3]==0){
			//alert("Debes estár registrado para valorar");
			abrirVentanaModal(valorar, debes_estar_registrado_para_poder_valorar); 
			return 0
		}
		if(voto==0)return 0;
		idvoto='valorar_'+dato[1]+'_'+dato[2]+'_'+dato[3];
		$.post("/ajax/valorarCliente.php", { relacion_tablas: dato[1], tipotabla: dato[2], valoracion: voto}, function(data){
			if (data.length>0){
				$('#'+idvoto).html(data);
				cargarpodervotar(idvoto);
			}
		});
	});
	
	$(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)*5)/ancho)
		porvoto=voto*20;
		$("#"+$(this).parent().get(0).id+" .estrellas-voto").css("width",porvoto+"%");
	});
}

//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 calendarioApuntar(elemento, fechaInicio, fechaFin){
$(document).ready(function() {
	$("#"+elemento).datepicker();
	if(fechaInicio!=""){
		fechaInicio=fechaInicio.split('-');
		$("#"+elemento).datepicker('option', 'minDate',new Date(fechaInicio[2],fechaInicio[1]-1,fechaInicio[0]));
	}
	
	if(fechaFin!=""){
		fechaFin=fechaFin.split('-');
		$("#"+elemento).datepicker('option', 'maxDate',new Date(fechaFin[2],fechaFin[1]-1,fechaFin[0]));
	}
});
}

function calendario(elemento, companero){
	$(document).ready(function() {
		$("#"+elemento).datepicker();
		if(companero!=""){
			$("#"+companero).datepicker();
			$("#"+elemento).datepicker('option', 'maxDate', $("#"+companero).datepicker( 'getDate' ) );
			$("#"+companero).datepicker('option', 'minDate', $("#"+elemento).datepicker( 'getDate' ) );
			$("#"+companero).bind("change", function(e){$("#"+elemento).datepicker('option', 'maxDate', $("#"+companero).datepicker( 'getDate' ) );})
			$("#"+elemento).bind("change", function(e){$("#"+companero).datepicker('option', 'minDate', $("#"+elemento).datepicker( 'getDate' ) );})
		}
	});
}

function vaciarCalendario(id){
	$("#"+id).val('')
	$("#"+id).change()
	return false;
}

function textoEnriquecido(id){tinyMCE.execCommand("mceAddControl", false, id);}

function cargarScroll(id){
	$("#"+id).scrollable({ 
			next: '#'+id+'_next', 
			prev: '#'+id+'_prev',
			disabledClass: ''
	});
};

function cargarScrollver(id){
	$("#"+id).scrollable({ 
        interval: 4000, 
        loop: true,  
        speed: 1000, 
        onBeforeSeek: function() {this.getItems().fadeTo(500, 0.2);}, 
        onSeek: function() {this.getItems().fadeTo(500, 1);}, 
        vertical:true, 
        size: 1
	});
};

function fill(nombre, id){
	var aEtiquetas = $('#aEtiquetas').val();
	
	if (!existeEnLista(aEtiquetas, nombre)){
		if (aEtiquetas==""){$('#aEtiquetas').val(id + "|" + nombre);}
		else{$('#aEtiquetas').val(aEtiquetas + ", " + id + "|" + nombre);}
		
		$('#listEtiquetas').html($('#listEtiquetas').html() + "<li>" + nombre + "<a onclick='quitarEtiqueta(\"" + nombre + "\");'>x</a></li>");
	}
	
	$('#q').val("");
}

function trim(stringToTrim) {return stringToTrim.replace(/^\s+|\s+$/g,"");}

function existeEnLista(lista, palabra){							
	palabra = palabra.split("|");
	
	if (palabra.length==1){palabra = palabra[0];}
	else if (palabra.length==2){palabra = palabra[1];}
	
	palabra = trim(palabra);
	palabra = palabra.toLowerCase();	

	if (lista.length>0){
		lista = lista.split(",");
										
		for(i=0; i<lista.length; i++){
			elemento = lista[i];									
			elementos = elemento.split("|");
			
			if (elementos.length==1){
				elementos[0] = trim(elementos[0]).toLowerCase();
				if (elementos[0] == palabra){return true;}
			}else if(elementos.length==2){
				elementos[1] = trim(elementos[1]).toLowerCase();
				if (elementos[1]==palabra){return true;}
			}
		}
	}
	
	return false;
}

function votar(valor){	
	var idElemento=0;
	var apartado="";
	var idUsuario=0;
	
	idElemento = $('#idElementoValorar').val();
	apartado = trim($('#apartadoValorar').val());
	idUsuario = $('#idUsuarioValorar').val();
	
	if (idUsuario>0){
		if (idElemento!="" && apartado!=""){
			$.post("/ajax/valorarCliente.php", { relacion_tablas: idElemento
												, tipotabla: apartado
												, valoracion: valor}, function(data){
				if (data.length>0){
					//abrirVentanaModal("Valoración", data);
					$("#dialogInvitar").html(data);
					//Get the screen height and width
					var maskHeight = $(document).height();
					var maskWidth = $(window).width();
				
					//Set heigth and width to mask to fill up the whole screen
					$('#mask').css({'width':maskWidth,'height':maskHeight});
					
					//transition effect	
					$('#mask').fadeTo("fast",0.4);	
				
					var anchoDialog=parseInt($('#dialogInvitar').css('width'));				
					anchoDialog=anchoDialog/2;
					var altoDialog=parseInt($('#dialogInvitar').css('height'));				
					altoDialog=altoDialog/2;
					
					//Altura de la cabecera
					var alturaCabecera=parseInt($('#cabecera100').height());		
					
					var top = getPageScroll()[1] + (getPageHeight() / 10);
    				var left = 385.5;
					$("#dialogInvitar").css('top',  top);
					$("#dialogInvitar").css('left', left);	
					
					//transition effect
					$("#dialogInvitar").fadeIn(300);
				}
				
				//Actualizar el valor de la nota media y el número de votos.
				$.post("/ajax/cacheValoracion.php", { relacion_tablas: idElemento, tipotabla: apartado}, function(valores){
					if(valores.length>0){
						valores=valores.split("_");
						$("#valoracionMediaEntrada").html("valoración: <span>"+valores[0]+"</span>");
						$("#nVotosEntrada").html(valores[1]+votos);
					}
				});
				
			});
		}
		//else{alert("Error");}
	}else{
		abrirVentanaModal(registrese,hay_que_estar_registrado_y_logueado_para_poder_valorar);
	}
	
}

function anadirTag(){
	var valor = $('#q').val();
	valor = trim(valor);
	var aEtiquetas = $('#aEtiquetas').val();		
	var idElemento = $('#idElemento').val();
	var nomApartado = $('#apartado').val();		
	
	if (valor!=""){			
		if (!existeEnLista(aEtiquetas,valor)){				
			if (aEtiquetas==""){$('#aEtiquetas').val(valor);}
			else{$('#aEtiquetas').val(aEtiquetas + ", " + valor);}
			
			var aEtiquetas = $('#aEtiquetas').val();
			
			$.post("/ajax/etiquetarCliente.php", { 
					Elemento_Id: idElemento, apartado: nomApartado, etiquetas: aEtiquetas
				}, function(data){
					if ($('#etiquetas').html()==sin_etiquetar){$('#etiquetas').html(data);}
					else{$('#etiquetas').html($('#etiquetas').html() + " " + data);}
				}
			);
		}
	}
	$('#q').val("");
}

function AgregarDestinatario(id,nombre){
	document.Form1.Usuario_To.value=id;
	document.Form1.Nombre_To.value=nombre;
	document.Form1.BuscadorUser.value="";
	
	$('#listadestinatarios').hide('slow');
}

function agregarHistorial(accion, seccionId, mensaje){
	//alert(anadir_al_historial+ accion + ", " + seccionId + ", " + mensaje);
	abrirVentanaModal("",anadir_al_historial+ accion + ", " + seccionId + ", " + mensaje);
}





