function pasaraURL(valor)
{
	if(valor!=null)
	{
		original = new Array("Ñ","&Ntilde;","&ntilde;","ñ","Á","É","Í","À","È","Ì","Ò","Ù","Î","î","ø","Ó","Ú","á","é","í","ó","ú","à","è","ì","ò","ù","Å"," ",",","&aacute;","&eacute;","&iacute;","&oacute;","&uacute;","&Aacute;","&Eacute;","&Iacute;","&Oacute;","&Uacute;","'","---","/","&acute;");
		cambio = new Array(  "N",       "N",       "n","n","A","E","I","A","E","I","O","U","I","i","o","O","U","a","e","i","o","u","a","e","i","o","u","A","-", "",       "a",       "e",       "i",       "o",       "u",       "A",       "E",       "I",       "O",       "U", "",  "-","-","");
	
		for(i=0;i<original.length;i++)
		{
			aux=new RegExp(original[i],'g');
			valor=valor.replace(aux,cambio[i]);
		}
		// . y * se cambian aparte para no provocar errores
		valor=valor.replace(/\*/g,'');
		valor=valor.replace(/\./g,'');
		return valor.toLowerCase();
	}
	else
		return '';
}

function quitarComillas(valor)
{
	if(valor!=null)
	{
		original = new Array("'",'"',"`","´");
		cambio = new Array("&#39;","&#39;","&#39;","&#39;");
	
		for(i=0;i<original.length;i++)
		{
			aux=new RegExp(original[i],'g');
			valor=valor.replace(aux,cambio[i]);
		}
		
		return valor.toLowerCase();
	}
	else
		return '';
}

function emailValido(email) 
{       
        var filtro=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
        if (filtro.test(email))	        
            return true;	        
        else
            return false;
}

function br2nl(texto)
{
	texto=texto.replace(/\n/ig,'');
	texto=texto.replace(/\<BR\>/ig,'\n');
	texto=texto.replace(/\<BR\/\>/ig,'\n');
	texto=texto.replace(/\<BR \/\>/ig,'\n');
	return texto;
	
}


///////////GOOGLEMAPS////////////
var map=null;
var infow_ficha = null;
var marcador=null;
var directionsDisplay = null;
var directionsService = null;
var listener_drag=null;
var listener_click=null;
var sin_ubicar=false;
geocoder = null;

function createMarker(punto,textoPintar,nombre)
{		
	var options = {
		position:punto,
		title:nombre
		};
	
	var marker = new google.maps.Marker(options);
	var infowindow = new google.maps.InfoWindow({
		content:textoPintar
		});

	google.maps.event.addListener(marker,"click",function()
		{
			if (infow_ficha != null)
				infow_ficha.close();
			infow_ficha = infowindow;
			infow_ficha.open(map,marker);
		});
	marcador=marker;
	return marker;
}

function mostrarMapa(nivel,idProvincia,idPoblacion,idPedania,idCasa)
{			
	directionsDisplay = new google.maps.DirectionsRenderer();
	directionsService = new google.maps.DirectionsService();
	geocoder = new google.maps.Geocoder();
	
		$.getJSON("./include/googlemaps.php",{
				nivel: nivel,
				provincia: idProvincia,
				poblacion: idPoblacion,
				pedania: idPedania,
				casa: idCasa
				},
				function(data){ 
					
					if(data.centro['y']=='' && data.centro['x']=='')
					{
						// Si no hay coordenadas y estamos editando iremos a una ubicación por defecto
						if(editar)
						{
							data.centro['x']='-3.7003454';
							data.centro['y']='40.4166909';
							$('#coord_x').val(data.centro['x']);
							$('#coord_y').val(data.centro['y']);
							data.zoom=14;
							sin_ubicar=true;
						}
						else
						{
							$('#casa_mapa').html("<br/>Ubicaci&oacute;n no disponible");
							$('#casa_mapa').css({'height':'20px','font-size':'18px'});
						}
						// Ocultamos el cálculo de rutas
						$('#comollegar').css('display','none');						
						
					}
					
					if(nivel==13 && data.centro['y']!='' && data.centro['x']!='' || nivel==4 || nivel==6 || nivel==7)
					{
						var marca=null;
						var myLatlng = new google.maps.LatLng(data.centro['y'],data.centro['x']);
						var myOptions = {
						  scrollwheel: false,
						  zoom: data.zoom,
						  center: myLatlng,
						  mapTypeId: google.maps.MapTypeId.ROADMAP						  
						}; 
						map = new google.maps.Map(document.getElementById("map"), myOptions); 			
						
						for(i=0;i<data.coordenadas.length;i++)
						{
							if(data.coordenadas[i]['x']!='' && data.coordenadas[i]['y']!='')
							{ 
								marca=createMarker(new google.maps.LatLng(data.coordenadas[i]['y'],data.coordenadas[i]['x']),data.infow[i],data.coordenadas[i]['nombre']);
								marca.setMap(map);
							}
						}
						
					}
					
					if(editar)
					{
						$('#editar_mapa').click(editarMapa);
						$('#guardar_mapa').live('click',guardarMapa);
						$('#cancelar_mapa').live('click',cancelarMapa);
						$('#buscar_ubicacion').live('click',function(){
							buscarUbicacion($('#ubicacion').val());
						});
						$('#ubica').live('keypress',function(e){
							if(e.keyCode==13) buscarUbicacion($('#ubica').val());
						});
					}
				});
}

function calcularRuta(direccion)
{
	
	var geocoder = new google.maps.Geocoder();
	var peticionGeocoder = {
		address: direccion,
		language:"spanish",
		region:"ES"
	};
	
	geocoder.geocode(peticionGeocoder, function(resultado,estado)
	{ 
		var punto = null; 
		if (estado == google.maps.GeocoderStatus.OK)
		{	
			directionsDisplay.setMap(null);
			punto = resultado[0].geometry.location;	
			directionsDisplay.setMap(map); 
			var request = {
					origin:punto, 
					destination:marcador.position,
					travelMode: google.maps.DirectionsTravelMode.DRIVING,
					unitSystem: google.maps.DirectionsUnitSystem.METRIC,
					region: 'es'
			};
			directionsService.route(request, function(response, status) {
				if (status == google.maps.DirectionsStatus.OK) {
					directionsDisplay.setDirections(response);
				}
			});
		}
		else
			alert(direccion + " no encontrada");
	});
}

