var base_url="/";
var base_static="http://www.nevasport.com/";
var mobile_client = false;
if(typeof(mobile) == "undefined"){
	var mobile = false;	
}


function rawurlencode (str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Michael Grier
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Joris
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // %          note 1: This reflects PHP 5.3/6.0+ behavior
    // %        note 2: Please be aware that this function expects to encode into UTF-8 encoded strings, as found on
    // %        note 2: pages served as UTF-8
    // *     example 1: rawurlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin%20van%20Zonneveld%21'
    // *     example 2: rawurlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: rawurlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
    str = (str + '').toString();
	
	return str.replace(/\+/g, 'AND ').replace(/(?!\S)-/g, 'NOT ');


    // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
    // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
    replace(/\)/g, '%29').replace(/\*/g, '%2A');
}



$(document).ready(function(){

	/* ************************************************* */
	/* FUNCIONES PARA PERFILES */
	/* ************************************************* */
	
	$(".add_amigo").click(function(event){
		add_amigo($(this),"add_amigo");
		event.preventDefault();
	});
	$(".del_amigo").click(function(event){
		add_amigo($(this),"del_amigo");
		event.preventDefault();
	});
	
	$("a.cambiar_estado").click(function(event){
		var self = $(this);
		$( "#form-estado" ).dialog( "open" );
		event.preventDefault();
	});
	$("a.cambiar_skifreak").click(function(event){
		var self = $(this);
		$( "#form-skifreak" ).dialog( "open" );
		event.preventDefault();
	});
	
	$("ul.listado_estaciones li .eliminar").click(function(event){
		var self = $(this);
		event.preventDefault();
		if(confirm("Eliminar estación?")){
			$.get("procesador.php",{
				funcion: "eliminar_mi_estacion",
				id:self.attr("rel")
			},function(data){
				var lista = self.parent().parent();
				self.parent().remove();
				if(lista.find("li").length==0){
					$("h3#titulo_"+lista.attr("id")).remove();
					lista.remove();	
				}
			});
		}
	});
	
	$("#nueva_estacion #paises").change(function(){
		var self = $(this);
		var listado_estaciones = $("#nueva_estacion #estaciones");
		listado_estaciones.empty();
		$.getJSON("procesador.php",{
			funcion: "listado_estaciones",
			id:self.val()
		},function(data){
			for(var i=0;i<data.length;i++){
//				console.log(data[i]);
				$('<option value="'+data[i].id+'">'+data[i].nombre+'</option>').appendTo(listado_estaciones);	
			}
		});
	});
	
	$("#nueva_estacion #asignar_estacion").click(function(){
		if($("#nueva_estacion #estaciones option").length==0){
			alert("Debes seleccionar un país y una estación!");
			return 0;	
		}
		var id_estacion = $("#nueva_estacion #estaciones").val();
		$.getJSON("procesador.php",{
			funcion: "add_mi_estacion",
			id:id_estacion
		},function(data){
//			console.log(data);
			var listado_paises = $("ul#estaciones_"+$("#paises option:selected").text());
			if(listado_paises.length==0){
				$('<h3 class="titulo_pais" id="titulo_estaciones_'+$("#paises option:selected").text()+'"><img alt="'+$("#paises option:selected").text()+'" src="/classic/banderas/'+$("#paises option:selected").attr("rel")+'"> '+$("#paises option:selected").text()+'</h3>').appendTo($(".actividadNevalog"));
				$('<ul id="estaciones_'+$("#paises option:selected").text()+'" class="listado_estaciones"></ul>').appendTo($(".actividadNevalog"));
				
				listado_paises = $("ul#estaciones_"+$("#paises option:selected").text());
			}
			
			$('<li><div><a rel="e:'+id_estacion+'" class="tooltip" href="/classic/estaciones-foreros/'+data.titulo+'/'+id_estacion+'"><img alt="'+data.titulo+'" src="/classic/resorts/'+data.logo+'"><span>'+data.titulo+'</span></a></div><img title="Eliminar estación" rel="'+id_estacion+'" src="/nevamedia/imagenes/delete-icon.png" class="eliminar"></li>').appendTo(listado_paises);	
			
			$("ul.listado_estaciones li .eliminar[rel="+id_estacion+"]").click(function(event){
				var self = $(this);
				event.preventDefault();
				if(confirm("Eliminar estación?")){
					$.get("procesador.php",{
						funcion: "eliminar_mi_estacion",
						id:self.attr("rel")
					},function(data){
						var lista = self.parent().parent();
						self.parent().remove();
						if(lista.find("li").length==0){
							$("h3#titulo_"+lista.attr("id")).remove();
							lista.remove();	
						}
					});
				}
			});
			
			$("#nueva_estacion #estaciones").empty();
			$("#nueva_estacion #paises").val(0);
			
		});
	});
	
	/* ************************************************* */
	/* FUNCIONES GLOBALES */
	/* ************************************************* */
	
	//OVERLIBS PARA LA INFORMACIÓN DE VISITAS,COMENTARIOS,FOTOS Y VIDEOS
	if(mobile!=true){

		
		if(typeof($.tipsy)!="undefined"){
			$('.n_comentarios').tipsy({gravity: 'n',title:'rel'});
			$('.n_visitas,.n_fotos,.n_videos').tipsy({gravity: 'n',title:'rel'});
			$('.over').tipsy({gravity: 'n',title:'rel'});
			$('#navBar .over').tipsy({gravity: 'n',title:'rel'});
		}
		
		
//		$(".n_visitas,.n_fotos,.n_videos").mouseover(function(){
//			$.cursorMessage($(this).find("span").attr("rel"),{hideTimeout:0});
//		}).mouseout(function(){$.hideCursorMessage();});
		
		
		
		
/*		
		$(".over").mouseover(function(){
			$.cursorMessage($(this).attr("rel"),{hideTimeout:0});
		}).mouseout(function(){$.hideCursorMessage();});
*/

		
		$('.tooltip').live('mouseenter mouseleave', tooltip.action);
	}
	
	$("#enviar_a_un_amigo").click(function(event){
		event.preventDefault();	
		$("#form-envia-amigo").dialog("open");
	});
	
	$("#contactar_editor, a[href=#contactar_editor]").click(function(event){
		event.preventDefault();	
		$("#form-contacto-editor").dialog("open");
	});
	
	$("#form_buscador input:button#buscar").click(function(event){
		event.preventDefault();
		buscar();	
	});
	$('#form_buscador #q').bind('keypress', function(event) {
		var code = (event.keyCode ? event.keyCode : event.which);
		if(code == 13) { //Tecla intro
			event.preventDefault();
		    buscar();
		}
	});
	if($("#bloque_resultados_seccion").length>0){
		$("ul.tabs a").click(function(event){
			event.preventDefault();
			$("ul.tabs a").removeClass("selected");
			var self = $(this);
			self.addClass("selected");
			$("div[id^=bloque_]").hide();
			$("#bloque_"+self.attr("rel")).show();
			$.get("procesador.php",{funcion:"vista_busqueda",valor:self.attr("rel")},function(data){return true;});
		});
	}
	if($("#form_newsletter").length>0){
		$("#form_newsletter input:submit").click(function(event){
			event.preventDefault();	
			var campo_email = $("#form_newsletter input[name=email]");
			if(campo_email.val()==""){
				alert("Debes introducir un email!");
			}
			$.get("procesador.php",{
				funcion:"suscribir_newsletter",
				email:campo_email.val()	
			},
			function(data){
				if(data=="OK"){
					alert("Gracias por suscribirte. En breves recibirás un email para confirmar la suscripción!");	
					campo_email.val("");
				}
				else if(data=="REPETIDO"){
					alert("El email introducido ya se encuentra suscrito!");
				}
			});
		});	
		
	}
	

	/* ************************************************* */
	/* VENTANAS DE JQUERY UI */
	/* ************************************************* */
	
	if($("#form-denuncia").length>0){
		$("#form-denuncia").dialog({
			autoOpen: false,
			height: 400,
			width: 400,
			modal: true,
			buttons: {
				"Enviar denuncia": function() {
						enviar_denuncia();
						$( this ).dialog( "close" );
				},
				Cancelar: function() {
					$( this ).dialog( "close" );
				}
			},
			close: function() {
				
			}
		});	
	}
	if($("#form-estado").length>0){
		$("#form-estado").dialog({
			autoOpen: false,
			height: 400,
			width: 400,
			modal: true,
			buttons: {
				"Guardar": function() {
						guardar_estado();
						$( this ).dialog( "close" );
				},
				Cancelar: function() {
					$( this ).dialog( "close" );
				}
			},
			close: function() {
				$("#nuevo_estado").val("");
			}
		});	
	}
	if($("#form-skifreak").length>0){
		$("#form-skifreak").dialog({
			autoOpen: false,
			height: 400,
			width: 400,
			modal: true,
			buttons: {
				"Guardar": function() {
						guardar_skifreak();
						$( this ).dialog( "close" );
				},
				Cancelar: function() {
					$( this ).dialog( "close" );
				}
			},
			close: function() {
//				$("#form-skifreak input:checkbox").attr('checked',false);
			}
		});	
	}
	if($("#form-editacomentarios").length>0){
		$("#form-editacomentarios").dialog({
			autoOpen: false,
			height: 400,
			width: 400,
			modal: true,
			buttons: {
				"Guardar": function() {
						editar_comentario();
						$( this ).dialog( "close" );
				},
				Cancelar: function() {
					$( this ).dialog( "close" );
				}
			},
			close: function() {
			}
		});	
	}
	
	if($("#form-envia-amigo").length>0){
		$("#form-envia-amigo").dialog({
			autoOpen: false,
			height: 400,
			width: 400,
			modal: true,
			buttons: {
				"Enviar": function() {
						enviar_a_amigo();
						$( this ).dialog( "close" );
				},
				Cancelar: function() {
					$( this ).dialog( "close" );
				}
			},
			close: function() {
			}
		});	
	}
	
	if($("#form-contacto-editor").length>0){
		$("#form-contacto-editor").dialog({
			autoOpen: false,
			height: 400,
			width: 400,
			modal: true,
			buttons: {
				"Enviar": function() {
						contacta_editor();
						$( this ).dialog( "close" );
				},
				Cancelar: function() {
					$( this ).dialog( "close" );
				}
			},
			close: function() {
			}
		});	
	}
	
	if($("input.fecha").length>0){
		
		jQuery(function($){
			$.datepicker.regional['es'] = {
				closeText: 'Cerrar',
				prevText: '&#x3c;Ant',
				nextText: 'Sig&#x3e;',
				currentText: 'Hoy',
				monthNames: ['Enero','Febrero','Marzo','Abril','Mayo','Junio',
				'Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'],
				monthNamesShort: ['Ene','Feb','Mar','Abr','May','Jun',
				'Jul','Ago','Sep','Oct','Nov','Dic'],
				dayNames: ['Domingo','Lunes','Martes','Mi&eacute;rcoles','Jueves','Viernes','S&aacute;bado'],
				dayNamesShort: ['Dom','Lun','Mar','Mi&eacute;','Juv','Vie','S&aacute;b'],
				dayNamesMin: ['Do','Lu','Ma','Mi','Ju','Vi','S&aacute;'],
				weekHeader: 'Sm',
				dateFormat: 'dd/mm/yy',
				firstDay: 1,
				isRTL: false,
				showMonthAfterYear: false,
				yearSuffix: ''};
			$.datepicker.setDefaults($.datepicker.regional['es']);
		});
		
		
		$("input.fecha").datepicker({numberOfMonths: 1, showButtonPanel: true, showOn: 'both', buttonImage: 'imagenes/calendario.jpg', buttonImageOnly: true });
	}
	
	
	
	$("#buscador_mobile").click(function(event){
		event.preventDefault();
		$(".buscador table").css("display","block");
		var altura = $("body").height();
		var anchura = $("body").width();
		$('<div class="jx-mask"></div>').width(anchura).height(altura).appendTo("body");
		$("#q").focus();
	});
	$("#cancelar-busqueda").click(function(event){
		event.preventDefault();
		$(".buscador table").css("display","none");
		$('.jx-mask').remove();
	});
	$("#despliega_desplegable").click(function(event){
		event.preventDefault();
		if($("#despliega_desplegable").hasClass("selected")){
			$("#lista_desplegable").hide();
			$("#despliega_desplegable").removeClass("selected");
		}
		else{
			$("#lista_desplegable").show();
			$("#despliega_desplegable").addClass("selected");
		}
	});	
	$("#despliega_filtros").click(function(event){
		event.preventDefault();
		if($("#despliega_filtros").hasClass("selected")){
			$(".lista_filtros").hide();
			$("#despliega_filtros").removeClass("selected");
		}
		else{
			$(".lista_filtros").show();
			$("#despliega_filtros").addClass("selected");
		}
	});	
	$("#despliega_submenu").click(function(event){
		event.preventDefault();
		if($("#despliega_submenu").hasClass("selected")){
			$("#desplegable_submenu").hide();
			$("#despliega_submenu").removeClass("selected");
		}
		else{
			$("#desplegable_submenu").show();
			$("#despliega_submenu").addClass("selected");
		}
	});	
	
	$("#cambiar_version_web").click(function(event){
		event.preventDefault();
		
		$.get("procesador.php",{
			funcion:"cambiar_version_web"
		},
		function(data){
			if(data=="OK"){
				location.reload();
			}
		});
	});	
	
	if(typeof($.fn.cycle)!="undefined"){
		$('#slideshow').cycle({ 
			fx:     'fade', 
			timeout: 4000, 
			next:   '#slideshow', 
			pause:   1 
		});
	}
	
	
});


