


function addTag(lugar) {
	$("#tags_"+ lugar).after("<div id='formulario_tag_" + lugar + "' class='formularioTag'><strong>Añadir etiqueta</strong><p><input type='text' size='20' name='tag' id='tag" + lugar + "' \/></p><p><input type='button' onclick=\"guardaTag('"+ lugar +"'); return false;\" class='botonOk' value='añadir' \/> o <a href=\"javascript://\" onclick=\"$('#formulario_tag_"+ lugar +"').hide();$('#tags_"+ lugar +"').show();\">cancelar</a></p></div>");
	$("#tags_"+ lugar).hide();
}
var lugarActivo;
function addImagenLugar(lugar) {
	if (lugarActivo != '') {
		$("#img_lugar_"+ lugarActivo +" a.addImgLugar").show();
	}
	lugarActivo = lugar;
	$("#frmImagenLugar").remove();
	var formX = "<form method=\"post\" action=\"#\"  enctype=\"multipart\/form-data\" id=\"frmImagenLugar\" class=\"formularioTag\">"
			formX  += "<fieldset><h3>Subir una foto<\/h3><p id=\"ok_imagen\"><\/p><div id=\"loading\" style=\"display:none;\"><img src=\"\/estilo\/cargando-item.gif\" alt=\"cargando\" \/> subiendo tu fotografía..";
			formX  += "<\/div><p><label for=\"descripcion_imgpoi\" class=\"bloque\">Título de la foto:<input type=\"text\" size=\"21\" id=\"descripcion_imgpoi\" name=\"descripcion_imgpoi\" maxlenght=\"50\" \/><\/label></p><p><input name=\"imagen\" type=\"file\" id=\"imagen\" size=\"9\" value=\"\" \/><\/p>";
			formX  += "<p><label for=\"copyright\" class=\"opciones\">";
			formX  += "<input name=\"copyright\" class=\"\" type=\"checkbox\" id=\"copyright\" value=\"1\" \/> Poseo el copyright sobre esta imagen<\/label><\/p>";
			formX  += "<input name=\"tipo\" type=\"button\"  onclick=\"if($('#copyright').attr('checked')) {return ajaxFileUpload('"+ lugar +"');}\" value=\"Subir foto\" \/>";
			formX  += " o <a id=\"cerrar-a-foto\" href=\"#\" onclick='eliminaFormImgLugar(\"" + lugar + "\"); return false;'>Cancelar</a>";
			formX  += "<input type=\"hidden\" name=\"lugar\" id=\"lugar\" value=\""+ lugar +"\" \/><\/fieldset><\/form>";
	$("#participa_lugar_"+ lugar).after(formX);
	$("#participa_lugar_"+ lugar +" li.addImgLugar").hide();
}

function ajaxFileUpload(lugar){
	$("#loading").ajaxStart(function(){
		$(this).show();
	})
	.ajaxComplete(function(){
		$(this).hide();
	});

	$.ajaxFileUpload
	(
		{
			url:'/ajax?tipo=imagenLugar_subir&lugar='+ lugar,
			secureuri:false,
			fileElementId:'imagen',
			form:'frmImagenLugar',
			dataType: 'xml',
			multipart: true,
			success: function (data, status,fileElementId)	{
				var mensajeError;
				var mensajeOk;
				var htmlRetorno;
				$('respuesta', data).each(function() {
					mensajeError = $("error", this).text();
					mensajeOk = $("msg", this).text();
					htmlRetorno = $("htmlRetorno", this).text();
					htmlViajero = $("htmlViajero", this).text();
					viajero = $("viajero", this).text();
					imagen = $("imagen",this).text();
				});

					if(mensajeError != '') {
						alert(mensajeError);
						$("div.opiniones_lugar_"+ lugar +" li.addImgLugar").show();
					}else {
						$('span#ok_imagen').html(mensajeOk).fadeIn();
						if ($('div#opinion_'+ viajero +'_'+ lugar).size() == 0) {
							if ($('div#galeria_general_'+ lugar).size() == 0) {
								$('div.opiniones_lugar_'+ lugar +' div.opinion:last').after('<div class="opinion" id="galeria_general_'+ lugar +'"><h2>Fotografías de otros viajeros</h2><ul class="galeria fotos"></ul><form method="post" action="/cuaderno?accion=add_imagen_lugar&amp;lugar='+ lugar +'"><input type="submit" value="Editar mis fotos" class="boton"/></form></div>');
							}
							$('div#galeria_general_'+ lugar +' ul.galeria').append(htmlRetorno);
							$('li#imgpoi_'+ imagen).prepend(htmlViajero);
						} else {
							if ($('div#opinion_'+ viajero +'_'+ lugar +' ul#galeria_lugar_'+ viajero +'_'+ lugar).size() == 0) {
								$('div#opinion_'+ viajero +'_'+ lugar).append('<h2>Fotografías '+ htmlViajero +'</h2><ul class="galeria fotos" id="galeria_lugar_'+ viajero +'_'+ lugar +'"></ul><form method="post" action="/cuaderno?accion=add_imagen_lugar&amp;lugar='+ lugar +'"><input type="submit" value="Editar mis fotos" class="boton"/></form>');
							}
							$('div#opinion_'+ viajero +'_'+ lugar +' ul#galeria_lugar_'+ viajero +'_'+ lugar).prepend(htmlRetorno);
						}
						tb_init('a.thickbox');
						$("input#imagen").val("");
						$("input#copyright").attr("checked","");
						$("#participa_lugar_"+ lugar +" li.addImgLugar").show();
						//activaEdicionTextos();
					}
				
			},
			error: function (data, status, e){
				alert("No ha sido posible subir la imagen");
				$("div.opiniones_lugar_"+ lugar +" li.addImgLugar").show();
			}
		}
	)
	
	return false;

}	
				