function buscarUbicacion(direccion)
{
	var peticionGeocoder = {
			address: direccion,
			language:"spanish",
			region:"ES"
		};
		
		geocoder.geocode(peticionGeocoder, function(resultado,estado)
		{
			var result = "";
			var punto = null;
			if (estado == google.maps.GeocoderStatus.OK)
			{	
				punto = resultado[0].geometry.location;
				result = resultado[0].formatted_address;
				map.setCenter(punto);
				marcador.setPosition(punto);
				
			}
			else
				alert(direccion + " no encontrada");
		});		
}

function editarMapa()
{
	$('#comollegar').css('display','none');
	$('#editar_mapa').css('display','none');
	$('#editar_mapa').after('<input type="button" id="guardar_mapa" value="Guardar"/><input type="button" id="cancelar_mapa" value="Cancelar"/>');
	$('#comollegar').before('<div id="div_ubicacion"><label>Buscar ubicaci&oacute;n:</label><input type="text" id="ubica" size="42"/><input type="button" class="bt_submit" id="buscar_ubicacion" value="Buscar"/></div>');
	$('#nuevo_x').val($('#coord_x').val());
	$('#nuevo_y').val($('#coord_y').val());
	if(marcador)
	{
		marcador.setDraggable(true);
		listener_drag=google.maps.event.addListener(marcador, "dragend", function(){
			guardarPosicionMarcador();
		});
	}
	listener_click=google.maps.event.addListener(map,"click",function(event){
		if(!marcador)
		{
			marcador=createMarker(event.latLng,null,null);
			marcador.setDraggable(true);
			listener_drag=google.maps.event.addListener(marcador, "dragend", function(){
				guardarPosicionMarcador();
			});
			marcador.setMap(map);
		}
		marcador.setPosition(event.latLng);
		guardarPosicionMarcador();
	});
}

function guardarMapa()
{
	if(marcador!=null)
	{
		var sessionid=$("#sessionid").val();
		var userid=$('#userid').val();
		var idcasa=$('#idcasa').val();
		var x=$('#nuevo_x').val();
		var y=$('#nuevo_y').val(); 
		$.post('./include/administrar/guardar_cambios.php',{sessionid:sessionid,userid:userid,idcasa:idcasa,x:x,y:y,tipo:"6"},function(respuesta){
			if(respuesta!=0)
				//alert("Se ha producido un error");
				alert(respuesta);
			else
			{
				$('#coord_x').val($('#nuevo_x').val());
				$('#coord_y').val($('#nuevo_y').val());
				if(sin_ubicar==true)
				{
					sin_ubicar=false;
					$('#comollegar').css('display','block');	
				}
				cancelarMapa();
			}
			
		});
	}
	else 
		cancelarMapa();
}

function cancelarMapa()
{
	if(marcador!=null)
	{
		google.maps.event.removeListener(listener_drag);
		google.maps.event.removeListener(listener_click);
		marcador.setDraggable(false);
		var punto=new google.maps.LatLng($('#coord_y').val(),$('#coord_x').val());
		marcador.setPosition(punto);
	}	
	map.setCenter(punto);
	$('#guardar_mapa').remove();
	$('#cancelar_mapa').remove();
	$('#div_ubicacion').remove();
	$('#editar_mapa').css('display','inline');	
	
	if(marcador!=null && sin_ubicar==true)
	{ 
		marcador.setMap(null);
		marcador=null;	
	}
	if(sin_ubicar==false)
		$('#comollegar').css('display','block');
}

function guardarPosicionMarcador()
{
	$('#nuevo_x').val(marcador.position.lng());
	$('#nuevo_y').val(marcador.position.lat());
}


/////GALERÍA DE FOTOS AD-GALLERY////
/**
 * Copyright (c) 2010 Anders Ekdahl (http://coffeescripter.com/)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Version: 1.2.4
 *
 * Demo and documentation: http://coffeescripter.com/code/ad-gallery/
 */
