document.write('<link rel="stylesheet" href="/css/jquery-ui-1.7.1.custom.css" type="text/css" media="screen" />'); 


function ocultarVivoreco(){
	document.vivoreco.style.visibility="hidden";
}

$(document).ready(function(){
	
	
	var isCtrl = false; 
	
	$(document).keyup(function (e) { 
		if(e.which == 17) isCtrl=false; 
	}).keydown(function (e) {
		if(e.which == 17) isCtrl=true; 
		if(e.which == 76 && isCtrl == true) { 
			//run code for CTRL+l 
			$('.logincabeceraoculto').slideToggle('slow');
			$('#botonLoginCabecera a').toggle();
			$('#Usuario_Nick').focus();
			return false; 
		} 
	}); 
	
	/*
	jQuery(document).bind('keydown', 'Ctrl+l',function (evt){
		if (evt.ctrlKey){
			alert(evt.ctrlKey);
			alert(evt.keyCode);
			//alert("Paso1");
			$('.logincabeceraoculto').slideToggle('slow');
			$('#botonLoginCabecera a').toggle();
			$('#Usuario_Nick').focus();
		}
		return false;
	});
	*/
	
	/*
	jQuery(document).bind('keypress', 'Ctrl+l',function (evt){
		alert("Paso2");
		$('.logincabeceraoculto').slideToggle('slow');
		$('#botonLoginCabecera a').toggle();
		$('#Usuario_Nick').focus();		
		return false;
	});
	*/
	
	/******************/
//	$(".sintetizar").hoverIntent({
//		sensitivity: 1,
//		interval: 100,
//		over: sintesis,
//		timeout: 300,
//		out: stopsintesis
//    });	
	/******************/

	$("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();
	$("#anadirComentario").click(function () {		
		var txtNick="";
		var txtEmail="";
		var txtUrl="";
		var txtComentario="";
		var idElemento=0;
		var apartadoComentario="";
		var respuesta="";
		
		txtComentario = trim($('#txtcomentario').val());
		idElemento = $('#idElemento').val();
		apartadoComentario = trim($('#apartadoComentario').val());		
		
		if ($('#nick').length > 0) {
			txtNick=trim($('#nick').val());
		}
			
		if ($('#email').length > 0) {
			txtEmail=trim($('#email').val());
		}
		
		if ($('#url').length > 0) {
			txtUrl=trim($('#url').val());
		}
		
		if (txtComentario!="" && idElemento!="" && apartadoComentario!=""){							
			$.post("/ajax/comentarCliente.php", { relacion_tablas: idElemento
												, tipotabla: apartadoComentario
												, comentario: txtComentario
												, nick: txtNick
												, email: txtEmail
												, url: txtUrl }, function(data){																
				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 ningún 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("");
					$('#url').val("");
					$('#txtcomentario').val("");							
					$('#errorcomentario').html("");				
				}				
			});
		}
	});	
	
	$("#anadirValor1").click(function () {votar(1);});
	
	$("#anadirValor2").click(function () {votar(2);});
	
	$("#anadirValor3").click(function () {votar(3);});
	
	$("#anadirValor4").click(function () {votar(4);});
	
	$("#anadirValor5").click(function () {votar(5);});
	
	$('#botonLoginCabecera').click(function(){
		$('.logincabeceraoculto').slideToggle('slow');
		$('#botonLoginCabecera a').toggle();
	});	
});

/* 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"); 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 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="";
	
	idElemento = $('#idElemento').val();
	apartado = trim($('#apartado').val());
	
	if (idElemento!="" && apartado!=""){							
		$.post("/ajax/valorarCliente.php", { relacion_tablas: idElemento
											, tipotabla: apartado
											, valoracion: valor}, function(data){				
			
			if (data.length>0){								
				$('#valoracion'+idElemento).html(data);
			}
		});
	}else{
		alert("Error");
	}
}

function mostrarsplash(x,y,tiempo){
	if(tiempo){
		$("#dialog").dialog({
				bgiframe: true,
				modal: true,
				show: 'slide',
				width: x+24,
				height: y+40,
				resizable: false,
				open: function(event, ui) {
					$('.ui-dialog-title').html($('.ui-dialog-title').html()+" (Se cerrará en <span id='contdown_splash'>"+tiempo+"</span>...)")
					setTimeout ( "splashcuentaatras();", 1000 ); 
				},
				close: function(event, ui) {$('#contdown_splash').html((0))}
		});
	} else {
		$("#dialog").dialog({
				bgiframe: true,
				modal: true,
				show: 'slide',
				width: x+24,
				height: y+40,
				resizable: false
		});
	}
}

function splashcuentaatras(){
	falta=parseInt($('#contdown_splash').html())
	if(falta==1){
		$("#dialog").dialog( 'close' )
	} else if(falta>1){
		$('#contdown_splash').html((falta-1))
		setTimeout ( "splashcuentaatras();", 1000 );
	}
}

function jingle(){
	galleta = valorGalleta("suenaJingle");	
	if (!galleta) {
		crearGalleta("suenaJingle",1);
		swfobject.embedSWF("/_archivos/ficheros/20090728_00001.swf", "jingle", "1", "1", "9.0.0","expressInstall.swf");
	} 
}

function crearGalleta(nombre, valor){
	caducidad=1
	var fecha = new Date();		
	fecha.setDate(fecha.getDate()+caducidad);		
	fecha.setHours(0);
	fecha.setMinutes(0);
	fecha.setSeconds(0);		
	document.cookie = nombre + "=" + escape(valor)
		+ "; expires=" + fecha.toGMTString();
}

function valorGalleta(nombre){
	var buscamos = nombre + "=";
	if (document.cookie.length > 0) {
		i = document.cookie.indexOf(buscamos);
		if (i != -1) {
			i += buscamos.length;
			j = document.cookie.indexOf(";", i);
			if (j == -1) j = document.cookie.length;
			return unescape(document.cookie.substring(i,j));
		}
	}
}

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');
}