function guardaTag(lugar) {
	var tag = $("#tag"+ lugar).val();
	if (tag != '') {
		$("#formulario"+ lugar).html("Guardando tu etiqueta..");
		$.post("/ajax",{ tipo : "add_tag", lugar: lugar, tag: tag}, function(data){
			$("#tags_"+ lugar).html(data);
		},"json")
	}
}

function valoraOpinion(opinion,util,poi) {
		$("#util_"+ opinion).html("Guardando tu valoración..");
		$.post("/ajax_rating",{ tipo : "rating_opinion", lugar: poi, item: opinion, valor: util}, function(data){
			resultado = data.resultado;
			$("#util_"+ opinion).html(data.body);
			if (resultado == 'ko') {
				alert(data.msgError);
			}
		},"json");
	  return false;
}

function eliminaFormTag(lugar) {
	$("#tags_"+ lugar +" a.addtag").show();
	$("#formulario"+ lugar).remove();
}

function eliminaFormImgLugar(lugar) {
	$("#participa_lugar_"+ lugar +" li.addImgLugar").show();
	$("#frmImagenLugar").remove();
}

function removeAmigo(viajero,ajax,enlace) {
	  $.post("/ajax_friends", { tipo : "remove_amigo",  viajero: viajero}, function(data){
			resultado = data.resultado;
			if (resultado == 'ko') {
				alert(data.msgError);
			} else {					
				$(enlace).after(data.body);
				$(enlace).remove();
				alert(data.msgError);
			}
	  }, "json");
	  return false;
}


function addAmigo(viajero,ajax,enlace) {
		var contactBoxy = null;
		var cargadorId = 'friend'+ viajero +'_loading'
		$(enlace).after('<span id="'+ cargadorId +'" style="display:block;">cargando..</span>');
		var boxy_content;
		$.post("/ajax_friends",{ tipo : "preadd_amigo", viajero: viajero}, function(data){
			resultado = data.resultado;
			if (resultado == 'ko') {
				$('#'+ cargadorId).remove();
				alert(data.msgError);
			} else {
				$('#'+ cargadorId).remove();
				boxy_content = data.body;
				contactBoxy = new Boxy(boxy_content, {
				title: "Añadir como amigo",
				draggable: false,
				modal: true,
				behaviours: function(c) {
						c.find('#requestFriend').submit(function() {
						  Boxy.get(this).setContent("<div style=\"width: 350px; height: 300px\">Enviando...</div>");
						  $.post("/ajax_friends", { tipo : "sendadd_amigo", mensaje: c.find("#mensaje").val(), viajero: c.find("#viajero").val(), cds: c.find("#cds_request").val()},
							function(data){
								resultado = data.resultado;
								if (resultado == 'ko') {
									alert(data.msgError);
								} else {								
									contactBoxy.setContent("<div style=\"width: 350px; height: 300px\">"+ data.body +"</div>");
								}
						  }, "json");
						  return false;
						});
					 }		
				});
			}
		}, "json");
		return false;	
}

function addAmigo(viajero,ajax,enlace) {
		var contactBoxy = null;
		var cargadorId = 'friend'+ viajero +'_loading'
		$(enlace).after('<span id="'+ cargadorId +'" style="display:block;">cargando..</span>');
		var boxy_content;
		$.post("/ajax_friends",{ tipo : "preadd_amigo", viajero: viajero}, function(data){
			resultado = data.resultado;
			if (resultado == 'ko') {
				$('#'+ cargadorId).remove();
				alert(data.msgError);
			} else {
				$('#'+ cargadorId).remove();
				boxy_content = data.body;
				contactBoxy = new Boxy(boxy_content, {
				title: "Añadir como amigo",
				draggable: false,
				modal: true,
				behaviours: function(c) {
						c.find('#requestFriend').submit(function() {
						  Boxy.get(this).setContent("<div style=\"width: 350px; height: 300px\">Enviando...</div>");
						  $.post("/ajax_friends", { tipo : "sendadd_amigo", mensaje: c.find("#mensaje").val(), viajero: c.find("#viajero").val(), cds: c.find("#cds_request").val()},
							function(data){
								resultado = data.resultado;
								if (resultado == 'ko') {
									contactBoxy.setContent("<div style=\"width: 350px; height: 300px\"><p class=\"error\">"+ data.msgError +"</p></div>");
								} else {								
									contactBoxy.setContent("<div style=\"width: 350px; height: 300px\">"+ data.body +"</div>");
								}
						  }, "json");
						  return false;
						});
					 }		
				});
			}
		}, "json");
		return false;	
}