(function($) {
  $.fn.adGallery = function(options) {
    var defaults = { loader_image: 'imagenes/loader.gif',
                     start_at_index: 0,
                     description_wrapper: false,
                     thumb_opacity: 0.7,
                     animate_first_image: false,
                     animation_speed: 400,
                     width: false,
                     height: false,
                     display_next_and_prev: true,
                     display_back_and_forward: true,
                     scroll_jump: 0, // If 0, it jumps the width of the container
                     slideshow: {
                       enable: true,
                       autostart: false,
                       speed: 5000,
                       start_label: 'Start',
                       stop_label: 'Stop',
                       stop_on_scroll: true,
                       countdown_prefix: '(',
                       countdown_sufix: ')',
                       onStart: false,
                       onStop: false
                     },
                     effect: 'slide-hori', // or 'slide-vert', 'fade', or 'resize', 'none'
                     enable_keyboard_move: true,
                     cycle: true,
                     callbacks: {
                       init: false,
                       afterImageVisible: false,
                       beforeImageVisible: false
                     }
    };
    var settings = $.extend(false, defaults, options);
    if(options && options.slideshow) {
      settings.slideshow = $.extend(false, defaults.slideshow, options.slideshow);
    };
    if(!settings.slideshow.enable) {
      settings.slideshow.autostart = false;
    };
    var galleries = [];
    $(this).each(function() {
      var gallery = new AdGallery(this, settings);
      galleries[galleries.length] = gallery;
    });
    // Sorry, breaking the jQuery chain because the gallery instances
    // are returned so you can fiddle with them
    return galleries;
  };

  function VerticalSlideAnimation(img_container, direction, desc) {
    var current_top = parseInt(img_container.css('top'), 10);
    if(direction == 'left') {
      var old_image_top = '-'+ this.image_wrapper_height +'px';
      img_container.css('top', this.image_wrapper_height +'px');
    } else {
      var old_image_top = this.image_wrapper_height +'px';
      img_container.css('top', '-'+ this.image_wrapper_height +'px');
    };
    if(desc) {
      desc.css('bottom', '-'+ desc[0].offsetHeight +'px');
      desc.animate({bottom: 0}, this.settings.animation_speed * 2);
    };
    if(this.current_description) {
      this.current_description.animate({bottom: '-'+ this.current_description[0].offsetHeight +'px'}, this.settings.animation_speed * 2);
    };
    return {old_image: {top: old_image_top},
            new_image: {top: current_top}};
  };

  function HorizontalSlideAnimation(img_container, direction, desc) {
    var current_left = parseInt(img_container.css('left'), 10);
    if(direction == 'left') {
      var old_image_left = '-'+ this.image_wrapper_width +'px';
      img_container.css('left',this.image_wrapper_width +'px');
    } else {
      var old_image_left = this.image_wrapper_width +'px';
      img_container.css('left','-'+ this.image_wrapper_width +'px');
    };
    if(desc) {
      desc.css('bottom', '-'+ desc[0].offsetHeight +'px');
      desc.animate({bottom: 0}, this.settings.animation_speed * 2);
    };
    if(this.current_description) {
      this.current_description.animate({bottom: '-'+ this.current_description[0].offsetHeight +'px'}, this.settings.animation_speed * 2);
    };
    return {old_image: {left: old_image_left},
            new_image: {left: current_left}};
  };

  function ResizeAnimation(img_container, direction, desc) {
    var image_width = img_container.width();
    var image_height = img_container.height();
    var current_left = parseInt(img_container.css('left'), 10);
    var current_top = parseInt(img_container.css('top'), 10);
    img_container.css({width: 0, height: 0, top: this.image_wrapper_height / 2, left: this.image_wrapper_width / 2});
    return {old_image: {width: 0,
                        height: 0,
                        top: this.image_wrapper_height / 2,
                        left: this.image_wrapper_width / 2},
            new_image: {width: image_width,
                        height: image_height,
                        top: current_top,
                        left: current_left}};
  };

  function FadeAnimation(img_container, direction, desc) {
    img_container.css('opacity', 0);
    return {old_image: {opacity: 0},
            new_image: {opacity: 1}};
  };

  // Sort of a hack, will clean this up... eventually
  function NoneAnimation(img_container, direction, desc) {
    img_container.css('opacity', 0);
    return {old_image: {opacity: 0},
            new_image: {opacity: 1},
            speed: 0};
  };

  function AdGallery(wrapper, settings) {
    this.init(wrapper, settings);
  };
  AdGallery.prototype = {
    // Elements
    wrapper: false,
    image_wrapper: false,
    gallery_info: false,
    nav: false,
    loader: false,
    preloads: false,
    thumbs_wrapper: false,
    scroll_back: false,
    scroll_forward: false,
    next_link: false,
    prev_link: false,

    slideshow: false,
    image_wrapper_width: 0,
    image_wrapper_height: 0,
    current_index: 0,
    current_image: false,
    current_description: false,
    nav_display_width: 0,
    settings: false,
    images: false,
    in_transition: false,
    animations: false,
    init: function(wrapper, settings) {
      var context = this;
      this.wrapper = $(wrapper);
      this.settings = settings;
      this.setupElements();
      this.setupAnimations();
      if(this.settings.width) {
        this.image_wrapper_width = this.settings.width;
        this.image_wrapper.width(this.settings.width);
        this.wrapper.width(this.settings.width);
      } else {
        this.image_wrapper_width = this.image_wrapper.width();
      };
      if(this.settings.height) {
        this.image_wrapper_height = this.settings.height;
        this.image_wrapper.height(this.settings.height);
      } else {
        this.image_wrapper_height = this.image_wrapper.height();
      };
      this.nav_display_width = this.nav.width();
      this.current_index = 0;
      this.current_image = false;
      this.current_description = false;
      this.in_transition = false;
      this.findImages();
      if(this.settings.display_next_and_prev) {
        this.initNextAndPrev();
      };
      // The slideshow needs a callback to trigger the next image to be shown
      // but we don't want to give it access to the whole gallery instance
      var nextimage_callback = function(callback) {
        return context.nextImage(callback);
      };
      this.slideshow = new AdGallerySlideshow(nextimage_callback, this.settings.slideshow);
      this.controls.append(this.slideshow.create());
      if(this.settings.slideshow.enable) {
        this.slideshow.enable();
      } else {
        this.slideshow.disable();
      };
      if(this.settings.display_back_and_forward) {
        this.initBackAndForward();
      };
      if(this.settings.enable_keyboard_move) {
        this.initKeyEvents();
      };
      var start_at = parseInt(this.settings.start_at_index, 10);
      if(window.location.hash && window.location.hash.indexOf('#ad-image') === 0) {
        start_at = window.location.hash.replace(/[^0-9]+/g, '');
        // Check if it's a number
        if((start_at * 1) != start_at) {
          start_at = this.settings.start_at_index;
        };
      };

      this.loading(true);
      this.showImage(start_at,
        function() {
          // We don't want to start the slideshow before the image has been
          // displayed
          if(context.settings.slideshow.autostart) {
            context.preloadImage(start_at + 1);
            context.slideshow.start();
          };
        }
      );
      this.fireCallback(this.settings.callbacks.init);
    },
    setupAnimations: function() {
      this.animations = {
        'slide-vert': VerticalSlideAnimation,
        'slide-hori': HorizontalSlideAnimation,
        'resize': ResizeAnimation,
        'fade': FadeAnimation,
        'none': NoneAnimation
      };
    },
    setupElements: function() {
      this.controls = this.wrapper.find('.ad-controls');
      this.gallery_info = $('<p class="ad-info"></p>');
      this.controls.append(this.gallery_info);
      this.image_wrapper = this.wrapper.find('.ad-image-wrapper');
      this.image_wrapper.empty();
      this.nav = this.wrapper.find('.ad-nav');
      this.thumbs_wrapper = this.nav.find('.ad-thumbs');
      this.preloads = $('<div class="ad-preloads"></div>');
      this.loader = $('<img class="ad-loader" src="'+ this.settings.loader_image +'">');
      this.image_wrapper.append(this.loader);
      this.loader.hide();
      $(document.body).append(this.preloads);
    },
    loading: function(bool) {
      if(bool) {
        this.loader.show();
      } else {
        this.loader.hide();
      };
    },
    addAnimation: function(name, fn) {
      if($.isFunction(fn)) {
        this.animations[name] = fn;
      };
    },
    findImages: function() {
      var context = this;
      this.images = [];
      var thumb_wrapper_width = 0;
      var thumbs_loaded = 0;
      var thumbs = this.thumbs_wrapper.find('a');
      var thumb_count = thumbs.length;
      if(this.settings.thumb_opacity < 1) {
        thumbs.find('img').css('opacity', this.settings.thumb_opacity);
      };
      thumbs.each(
        function(i) {
          var link = $(this);
          var image_src = link.attr('href');
          var thumb = link.find('img');
          // Check if the thumb has already loaded
          if(!context.isImageLoaded(thumb[0])) {
            thumb.load(
              function() {
                thumb_wrapper_width += this.parentNode.parentNode.offsetWidth;
                thumbs_loaded++;
              }
            );
          } else{
            thumb_wrapper_width += thumb[0].parentNode.parentNode.offsetWidth;
            thumbs_loaded++;
          };
          link.addClass('ad-thumb'+ i);
          link.click(
            function() {
              context.showImage(i);
              context.slideshow.stop();
              return false;
            }
          ).hover(
            function() {
              if(!$(this).is('.ad-active') && context.settings.thumb_opacity < 1) {
                $(this).find('img').fadeTo(300, 1);
              };
              context.preloadImage(i);
            },
            function() {
              if(!$(this).is('.ad-active') && context.settings.thumb_opacity < 1) {
                $(this).find('img').fadeTo(300, context.settings.thumb_opacity);
              };
            }
          );
          var link = false;
          if(thumb.data('ad-link')) {
            link = thumb.data('ad-link');
          } else if(thumb.attr('longdesc') && thumb.attr('longdesc').length) {
            link = thumb.attr('longdesc');
          };
          var desc = false;
          if(thumb.data('ad-desc')) {
            desc = thumb.data('ad-desc');
          } else if(thumb.attr('alt') && thumb.attr('alt').length) {
            desc = thumb.attr('alt');
          };
          var title = false;
          if(thumb.data('ad-title')) {
            title = thumb.data('ad-title');
          } else if(thumb.attr('title') && thumb.attr('title').length) {
            title = thumb.attr('title');
          };
          context.images[i] = { thumb: thumb.attr('src'), image: image_src, error: false,
                                preloaded: false, desc: desc, title: title, size: false,
                                link: link };
        }
      );
      // Wait until all thumbs are loaded, and then set the width of the ul
      var inter = setInterval(
        function() {
          if(thumb_count == thumbs_loaded) {
            thumb_wrapper_width -= 100;
            var list = context.nav.find('.ad-thumb-list');
            list.css('width', thumb_wrapper_width +'px');
            var i = 1;
            var last_height = list.height();
            while(i < 201) {
              list.css('width', (thumb_wrapper_width + i) +'px');
              if(last_height != list.height()) {
                break;
              }
              last_height = list.height();
              i++;
            }
            clearInterval(inter);
          };
        },
        100
      );
    },
    initKeyEvents: function() {
      var context = this;
      $(document).keydown(
        function(e) {
          if(e.keyCode == 39) {
            // right arrow
            context.nextImage();
            context.slideshow.stop();
          } else if(e.keyCode == 37) {
            // left arrow
            context.prevImage();
            context.slideshow.stop();
          };
        }
      );
    },
    initNextAndPrev: function() {
      this.next_link = $('<div class="ad-next"><div class="ad-next-image"></div></div>');
      this.prev_link = $('<div class="ad-prev"><div class="ad-prev-image"></div></div>');
      this.image_wrapper.append(this.next_link);
      this.image_wrapper.append(this.prev_link);
      var context = this;
      this.prev_link.add(this.next_link).mouseover(
        function(e) {
          // IE 6 hides the wrapper div, so we have to set it's width
          $(this).css('height', context.image_wrapper_height);
          $(this).find('div').show();
        }
      ).mouseout(
        function(e) {
          $(this).find('div').hide();
        }
      ).click(
        function() {
          if($(this).is('.ad-next')) {
            context.nextImage();
            context.slideshow.stop();
          } else {
            context.prevImage();
            context.slideshow.stop();
          };
        }
      ).find('div').css('opacity', 0.7);
    },
    initBackAndForward: function() {
      var context = this;
      this.scroll_forward = $('<div class="ad-forward"></div>');
      this.scroll_back = $('<div class="ad-back"></div>');
      this.nav.append(this.scroll_forward);
      this.nav.prepend(this.scroll_back);
      var has_scrolled = 0;
      var thumbs_scroll_interval = false;
      $(this.scroll_back).add(this.scroll_forward).click(
        function() {
          // We don't want to jump the whole width, since an image
          // might be cut at the edge
          var width = context.nav_display_width - 50;
          if(context.settings.scroll_jump > 0) {
            var width = context.settings.scroll_jump;
          };
          if($(this).is('.ad-forward')) {
            var left = context.thumbs_wrapper.scrollLeft() + width;
          } else {
            var left = context.thumbs_wrapper.scrollLeft() - width;
          };
          if(context.settings.slideshow.stop_on_scroll) {
            context.slideshow.stop();
          };
          context.thumbs_wrapper.animate({scrollLeft: left +'px'});
          return false;
        }
      ).css('opacity', 0.6).hover(
        function() {
          var direction = 'left';
          if($(this).is('.ad-forward')) {
            direction = 'right';
          };
          thumbs_scroll_interval = setInterval(
            function() {
              has_scrolled++;
              // Don't want to stop the slideshow just because we scrolled a pixel or two
              if(has_scrolled > 30 && context.settings.slideshow.stop_on_scroll) {
                context.slideshow.stop();
              };
              var left = context.thumbs_wrapper.scrollLeft() + 1;
              if(direction == 'left') {
                left = context.thumbs_wrapper.scrollLeft() - 1;
              };
              context.thumbs_wrapper.scrollLeft(left);
            },
            10
          );
          $(this).css('opacity', 1);
        },
        function() {
          has_scrolled = 0;
          clearInterval(thumbs_scroll_interval);
          $(this).css('opacity', 0.6);
        }
      );
    },
    _afterShow: function() {
      this.gallery_info.html((this.current_index + 1) +' / '+ this.images.length);
      if(!this.settings.cycle) {
        // Needed for IE
        this.prev_link.show().css('height', this.image_wrapper_height);
        this.next_link.show().css('height', this.image_wrapper_height);
        if(this.current_index == (this.images.length - 1)) {
          this.next_link.hide();
        };
        if(this.current_index == 0) {
          this.prev_link.hide();
        };
      };
      this.fireCallback(this.settings.callbacks.afterImageVisible);
    },
    /**
     * Checks if the image is small enough to fit inside the container
     * If it's not, shrink it proportionally
     */
    _getContainedImageSize: function(image_width, image_height) {
      if(image_height > this.image_wrapper_height) {
        var ratio = image_width / image_height;
        image_height = this.image_wrapper_height;
        image_width = this.image_wrapper_height * ratio;
      };
      if(image_width > this.image_wrapper_width) {
  	    var ratio = image_height / image_width;
  	    image_width = this.image_wrapper_width;
  	    image_height = this.image_wrapper_width * ratio;
  	  };
      return {width: image_width, height: image_height};
    },
    /**
     * If the image dimensions are smaller than the wrapper, we position
     * it in the middle anyway
     */
    _centerImage: function(img_container, image_width, image_height) {
      img_container.css('top', '0px');
      if(image_height < this.image_wrapper_height) {
        var dif = this.image_wrapper_height - image_height;
        img_container.css('top', (dif / 2) +'px');
      };
      img_container.css('left', '0px');
      if(image_width < this.image_wrapper_width) {
        var dif = this.image_wrapper_width - image_width;
        img_container.css('left', (dif / 2) +'px');
      };
    },
    _getDescription: function(image) {
      var desc = false;
      if(image.desc.length || image.title.length) {
        var title = '';
        if(image.title.length) {
          title = '<strong class="ad-description-title">'+ image.title +'</strong>';
        };
        var desc = '';
        if(image.desc.length) {
          desc = '<span>'+ image.desc +'</span>';
        };
        desc = $('<p class="ad-image-description">'+ title + desc +'</p>');
      };
      return desc;
    },
    /**
     * @param function callback Gets fired when the image has loaded, is displaying
     *                          and it's animation has finished
     */
    showImage: function(index, callback) {
      if(this.images[index] && !this.in_transition) {
        var context = this;
        var image = this.images[index];
        this.in_transition = true;
        if(!image.preloaded) {
          this.loading(true);
          this.preloadImage(index, function() {
            context.loading(false);
            context._showWhenLoaded(index, callback);
          });
        } else {
          this._showWhenLoaded(index, callback);
        };
      };
    },
    /**
     * @param function callback Gets fired when the image has loaded, is displaying
     *                          and it's animation has finished
     */
    _showWhenLoaded: function(index, callback) {
      if(this.images[index]) {
        var context = this;
        var image = this.images[index];
        var img_container = $(document.createElement('div')).addClass('ad-image');
        var img = $(new Image()).attr('src', image.image);
        if(image.link) {
          var link = $('<a href="'+ image.link +'" target="_blank"></a>');
          link.append(img);
          img_container.append(link);
        } else {
          img_container.append(img);
        }
        this.image_wrapper.prepend(img_container);
        var size = this._getContainedImageSize(image.size.width, image.size.height);
        img.attr('width', size.width);
        img.attr('height', size.height);
        img_container.css({width: size.width +'px', height: size.height +'px'});
        this._centerImage(img_container, size.width, size.height);
        var desc = this._getDescription(image, img_container);
        if(desc) {
          if(!this.settings.description_wrapper) {
            img_container.append(desc);
            var width = size.width - parseInt(desc.css('padding-left'), 10) - parseInt(desc.css('padding-right'), 10);
            desc.css('width', width +'px');
          } else {
            this.settings.description_wrapper.append(desc);
          }
        };
        this.highLightThumb(this.nav.find('.ad-thumb'+ index));

        var direction = 'right';
        if(this.current_index < index) {
          direction = 'left';
        };
        this.fireCallback(this.settings.callbacks.beforeImageVisible);
        if(this.current_image || this.settings.animate_first_image) {
          var animation_speed = this.settings.animation_speed;
          var easing = 'swing';
          var animation = this.animations[this.settings.effect].call(this, img_container, direction, desc);
          if(typeof animation.speed != 'undefined') {
            animation_speed = animation.speed;
          };
          if(typeof animation.easing != 'undefined') {
            easing = animation.easing;
          };
          if(this.current_image) {
            var old_image = this.current_image;
            var old_description = this.current_description;
            old_image.animate(animation.old_image, animation_speed, easing,
              function() {
                old_image.remove();
                if(old_description) old_description.remove();
              }
            );
          };
          img_container.animate(animation.new_image, animation_speed, easing,
            function() {
              context.current_index = index;
              context.current_image = img_container;
              context.current_description = desc;
              context.in_transition = false;
              context._afterShow();
              context.fireCallback(callback);
            }
          );
        } else {
          this.current_index = index;
          this.current_image = img_container;
          context.current_description = desc;
          this.in_transition = false;
          context._afterShow();
          this.fireCallback(callback);
        };
      };
    },
    nextIndex: function() {
      if(this.current_index == (this.images.length - 1)) {
        if(!this.settings.cycle) {
          return false;
        };
        var next = 0;
      } else {
        var next = this.current_index + 1;
      };
      return next;
    },
    nextImage: function(callback) {
      var next = this.nextIndex();
      if(next === false) return false;
      this.preloadImage(next + 1);
      this.showImage(next, callback);
      return true;
    },
    prevIndex: function() {
      if(this.current_index == 0) {
        if(!this.settings.cycle) {
          return false;
        };
        var prev = this.images.length - 1;
      } else {
        var prev = this.current_index - 1;
      };
      return prev;
    },
    prevImage: function(callback) {
      var prev = this.prevIndex();
      if(prev === false) return false;
      this.preloadImage(prev - 1);
      this.showImage(prev, callback);
      return true;
    },
    preloadAll: function() {
      var context = this;
      var i = 0;
      function preloadNext() {
        if(i < context.images.length) {
          i++;
          context.preloadImage(i, preloadNext);
        };
      };
      context.preloadImage(i, preloadNext);
    },
    preloadImage: function(index, callback) {
      if(this.images[index]) {
        var image = this.images[index];
        if(!this.images[index].preloaded) {
          var img = $(new Image());
          img.attr('src', image.image);
          if(!this.isImageLoaded(img[0])) {
            this.preloads.append(img);
            var context = this;
            img.load(
              function() {
                image.preloaded = true;
                image.size = { width: this.width, height: this.height };
                context.fireCallback(callback);
              }
            ).error(
              function() {
                image.error = true;
                image.preloaded = false;
                image.size = false;
              }
            );
          } else {
            image.preloaded = true;
            image.size = { width: img[0].width, height: img[0].height };
            this.fireCallback(callback);
          };
        } else {
          this.fireCallback(callback);
        };
      };
    },
    isImageLoaded: function(img) {
      if(typeof img.complete != 'undefined' && !img.complete) {
        return false;
      };
      if(typeof img.naturalWidth != 'undefined' && img.naturalWidth == 0) {
        return false;
      };
      return true;
    },
    highLightThumb: function(thumb) {
      this.thumbs_wrapper.find('.ad-active').removeClass('ad-active');
      thumb.addClass('ad-active');
      if(this.settings.thumb_opacity < 1) {
        this.thumbs_wrapper.find('a:not(.ad-active) img').fadeTo(300, this.settings.thumb_opacity);
        thumb.find('img').fadeTo(300, 1);
      };
      var left = thumb[0].parentNode.offsetLeft;
      left -= (this.nav_display_width / 2) - (thumb[0].offsetWidth / 2);
      this.thumbs_wrapper.animate({scrollLeft: left +'px'});
    },
    fireCallback: function(fn) {
      if($.isFunction(fn)) {
        fn.call(this);
      };
    }
  };

  function AdGallerySlideshow(nextimage_callback, settings) {
    this.init(nextimage_callback, settings);
  };
  AdGallerySlideshow.prototype = {
    start_link: false,
    stop_link: false,
    countdown: false,
    controls: false,

    settings: false,
    nextimage_callback: false,
    enabled: false,
    running: false,
    countdown_interval: false,
    init: function(nextimage_callback, settings) {
      var context = this;
      this.nextimage_callback = nextimage_callback;
      this.settings = settings;
    },
    create: function() {
      this.start_link = $('<span class="ad-slideshow-start">'+ this.settings.start_label +'</span>');
      this.stop_link = $('<span class="ad-slideshow-stop">'+ this.settings.stop_label +'</span>');
      this.countdown = $('<span class="ad-slideshow-countdown"></span>');
      this.controls = $('<div class="ad-slideshow-controls"></div>');
      this.controls.append(this.start_link).append(this.stop_link).append(this.countdown);
      this.countdown.hide();

      var context = this;
      this.start_link.click(
        function() {
          context.start();
        }
      );
      this.stop_link.click(
        function() {
          context.stop();
        }
      );
      $(document).keydown(
        function(e) {
          if(e.keyCode == 83) {
            // 's'
            if(context.running) {
              context.stop();
            } else {
              context.start();
            };
          };
        }
      );
      return this.controls;
    },
    disable: function() {
      this.enabled = false;
      this.stop();
      this.controls.hide();
    },
    enable: function() {
      this.enabled = true;
      this.controls.show();
    },
    toggle: function() {
      if(this.enabled) {
        this.disable();
      } else {
        this.enable();
      };
    },
    start: function() {
      if(this.running || !this.enabled) return false;
      var context = this;
      this.running = true;
      this.controls.addClass('ad-slideshow-running');
      this._next();
      this.fireCallback(this.settings.onStart);
      return true;
    },
    stop: function() {
      if(!this.running) return false;
      this.running = false;
      this.countdown.hide();
      this.controls.removeClass('ad-slideshow-running');
      clearInterval(this.countdown_interval);
      this.fireCallback(this.settings.onStop);
      return true;
    },
    _next: function() {
      var context = this;
      var pre = this.settings.countdown_prefix;
      var su = this.settings.countdown_sufix;
      clearInterval(context.countdown_interval);
      this.countdown.show().html(pre + (this.settings.speed / 1000) + su);
      var slide_timer = 0;
      this.countdown_interval = setInterval(
        function() {
          slide_timer += 1000;
          if(slide_timer >= context.settings.speed) {
            var whenNextIsShown = function() {
              // A check so the user hasn't stoped the slideshow during the
              // animation
              if(context.running) {
                context._next();
              };
              slide_timer = 0;
            };
            if(!context.nextimage_callback(whenNextIsShown)) {
              context.stop();
            };
            slide_timer = 0;
          };
          var sec = parseInt(context.countdown.text().replace(/[^0-9]/g, ''), 10);
          sec--;
          if(sec > 0) {
            context.countdown.html(pre + sec + su);
          };
        },
        1000
      );
    },
    fireCallback: function(fn) {
      if($.isFunction(fn)) {
        fn.call(this);
      };
    }
  };
})(jQuery);