/* ************************************************* */
/* FUNCIONES VARIAS */
/* ************************************************* */

function guardar_estado(){
	var nuevo_estado = $("#nuevo_estado").val();
	$.get("procesador.php",{
		funcion: "cambiar_estado",
		estado: nuevo_estado
	},function(data){
		$("span#estado").html(nuevo_estado);
	});		
}
function guardar_skifreak(){
	$.get("procesador.php",
	$("#form_chapas").serialize()
	,function(data){
		$(".datos p.options").html(data);
	});		
}

function add_amigo(self,accion){
		$.get("procesador.php",{
			funcion: accion,
			id:self.attr("rel")
		},function(data){
			if(accion=="add_amigo"){
				var ide = self.attr("rel");
				self.remove();
				$('<a rel="'+ide+'" class="boton del_amigo" href="#"><span class="icono-seguir">Dejar de seguir</span></a>').click(function(event){add_amigo($(this),"del_amigo");event.preventDefault();}).prependTo($(".datos .options"));
			}
			else{
				var ide = self.attr("rel");
				self.remove();
				$('<a rel="'+ide+'" class="boton add_amigo" href="#"><span class="icono-seguir">Volver a seguir</span></a>').click(function(event){add_amigo($(this),"add_amigo");event.preventDefault();}).prependTo($(".datos .options"));
			}
		});	
}

