/**
 * Gestiona el javascript de *.vapaya.com
 * @namespace VAPAYA
 * @author Daniel Cortés Hoyos (daniel@vapaya.com)
 */

var VAPAYA = {
	/**
	 * Gestiona la generación, borrado y recuperación de cookies
	 * @class
	 */
	cookies: {
		/**
		 * Genera una cookie con el nombre y el contenido deseados. El dominio, el path y la fecha de expiración
		 * son de sólo lectura.
		 * Si no se establece el valor, borra la cookie
		 * @param {String} name
		 * @param {String} value
		 * @type function		 
		 */
		escribirCookie: function (nombre, contenido) {
			var fecha, expira, path, dominio;
			//////////
			if (contenido === null) {
				contenido = '';
				fecha = new Date();
				fecha.setTime(fecha.getTime() - 86400000); // hace 24 horas
			} else {
				fecha = VAPAYA.fecha;
			}
			expira = '; expires=' + fecha.toUTCString();
			path = '; path=/';
			dominio = '; domain=.vapaya.com';
			document.cookie = [nombre, '=', encodeURIComponent(contenido), expira, path, dominio].join('');
		},
		/**
		 * Recupera el contenido de una cookie
		 * @param {string} nombre
		 * @type function 		 
		 */
		leerCookie: function (nombre) {
			var i, cookie,
				cookies = document.cookie.split(';'),
				max = cookies.length,
				cookieValue = null;
			//////////
			if (document.cookie && document.cookie !== '') {
				for (i = 0; i < max; i += 1) {
					cookie = $.trim(cookies[i]);
					if (cookie.substring(0, nombre.length + 1) === (nombre + '=')) {
						cookieValue = decodeURIComponent(cookie.substring(nombre.length + 1));
						break;
					}
				}
			}
			return cookieValue;
		}
	},
	/**
	 * Impide que un evento se propague en el DOM
	 * @class
	 */
	detenerEvento: function (e) {
		if (e.preventDefault) {
			e.preventDefault();
		}
		if (e.stopPropagation) {
			e.stopPropagation();
		}
		e.cancelBubble = true;
		e.returnValue = false;
	},
	/**
	 * Se ejecuta al cerrar el popup. Lo destruye y limpia el inner html
	 */
	cerrarDialog: function () {
		$('#dialog').dialog('destroy').html('<p class="loading">' + vapayaTexts.cargando + '</p>');
	},
	configurarPantallaCompletaDialog: function () {
		var isMaximizable = $('#dialog').dialog("option", "maximize") === true ? true : false;
		//////////
		if (isMaximizable) {
			$('<a href="#"/>').addClass("ui-dialog-titlebar-maximize").attr("role", "button")
				.append($("<span/>")
				.addClass("ui-icon ui-icon-max"))
				.insertAfter($(".ui-dialog-titlebar-close"))
				.click(function () {
					//////////			 
					var center,
						dialog = $('#dialog');
					//////////
					if (dialog.hasClass("fullscreen")) {
						$('#wrap').css('display', 'block');
						dialog.dialog({
							width: 800,
							height: 540
						}).dialog("option", "position", ['center', 50])
							.removeClass('fullscreen');
					} else {
						$('#wrap').css('display', 'none');
						dialog.dialog({
							width: $(window).width() - 20,
							height: $(window).height() - 20
						}).dialog("option", "position", ['center', 0])
							.addClass('fullscreen');
					}
					center = VAPAYA.direccionBusqueda.mapas.map.getCenter();
					google.maps.event.trigger(VAPAYA.direccionBusqueda.mapas.map, 'resize');
					VAPAYA.direccionBusqueda.mapas.map.setCenter(center);
			});
		}
	},
	/**
	 * Almacena el nombre de la página actual (por ahora sólo si es la página de resultados). Se autoinicia.
	 * @type function
	 */
	paginaActual: (function () {
		return location.href.indexOf('/resultados/') !== -1 ? 'results' : '';
	}()),
	/**
	 * Almacena si el navegador admite geolocalización. Se autoinicia
	 * @type function
	 */
	navegadorAdmiteGeolocalizacion: (function () {
		if (navigator.geolocation) {
			return true;
		} else {
			return false;
		}
	}()),
	/**
	 * Almacena la fecha de expiracion de las cookies. Se establece en init
	 * @type date
	 */
	fecha: new Date(),
	/**
	 * Almacena el código de pais actual
	 * @type string
	 */
	pais: {
		codigoPais: '',
		geodata: {
			coords: '',
			viewport: ''
		}
	},
	/**
	 * Almacena la ciudad actual
	 * @type string
	 */
	ciudad: {
		codigoCiudad: '',
		geodata: {
			coords: '',
			viewport: ''
		}
	},
	/**
	 * Almacena el lenguage del navegador o el seleccionado por el usuario
	 * @type string
	 */
	idioma: '',	
	/**
	 * Inicia VAPAYA.fecha 
	 * Inicia VAPAYA.pais.codigoPais (desde cookie, google loader o filtro ip)
	 * Inicia VAPAYA.idioma (desde cookies o vapayaTexts - navegador)
 	 * Inicia VAPAYA.ciudad.codigoCiudad (desde google loader)
	 * Genera cookies 'country' (desde google loader o filtro ip) y 'lang' (desde vapayaTexts - navegador) si no las hay
	 * @type function
	*/
	iniciar: function () {
		var ciudad,
			pais = VAPAYA.cookies.leerCookie('country'),
			idioma = VAPAYA.cookies.leerCookie('lang');
		//////////
		
		VAPAYA.fecha.setTime(VAPAYA.fecha.getTime() + (30 * 24 * 60 * 60 * 1000)); //dentro de un mes
		if (pais === null) {
			if (google.loader.ClientLocation) {
				pais = google.loader.ClientLocation.address.country_code;
				VAPAYA.cookies.escribirCookie('country', pais);
				VAPAYA.pais.codigoPais = pais;
			} else {
				//si no está disponible desde google conseguimos el país de manera asincrona del filtro por ip
				$.ajax({
					type: "POST",
					url: "http://" + document.domain + "/web/misc/langswitch.php",
					data: "ajax_req=true",
					success: function (data) {
						VAPAYA.cookies.escribirCookie('country', data);
						VAPAYA.pais.codigoPais = data;
						//Hay que actualizar el campo nombrepais
						$('#nombrepais').text(vapayaTexts[data]);
					}
				});
			}
		} else {
			VAPAYA.pais.codigoPais = pais;
		}
		if (idioma === null) {
			VAPAYA.cookies.escribirCookie('lang', vapayaTexts.lang);
			VAPAYA.idioma = vapayaTexts.lang;
		} else {
			VAPAYA.idioma = idioma;
		}
		if (google.loader.ClientLocation) {
			if (VAPAYA.pais.codigoPais === google.loader.ClientLocation.address.country_code) {
				ciudad = google.loader.ClientLocation.address.city;
				VAPAYA.ciudad.codigoCiudad = ciudad;
			}
		}
	},
	/**
	 * Gestiona el apartado de palabras clave en el formulario de búsqueda
	 * @class
	 */
	palabrasClaveBusqueda: {
		/**
		 * Gestiona los botones de la ui de los keywords, a saber el boton lupa que abre el cuadro keywords.
		 * Y la interacción con el ratón y el teclado del campo de texto keywords.
		 */
		iniciar: function () {
			$('#lupa').click(function () {
				VAPAYA.palabrasClaveBusqueda.abreDialog();
			});
			$('#keywords').focus(function () {
				$('div#d_keywords').addClass("selected");			
			}).blur(function () {
				$('div#d_keywords').removeClass("selected");
			}).keypress( function (e) {
				VAPAYA.palabrasClaveBusqueda.palabrasClavePulsarTecla(e);
			}).keyup(function () {
				if (VAPAYA.paginaActual === 'results') {  
					VAPAYA.resultados.show_hide_search_button();
					VAPAYA.resultados.masopcionesdeordenar();
				}
			});
		},
		/**
		 * Abre el cuadro de dialogo de palabras clave
		 */
		abreDialog: function () {
			$("#dialog").dialog({
				autoOpen: true,
				maximize: false,
				modal: true,
				width: 400,
				height: 252,
				position: ['center', 50],
				title: vapayaTexts.keywords_tit,
				open: function () {
					VAPAYA.palabrasClaveBusqueda.controlarPalabrasClave();
				},
				close: function () {
					VAPAYA.cerrarDialog();
				},
				show: 'fade',
				hide: 'fade'
			});
		},
		/**
		 * Gestiona las keywords. Se ejecuta al abrir el popup
		 */
		controlarPalabrasClave: function () {
			var coords = encodeURIComponent($('#coords').val()),
				cats = encodeURIComponent($('#cats').val()),
				pais = encodeURIComponent($('#pais').val()),
				region = encodeURIComponent($('#region').val()),
				provincia = encodeURIComponent($('#provincia').val()),
				comarca = encodeURIComponent($('#comarca').val()),
				localidad = encodeURIComponent($('#localidad').val());
			//////////	
			$('#dialog').load('http://' + document.domain + 
				'/get-results/?action=ajax-keywords-search&coords=' + 
				coords + '&cats=' +
				cats + '&pais=' +
				pais + '&region=' +
				region + '&provincia' + 
				provincia + '&comarca' +
				comarca + '&localidad' +
				localidad, function (response, status) {
					if (status !== "error") {
						$('.keyword-in-cloud').click(function () {
							$('input#keywords').val($(this).text());
							$('#dialog').dialog('close');
						});
					} else {
						response = "<p align=center>" + vapayaTexts.conexerrortext + "</p>";
						$('#dialog').dialog('option', {
							title: vapayaTexts.conexerror
						}).html(response);
					}
				});
		},
		/**
		 * Envía el formulario de búsqueda al pulsar enter.
		 */
		palabrasClavePulsarTecla: function (e) {
			if (13 === e.keyCode) {
				VAPAYA.envioFormularioBusqueda.enviar();
				return false;
			}
			return true;
		}
	},
	/**
	 * Gestiona el apartado dirección del formulario de búsqueda
	 * @class
	 */
	direccionBusqueda: {
		iniciar : function () {
			VAPAYA.direccionBusqueda.gestorUI.iniciar();
			VAPAYA.direccionBusqueda.mapas.geocoder = new google.maps.Geocoder();
			VAPAYA.direccionBusqueda.paises.countriesInitialize();
		},
		/**
	 	 * Gestiona la interfaz del apartado: abrir mapa, geolocalizacion, click en campo de texto,
		 * recordar dirección, cambiar dirección
	 	 */
		gestorUI: {
			iniciar: function () {
				$('#marcarenmapa, #vermapa').live('click', function () {
					if ($('#cont_paises').is(':visible')) {
						$('.tt, .ta').toggle();
					}												 
					VAPAYA.direccionBusqueda.paises.paisesCargados = false;
					VAPAYA.direccionBusqueda.mapas.abreDialog();
					VAPAYA.configurarPantallaCompletaDialog();
					$('#mapa_user_dir').sugerir({ delay: 200, minchars: 4, src: 'mapa' });
				});
				if (VAPAYA.navegadorAdmiteGeolocalizacion) {
					$('#locateButton').live('click', function () {
						VAPAYA.direccionBusqueda.mapas.geoLocalizame();
					});
				} else {
					$('#locateButton').css('display', 'none');
				}
				$(window).resize(function () {
					var dialog = $('#dialog');
					//////////
					if (dialog.hasClass("fullscreen")) {
						dialog.dialog({
							width: $(window).width() - 20,
							height: $(window).height() - 20
						}).dialog("option", "position", ['center', 0]);
						google.maps.event.trigger(VAPAYA.direccionBusqueda.mapas.map, 'resize');	
					}
				});
				$('#user_dir').live('click', function (e) {
					VAPAYA.detenerEvento(e);
					if ($('#cont_paises').is(':visible')) {
						$('.tt, .ta').toggle();
					}
				}).focus(function () {
					$('div#user_dir_cont').addClass("selected");					
				}).blur(function () {
					$('div#user_dir_cont').removeClass("selected");
				});
	
				$('#recordar').live('click', function() {
					VAPAYA.direccionBusqueda.direccion.talVezRecordarDireccion();
				});
				
				$('#cambiar').live('click', function () {
					VAPAYA.direccionBusqueda.direccion.cambiardireccionClick();
				});
				
				$('#d_cambiar').live('click', function () {
					VAPAYA.direccionBusqueda.direccion.cambiarDireccionClickMapa();
				});
				
				//¿y si comprobamos la pagina actual en sugerir directamente?
				if (VAPAYA.paginaActual === 'results') {
					$('#user_dir').sugerir( { delay: 200, minchars: 4, src: 'results' } );
				} else {
					$('#user_dir').sugerir( { delay: 200, minchars: 4  } );
				}
			}
		},
		direccion: {
			bloqueDireccion: function () {
				if (VAPAYA.cookies.leerCookie('dir_cookie') !== null && VAPAYA.cookies.leerCookie('dir_cookie').indexOf('|*') !== -1) {
					var vars = VAPAYA.cookies.leerCookie('dir_cookie').split('|*'),
						direccion = vars[0],
						coords = vars[1],
						viewport = vars[2],
						pais = vars[3],
						region = vars[4],
						provincia = vars[5],
						comarca = vars[6],
						localidad = vars[7];
					return '<h1><label for="direccion">' + vapayaTexts.direccion + '</label></h1>'
						+ '<input name="coords" id="coords" type="hidden" value="' + coords + '" />'
						+ '<input name="viewport" id="viewport" type="hidden" value="' + viewport + '" />'
						+ '<input name="pais" id="pais" type="hidden" value="' + pais + '" />'
						+ '<input name="region" id="region" type="hidden" value="' + region + '" />'
						+ '<input name="provincia" id="provincia" type="hidden" value="' + provincia + '" />'
						+ '<input name="comarca" id="comarca" type="hidden" value="' + comarca + '" />'
						+ '<input name="localidad" id="localidad" type="hidden" value="' + localidad + '" />'
						+ '<input name="direccion" id="direccion" type="hidden" value="' + direccion + '" />'
						+ '<div id="dir_fija">'
						+ '<div>'
						+ '<span class="cont_icons"><a id="vermapa" href="javascript:;"></a></span>'
						+ '<span id="fdir">' + direccion + '</span>'
						+ '<a id="cambiar" href="javascript:;"></a>'
						+ '</div>'
						+ '<small>'
						+ '<span id="recordar" onclick="VAPAYA.ui.toggle_content_value(\'rem_address\', [[\'<span id=rec_img_on></span>' + vapayaTexts.rec_post + '\', \'1\'], [\'<span id=rec_img_off></span>' + vapayaTexts.n_rec_post + '\', \'0\']], undefined)">'
						+ '<span id="rec_img_on"></span>' + vapayaTexts.rec_post
						+ '</span>'
						+ '<input name="rem_address" id="rem_address" value="1" type="hidden" />'
						+ '<a class="b_avanzada" href="javascript:;">Búsqueda avanzada</a>'
						+ '</small>'
						+ '</div>'
						+ '<div id="dirs_cont"><div id="localizdiv" style="display: none;">'
						+ '<span id="ccc">Te mostramos direcciones de <span id="nombrepais">' + vapayaTexts[VAPAYA.pais.codigoPais] 
						+ '</span><a class="ta" id="mostrarlista" href="javascript:;">(cambiar pais)</a>'
						+ '<a class="ta" style="display: none;" id="cerrarlista" href="javascript:;">(cerrar lista)</a></span>'
						+ '<ul class="tt" id="ulresultados"></ul>'
						+ '<div id="cont_paises" class="tt loading" style="display: none;"></div>'
						+ '</div></div>';
				} else {
					return '<h1><label for="user_dir">' + vapayaTexts.direccion + '</label></h1>'
						+ '<input name="coords" id="coords" type="hidden" value="" />'
						+ '<input name="viewport" id="viewport" type="hidden" value="" />'
						+ '<input name="pais" id="pais" type="hidden" value="" />'
						+ '<input name="region" id="region" type="hidden" value="" />'
						+ '<input name="provincia" id="provincia" type="hidden" value="" />'
						+ '<input name="comarca" id="comarca" type="hidden" value="" />'
						+ '<input name="localidad" id="localidad" type="hidden" value="" />'
						+ '<input name="direccion" id="direccion" type="hidden" />'
						+ '<div id="user_dir_cont">'
						+ '<a id="locateButton" title="Mi ubicación" href="javascript:;"></a>'					
						+ '<a id="marcarenmapa" title="' + vapayaTexts.localizar + '" href="javascript:;" ></a>'
						+ '<input name="user_dir" id="user_dir" type="text" />'
						+ '<small>'
						+ '<a class="b_avanzada" href="javascript:;">Búsqueda avanzada</a>'
						+ '</small>'
						+ '</div>'
						+ '<div id="dirs_cont"><div id="localizdiv" style="display: none;">'
						+ '<span id="ccc">Te mostramos direcciones de <span id="nombrepais">' + vapayaTexts[VAPAYA.pais.codigoPais] 
						+ '</span><a class="ta" id="mostrarlista" href="javascript:;">(cambiar pais)</a>'
						+ '<a class="ta" style="display: none;" id="cerrarlista" href="javascript:;">(cerrar lista)</a></span>'
						+ '<ul class="tt" id="ulresultados"></ul>'
						+ '<div id="cont_paises" class="tt loading" style="display: none;"></div>'
						+ '</div></div>';
				}
			},
			bloqueDireccionMapa: function () {
				VAPAYA.localizdiv = $('#localizdiv').detach();
				if (VAPAYA.cookies.leerCookie('dir_cookie') !== null && VAPAYA.cookies.leerCookie('dir_cookie').indexOf('|*') !== -1) {
					var vars = VAPAYA.cookies.leerCookie('dir_cookie').split('|*'),
						direccion = vars[0],
						coords = vars[1],
						viewport = vars[2],
						pais = vars[3],
						region = vars[4],
						provincia = vars[5],
						comarca = vars[6],
						localidad = vars[7];
					return '<input name="mapa_coords" id="mapa_coords" type="hidden" value="' + coords + '" />'
						+ '<input name="mapa_viewport" id="mapa_viewport" type="hidden" value="' + viewport + '" />'
						+ '<input name="mapa_pais" id="mapa_pais" type="hidden" value="' + pais + '" />'
						+ '<input name="mapa_region" id="mapa_region" type="hidden" value="' + region + '" />'
						+ '<input name="mapa_provincia" id="mapa_provincia" type="hidden" value="' + provincia + '" />'
						+ '<input name="mapa_comarca" id="mapa_comarca" type="hidden" value="' + comarca + '" />'
						+ '<input name="mapa_localidad" id="mapa_localidad" type="hidden" value="' + localidad + '" />'
						+ '<input name="mapa_direccion" id="mapa_direccion" type="hidden" value="' + direccion + '" />'
						+ '<div id="mapa_dir_fija">'
						+ '<div>'
						+ '<span id="mapa_fdir">' + direccion + '</span>'
						+ '<a id="d_cambiar" href="javascript:;">Cambiar</a>'
						+ '</div>'
						+ '</div>'
						+ '<div id="mapa_dirs_cont"><div id="localizdiv" style="display: none;">'
						+ '<span id="ccc">Te mostramos direcciones de <span id="nombrepais">' + vapayaTexts[VAPAYA.pais.codigoPais] 
						+ '</span><a class="ta" id="mostrarlista" href="javascript:;">(cambiar pais)</a>'
						+ '<a class="ta" style="display: none;" id="cerrarlista" href="javascript:;">(cerrar lista)</a></span>'
						+ '<ul class="tt" id="ulresultados"></ul>'
						+ '<div id="cont_paises" class="tt loading" style="display: none;"></div>'
						+ '</div></div>';
				} else {
					return '<input name="mapa_coords" id="mapa_coords" type="hidden" value="" />'
						+ '<input name="mapa_viewport" id="mapa_viewport" type="hidden" value="" />'
						+ '<input name="mapa_pais" id="mapa_pais" type="hidden" value="" />'
						+ '<input name="mapa_region" id="mapa_region" type="hidden" value="" />'
						+ '<input name="mapa_provincia" id="mapa_provincia" type="hidden" value="" />'
						+ '<input name="mapa_comarca" id="mapa_comarca" type="hidden" value="" />'
						+ '<input name="mapa_localidad" id="mapa_localidad" type="hidden" value="" />'
						+ '<input name="mapa_direccion" id="mapa_direccion" type="hidden" />'
						+ '<div id="mapa_user_dir_cont">'
						+ '<input name="mapa_user_dir" id="mapa_user_dir" type="text" />'
						+ '</div>'
						+ '<div id="mapa_dirs_cont"><div id="localizdiv" style="display: none;">'
						+ '<span id="ccc">Te mostramos direcciones de <span id="nombrepais">' + vapayaTexts[VAPAYA.pais.codigoPais] 
						+ '</span><a class="ta" id="mostrarlista" href="javascript:;">(cambiar pais)</a>'
						+ '<a class="ta" style="display: none;" id="cerrarlista" href="javascript:;">(cerrar lista)</a></span>'
						+ '<ul class="tt" id="ulresultados"></ul>'
						+ '<div id="cont_paises" class="tt loading" style="display: none;"></div>'
						+ '</div></div>';
				}
			},
			cambiardireccionClick: function () {
				var src = VAPAYA.paginaActual,
					input_cont = $('<div>').attr('id', 'user_dir_cont'),
					buttonA = $('<a>').attr('id', 'locateButton').attr('title', 'Mi ubicación').attr('href', 'javascript:;'),
					buttonB = $('<a>').attr('id', 'marcarenmapa').attr('title', vapayaTexts.localizar).attr('href', 'javascript:;'),
					input = $('<input type="text">').attr('autocomplete', 'off').attr('name', 'user_dir').attr('id', 'user_dir').attr('value', ''),
					small = $('<small>').append($('<a>').attr('class', 'b_avanzada').attr('href', 'javascript:;').text('Búsqueda avanzada')),
					dirfija = $('#dir_fija');
				//////////	
				buttonA.appendTo(input_cont);
				buttonB.appendTo(input_cont);
				input.appendTo(input_cont);
				if (src !== 'results') {
					small.appendTo(input_cont);
				}
				dirfija.replaceWith(input_cont);
				$('label[for="direccion"]').attr('for', 'user_dir'); 
				input.focus(function () {
					input_cont.addClass("selected");					
				}).blur(function () {
					input_cont.removeClass("selected");
				}).focus();
				$('a#locateButton').mouseleave(function() {
					$(this).addClass('mouseleave');
				}).mouseenter(function() {
					$(this).removeClass('mouseleave');
				});
				
				if (src === 'results') {
					input.sugerir({ delay: 200, minchars: 4, src: 'results' });
					VAPAYA.resultados.show_hide_search_button();
				} else {
					input.sugerir({ delay: 200, minchars: 4  });
				}
				
				
				VAPAYA.cookies.escribirCookie('dir_cookie', null);
				$('#direccion').val('');
				$('#coords').val('');
				$('#viewport').val('');	
				$('#pais').val('');
				$('#region').val('');	
				$('#provincia').val('');
				$('#comarca').val('');	
				$('#localidad').val('');		
			},
			cambiarDireccionClickMapa: function () {
				var input_cont = $('<div>').attr('id', 'mapa_user_dir_cont'),
					input = $('<input type="text">').attr('autocomplete', 'off').attr('name', 'mapa_user_dir').attr('id', 'mapa_user_dir').attr('value', ''),
					dirfija = $('#mapa_dir_fija');
				//////////	
				input.appendTo(input_cont);	
				dirfija.replaceWith(input_cont);
				input.focus(function () {
					input_cont.addClass("selected");					
				}).blur(function () {
					input_cont.removeClass("selected");
				}).focus();
				input.sugerir({ delay: 200, minchars: 4, src: 'mapa' });
				VAPAYA.cookies.escribirCookie('dir_cookie', null);
				$('#mapa_direccion').val('');
				$('#mapa_coords').val('');
				$('#mapa_viewport').val('');	
				$('#mapa_pais').val('');
				$('#mapa_region').val('');	
				$('#mapa_provincia').val('');
				$('#mapa_comarca').val('');	
				$('#mapa_localidad').val('');		
			},
			hacerFijaDireccion: function (currentResult) {
				var src = VAPAYA.paginaActual,
					fixeddirdiv = '<div id="dir_fija"><div><span class="cont_icons"><a id="vermapa" href="javascript:;"></a></span><span id="fdir">' + currentResult[0].text + '</span><a id="cambiar" href="javascript:;"></a></div>';
				//////////
				
				if (src === '') {
					fixeddirdiv += '<small><span id="recordar" onclick="VAPAYA.ui.toggle_content_value(\'rem_address\', [[\'<span id=rec_img_on></span>' + vapayaTexts.rec_post + '\', \'1\'], [\'<span id=rec_img_off></span>' + vapayaTexts.n_rec_post + '\', \'0\']], undefined)"><span id=rec_img_on></span>' + vapayaTexts.rec_post + '</span><input name="rem_address" id="rem_address" value="1" type="hidden" /><a class="b_avanzada" href="javascript:;">Búsqueda avanzada</a></small>';
				}
				fixeddirdiv += '</div>';
			
				if($('div#user_dir_cont').exists()) {
					$('div#user_dir_cont').replaceWith(fixeddirdiv);
				} else {
					$('div#dir_fija').replaceWith(fixeddirdiv);
				}
				
				$('#coords').val(currentResult[0].coords.toString().replace(/[\(\)]/g, ''));
				$('#viewport').val(currentResult[0].viewport.toString().replace(/[\(\)]/g, ''));					
				$('#direccion').val(currentResult[0].text);
				$('#pais').val(currentResult[0].pais);
				$('#region').val(currentResult[0].region);
				$('#provincia').val(currentResult[0].provincia);
				$('#comarca').val(currentResult[0].comarca);				
				$('#localidad').val(currentResult[0].localidad);								
			
				if (src === '') {
					VAPAYA.cookies.escribirCookie('dir_cookie', currentResult[0].text + '|*' + currentResult[0].coords + '|*' + currentResult[0].viewport + '|*' + currentResult[0].pais + '|*' + currentResult[0].region + '|*' + currentResult[0].provincia + '|*' + currentResult[0].comarca + '|*' + currentResult[0].localidad);
				} else {
					VAPAYA.resultados.show_hide_search_button();
				}
			},
			hacerFijaDireccionMapa: function (currentResult, movermapa) {
				var fixeddirdiv = '<div id="mapa_dir_fija"><div><span id="mapa_fdir">' + currentResult[0].text + '</span><a id="d_cambiar" href="javascript:;">Cambiar</a></div></div>';
				
				if($('div#mapa_user_dir_cont').exists()) {
					$('div#mapa_user_dir_cont').replaceWith(fixeddirdiv);
				} else {
					$('div#mapa_dir_fija').replaceWith(fixeddirdiv);
				}
				
				coords = currentResult[0].coords.toString().replace(/[\(\)]/g, '');
				viewport = currentResult[0].viewport.toString().replace(/[\(\)]/g, '');
				$('#mapa_coords').val(coords);
				$('#mapa_viewport').val(viewport);					
				$('#mapa_direccion').val(currentResult[0].text);
				$('#mapa_pais').val(currentResult[0].pais);
				$('#mapa_region').val(currentResult[0].region);
				$('#mapa_provincia').val(currentResult[0].provincia);
				$('#mapa_comarca').val(currentResult[0].comarca);				
				$('#mapa_localidad').val(currentResult[0].localidad);								

				if (movermapa == true) {
					coords = coords.split(',');
					lat = coords[0];
					lng = coords[1];
					point = new google.maps.LatLng(parseFloat(lat), parseFloat(lng));
					VAPAYA.direccionBusqueda.mapas.mostrarmarker = true;
					zoom = 18;
					
					viewport = viewport.split(',');
					lat1 = viewport[0];
					lng1 = viewport[1];
					lat2 = viewport[2];
					lng2 = viewport[3];
					southWest = new google.maps.LatLng(lat1, lng1);
					northEast = new google.maps.LatLng(lat2, lng2);
					viewport = new google.maps.LatLngBounds(southWest, northEast);
					VAPAYA.direccionBusqueda.mapas.movermapa(point, viewport);
				}
			},
			talVezRecordarDireccion: function () {
				if ($('#rem_address').val() === "1") {
					VAPAYA.cookies.escribirCookie('dir_cookie', $('#dir_fija >div >span#fdir').html() + '|*' + $('#coords').val() +  '|*' + $('#viewport').val() +'|*' + $('#pais').val() + '|*' + $('#region').val() + '|*' + $('#provincia').val() + '|*' + $('#comarca').val() + '|*' + $('#localidad').val());
				} else {
					VAPAYA.cookies.escribirCookie('dir_cookie', null);
				}
			},
			geocodificarPunto : function (evt) {
				var point, marker, query;
				//////////
				VAPAYA.direccionBusqueda.mapas.mostrarmarker = true;
				point = evt.latLng;
				VAPAYA.direccionBusqueda.mapas.dibujarMarker(point);
				query = {'latLng': point, 'language': vapayaTexts.lang};
				VAPAYA.direccionBusqueda.mapas.geocoder.geocode(query, VAPAYA.direccionBusqueda.direccion.mostarDireccionClickadaEnMapa);
			},
			mostarDireccionClickadaEnMapa : function (results, status) {
				var address, res, result, place, tipos, tipo, viewport,
					accepted_types = ['street_address', 'route', 'intersection', 'airport', 'park', 'point_of_interest', 'street_number', 'train_station', 'transit_station', 'establishment'];
				//////////
				if (!results || status !== google.maps.GeocoderStatus.OK) {
					return false;
				} else {
					res = [];
					result = {pais:'', region:'', provincia:'', comarca:'', localidad:''};
					if (results[0]) {
						place = results[0];
						tipos = place.types;
						for (a in tipos) {
							tipo = tipos[a];
							if ($.inArray(tipo, accepted_types) !== -1) {
								viewport = place.geometry.viewport;
								coords = place.geometry.location;					
								result.text	= place.formatted_address;
								result.coords = coords;
								result.viewport = viewport;
								for (z in place.address_components) {
									addressComponent = place.address_components[z];
									for (j in addressComponent.types) {
										componentType = addressComponent.types[j];
										switch (componentType) {
										case 'country':
											result.pais = addressComponent.short_name;
											break;
										case 'administrative_area_level_1':
											result.region = addressComponent.short_name;
											break;
										case 'administrative_area_level_2':
											result.provincia = addressComponent.short_name;
											break;
										case 'administrative_area_level_3':
											result.comarca = addressComponent.short_name;
											break;
										case 'locality':
											result.localidad = addressComponent.short_name;
											break;
										}
									}
								}
								break;
							}
						}
					}
					res.push(result);
					VAPAYA.direccionBusqueda.direccion.hacerFijaDireccionMapa(res, false);
					VAPAYA.direccionBusqueda.direccion.hacerFijaDireccion(res);
				}
			},
			mostrarDireccionEnCampoTexto: function (results, status) {
				alert("entra en mostrarDireccionEnCampoTexto");
				var address, res, result, place, tipos, tipo, viewport,
					accepted_types = ['street_address', 'route', 'intersection', 'airport', 'park', 'point_of_interest', 'street_number', 'train_station', 'transit_station', 'establishment'];
				//////////
				if (!results || status !== google.maps.GeocoderStatus.OK) {
					return false;
				} else {
					res = [];
					result = {pais:'', region:'', provincia:'', comarca:'', localidad:''};
					if (results[0]) {
						place = results[0];
						tipos = place.types;
						for (a in tipos) {
							tipo = tipos[a];
							if ($.inArray(tipo, accepted_types) !== -1) {
								viewport = place.geometry.viewport;
								coords = place.geometry.location;					
								result.text	= place.formatted_address;
								result.coords = coords;
								result.viewport = viewport;
								
								for (z in place.address_components) {
									addressComponent = place.address_components[z];
									for (j in addressComponent.types) {
										componentType = addressComponent.types[j];
										switch (componentType) {
										case 'country':
											result.pais = addressComponent.short_name;
											break;
										case 'administrative_area_level_1':
											result.region = addressComponent.short_name;
											break;
										case 'administrative_area_level_2':
											result.provincia = addressComponent.short_name;
											break;
										case 'administrative_area_level_3':
											result.comarca = addressComponent.short_name;
											break;
										case 'locality':
											result.localidad = addressComponent.short_name;
											break;
										}
									}
								}
								break;
							}
						}
					}
					res.push(result);
					VAPAYA.direccionBusqueda.direccion.hacerFijaDireccion(res);
				}
			}
		},
		mapas: {
			viewport: '',
			center: '',		
			mostrarmarker: false,
			geocoder: null,
			map: null,
			markersArray : [],
			abreDialog: function () {
				$("#dialog").dialog({
					autoOpen: true,
					maximize: true,
					modal: true,
					width: 800,
					height: 540,
					closeText: vapayaTexts.cerrar,
					position: ['center', 50],
					title: vapayaTexts.marcadireccion,
					open: function () {
						VAPAYA.direccionBusqueda.mapas.prepararDialogMapa();
					},
					close: function () {
						VAPAYA.cerrarDialog();
						VAPAYA.direccionBusqueda.mapas.cerrarMarcarEnMapa();
					},
					show: 'fade',
					hide: 'fade'
				});
			},
			/*
			 * En primer lugar prepara el html del dialog para albergar el mapa
			 * Da valor a viewport y center
			 * También a ciudad
			 */
			prepararDialogMapa: function () {
				$('#dialog').html('<div id="wrap_buscador"></div><div id="mapa"></div>');
				VAPAYA.direccionBusqueda.mapas.viewport = VAPAYA.direccionBusqueda.mapas.mapGetBounds($('#viewport').val());
				VAPAYA.direccionBusqueda.mapas.center = VAPAYA.direccionBusqueda.mapas.mapGetCenter($('#coords').val());
				
				// lA LOCALIZACION NOS VIENE DE LOS INPUTS
				if (VAPAYA.direccionBusqueda.mapas.viewport !== '' || VAPAYA.direccionBusqueda.mapas.center !== '') {
					VAPAYA.direccionBusqueda.mapas.mostrarmarker = true;
				// LA LOCALIZACION NOS VIENE DEL PAIS O CIUDAD	
				} else {
					// el campo dirección está en blanco, vamos a adivinar que mapa tenemos que mostrarle
					VAPAYA.direccionBusqueda.mapas.mostrarmarker = false;
					if (VAPAYA.ciudad.codigoCiudad !== '' && VAPAYA.pais.codigoPais !== '') {
						VAPAYA.direccionBusqueda.mapas.viewport = VAPAYA.ciudad.geodata.viewport;
						VAPAYA.direccionBusqueda.mapas.center = VAPAYA.ciudad.geodata.coords;
					} else if (VAPAYA.pais.codigoPais !== '') {
						VAPAYA.direccionBusqueda.mapas.viewport = VAPAYA.pais.geodata.viewport;
						VAPAYA.direccionBusqueda.mapas.center = VAPAYA.pais.geodata.coords;
					}
				}
				VAPAYA.direccionBusqueda.mapas.mostrarMapa();
			},
			dibujarMarker: function (point) {
				VAPAYA.direccionBusqueda.mapas.mapClearOverlays();
				if (VAPAYA.direccionBusqueda.mapas.mostrarmarker === true) {
					marker = new google.maps.Marker({ position: point, map: VAPAYA.direccionBusqueda.mapas.map });
					VAPAYA.direccionBusqueda.mapas.markersArray.push(marker);
				}
			},
			cerrarMarcarEnMapa: function () {
				VAPAYA.direccionBusqueda.paises.paisesCargados = false;
				$('#localizdiv').detach();
				VAPAYA.localizdiv.appendTo('#dirs_cont');
				VAPAYA.localizdiv = null;
				$('#nombrepais').text(vapayaTexts[VAPAYA.pais.codigoPais]);
				$('#cont_paises').html('');				
			},
			mapGetBounds: function (str) {
				var viewport, lat1, lng1, lat2, lng2, southWest, northEast, bounds;
				//////////	
				if (str === '') {
					return '';
				}
				viewport = str.split(',');
				lat1 = $.trim(viewport[0]);
				lng1 = $.trim(viewport[1]);
				lat2 = $.trim(viewport[2]);
				lng2 = $.trim(viewport[3]);
				southWest = new google.maps.LatLng(lat1, lng1);
				northEast = new google.maps.LatLng(lat2, lng2);
				bounds = new google.maps.LatLngBounds(southWest, northEast);
				return bounds; 
			},
			mapGetCenter: function (str) {
				var coords, lat, lng, point;
				//////////
				if (str === '') {
					return '';
				}
				coords = str.split(', ');
				lat = coords[0];
				lng = coords[1];
				point = new google.maps.LatLng(parseFloat(lat), parseFloat(lng));
				return point;
			},
			mapGeocode: function (query, quetipo, callback) {
				VAPAYA.direccionBusqueda.mapas.geocoder.geocode(query, function (response, status) {
					var x, place, tipos, a,	tipo, viewport, coords;
					//////////	
					if (!response || status !== google.maps.GeocoderStatus.OK) {
						//no hemos podido ubicarle
						coords = null;
					} else {
						for (x in response) {
							if (response.hasOwnProperty(x)) {
								place = response[x];
								tipos = place.types;
								for (a in tipos) {
									if (tipos.hasOwnProperty(a)) {
										tipo = tipos[a];
										if (tipo === quetipo) {
											viewport = place.geometry.viewport;
											coords = place.geometry.location;
											break;
										}
									}
								}
								if (coords !== '') {
									break;
								}
							}
						}
					}
					callback ({'coords': coords, 'viewport': viewport });
					/*if($('#mapa').is(':visible')) {
						VAPAYA.direccionBusqueda.mapas.viewport = viewport;
						VAPAYA.direccionBusqueda.mapas.center = coords;
						VAPAYA.direccionBusqueda.mapas.mostrarMapa();
					}*/
				});
				
			},
			mostrarMapa: function () {
				var point, marker, zoom;
				//////////
				VAPAYA.direccionBusqueda.mapas.map = new google.maps.Map(document.getElementById("mapa"), { 
					mapTypeId: google.maps.MapTypeId.ROADMAP,
					disableDefaultUI: true,
					navigationControl: true,
					navigationControlOptions: {
						style: google.maps.NavigationControlStyle.SMALL
					},
					scaleControl: true,
					disableDoubleClickZoom: true,
					scrollwheel: false
				});
				point = VAPAYA.direccionBusqueda.mapas.center;
				if (VAPAYA.direccionBusqueda.mapas.viewport) {
					VAPAYA.direccionBusqueda.mapas.map.fitBounds(VAPAYA.direccionBusqueda.mapas.viewport);
					zoomChangeBoundsListener = google.maps.event.addListener(VAPAYA.direccionBusqueda.mapas.map, 'bounds_changed', function() {
						zoom = this.getZoom();
						this.setZoom(zoom + 1);
						google.maps.event.removeListener(zoomChangeBoundsListener);																						 					});
				} else {
					VAPAYA.direccionBusqueda.mapas.map.setCenter(point);
					VAPAYA.direccionBusqueda.mapas.map.setZoom(8);
				}
				VAPAYA.direccionBusqueda.mapas.map.enableKeyDragZoom({
					visualEnabled: true,
					visualPosition: google.maps.ControlPosition.LEFT,
					visualPositionOffset: new google.maps.Size(5, 0),
					visualPositionIndex: null,
					visualSprite: "http://maps.gstatic.com/mapfiles/ftr/controls/dragzoom_btn.png",
					visualSize: new google.maps.Size(20, 20),
					visualTips: {
						off: "Encender",
						on: "Apagar"
					},
					boxStyle: {
            			border: "1px dashed black",
           				backgroundColor: "transparent",
            			opacity: 1.0
          			}
				});
				VAPAYA.direccionBusqueda.mapas.dibujarMarker(point);
				$('#wrap_buscador').html(VAPAYA.direccionBusqueda.direccion.bloqueDireccionMapa());
				google.maps.event.addListener(VAPAYA.direccionBusqueda.mapas.map, "click", VAPAYA.direccionBusqueda.direccion.geocodificarPunto);
			},
			geoLocalizame: function () {
				var options = {timeout: 50000};
				navigator.geolocation.getCurrentPosition(VAPAYA.direccionBusqueda.mapas.success, VAPAYA.direccionBusqueda.mapas.handleError, options);
			},
			success: function (position) {
				//////////
				var latitude = position.coords.latitude,
					longitude = position.coords.longitude,
					point = new google.maps.LatLng(latitude, longitude),
					query = {'latLng': point, 'language': vapayaTexts.lang};
				//////////
				VAPAYA.direccionBusqueda.mapas.geocoder.geocode(query, VAPAYA.direccionBusqueda.direccion.mostrarDireccionEnCampoTexto);
			},
			handleError: function (err) {
				var html = $('<p style="padding: 10px;">');
				if (err.code === 1) {
					html.text("Se ha denegado el acceso");
				} else if (err.code === 2) {
					html.text("No ha sido posible acceder a tu ubicación");
				} else {
					html.text("Se ha producido un error");
				}
				$('#dialog').html(html);
				$("#dialog").dialog({
					autoOpen: true,
					maximize: true,
					modal: true,
					width: 400,
					height: 252,
					closeText: vapayaTexts.cerrar,
					position: ['center', 50],
					title: "Error al intentar localizar tu ubicación",
					close: function () {
						VAPAYA.cerrarDialog();
					},
					show: 'fade',
					hide: 'fade'
				});
			},
			movermapa: function (point, viewport) {
				if (viewport !== '') {
					VAPAYA.direccionBusqueda.mapas.map.fitBounds(viewport);
				} else {
					VAPAYA.direccionBusqueda.mapas.map.setCenter(point);
					VAPAYA.direccionBusqueda.mapas.map.setZoom(18);
				}
				VAPAYA.direccionBusqueda.mapas.dibujarMarker(point);
			},
			mapClearOverlays: function () {
				if (VAPAYA.direccionBusqueda.mapas.markersArray) {
					var i, 
						max = VAPAYA.direccionBusqueda.mapas.markersArray.length;
					//////////
					for (i = 0; i < max; i += 1) {
						VAPAYA.direccionBusqueda.mapas.markersArray[i].setMap(null);
					}
					VAPAYA.direccionBusqueda.mapas.markersArray.length = 0;
				}
			}
		},
		/**
		 * Gestiona el apartado de paises que aparece al sugerir direcciones
		 * @class
		 */
		paises: {
			/**
			 * Inicia la movida de los paises llamando a cargarListaPaises().
			 */
			countriesInitialize: function () {
				VAPAYA.direccionBusqueda.paises.gestorUI();
			},
			gestorUI: function () {
				$('#mostrarlista').live('click', function (e) {
					VAPAYA.detenerEvento(e);											 
					$('.tt, .ta').toggle();
					if (!(VAPAYA.direccionBusqueda.paises.paisesCargados)) {
						VAPAYA.direccionBusqueda.paises.cargarListaPaises();
					}
				});
				$('#cont_paises, #ccc').live('click', function (e) {
					VAPAYA.detenerEvento(e);
				});
				$('#cerrarlista').live('click', function (e) {
					//VAPAYA.detenerEvento(e);
					$('.tt, .ta').toggle();
					$('#user_dir').focus();
				});
			},
			/**
			 * Ajax para cargar el contenido de paises.php en el mapa
			 */
			cargarListaPaises: function () {
				$('#cont_paises').load('http://' + document.domain + '/paises/?current=' + VAPAYA.pais.codigoPais, function (response, status) {
					if (status !== "error") {
						$('.vinc_pais').click(function (e) {
							VAPAYA.detenerEvento(e);							
							$('.pais').removeClass('paisseleccionado');
							$(this).addClass('paisseleccionado');
							VAPAYA.direccionBusqueda.mapas.mostrarmarker = false;
							VAPAYA.direccionBusqueda.paises.establece_pais($(this).attr('id'));
							VAPAYA.direccionBusqueda.mapas.mapClearOverlays();
							if ($('#mapa_user_dir').exists()) {
								$('#mapa_user_dir').sugerir({sigueSugiriendo:true});
							} else {
								$('#user_dir').sugerir({sigueSugiriendo:true});
							}
						});
						var cTab = $('li.ui-tabs-selected').attr('id');
						var currentTab = cTab.split('-');
						$("#tabs_paises").tabs({ selected: currentTab[1] });
						var scrolltop = 120;
						$("div.tab-letra").scrollTop(scrolltop);
						VAPAYA.direccionBusqueda.paises.paisesCargados = true;
					}
				});
			},
			/**
			 * Cambia el pais (pais.codigoPais y cookie)
			 */
			establece_pais: function (ppais) {
				//////////
				var geocoder_query,
					pais = ppais.toUpperCase();
				//////////
				$('#nombrepais').text(vapayaTexts[pais]);
				VAPAYA.pais.codigoPais = pais;
				geocoder_query = {'address': vapayaTexts[VAPAYA.pais.codigoPais]};
				VAPAYA.direccionBusqueda.mapas.mapGeocode(geocoder_query, 'country', function(data){
    				VAPAYA.pais.geodata.viewport = data.viewport;
					VAPAYA.pais.geodata.coords = data.coords;
  				});
				if (google.loader.ClientLocation && VAPAYA.pais.codigoPais === google.loader.ClientLocation.address.country_code) {
					VAPAYA.ciudad.codigoCiudad = google.loader.ClientLocation.address.city;
					geocoder_query = {'address': VAPAYA.ciudad.codigoCiudad + ', ' + vapayaTexts[VAPAYA.pais.codigoPais]};
					VAPAYA.direccionBusqueda.mapas.mapGeocode(geocoder_query, 'locality', function(data){
	    				VAPAYA.ciudad.geodata.viewport = data.viewport;
						VAPAYA.ciudad.geodata.coords = data.coords;
  					});
				} else {
					VAPAYA.ciudad.codigoCiudad = '';
				}

				VAPAYA.cookies.escribirCookie('country', pais);
				$.sugerir.cache = [];
			}
		}
	},
	/**
	 * Gestiona el apartado de búsqueda avanzada
	 * @class
	 */
	busquedaAvanzada: {
		iniciar: function () {
			$('a.b_avanzada').live('click', function () { 
				VAPAYA.busquedaAvanzada.avanzadasOpen();
			});
		},
		avanzadasOpen: function () {
			$("#dialog").dialog({
				autoOpen: true,
				modal: true,
				width: 646,
				height: 'auto',
				position: ['center', 50],
				title: 'Opciones avanzadas de búsqueda',
				open: function () {
					VAPAYA.busquedaAvanzada.controlarBusquedaAvanzada();
				},
				close: function () {
					VAPAYA.busquedaAvanzada.cerrarBusquedaAvanzada();
					VAPAYA.cerrarDialog();
				},
				show: 'fade',
				hide: 'fade'
			});
		},
		controlarBusquedaAvanzada: function () {
			$('#dialog').load('http://' + document.domain + '/get-results/?action=avanzada', {
				search_mode: $('#search_mode').val(), 
				cats: $('#cats').val(),
				p_cats: $('#p_cats').val(),
				col_izq: $('#col_izq').val(),
				publicadopor: $('#publicadopor').val()
				}, 
				function (response, status) {
					if (status !== "error") {
						VAPAYA.busquedaAvanzada.categorias.iniciar();
					} else {
						alert("error");
					}
				});
		},
		cerrarBusquedaAvanzada: function() {
			var search_mode = $("input[name='jaxsearch_mode']:checked").val(),
				col_izq = $("input[name='jaxcol_izq']").val(),
				publicadopor = $('#jaxpublicadopor').val();
				
			var pcatsVals = [];
	 		$("input[name='jaxp_cats[]']:checked").each(function() {
	   			pcatsVals.push($(this).val());
	 		});
			var p_cats = pcatsVals.join(',');
			
			var catsVals = [];
	 		$("input[name='jaxcats[]']:checked").each(function() {
	   			catsVals.push($(this).val());
	 		});
			var cats = catsVals.join(',');
	
				
			$('#search_mode').val(search_mode);
			$('#col_izq').val(col_izq);
			$('#p_cats').val(p_cats);
			$('#cats').val(cats);
			$('#publicadopor').val(publicadopor);
		},
		/**
		 * Gestiona el apartado de categorias en el formulario de búsqueda
		 * @class
		 */
		categorias: {
			iniciar: function () {
				var inputs = $("input:checkbox", $('#ui-cats')),
					that = this;
				//////////
				inputs.each(function (index, elem) {
					var span = $("<span></span>").attr('class', 'checkbox');
					//////////
					span.insertBefore($(elem)).mousedown(function () {
						that.personalizarCheckboxes.pushed(this);
					}).mouseup(function () {
						that.personalizarCheckboxes.check(this);
					});
					
				});
				this.gestorUI();
			},
			gestorUI: function () {
				this.personalizarCheckboxes.update();
				//tabs categorias
				$("#ui-cats").tabs({selected: -1});	
				//boton cerrar grupo de categorías
				$('.btn_cerrar_subs, .ui-dialog-titlebar-close').click(function () {
					$("#ui-cats").tabs('destroy').tabs({selected: -1});
				});
				//marcar-desmarcar categoria
				$("label.for_cat, label.for_col").mousedown(function () {
					var span = $(this).prev('input').prev('span').get();
					//////////
					VAPAYA.busquedaAvanzada.categorias.personalizarCheckboxes.pushed(span);
				}).mouseup(function () {
					var span = $(this).prev('input').prev('span').get();
					//////////
					VAPAYA.busquedaAvanzada.categorias.personalizarCheckboxes.check(span);
				}).click(function () {
					return false;
				});
			},
			actualizarCategoriasSeleccionadas: function () {
				//////////
				var label, slug, inputs, text, id,
					as = $("li.nav_izq > a"),
					msg = 'La búsqueda se hará en las siguientes categorías:<br />',
					total = 0;
				//////////	
				as.each(function (index, a) {
					text = $(a).text();
					id = $(a).attr('href');
					inputs = $("input.child_check:checked", $('div' + id));
					if (inputs.length > 0) {
						msg += '<div style="margin-bottom: 10px;">';
						msg += '<b>' + text + '</b>';
						inputs.each(function (index, elem) {
							total = total + 1;
							slug = $(elem).attr('id');
							label = $('label.for_cat[for=' + slug + ']');
							msg += '<br /><span>' + label.text() + '</span>';
						});
						msg += '</div>';
					}
				});
				if (total === 0) {
					msg = "Elige al menos una categoría para hacer la búsqueda";
				} 
				$('#selected_cats').html(msg);
			},
			personalizarCheckboxes: {
				update: function () {
					var inputs = $("input:checkbox", $('#ui-cats')),
						checkeds = $("input:checkbox:checked", $('#ui-cats')).length;
					//////////
					inputs.each(function (index, elem) {
						var offset, pos,
							inputs_semi = inputs.filter('.semi').get();
						//////////	
						offset = $.inArray(elem, inputs_semi) !== -1 ? 52 : 0;
						if ($(elem).is(':checked')) {
							pos = parseInt(100 + offset, 10);
						} else {
							pos = parseInt(74 + offset, 10);
						}
						$(elem).prev('span').css('backgroundPosition', "0 -" + pos + "px");
					});
					VAPAYA.ui.toggleCloseButton(checkeds);
					VAPAYA.busquedaAvanzada.categorias.actualizarCategoriasSeleccionadas();				
				},
				pushed: function (el) {
					var pos,
						span = $(el),
						input = span.next('input'),
						offset = input.attr('class') === 'semi' ? 52 : 0;
					//////////	
					if (input.is(':checked')) {
						pos = parseInt(113 + offset, 10);
					} else {
						pos = parseInt(87 + offset, 10);
					}
					span.css('backgroundPosition', "0 -" + pos + "px");
				},
				check: function (el) {
					var pos,
						span = $(el),
						input = span.next('input'),
						offset = input.attr('class') === 'semi' ? 52 : 0;
					//////////
					if (input.is(':checked')) {
						pos = parseInt(74 + offset, 10);
						input.removeAttr('checked');
					} else {
						pos = parseInt(100 + offset, 10);
						input.attr('checked', 'checked');
					}
					span.css('backgroundPosition', "0 -" + pos + "px");
					if (input.hasClass('cat_first')) {
						VAPAYA.busquedaAvanzada.categorias.toggleCol(input);
					} else if (input.hasClass('cat_check')) {
						VAPAYA.busquedaAvanzada.categorias.toggleCat(input);
					} else if (input.hasClass('child_check')) {
						VAPAYA.busquedaAvanzada.categorias.toggleParent(input);
					}
					VAPAYA.busquedaAvanzada.categorias.personalizarCheckboxes.update();
					VAPAYA.resultados.show_hide_search_button();
				}
			},
			toggleCol: function (element) {
				var checks, num,
					clase = $(element).attr('id').replace('col', 'nav');
				//////////	
				if ($(element).is(':checked')) {
					$("." + clase + ">input:checkbox").removeClass('semi').attr('checked', 'checked');
				} else {
					$("." + clase + ">input:checkbox").removeAttr('checked');
				}
				checks = $("." + clase + ">input:checkbox").get();
				for (num in checks) {
					if (checks.hasOwnProperty(num)) {
						this.toggleCat(checks[num]);
					}
				}
			},
			toggleCat: function (element) {
				var id = $(element).attr('id').replace('_parent', ''),
					col = $.trim($(element).parent().attr('class').slice(0, 8)),
					clase = $.trim($(element).parent().attr('class').replace('nav', 'col').slice(0, 8)),
					max_checks = $("." + col + ">input:checkbox").length,
					checkeds = $("." + col + ">input:checkbox:checked").length;
				//////////
				if (checkeds > 0 && checkeds < max_checks) {
					$("#" + clase).addClass('semi').attr('checked', 'checked');
				} else if (checkeds > 0 && checkeds === max_checks) {
					$("#" + clase).removeClass('semi');
				} else {
					$("#" + clase).removeAttr('checked');
				}
				if ($(element).is(':checked')) {
					$(element).removeClass('semi');
					$("#" + id + ">div>input:checkbox").attr('checked', 'checked');
				} else {
					$("#" + id + ">div>input:checkbox").removeAttr('checked');
				}
			},
			toggleParent: function (element) {
				var p_max_checks, p_checkeds, p_is_semi,
					parent_id = $(element).parent().parent().attr('id'),
					id = parent_id + '_parent',
					col = $.trim($("#" + id).parent().attr('class').slice(0, 8)),
					clase = col.replace('nav', 'col'),
					max_checks = $("#" + parent_id + ">div>input:checkbox").length,
					checkeds = $("#" + parent_id + ">div>input:checkbox:checked").length;
				//////////	
				if (checkeds > 0 && checkeds < max_checks) {
					$("#" + clase).addClass('semi').attr('checked', 'checked');
					$("#" + id).addClass('semi').attr('checked', 'checked');
				} else if (checkeds > 0 && checkeds === max_checks) {
					p_max_checks = $("." + col + ">input:checkbox").length;
					p_checkeds = $("." + col + ">input:checkbox:checked").length;
					p_is_semi = $("." + col + ">input:checkbox:checked.semi").length;
					if (p_checkeds > 0 && p_checkeds < p_max_checks) {
						if (0 === p_max_checks - (p_checkeds + 1) && 0 === p_is_semi) {
							$("#" + clase).removeClass('semi').attr('checked', 'checked');
						} else {
							$("#" + clase).addClass('semi').attr('checked', 'checked');
						}
					} else if (p_checkeds > 0 && p_checkeds === p_max_checks) {
						if (p_is_semi > 1) {
							$("#" + clase).attr('checked', 'checked');
						} else {
							$("#" + clase).removeClass('semi').attr('checked', 'checked');
						}
					} else {
						$("#" + clase).addClass('semi').attr('checked', 'checked');
					}
					$("#" + id).removeClass('semi').attr('checked', 'checked');
				} else {
					p_max_checks = $("." + col + ">input:checkbox").length;
					p_checkeds = $("." + col + ">input:checkbox:checked").length;
					if (1 === p_checkeds) {
						$("#" + clase).removeClass('semi').removeAttr('checked');
					} else {
						$("#" + clase).addClass('semi');
					}
					$("#" + id).removeAttr('checked');
				}
			}
		}
	},
	/**
	 * Gestiona el formulario de acceso de la barra superior
	 */
	formularioAccesoSuperior: {
		/**
	 	 * Controla los botones del formulario de acceso sup
	 	 */
		iniciar: function () {
			$('#a_login').click( function () {
				if ($('#user_login').val() === vapayaTexts.usuario) {
					$('#user_login').val('');
				}
				$('#loginform').submit();
			});
			$("a#acceder").click(function () {
				$("#topbar_login").show();
				$('div#formsup').hide();
			});
			$("a#login_close").click(function () {
				$("#topbar_login").hide();
				$('div#formsup').show();		
			});
		}
	},
	/**
	 * Actualiza la frase con el numero de anuncios publicados de la barra superior
	 */
	barraInfoAnuncios: {
		iniciar: function () {
		}
	},
	/**
	 * Gestiona el envio del formulario de búsqueda
	 */
	envioFormularioBusqueda: {
		iniciar: function () {
			// BOTON ENVIAR
			$('a#send_btn').click(function(e){
				if ($(this).hasClass('disabled')) {
					VAPAYA.detenerEvento(e);
				} else {
					VAPAYA.envioFormularioBusqueda.enviar();
				}
			});
		},
		enviar: function () {
			if (VAPAYA.paginaActual !== 'results') {
				VAPAYA.prepareForm();
			} else {
				VAPAYA.prepare_results_form();
			}
		}
	},
	/**
	 * Gestiona los botones de las páginas de ayuda
	 */
	ayuda: {
		iniciar: function () {
		}
	},
	/**
	 * Gestiona el desplegable de cambio de idioma
	 */
	idiomas: {
		iniciar: function () {
			$('#langs').change(function () {
				if (!$('#search').exists()) {
					VAPAYA.idiomas.cambia_lang($(this).val());
				} else {
					$('#search').attr('action', $(this).val());
					VAPAYA.prepare_results_form();
				}
			});
		},
		cambia_lang: function (url) {
			var idioma = (url.split('//')[1]).split('.')[0];
			//////////	
			VAPAYA.cookies.escribirCookie('lang', idioma);
			document.location.href = url;
		}
	},
	/**
	 * Gestiona la paginacion entre anuncios
	 * @class
	 */
	paginacion: {
		page_data: '', 
		pagenum: 1, 
		totalpages: '', 
		permalinks: [], 
		totallinks: '', 
		ant: '', 
		index: '', 
		sig: '', 
		restantes: '', 
		a: '', 
		act: '',
		currentpermalink: location.pathname.substr(1),
		iniciar: function (){
		},
		consultaCookies: function() {
			if (VAPAYA.cookies.leerCookie('currpage') !== null) {
				this.page_data = VAPAYA.cookies.leerCookie('currpage').split(':');
				this.pagenum = this.page_data[0];
				this.totalpages = this.page_data[1];
				if (VAPAYA.cookies.leerCookie('anuncios' + this.pagenum) !== null) {
					this.permalinks = VAPAYA.cookies.leerCookie('anuncios' + this.pagenum).split(':');
					this.totallinks = this.permalinks.length;
					for (a = 0; a < this.totallinks; a += 1) {
						if (this.permalinks[a] === this.currentpermalink) {
							this.index = a;
							this.act = parseInt(a, 10) + 1;
							this.sig = this.act + 1;
							this.ant = this.act - 1;
							this.restantes = this.totallinks - this.act;
						}
					}
				}
			}
		},
		dibujaBloquelinks: function() {
			this.consultaCookies();
			//////////
			var dominio = document.domain,
				ret = '';
			//////////	
			if (VAPAYA.cookies.leerCookie('anuncios' + this.pagenum) !== null) {
				ret += '<div class="anuncioanterior left">';
				if (this.ant > 0) {
					ret += '<a id="link_anterior" href="http://' + dominio + '/' + this.permalinks[parseInt(this.index, 10) - 1] + '">' + vapayaTexts.anuncioanterior + '</a>';
				} else {
					ret += '<span id="link_anterior" class="disabled" >' + vapayaTexts.anuncioanterior + '</span>';
				}
				ret += '</div>';
				ret += '<div class="volverares center"><a id="volverares" href="http://' + dominio + '/resultados/">' + vapayaTexts.volveraresultados + '</a></div>';
				ret += '<div class="anunciosiguiente right">';
				if (this.sig <= this.totallinks) {
					ret += '<a id="link_siguiente" href="http://' + dominio + '/' + this.permalinks[parseInt(this.index, 10) + 1] + '">' + vapayaTexts.anunciosiguiente + '</a>';
				} else {
					ret += '<span id="link_siguiente" class="disabled" >' + vapayaTexts.anunciosiguiente + '</span>';
				}
				ret += '</div>';
			}
			return ret;
		},
		psiguiente: function() {
			if (this.restantes === 1 && this.pagenum < this.totalpages) {
				VAPAYA.cookies.escribirCookie('currpage', (parseInt(this.pagenum, 10) + 1) + ':' + this.totalpages);
			}
		},
		panterior: function() {
			if (this.restantes === this.totallinks - 2 && this.pagenum > 1) {
				VAPAYA.cookies.escribirCookie('currpage', (parseInt(this.pagenum, 10) - 1) + ':' + this.totalpages);
			}
		}
	},
	prepareForm: function () {
		//////////
		var detener = false,
			cats = $('#ui-cats'),
			search_mode = $("input[name='search_mode']"),
			publicadopor = $("input#publicadopor");
		//////////	
		if ($('#fdir').exists()) {
			if ($.trim($('#keywords').val()) === '' && $.trim($('#fdir').text()) === '') {
				detener = true;
			}
		} else {
			if ($.trim($('#keywords').val()) === '') {
				detener = true;
				$('#localizdiv').hide();
				if ($('#user_dir').val() !== '') {
					$('#user_dir').val('').focus();
				} else {
					$('#keywords').val('').focus();
				}
			}
		}
		if (detener) {
			return false;
		}
		$('input.semi').each(function () {
			//////////						   
			var v = $(this).val();
			//////////
			$('#avanzadas_cont').append('<input type="hidden" name="semi[]" value="' + v + '" />');
		});
		$('#avanzadas_cont').append(cats).append(search_mode).append(publicadopor);
		$('form#mainform').submit();
	},
	prepare_results_form: function (page) {
		//////////
		var agr, ord, perpage,
			col_izq = $("input[name='col_izq']:checked").clone(),
			p_cats = $("input[name='p_cats[]']:checked").clone(),
			cats = $("input[name='cats[]']:checked").clone();
		//////////	
		if (typeof (page) !== "undefined") {
			$('form#search input#currentpage').val(page);
		}
		$('input.semi').each(function () {
			var v = $(this).val();
			//////////
			$('#morevalues').append('<input type="hidden" name="semi[]" value="' + v + '" />');
		});
		agr = $('#agr').exists() ? $('<input type="hidden" name="agr" value="' + $("select#agr option:selected").val() + '"/>') : '';
		ord = $('#ord').exists() ? $('<input type="hidden" name="ord" value="' + $("select#ord option:selected").val() + '"/>') : '';
		perpage = $('#perpage').exists() ? $('<input type="hidden" name="perpage" value="' + $("select#perpage option:selected").val() + '"/>') : '';
		$('#morevalues').append(col_izq).append(p_cats).append(cats).append(agr).append(ord).append(perpage);
		$('form#search').submit();
	},
	/**
	 * Gestiona algunos aspectos de la interfaz de usuario
	 * @class
	 */
	ui: {
		uiInitialize: function () {
			this.gestorUI();
		},
		gestorUI: function () {
			$.ui.dialog.prototype.options.bgiframe = true;

			$("#s_head").click(function () {
				VAPAYA.ui.toggle_search_form();
			});
			$('a#quees, a#comob, a#comop, a#headerlogo, a#locateButton, a#send_btn').mouseleave(function() {
				$(this).addClass('mouseleave');
			}).mouseenter(function() {
				$(this).removeClass('mouseleave');
			});
		},
		toggleCloseButton: function (val) {
			if (val === 0) {
				$('.ui-dialog-titlebar-close').hide();
				$('#dialog').dialog({ closeOnEscape: false });
			} else {
				$('.ui-dialog-titlebar-close').show();
				$('#dialog').dialog({ closeOnEscape: true });
			}
		},
		cuantos_anuncios: function (country) {
			$.getJSON('http://' + document.domain + '/home.log', function (data) {
				//////////
				var total = '0',
					item = '0';
				//////////	
				$.each(data, function (key, val) {
					if (key === "total") {
						total = '<span>' + val + '</span>';
					} else if (key === country) {
						item = '<span>' + val + '</span>';
					}
				});
				$('#total_anuncios').html(total);
				$('#nac_anuncios').html(item);
			});
		},
		toggle_search_form: function () {
			$("div#mostrando").slideToggle("fast", function () {
				$('#s_head').toggleText('Ocultar', 'Nueva búsqueda');
				//Cufon.replace('#s_head'); /*$("div#mostrando_inf").toggleClass('desplegado');*/
				$("div#mascara").toggleClass('topmargin');
				$("div#single_cont").toggleClass('topmargin');
				$("#f_cont").toggleClass('abierto');
			});
		},
		toggle_content_value: function (input_id, values, selected) {
			var i,
				curr = 0,
				next = 1,
				max = values.length;
			//////////	
			if (selected === null) {
				return;
			}
			for (i = 0; i < max; i = i + 1) {
				if (typeof (selected) !== "undefined") {
					if (values[i][1] === selected) {
						next = i;
						curr = (i - 1 < 0 ? values.length - 1 : i - 1);
						break;
					}
				} else if (values[i][1] === $('#' + input_id).val()) {
					curr = i;
					next = (i + 1 > values.length - 1 ? 0 : i + 1);
					break;
				}
			}
			$('#' + input_id).prev().attr('innerHTML', values[next][0]);
			$('#' + input_id).val(values[next][1]).change();
		},
		rellena_banner_home: function () {
			$('#vinc_paises').text(vapayaTexts[VAPAYA.pais.codigoPais]);
			this.cuantos_anuncios(VAPAYA.pais.codigoPais);
		}
	},
	anunciar: {
		iniciar: function () {
			VAPAYA.anunciar.email.emailInitialize();
			VAPAYA.anunciar.gestorUI();
		},
		gestorUI: function () {
			$('#compartelink').click(function(){
				VAPAYA.anunciar.abreDialog();
			});
		},
		abreDialog: function () {
			$("#dialog").dialog({
				autoOpen: true,
				maximize: false,
				modal: true,
				width: 400,
				height: 252,
				position: ['center', 50],
				title: vapayaTexts.keywords_tit,
				open: function () {
					VAPAYA.anunciar.controlarAnunciar();
				},
				close: function () {
					VAPAYA.cerrarDialog();
				},
				show: 'fade',
				hide: 'fade'
			});
		},
		controlarAnunciar: function () {
			$('#dialog').load('http://' + document.domain + 
			'/get-results/?action=anunciar', function (response, status) {
				if (status !== "error") {
					
				} else {
					response = "<p align=center>" + vapayaTexts.conexerrortext + "</p>";
					$('#dialog').dialog('option', {
						title: vapayaTexts.conexerror
					}).html(response);
				}
			});
		},
		/**
		 * Gestiona el apartado de enviar por email
		 * @class
		 */
		email: {
			email_p : 0,
			email_pageid : 0,
			email_max_allowed : 5,
			emailOpen: function () {
				$("#dialog").dialog('open');
			},
			emailInitialize: function () {
				$("#dialog").dialog({ 
					title: '¡Danos a conocer!',
					autoOpen: false, 
					width: 550, 
					minHeight: 100, 
					position: ['center', 50], 
					height: 'auto', 
					modal: true,
					open: function () {
						VAPAYA.anunciar.email.maneja_email();
					},
					close: function () {
						VAPAYA.cerrarDialog();
					},
					closeText: 'Cerrar' 
				});
				this.gestorUI();
			},
			maneja_email: function () {
				$('#dialog').load('http://' + document.domain + '/get-results/?action=email',
					function (response, status) {
						if (status !== "error") {
							$('#vapaya-email-submit').click(function () {
								VAPAYA.anunciar.email.email_form();
							});
							$('#yourname, #youremail, #yourremarks, #friendname, #friendemail, #imageverify').focus(function () {
								$(this).removeClass('warning');
							});
						} else {
							alert("error");
						}
					});
			},
			gestorUI: function () {
				$('#mailverde').click(function () {															
					VAPAYA.anunciar.email.emailOpen();
				});
			},
			// Email Form AJAX
			email_form: function () {
				//////////
				var yourname = $('#yourname').val(),
					youremail = $('#youremail').val(),
					yourremarks = $('#yourremarks').val(),
					friendname = $('#friendname').val(),
					friendnames = friendname.split(","),
					friendemail = $('#friendemail').val(),
					friendemails = friendemail.split(","),
					imageverify = $('#imageverify').val(),
					email_ajax_data = 'sendemail=1',
					rn = Math.floor(Math.random() * 10001);
				//////////
				if (this.validate_email_form(yourname, youremail, yourremarks, friendname, friendnames, friendemail, friendemails, imageverify)) {
					$('#wp-email-submit').attr('disabled', true);
					$('#wp-email-loading').show();
					email_ajax_data += '&yourname=' + yourname;
					email_ajax_data += '&youremail=' + youremail;
					email_ajax_data += '&yourremarks=' + yourremarks;
					email_ajax_data += '&friendname=' + friendname;
					email_ajax_data += '&friendemail=' + friendemail;
					email_ajax_data += '&imageverify=' + imageverify;
					$('#yourname, #youremail, #yourremarks, #friendname, #friendemail, #imageverify').attr('disabled', true);
					$.ajax({type: 'POST',
						url: 'http://' + document.domain + '/web/misc/email/email.php',
						data: email_ajax_data, 
						cache: false, 
						success: function (data) {
							$('#wp-email-submit, #yourname, #youremail, #yourremarks, #friendname, #friendemail, #imageverify').attr('disabled', false);
							$('#wp-email-loading').hide();						
							$('#imgever').replaceWith('<img id="imgever" src="http://' + document.domain 
								+ '/web/misc/email/email-image-verify.php?r='
								+ rn + '" width="55" height="15" />');
							eval(data);
						}
						});
				}
			},
			validate_email_form: function (yourname, youremail, yourremarks, friendname, friendnames, friendemail, friendemails, imageverify) {
				//////////
				var i,
					errFlag = false,
					friendnames_total = friendnames.length,
					friendemails_total = friendemails.length;
				//////////	
				// Your Name Validation
				if (this.isEmpty(yourname) || !this.is_valid_name(yourname)) {
					$('#yourname').addClass('warning');
					errFlag = true;
				}
				// Your Email Validation
				if (this.isEmpty(youremail) || !this.is_valid_email(youremail)) {
					$('#youremail').addClass('warning');
					errFlag = true;
				}
				// Your Remarks Validation
				if (!this.isEmpty(yourremarks)) {
					if (!this.is_valid_remarks(yourremarks)) {
						$('#yourremarks').addClass('warning');
						errFlag = true;
					}
				}
				// Friend Name(s) Validation
				if (this.isEmpty(friendname)) {
					$('#friendname').addClass('warning');
					errFlag = true;
				} else {
					for (i = 0; i < friendnames_total; i = 1 + 1) {
						if (this.isEmpty(friendnames[i]) || !this.is_valid_name(friendnames[i])) {
							$('#friendname').addClass('warning');
							errFlag = true;
						}
					}
				}
				if (friendnames.length > this.email_max_allowed) {
					$('#friendname').addClass('warning');
					errFlag = true;
				}
				// Friend Email(s) Validation
				if (this.isEmpty(friendemail)) {
					$('#friendemail').addClass('warning');
					errFlag = true;
				} else {
					for (i = 0; i < friendemails_total; i = i + 1) {
						if (this.isEmpty(friendemails[i]) || !this.is_valid_email(friendemails[i])) {
							$('#friendemail').addClass('warning');
							errFlag = true;
						}
					}
				}
				if (friendemails.length > this.email_max_allowed) {
					$('#friendemail').addClass('warning');
					errFlag = true;
				}
				// Friend Name(s) And Email(s) Validation
				if (friendnames.length !== friendemails.length) {
					$('#friendname, #friendemail').addClass('warning');
					errFlag = true;
				}
				if (this.isEmpty(imageverify)) {
					$('#imageverify').addClass('warning');
					errFlag = true;
				}
				if (errFlag === true) {
					return false;
				} else {
					return true;
				}
			},
			// Check Form Field Is Empty
			isEmpty: function (value) {
				if ($.trim(value) === "") {
					return true;
				}
				return false;
			},
			// Check Name
			is_valid_name: function (name) {
				//////////
				var filter  = /[(\*\(\)\[\]\+\,\/\?\:\;\'\"\`\~\\#\$\%\^\&\<\>)+]/;
				//////////
				return !filter.test($.trim(name));
			},
			// Check Email
			is_valid_email: function (email) {
				//////////
				var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
				//////////
				return filter.test($.trim(email));
			},
			// Check Remarks
			is_valid_remarks: function (remarks) {
				//////////
				var i,
					injection_strings = ['apparently-to', 'cc', 'bcc', 'boundary', 'charset', 'content-disposition', 'content-type', 'content-transfer-encoding', 'errors-to', 'in-reply-to', 'message-id', 'mime-version', 'multipart/mixed', 'multipart/alternative', 'multipart/related', 'reply-to', 'x-mailer', 'x-sender', 'x-uidl'],
					injection_strings_total = injection_strings.length;
				//////////
				remarks = $.trim(remarks);
				for (i = 0; i < injection_strings_total; i = i + 1) {
					if (remarks.indexOf(injection_strings[i]) !== -1) {
						return false;
					}
				}
				return true;
			}
		}
	},
	contactar: {
		iniciar: function () {
		}
	},
	resultados: {
		iniciar: function () {
			$('#agr,#ord,#perpage').change(function() {
				VAPAYA.prepare_results_form();
			});
			$('.results_result').hover(function(){
				$(this).parent().css('background-color','#f1f1f1');
			}, function(){
				$(this).parent().css('background','none');
			});
			$('.results_thumb').each(function(index) { 
				if($(this).find("img.res_thumb").exists()) {
					$(this).cycle({ 
						timeout: 0,
						next:   $(this).find("img")
					});
				}
				//alert(index + ': ' + $(this));
			});
			$("input[name='search_mode']").click(function() {VAPAYA.resultados.show_hide_search_button();});
			$("input[name='publicadopor']").change(function() {VAPAYA.resultados.show_hide_search_button();});
			
			$("span.btn").toggle(function(){
				$(this).addClass("active");
			}, function () {
				$(this).removeClass("active");
			}).click(function(){
				$(this).parent().next(".tablas_resultados").slideToggle("slow");
			});
		},
		masopcionesdeordenar: function() {
			//if ($('#res_keywords').val() != '')
			//alert("entra");
		},
		show_hide_search_button: function () {
			//////////
			var new_search, a, btn_buscar, s_head,
				show = false,
				cat_vals = [],
				perp = $('#perpage').exists() ? $('#perpage').val() : '5';
			//////////	
			
			$("input[name='cats[]']:checked").each(function () {
				cat_vals.push($(this).val());
			});
			cat_vals = cat_vals.join(',');
			new_search = {
				keywords: $('#keywords').val(),
				publicadopor: $('#publicadopor').val(),
				search_mode: $("input[name='search_mode']:checked").val(),
				direccion: $('#direccion').val(),
				cats: cat_vals,
				agr: $('#agr').val(),
				ord: $('#ord').val(),
				perpage: perp
			};
			if ($.trim(new_search.direccion) !== '' || $.trim(new_search.keywords) !== '') {
				for (a in curr_search) {
					if (curr_search.hasOwnProperty(a)) {
						if (curr_search[a] !== new_search[a]) {
							show = true;
						}
					}
				}
			}
			
			if (show === true) {
				$('#send_btn').removeClass('disabled').attr('title','Buscar anuncios');
				$('#mascara').addClass('opaco');
			} else {
				$('#send_btn').addClass('disabled').attr('title','');
				$('#mascara').removeClass('opaco');
			}
		}
	},
	valorarResultado: {
		iniciar: function () {
		}
	},
	comentarResultado: {
		iniciar: function () {
		}
	},
	imagenesResultado: {
		iniciar: function () {
		}
	},
	validacionesFormularios: {
		iniciar: function () {
		}
	},
	php_serialize: function(obj) {
		var string = '';
		if (typeof(obj) == 'object') {
			if (obj instanceof Array) {
				string = 'a:';
				tmpstring = '';
				for (var key in obj) {
					tmpstring += this.php_serialize(key);
					tmpstring += this.php_serialize(obj[key]);
				}
				string += obj.length + ':{';
				string += tmpstring;
				string += '}';
			} else if (obj instanceof Object) {
				classname = obj.toString();
				if (classname == '[object Object]')
					classname = 'StdClass';
				string = 'O:' + classname.length + ':"' + classname + '":';
				tmpstring = '';
				count = 0;
				for (var key in obj) {
					tmpstring += this.php_serialize(key);
					if (obj[key])
						tmpstring += this.php_serialize(obj[key]);
					else
						tmpstring += this.php_serialize('');
					count++;
				}
				string += count + ':{' + tmpstring + '}';
			}
		} else {
			switch (typeof(obj)) {
				case 'number':
					if (obj - Math.floor(obj) != 0)
						string += 'd:' + obj + ';';
					else
						string += 'i:' + obj + ';';
				break;
				case 'string':
					string += 's:' + obj.length + ':"' + obj + '";';
				break;
				case 'boolean':
					if (obj)
						string += 'b:1;';
					else
						string += 'b:0;';
				break;
			}
		}
		return string;
	}
};


/**
 * Añadidos a jQuery
 */

$.fn.exists = function () {
	return $(this).length > 0;
};

$.fn.toggleText = function (a, b) {
	return this.each(function () {
		$(this).text($(this).text() === a ? b : a);
	});
};

$.fn.selectbox = function (options) {
	//////////
	var settings = {
			className: 'jquery-selectbox',
			animationSpeed: "fast",
			listboxMaxSize: 10,
			replaceInvisible: false,
			posclass: 'topp'
		},
		commonClass = 'jquery-custom-selectboxes-replaced',
		listOpen = false,
		onBlurList, hideList, showList;
	//////////
	onBlurList = function (e) {
		//////////
		var trgt = e.target,
			currentListElements = $('.' + settings.className + '-list:visible').parent().find('*').andSelf();
		//////////	
		if ($.inArray(trgt, currentListElements) < 0 && listOpen) {
			hideList($('.' + commonClass + '-list'));
		}
		return false;
	};
	hideList = function (listObj) {
		listObj.slideUp(settings.animationSpeed, function () {
			listOpen = false;
			$(this).parents('.' + settings.className).removeClass('selecthover');
		});
		$(document).unbind('click', onBlurList);
		return listObj;
	};
	showList = function (listObj) {
		var selectbox = listObj.parents('.' + settings.className);
		listObj.slideDown(settings.animationSpeed, function () {
			listOpen = true;
		});
		selectbox.addClass('selecthover');
		$(document).bind('click', onBlurList);
		return listObj;
	}; /* Processing settings */
	settings = $.extend(settings, options || {}); /* Wrapping all passed elements */
	return this.each(function () {
		var that = $(this),
			replacement, 
			thisListBox, 
			thisListBoxSize, 
			thisListBoxWidth;
		if (that.filter(':visible').length === 0 && !settings.replaceInvisible) {
			return;
		}
		replacement = $('<div class="' + settings.className + ' ' + commonClass + '">' + '<div class="' + settings.className + '-moreButton" />' + '<div class="' + settings.className + '-list ' + commonClass + '-list ' + settings.posclass + '" />' + '<span class="' + settings.className + '-currentItem" />' + '</div>');
		var gr = [];
		$('option, optgroup', that).each(function (k) {
			var clase = $(this).get(0).className;										   
			if ($.inArray(clase, gr) == -1) {
				gr.push(clase);
			}
			var listElement = $(this).get(0).tagName.toLowerCase() == 'optgroup'?
				$('<span class="grupo">' + $(this).attr('label') + '</span>')
				:
				$('<span class="' + clase + ' ' + settings.className + '-item value-' + $(this).val() + ' item-' + k + '">' + $(this).text() + '</span>');

			$('.' + settings.className + '-list', replacement).append(listElement);
			if ($(this).filter(':selected').length > 0) {
				$('.' + settings.className + '-currentItem', replacement).text($(this).text());
			}
			listElement.click(function () {
				if ($(this).hasClass('grupo')) {
					return;
				}
				var thisListElement = $(this),
					thisReplacment = thisListElement.parents('.' + settings.className),
					thisIndexAndValue = thisListElement[0].className.split(' '),
					k1, 
					max = thisIndexAndValue.length,
					thisIndex, 
					thisValue, 
					thisSublist;
				for (k1 = 0; k1 < max; k1 += 1) {
					if (/^item-[0-9]+$/.test(thisIndexAndValue[k1])) {
						thisIndex = parseInt(thisIndexAndValue[k1].replace('item-', ''), 10);
						break;
					}
					if (/^value-.+$/.test(thisIndexAndValue[k1])) {
						thisValue = thisIndexAndValue[k1].replace('value-', '');
						break;
					}
				}
				thisReplacment.find('.' + settings.className + '-currentItem').text(thisListElement.text());
				thisReplacment.find('select').val(thisValue).triggerHandler('change');
				thisSublist = thisReplacment.find('.' + settings.className + '-list');
				if (thisSublist.filter(":visible").length > 0) {
					hideList(thisSublist);
				} else {
					showList(thisSublist);
				}
			}).bind('mouseenter', function () {
				if ($(this).hasClass('grupo')) {
					return;
				}
				$(this).addClass('listelementhover');
			}).bind('mouseleave', function () {
				if ($(this).hasClass('grupo')) {
					return;
				}
				$(this).removeClass('listelementhover');
			});
		});
		
		for (var a =1; a < gr.length; a++) {
			$('.'+gr[a], replacement).wrapAll('<span class="subap" />');
		}
		replacement.find('.' + settings.className + '-moreButton').click(function () {
			var thisMoreButton = $(this),
				otherLists = $('.' + settings.className + '-list').not(thisMoreButton.siblings('.' + settings.className + '-list')),
				thisList = thisMoreButton.siblings('.' + settings.className + '-list');
			hideList(otherLists);
			if (thisList.filter(":visible").length > 0) {
				hideList(thisList);
			} else {
				showList(thisList);
			}
		}).bind('mouseenter', function () {
			$(this).addClass('morebuttonhover');
		}).bind('mouseleave', function () {
			$(this).removeClass('morebuttonhover');
		});
		replacement.find('.' + settings.className + '-currentItem').click(function () {
			replacement.find('.' + settings.className + '-moreButton').trigger('click');
		}).bind('mouseenter', function () {
			replacement.find('.' + settings.className + '-moreButton').trigger('mouseenter');
		}).bind('mouseleave', function () {
			replacement.find('.' + settings.className + '-moreButton').trigger('mouseleave');
		});
		that.hide().replaceWith(replacement).appendTo(replacement);
		thisListBox = replacement.find('.' + settings.className + '-list');
		thisListBoxSize = thisListBox.find('.' + settings.className + '-item').length;
		if (thisListBoxSize > settings.listboxMaxSize) {
			thisListBoxSize = settings.listboxMaxSize;
		}
		if (thisListBoxSize === 0) {
			thisListBoxSize = 1;
		}
		thisListBoxWidth = Math.round(that.width() + 24);
		if (settings.replaceInvisible) {
			thisListBoxWidth = 190;
		}
		if ($.browser.safari) {
			thisListBoxWidth = thisListBoxWidth * 0.94;
		}
		replacement.css('width', thisListBoxWidth + 'px');
		thisListBox.css({
			width: Math.round(thisListBoxWidth - 10) + 'px'
			//height: Math.round(thisListBoxSize * 18) + 'px'
		});
	});
};

(function ($) {
	$.sugerir = function (input, options) {
		var $input = $(input).attr("autocomplete", "off"),
			$resultsDiv = $('#' + options.resultsDiv),
			$resultsDivUl = $('#' + options.resultsDiv + ' ul#ulresultados'),
			timeout = false,		// hold timeout ID for suggestion results to appear	
			prevLength = 0,			// last recorded length of $input.val()
			cacheSize = 0,			// size of cache in chars (bytes?)
			error = false;
			
		if (options.sigueSugiriendo) {
			sugerir();
			return true;
		}

		$.sugerir.cache = [];

		$resultsDiv.addClass(options.resultsClass);
		function getCurrentResult() {
			var result = [],
				$currentResult = $resultsDivUl.children('li.' + options.selectClass),
				icoords = '',
				iviewport = '', 
				ipais = '',
				iregion = '',
				iprovincia = '',
				icomarca = '',
				ilocalidad = '';
			if (!$resultsDiv.is(':visible') || !$currentResult.length) {
				return false;
			}
			$.each($currentResult.children('input'), function (index, value) { 
				eval($(this).attr('id') + ' = "' + $(this).val() + '";'); 
			});
			result.push({
				cont: $currentResult,
				text: $currentResult.text(),
				viewport: iviewport.replace(/[\(\)]/g, ''),
				coords: icoords.replace(/[\(\)]/g, ''),
				pais: ipais,
				region: iregion,
				provincia: iprovincia,				
				comarca: icomarca,				
				localidad: ilocalidad
			});
			return result;
		}
		function prevResult() {
			var $currentResult = getCurrentResult();
			if (error == false){
				if ($currentResult) {
					$currentResult = $currentResult[0].cont;
					$currentResult.removeClass(options.selectClass).prev().addClass(options.selectClass);
				} else {
					$resultsDivUl.children('li:last-child').addClass(options.selectClass);
				}
			}
		}
		function nextResult() {
			var $currentResult = getCurrentResult();
			if (error == false){
				if ($currentResult) {
					$currentResult = $currentResult[0].cont;
					$currentResult.removeClass(options.selectClass).next().addClass(options.selectClass);
				} else {
					$resultsDivUl.children('li:first-child').addClass(options.selectClass);
				}
			}
		}
		function selectCurrentResult() {
			var $fixeddirdiv,
				coords,
				lat,
				lng,
				point,
				mostrarmarker,
				zoom,
				viewport,
				lat1,
				lng1,
				lat2,
				lng2,
				southWest,
				northEast,
				$currentResult = getCurrentResult();
			if ($currentResult) {
				$input.val($currentResult[0].text);
				if (options.src !== 'mapa') {
					VAPAYA.direccionBusqueda.direccion.hacerFijaDireccion($currentResult);
				} else {
					VAPAYA.direccionBusqueda.direccion.hacerFijaDireccionMapa($currentResult, true);
					VAPAYA.direccionBusqueda.direccion.hacerFijaDireccion($currentResult);
				}
			}
			
			$resultsDiv.hide();
		}
		function comprobarCache(q) {
			var i;
			for (i = 0; i < $.sugerir.cache.length; i = i + 1) {
				if ($.sugerir.cache[i].q === q) {
					$.sugerir.cache.unshift($.sugerir.cache.splice(i, 1)[0]);
					return $.sugerir.cache[0];
				}
			}
			return false;
		}
		function mostrarItems(items) {
			var i,
				html = '';
			if (!items) {
				return;
			}
			if (!items.length) {
				$resultsDiv.hide();
				return;
			}
			for (i = 0; i < items.length; i = i + 1) {
				html += '<li>' + items[i] + '</li>';
			}
			html += '';
			$resultsDivUl.html(html);
			$resultsDiv.show();
			if (error === false) {
				$resultsDivUl.children('li:first-child').addClass(options.selectClass);
				$resultsDivUl.children('li').mouseover(function () {
					$resultsDivUl.children('li').removeClass(options.selectClass);
					$(this).addClass(options.selectClass);
				}).mouseout(function () {
					$resultsDivUl.children('li').removeClass(options.selectClass);
				}).click(function (e) {
					VAPAYA.detenerEvento(e);
					selectCurrentResult();
				});
			}
		}
		function parseTxt(txt, q) {
			var i, token,
				items = [],
				tokens = txt.split(options.delimiter);
			// parse returned data for non-empty items
			for (i = 0; i < tokens.length; i = i + 1) {
				token = $.trim(tokens[i]);
				if (token) {
					items[items.length] = token;
				}
			}
			return items;
		}
		function anadirCache(q, items, size) {
			while ($.sugerir.cache.length && (cacheSize + size > options.maxCacheSize)) {
				var cached = $.sugerir.cache.pop();
				cacheSize -= cached.size;
			}
			$.sugerir.cache.push({
				q: q,
				size: size,
				items: items
			});
			cacheSize += size;
		}
		function encontrarDireccion(q) {
			var geocoder = VAPAYA.direccionBusqueda.mapas.geocoder,
				query = {'address': q, 'region': VAPAYA.pais.codigoPais, 'language': vapayaTexts.lang},
				point = geocoder.geocode(query, function (results, status) {
					var x, 
						a, 
						viewport, 
						place, 
						tipos, 
						tipo, 
						z, 
						addressComponent, 
						j, 
						componentType, 
						items, 
						check,
						pais,
						pais_input,
						region,
						region_input,
						provincia,
						provincia_input,
						comarca,
						comarca_input,
						localidad,
						localidad_input,
						msg = "",
						coords = "",
						error_msg = '',
						accepted_types = ['street_address', 'route', 'intersection', 'airport', 'park', 'point_of_interest', 'street_number', 'train_station', 'transit_station', 'establishment'],
						num_places = 0,
						app = '';
						//////////
					
					if (!results || status !== google.maps.GeocoderStatus.OK) {
						error_msg = vapayaTexts.noencontrado + ' "' + q + '", ' + vapayaTexts.reintentar;
					} else {
						bucleplaces:  for (x in results) {
							pais = '';
							pais_input = '';
							region = '';
							region_input = '';
							provincia = '';
							provincia_input = '';
							comarca = '';
							comarca_input = '';
							localidad = '';
							localidad_input = '';
							place = results[x];
							tipos = place.types;
							
							for (a in tipos) {
								tipo = tipos[a];
								check = $.inArray(tipo, accepted_types);
								
								if (check !== -1) {
									
									viewport = place.geometry.viewport;
									coords = place.geometry.location;
									
									for (z in place.address_components) {
										addressComponent = place.address_components[z];
										
										for (j in addressComponent.types) {
											componentType = addressComponent.types[j];
											switch (componentType) {
											case 'country':
												pais = addressComponent.short_name;
												if (pais !== VAPAYA.pais.codigoPais) {
													break bucleplaces;
												}
												pais_input = '<input id="ipais" type="hidden" value="' + pais + '" />';
												break;
											case 'administrative_area_level_1':
												region = addressComponent.short_name;
												region_input = '<input id="iregion" type="hidden" value="' + region + '" />';
												break;
											case 'administrative_area_level_2':
												provincia = addressComponent.short_name;
												provincia_input = '<input id="iprovincia" type="hidden" value="' + provincia  + '" />';
												break;
											case 'administrative_area_level_3':
												comarca = addressComponent.short_name;
												console.log(comarca);
												comarca_input = '<input id="icomarca" type="hidden" value="' + comarca + '" />';
												break;
											case 'locality':
												localidad = addressComponent.short_name;
												localidad_input = '<input id="ilocalidad" type="hidden" value="' + localidad + '" />';
												break;
											}
										}
									}
									msg += place.formatted_address;
									msg += '<input id="icoords" type="hidden" value="' + coords + '" />';
									msg += '<input id="iviewport" type="hidden" value="' + viewport + '" />';
									if (typeof(pais_input) !== 'undefined') {
										msg += pais_input;
									}
									if (typeof(region_input) !== 'undefined') {
										msg += region_input;
									}
									if (typeof(provincia_input) !== 'undefined') {
										msg += provincia_input;
									}
									if (typeof(comarca_input) !== 'undefined') {
										msg += comarca_input;
									}
									if (typeof(localidad_input) !== 'undefined') {
										msg += localidad_input;
									}
									msg += "\n";
									num_places = num_places + 1;
									break;
								}
								
							}
							
						}
						
						if (num_places === 0) {
							error_msg = vapayaTexts.noencontrado + ' "' + q + '", ' + vapayaTexts.reintentar;
						}
					}
					
					if (error_msg !== '') {
						error_msg = parseTxt(error_msg, q);
						error = true;
						mostrarItems(error_msg);
						return;
					}
					items = parseTxt(msg, q);
					error = false;
					mostrarItems(items);
					anadirCache(q, items, msg.length);
				});
		}
		function sugerir() {
			var cached,
				q = $.trim($input.val());
			if (q.length >= options.minchars) {
				cached = comprobarCache(q);
				if (cached) {
					error = false;
					mostrarItems(cached.items, false);
				} else {
					encontrarDireccion(q);
				}
			} else {
				$resultsDiv.hide();
			}
		}
		function procesarTecla(e) {
			// handling up/down/escape requires results to be visible
			// handling enter/tab requires that AND a result to be selected
			if ((/27$|38$|40$/.test(e.keyCode) && $resultsDiv.is(':visible')) ||
					(/^13$|^9$/.test(e.keyCode) && getCurrentResult())) {
				VAPAYA.detenerEvento(e);
				switch (e.keyCode) {
				case 38: // up
					prevResult();
					break;
				case 40: // down
					nextResult();
					break;
				case 9:  // tab
				case 13: // return
					selectCurrentResult();
					break;
				case 27: //	escape
					$resultsDiv.hide();
					break;
				}
			} else if ($input.val().length !== prevLength) {
				if (timeout) { 
					clearTimeout(timeout);
				}
				timeout = setTimeout(sugerir, options.delay);
				prevLength = $input.val().length;
			}			
		}
		function sigueSugiriendo () {					   
			if ($input.val().length != 0) {
				sugerir();
			}
		}
		if ($.browser.mozilla) {
			$input.keypress(procesarTecla);	// onkeypress repeats arrow keys in Mozilla/Opera
		} else {
			$input.keydown(procesarTecla);		// onkeydown repeats arrow keys in IE/Safari
		}
		
		$(document).click(function (e) {
			if(e.isPropagationStopped()) return;
			$('#user_dir').val('');
			if ($('#cont_paises').is(':visible')) {
				$('.tt, .ta').toggle();
			}
			$resultsDiv.hide();
		});
		
	};
	
	$.fn.sugerir = function (options) {
		options = options || {};
		options.delay = options.delay || 100;
		options.resultsDiv = options.resultsDiv || 'localizdiv';
		options.resultsClass = options.resultsClass || 'ac_results';
		options.selectClass = options.selectClass || 'ac_over';
		options.matchClass = options.matchClass || 'ac_match';
		options.minchars = options.minchars || 2;
		options.delimiter = options.delimiter || '\n';
		options.maxCacheSize = options.maxCacheSize || 65536;
		options.sigueSugiriendo = options.sigueSugiriendo || false;
		options.src = options.src || '';
		this.each(function () {
			new $.sugerir(this, options);
		});

		return this;
		
	};
	
})(jQuery);

(function($) {
	$.fn.jCarouselLite = function(o) {
		o = $.extend({
			btnPrev: null,
			btnNext: null,
			btnGo: null,
			mouseWheel: false,
			auto: null,
	
			speed: 200,
			easing: null,
	
			vertical: false,
			circular: true,
			visible: 6,
			start: 0,
			scroll: 2,
	
			beforeStart: null,
			afterEnd: null
		}, o || {});
	
		return this.each(function() {                           // Returns the element collection. Chainable.
	
			var running = false, animCss=o.vertical?"top":"left", sizeCss=o.vertical?"height":"width";
			var div = $(this), ul = $("ul", div), tLi = $("li", ul), tl = tLi.size(), v = o.visible;
	
			if(o.circular) {
				ul.prepend(tLi.slice(tl-v-1+1).clone())
				  .append(tLi.slice(0,v).clone());
				o.start += v;
			}
	
			var li = $("li", ul), itemLength = li.size(), curr = o.start;
			div.css("visibility", "visible");
	
			li.css({overflow: "hidden", float: o.vertical ? "none" : "left"});
			ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"});
			div.css({overflow: "hidden", position: "relative", "z-index": "2", left: "0px"});
	
			var liSize = o.vertical ? height(li) : width(li);   // Full li size(incl margin)-Used for animation
			var ulSize = liSize * itemLength;                   // size of full ul(total length, not just for the visible items)
			var divSize = liSize * v;                           // size of entire div(total length for just the visible items)
	
			li.css({width: li.width(), height: li.height()});
			ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize));
	
			div.css(sizeCss, divSize+"px");                     // Width of the DIV. length of visible images
	
			if(o.btnPrev)
				$(o.btnPrev).click(function() {
					return go(curr-o.scroll);
				});
	
			if(o.btnNext)
				$(o.btnNext).click(function() {
					return go(curr+o.scroll);
				});
	
			if(o.btnGo)
				$.each(o.btnGo, function(i, val) {
					$(val).click(function() {
						return go(o.circular ? o.visible+i : i);
					});
				});
	
			if(o.mouseWheel && div.mousewheel)
				div.mousewheel(function(e, d) {
					return d>0 ? go(curr-o.scroll) : go(curr+o.scroll);
				});
	
			if(o.auto)
				setInterval(function() {
					go(curr+o.scroll);
				}, o.auto+o.speed);
	
			function vis() {
				return li.slice(curr).slice(0,v);
			};
	
			function go(to) {
				if(!running) {
	
					if(o.beforeStart)
						o.beforeStart.call(this, vis());
	
					if(o.circular) {            // If circular we are in first or last, then goto the other end
						if(to<=o.start-v-1) {           // If first, then goto last
							ul.css(animCss, -((itemLength-(v*2))*liSize)+"px");
							// If "scroll" > 1, then the "to" might not be equal to the condition; it can be lesser depending on the number of elements.
							curr = to==o.start-v-1 ? itemLength-(v*2)-1 : itemLength-(v*2)-o.scroll;
						} else if(to>=itemLength-v+1) { // If last, then goto first
							ul.css(animCss, -( (v) * liSize ) + "px" );
							// If "scroll" > 1, then the "to" might not be equal to the condition; it can be greater depending on the number of elements.
							curr = to==itemLength-v+1 ? v+1 : v+o.scroll;
						} else curr = to;
					} else {                    // If non-circular and to points to first or last, we just return.
						if(to<0 || to>itemLength-v) return;
						else curr = to;
					}                           // If neither overrides it, the curr will still be "to" and we can proceed.
	
					running = true;
	
					ul.animate(
						animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing,
						function() {
							if(o.afterEnd)
								o.afterEnd.call(this, vis());
							running = false;
						}
					);
					// Disable buttons when the carousel reaches the last/first, and enable when not
					if(!o.circular) {
						$(o.btnPrev + "," + o.btnNext).removeClass("disabled");
						$( (curr-o.scroll<0 && o.btnPrev)
							||
						   (curr+o.scroll > itemLength-v && o.btnNext)
							||
						   []
						 ).addClass("disabled");
					}
	
				}
				return false;
			};
		});
	};
	
	function css(el, prop) {
		return parseInt($.css(el[0], prop)) || 0;
	};
	function width(el) {
		return  el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
	};
	function height(el) {
		return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
	};

})(jQuery);