//////////BUSCADOR//////////////7
var z;
z=$(document);
z.ready(inicializarEventos);

var Primera=false;
var contador=0;

function inicializarEventos()
{
	$("#buscar").keyup(filtrar);
	$("#buscar").click(primera);
	$("#buscar").blur(posterior);
	$("#botonbuscar").click(buscarTodo);
}

function buscarTodo(e)
{
	e.preventDefault();
	if(Primera==false)
		alert("Introduzca un t\xe9rmino de b\xfasqueda");
	else if($('#buscar').val().length<3)
		alert("T\xe9rmino de b\xfasqueda demasiado corto");
	else
		$('#buscador').submit();
}

function primera()
{
	if (!Primera)
	{
		$("#buscar").attr("value","");
		Primera=true;
	}
	else
	{
		filtrar();
	}
}

function posterior()
{
	if ($("#buscar").attr("value") == "")
	{
		$("#buscar").attr("value","Introduzca un término de búsqueda...");

		Primera=false;
	}
}

function filtrar()
{ 
	var texto = $("#buscar").attr("value");			
	if (texto.length>2)
	{
		contador+=1; 
		texto=quitarComillas(texto);
		$.getJSON("./include/cabeza/buscador.php",{texto:texto,contador:contador},resultadoBuscadorHead);
	}		
	else
		ocultarBusqueda();		
}