function usuario_no_registrado(user){
	$("<div id='capa_opaca'></div>").appendTo("body");
	$("<div id='capa_over'><p>El usuario <b>"+user+"</b> no está registrado en Nevasport.</p><p><a href='javascript:history.back();'>Volver</a></div>").appendTo("body");
}

function usuario_desactivado(user){
	$("<div id='capa_opaca'></div>").appendTo("body");
	$("<div id='capa_over'><p>El usuario <b>"+user+"</b> ha sido desactivado.</p><p><a href='javascript:history.back();'>Volver</a></div>").appendTo("body");
}

function enviar_a_amigo(){
	$.get("procesador.php",
	$("#form-envia-amigo form").serialize()
	,function(data){
		alert(data);
	});
}

function contacta_editor(){
	$.get("procesador.php",
	$("#form-contacto-editor form").serialize()
	,function(data){
		alert(data);
		$("#form-contacto-editor #email, #form-contacto-editor #comentario").val("");
	});
}

function buscar(){
	if($("#form_buscador #seccion_busqueda").val()=="viajes/"){
		document.location.href="/"+$("#form_buscador #seccion_busqueda").val()+"lista-ofertas.php?tab=2&search="+$("#form_buscador #q").val();
	}
	else{
		document.location.href="/"+$("#form_buscador #seccion_busqueda").val()+"busqueda/"+rawurlencode($("#form_buscador #q").val())+"/";
	}
}