$(document).bind("dragstart", function() {
	return false;
}).ready( function() {
	VAPAYA.palabrasClaveBusqueda.iniciar();
	VAPAYA.direccionBusqueda.iniciar();
	VAPAYA.busquedaAvanzada.iniciar();
	VAPAYA.formularioAccesoSuperior.iniciar();
	VAPAYA.barraInfoAnuncios.iniciar();
	VAPAYA.envioFormularioBusqueda.iniciar();
	VAPAYA.ayuda.iniciar();
	VAPAYA.idiomas.iniciar();
	VAPAYA.anunciar.iniciar();
	VAPAYA.contactar.iniciar();
	VAPAYA.resultados.iniciar();
	VAPAYA.paginacion.iniciar();
	VAPAYA.valorarResultado.iniciar();
	VAPAYA.comentarResultado.iniciar();
	VAPAYA.imagenesResultado.iniciar();		
	VAPAYA.validacionesFormularios.iniciar();
	VAPAYA.ui.uiInitialize();
	
	if (VAPAYA.pais.codigoPais != '') {
		geocoder_query = {'address': vapayaTexts[VAPAYA.pais.codigoPais]};
		VAPAYA.direccionBusqueda.mapas.mapGeocode(geocoder_query, 'country', function(data){
			VAPAYA.pais.geodata.viewport = data.viewport;
			VAPAYA.pais.geodata.coords = data.coords;
		});
	}
	if (VAPAYA.ciudad.codigoCiudad != '') {
		geocoder_query = {'address': VAPAYA.ciudad.codigoCiudad + ', ' + vapayaTexts[VAPAYA.pais.codigoPais]};
		VAPAYA.direccionBusqueda.mapas.mapGeocode(geocoder_query, 'locality', function(data){
			VAPAYA.ciudad.geodata.viewport = data.viewport;
			VAPAYA.ciudad.geodata.coords = data.coords;
		});
	}
	
	$("#carousel").jCarouselLite({
		btnNext: "#car_right",
		btnPrev: "#car_left"
	});
});

//Embellece la tipografía
//Cufon.replace('.col h2, h4 label, span#sendbtn, p.mensajes, #s_head, ul.ayuda_menu li, #nav span.txt, .enc, p.t, .posts_navigation a, .menu li').replace('h1 label, #logo_p', {
	//textShadow: '#666 1px 1px'
//});

//Empezamos!!
VAPAYA.iniciar();