function ocultarBusqueda()
{
	$("#linkresul").slideUp(function(){
		$("#linkresul").html("");
	});
	$(document).unbind('click');
}


function resultadoBuscadorHead(datos)
{ 
	// Comprobamos que es la última búsqueda que se ha enviado
	if(datos['contador']==contador)	
		$("#resultados").html(pintarBusqueda(datos));
}

function pintarBusqueda(datos)
{ 
	var i=0; 
	var div=''; 
	var s='s';
	if(datos['provincias']!=null && datos['provincias'].length>0)
	{
		div+='<span class="titub">Provincias</span>';	
		for(i=0;i<datos['provincias'].length;i++)
			div+='<a href="./casas-rurales-en-'+pasaraURL(datos['provincias'][i]['nombre'])+'-P'+datos['provincias'][i]['id']+'.html" title="Casas rurales en la prov&iacute;ncia de '+datos['provincias'][i]['nombre']+': '+datos['provincias'][i]['cantidad']+'">'+datos['provincias'][i]['nombre']+' <span>('+datos['provincias'][i]['cantidad']+' alojamientos)</span></a>';
		div+='<br/>';
	} 
	
	if(datos['poblaciones']!=null && datos['poblaciones'].length>0)
	{
		div+='<span class="titub">Poblaciones</span>';
		for(i=0;i<datos['poblaciones'].length;i++)
		{
			if(datos['poblaciones'][i]['cantidad']==1)
				s='';
			else
				s='s';
			div+='<a href="./casas-rurales-en-'+pasaraURL(datos['poblaciones'][i]['nombre'])+'-M'+datos['poblaciones'][i]['id']+'.html" title="Casas rurales en '+datos['poblaciones'][i]['nombre']+': '+datos['poblaciones'][i]['cantidad']+'">'+datos['poblaciones'][i]['nombre']+' <span>('+datos['poblaciones'][i]['nombreprov']+') ('+datos['poblaciones'][i]['cantidad']+' alojamiento'+s+')</span></a>';
		}
		div+='<br/>';
	}
	
	if(datos['pedanias']!=null && datos['pedanias'].length>0)
	{
		div+='<span class="titub">Pedan&iacute;as</span>';
		for(i=0;i<datos['pedanias'].length;i++)
		{
			if(datos['pedanias'][i]['cantidad']==1)
				s='';
			else
				s='s';
			div+='<a href="./casas-rurales-en-'+pasaraURL(datos['pedanias'][i]['nombre'])+'-M'+datos['pedanias'][i]['idpob']+'-R'+datos['pedanias'][i]['id']+'.html" title="Casas rurales en '+datos['pedanias'][i]['nombre']+': '+datos['pedanias'][i]['cantidad']+'">'+datos['pedanias'][i]['nombre']+' <span>('+datos['pedanias'][i]['nombrepob']+','+datos['pedanias'][i]['nombreprov']+') ('+datos['pedanias'][i]['cantidad']+' alojamiento'+s+')</span></a>';			
		}
		div+='<br/>';
	}
	
	if(datos['casas']!=null && datos['casas'].length>0)
	{
		div+='<span class="titub">Alojamientos</span>';
		for(i=0;i<datos['casas'].length;i++)
		{
			div+='<a href="./'+pasaraURL(datos['casas'][i]['nombre'])+'-L'+datos['casas'][i]['id']+'.html" title="'+datos['casas'][i]['nombre']+'">'+datos['casas'][i]['nombre']+' <span>(';
			if (datos['casas'][i]['idped'] > 0)		
				div+=datos['casas'][i]['nombreped']+',';
			div+=datos['casas'][i]['nombrepob']+','+datos['casas'][i]['nombreprov']+')</span></a>';
		}
		div+='<br/>';
	}
		
	
	if(div.length==0)
		div='<span class="titub">No hay resultados</span>'
	$('#linkresul').html(div);
	$('#linkresul').slideDown();
	$(document).bind('click',ocultarBusqueda);
		
}