/**************************************
Tooltips functions
***************************************/
/**
  Stronglky modified, onky works with DOM2 compatible browsers.
	Ricardo Galli
  From http://ljouanneau.com/softs/javascript/tooltip.php
  
    Little Modifications by Imanol Gorosabel www.berein.com
  
 */

// create the tooltip object
function tooltip(){}

// setup properties of tooltip object
tooltip.offsetx = 5;
tooltip.reverse = false;
tooltip.offsety = 5;
tooltip.box = null;
tooltip.timer = null;
tooltip.active = false;

tooltip.init = function (event) {
	if (tooltip.box == null) {
		tooltip.box = $("<div>").attr({ id: 'tooltip-text' });
		$('body').append( tooltip.box );
	}
	if (tooltip.timer || tooltip.active) tooltip.hide();
	tooltip.active = true;

	$(document).bind('mousemove.tooltip', tooltip.mouseMove);
	if (tooltip.box.outerWidth() > 0 && event.pageX  > $(window).width() * 0.55) tooltip.reverse = true;
	else tooltip.reverse = false;
}

tooltip.show = function (text) {
	tooltip.box.html(text).show();
	return false;
}

tooltip.hide = function () {
	if (tooltip.box == null) {
		tooltip.box = $("<div>").attr({ id: 'tooltip-text' });
		$('body').append( tooltip.box );
	}
	if (tooltip.timer != null) {
		clearTimeout(tooltip.timer);
		tooltip.timer = null;
	}
	$(document).unbind('mousemove.tooltip');
	tooltip.active = false;
	tooltip.box.hide().html('');
}