function reportarItem(item,tipo,ajax,enlace) {
		var contactBoxy = null;
		var cargadorId = 'report'+ item +'_'+ tipo +'_loading'
		var boxy_content;
		$.post("/ajax_report",{ tipo : "form_report", item: item, tipoContenido : tipo}, function(data){
			resultado = data.resultado;
			if (resultado == 'ko') {
				$('#'+ cargadorId).remove();
				alert(data.msgError);
			} else {
				$('#'+ cargadorId).remove();
				boxy_content = data.body;
				contactBoxy = new Boxy(boxy_content, {
				title: "Reportar contenido inapropiado",
				draggable: false,
				modal: true,
				behaviours: function(c) {
						c.find('#reportRequest').submit(function() {
							motivoReport = c.find("#motivoReport").val();
							if (motivoReport == '') {
								alert('Selecciona uno de los motivos');
								return false;
							} else {
							  Boxy.get(this).setContent("<div style=\"width: 350px; height: 300px\">Enviando...</div>");
							  $.post("/ajax_report", { tipo : "send_report", item : c.find("#item").val(), tipoContenido : c.find("#tipoContenido").val(), mensaje: c.find("#mensaje").val(), motivoReport: c.find("#motivoReport").val(), cds: c.find("#cds_request").val()},
								function(data){
									resultado = data.resultado;
									if (resultado == 'ko') {
										contactBoxy.setContent("<div style=\"width: 350px; height: 300px\"><p class=\"error\">"+ data.msgError +"</p></div>");
									} else {								
										contactBoxy.setContent("<div style=\"width: 350px; height: 300px\">"+ data.body +"</div>");
									}
							  }, "json");
							  return false;
							}  
							
						});
					 }		
				});
			}
		}, "json");
		return false;	
}

function stringValido(szValor)
{
	szNuevo = "";
	for (i = 0; i < szValor.length; i++)
	{
		ch = szValor.substring(i, i+1);
		if ((ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z") || (ch >= "0" && ch <= "9") || (ch=="-") || (ch=="_") || (ch=="@") || (ch=="."))
		{
			szNuevo+=ch;
		}
	}
	if (szValor != szNuevo)
	{
		return(false);
	}
	return(true);
}

function multipleCheckbox(elemento) {
	aux="";
	
	elementos=eval("document.getElementsByName(\""+ elemento +"\")");
	
	if(elementos.length==undefined)	{
		if(eval("document.getElementsByName(\""+ elemento +"\").checked"))
			aux=eval("document.getElementsByName(\""+ elemento +"\").value");
	} else	{
		for(i=0;i<elementos.length;i++)	{
			if(elementos[i].checked){
				aux=aux+elementos[i].value+",";
			}
		}
		if(aux.substring(aux.length-1,aux.length)==",")
			aux=aux.substring(0,aux.length-1);
	}
	eval("document.getElementById(\""+ elemento.substring(0,elemento.length-3) +"\").value='"+aux+"'");
}


(function($){
	/* hoverIntent by Brian Cherne */
	$.fn.hoverIntent = function(f,g) {
		// default configuration options
		var cfg = {
			sensitivity: 7,
			interval: 100,
			timeout: 0
		};
		// override configuration options with user supplied object
		cfg = $.extend(cfg, g ? { over: f, out: g } : f );

		// instantiate variables
		// cX, cY = current X and Y position of mouse, updated by mousemove event
		// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
		var cX, cY, pX, pY;

		// A private function for getting mouse position
		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		// A private function for comparing current and previous mouse position
		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			// compare mouse positions to see if they've crossed the threshold
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$(ob).unbind("mousemove",track);
				// set hoverIntent state to true (so mouseOut can be called)
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				// set previous coordinates for next time
				pX = cX; pY = cY;
				// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		// A private function for delaying the mouseOut function
		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		// A private function for handling mouse 'hovering'
		var handleHover = function(e) {
			// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
			var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
			while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
			if ( p == this ) { return false; }

			// copy objects to be passed into t (required for event object to be passed in IE)
			var ev = jQuery.extend({},e);
			var ob = this;

			// cancel hoverIntent timer if it exists
			if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

			// else e.type == "onmouseover"
			if (e.type == "mouseover") {
				// set "previous" X and Y position based on initial entry point
				pX = ev.pageX; pY = ev.pageY;
				// update "current" X and Y position based on mousemove
				$(ob).bind("mousemove",track);
				// start polling interval (self-calling timeout) to compare mouse coordinates over time
				if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

			// else e.type == "onmouseout"
			} else {
				// unbind expensive mousemove event
				$(ob).unbind("mousemove",track);
				// if hoverIntent state is true, then call the mouseOut function after the specified delay
				if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
			}
		};

		// bind the function to the two event listeners
		return this.mouseover(handleHover).mouseout(handleHover);
	};
	
})(jQuery);