//// ACCESO PROPIETARIOS//////
var titularidad=0;
$(document).ready(function(){	
		inicializar_propietarios();
	});
	
	function inicializar_propietarios()
	{
		$('#propietarios').css("display","block");
		$('#micasa').click(function(){
			titularidad=1;
			$('#propietarios').dialog('open');
		});
		
		$('#acceso_prop').click(function(){
			$('#propietarios').dialog('open');
		});		
			
		$("#propietarios").dialog({
			buttons: //botones
				{
					"Aceptar": aceptarPropietarios,
					"Cancelar": cancelarPropietarios
				},
			resizable:true,
			draggable:true, // se puede mover la ventana
		//	height:alto, // alto
			width:430, // ancho
			hide:'drop', // animación al cerrar
			show:'drop', // animación al abrir
			modal:true, // ventana modal
			position:'center', // posicion de la ventana
			autoOpen:false, // no abrir automaticamente al cargar la pagina
			title:'Acceso a Propietarios', // titulo de la ventana
			open: function(event,ui) // evento ejecutado al cargar abrir el cuadro de dialogo
				{
					// establecer el foco en el campo de usuario
					setTimeout(function()
						{
							$("#pro_usuario0").focus();
						}, 500);
					//capturamos la tecla ENTER para aceptar el formulario
					var oldonkeydown=document.body.onkeydown;
					if(typeof oldonkeydown!='function')
						document.body.onkeydown=aceptarPropietariosEvt;
					else
					{
						document.body.onkeydown=function()
							{
								oldonkeydown();
								aceptarPropietariosEvt();
							}
					}
					limpiar();
					
				},
			close: function(event,ui)
				{
					document.body.onkeydown=null;
				},
			stack:true // la ventana se coloca encima del resto de ventanas
			});
	
		$("#prof_accord").accordion(
				{
					header: 'div.prof_header', // etiqueta seleccionada como cabecera
					autoHeight: false,
					clearStyle: true,
					icons: false,
					changestart: function (event,ui) // al cambiar de capa
					{
						//eliminamos el captcha que haya pintado
						Recaptcha.destroy();
						//comprobamos la capa que se ha activado
						var actual = $("#prof_accord").accordion("option","active");
						switch (actual)
						{
							//pintamos el captcha en las páginas que lo incluyen
							case 1:
							case 2:						
								Recaptcha.create(rc_public,"recaptcha"+actual,
									{
										theme: "white",
										lang: "es",
										callback: Recaptcha.focus_response_field
									});
								break;
						}
					}			
						
				});
	
	}
	function aceptarPropietariosEvt(e)
	{
		if(e.keyCode==13)	// Enter
			aceptarPropietarios();			
	}
	
	function aceptarPropietarios()
	{
		var actual = $("#prof_accord").accordion("option","active");
		switch (actual)
		{
			case 0:
				iniciarSesion();
				break;	
			case 1:
				alta();
				break;
			case 2:
				recordar();
				break;
		}
	}

	function cancelarPropietarios()
	{
		$('#propietarios').dialog('close');
		limpiar();
	}

	function alta()
	{
		var response = $("#recaptcha_response_field").attr("value");
		var challenge = $("#recaptcha_challenge_field").attr("value"); 		
		var nombre = $("#nuevo_nombre").attr("value"); 
		var apellidos = $("#nuevo_apellidos").attr("value");
		var email = $("#nuevo_email").attr("value");
		var tlf = $("#nuevo_tlf").attr("value");
		var comentario = $("#nuevo_comentario").attr("value");
		var casa = -1;
		if (nombre == "")
			alert("Introduzca su nombre.");
		else
		{
			if (apellidos=="")
				alert("Introduzca sus apellidos.");
			else
			{
				if (tlf=="")
					alert("Debe introducir su número de teléfono.");
				else
				{
					if (email=="")
						alert("Introduzca sus dirección de correo electrónico.");
					else if(!emailValido(email))
						alert("Email no válido");
					else
						$.post("./include/titularidad/validar_titular.php",{casa:casa,nombre:nombre,apellidos:apellidos,email:email,tlf:tlf,comentario:comentario,challenge:challenge,response:response},afterAlta);
				}
			}
		}
	}

	function afterAlta(datos)
	{
		if(datos.length!=0)
		{
			alert(datos);			
		}
		else
		{
			$('#propietarios').dialog('close');
			alert("El nuevo usuario creado deber\xe1 ser validado por nuestros agentes, recibir\xe1 un correo electr\xf3nico en la direcci\xf3n que nos ha proporcionado indic\xe1ndole sus datos de acceso");
			
		}
		Recaptcha.reload();
	}

	function recordar()
	{
		var email=$('#re_pass_email').attr('value');
		var response = $("#recaptcha_response_field").attr("value");
		var challenge = $("#recaptcha_challenge_field").attr("value"); 
		if(emailValido(email))
			$.post("./include/administrar/recordar.php",{nombre_usuario:email,response:response,challenge:challenge},afterRecordar);
		else
			alert("Email no v\xe1lido");
	}

	function afterRecordar(datos)
	{
		Recaptcha.reload();
		alert(datos);
	}

	function iniciarSesion()
	{
		
		var email=$('#acceso_email').attr('value');
		var pass=$('#acceso_pass').attr('value');
		if(email=="")
			alert("Introduzca su email");
		else if(!emailValido(email))
			alert("Email no válido");
		else if(pass=="")
			alert("Introduzca su contraseña");
		else
			$.post("./include/administrar/sesion.php",{email:email,pass:pass,titularidad:titularidad},afterIniciarSesion);
	}

	function afterIniciarSesion(datos)
	{	
		datos=$.trim(datos); 
		if(datos.charAt(0)=="1")
		{
			alert(datos.substr(1));
			window.location = document.location;
		}
		else if(datos.charAt(0)=="2")
		{ 
			datos=datos.split(' ');
			$('#sessionid').val(datos[1]);
			$('#userid').val(datos[2]);
			pedirTitularidadAuto();
			
		}
		else
			alert(datos);
	}

	function pedirTitularidadAuto()
	{		
		var sessionid=$("#sessionid").attr("value");
		var userid=$('#userid').attr("value");
		var idcasa=$('#idcasa').attr("value");
		$.post('./include/administrar/titularidad.php',{sessionid:sessionid,userid:userid,idcasa:idcasa},function(respuesta){
			respuesta=$.trim(respuesta);
			if(respuesta=="1")
			{
				alert("Petici\xf3n aceptada. El adminstrador deber\xe1 activar la titularidad.")
				window.location = document.location;
			}
			else
			{
				alert(respuesta);
				window.location = document.location;
			}
				
		});		
	}
		
	function limpiar()
	{
		$('#acceso_email').attr('value','');
		$('#acceso_pass').attr('value','');
		$('#nuevo_nombre').attr('value','');
		$('#nuevo_apellidos').attr('value','');
		$('#nuevo_email').attr('value','');
		$('#nuevo_tlf').attr('value','');
		$('#nuevo_coment').attr('value','');
		$('#re_pass_email').attr('value','');
		$("#prof_accord").accordion("activate",0);
	}
	
	