// Moves the tooltip element
tooltip.mouseMove = function (e) {
	if (tooltip.reverse) xL = e.pageX - (tooltip.box.outerWidth() + tooltip.offsetx);
	else xL = e.pageX + tooltip.offsetx;
	yL = e.pageY + tooltip.offsety;
	tooltip.box.css({left: xL +"px", top: yL +"px"});
}

tooltip.ajax_request = function(event, script, id) {
	tooltip.timer = null;
	var url = base_url + 'procesador.php?funcion='+script+'&dato='+id;
	tooltip.show('');
	$.ajax({
		url: url,
		dataType: "html",
		success: function(html) {
			if (tooltip.active) tooltip.show(html);
//			reportAjaxStats('tooltip', script);
		}
    });
}

tooltip.action = function (event) {
	if (event.type == 'mouseenter') {
		try {
			args = $(this).attr('rel').split(':');
			key = args[0];
			value = args[1];
		}
		catch (e) {
			tooltip.hide();
			return;
		}
		if (key == 'u') ajax = 'get_user_info';
		if (key == 'e') ajax = 'get_classic_info';
		if (key == 'c') ajax = 'get_comentario_info';

		tooltip.init(event);
		tooltip.timer = setTimeout(function() {tooltip.ajax_request(event, ajax, value)}, 300);
	} else if (event.type == 'mouseleave') {
		tooltip.hide();
	}
}