////////////COMENTARIOS//////////////

	function comentarioOtros()
	{
		var estado
		estado = document.comentarios.otros_coment.checked;
		document.comentarios.otros_coment2.disabled=!estado;
		if (!estado)
			document.comentarios.otros_coment2.value="";
	}

	function enviar_comentario()
	{ 		
		var titulo = $('#titulo_coment').attr('value');
		if(titulo.length==0)
		{
			alert('Introduzca un t\xedtulo');
			return false;
		}
		var response = $('#recaptcha_response_field').attr('value');
		var challenge = $('#recaptcha_challenge_field').attr('value');		
		var nombre = $('#nombre_coment').attr('value');
		var email = $('#email_coment').attr('value');
		var opinion = $('#opinion_coment').attr('value');
		var otros = $('#otros_coment').attr('checked');
		var otrosCom = $('#otros_coment2').attr('value');
		var id_casa = $('#id_casa_coment').attr('value');
		
		
		var param='response='+response+'&challenge='+challenge+'&titulo='+titulo+'&nombre='+nombre+'&email='+email+'&opinion='+opinion+'&otros='+otros+'&otrosCom='+otrosCom+'&id_casa='+id_casa;
		
		$.getJSON('./include/comentarios_tipos.php',{},function(resp){
				var recomendado=new Array();
				var valoracion=new Array(); 
				for(var i=0;i<resp.recomendado.length;i++)
				{ 
					param+='&'+resp.recomendado[i]+'='+$('#'+resp.recomendado[i]+'_coment').attr('checked');
				}
				for(var i=0;i<resp.valoracion.length;i++)
				{
					param+='&'+resp.valoracion[i]+'='+$('#'+resp.valoracion[i]+'_coment').attr('value');
				}
				$.post('./include/enviar_comentario.php',param,function(resp){
					$('#msg_coment').html(resp);
					Recaptcha.reload();
					if(resp.indexOf("Captcha")==-1)
					{
						comentarioOtros();
						document.getElementById('comentarios').reset();					}	
				});
		});
	}





