// Funciones
function ltrim(s) {
	return s.replace(/^\s+/, "");
}

function rtrim(s) {
	return s.replace(/\s+$/, "");
}

function trim(s) {
	return rtrim(ltrim(s));
}

MensajeCargando();
function MensajeCargando(){
	if($.browser.msie&&$.browser.version<8) alert("Esta página está diseñada para Firefox 2+, Chrome 1.5+, Opera 9+ e IE 7+.\nSi está utilizando un navegador diferente ó una versión más antigüa puede que no vea correctamente la página.");
	
	document.write('<div id="boxLoad" class="boxLoad"><img src="Style/images/bodyloader.gif" /></div>');	
    $('#boxLoad').modal();

}
function CloseModalLoad(){
    $.modal.close();
	$('#boxLoad').remove();
	}

function inicializarEventos()
{  
  // Lanzamos las fotos aleatorias
   Foto_Aleatoria();
  // Redondeamos Título imagenes de interés    
  Rounded("div#TituloImagenInteres","transparent small same-height");
// Animación Menú principal
    Rounded("#nav1 li a small","big transparent top same-height"); 
    Rounded("#nav_move small","big transparent top"); 
	
      $('#nav1 li:first').addClass('cur');
	  $('#nav1 li:first').css('font-weight','bold');
	  $('#nav1 li:first').css('background','#00FF00');
	  
      $('#nav1 li').click(function() {
        var offset = $(this).offset();
        var offsetBody = $('#wrapper').offset(); //find the offset of the wrapping div    
		$('#nav_move').css({ 
        width: $('#nav1 li:first').width(), 
        height: $('#nav1 li:first').height()
      });
        $('#nav_move').animate(
          { 
            width: $(this).width(), 
            height: $(this).height(), 
            left: (offset.left - offsetBody.left+147) 
          }, 
          { duration: 550}
        );
		if($(this).html()==$('.cur').html()) return false;
		$('#nav_move').html($(this).html());
		Nifty("#nav_move","big transparent top"); 
		$('#nav_move').toggle("fast");
		
        $(this).css('background','#00FF00');
		$(this).css('font-weight','bold');
		$('.cur').css('background','transparent');
		
		$('.cur').removeClass('cur');
		$(this).addClass('cur');
		
		
		// Cargamos el contenido deseado
		Cargar_Contenido($(this).text());
		
        return false;
      });

// Animaciones Título y Subtitulo
      $('#titulo').mouseover(function() {
		 $(this).css("font-size", "60px"); 
          });

	  $('#titulo').mouseout(function() {
		 $(this).css("font-size", "36px");
		});
	   $('#subtitulo').mouseover(function() {
		 $(this).css("font-size", "40px"); 
		 $(this).css("color", "white"); 
          });

	  $('#subtitulo').mouseout(function() {
		 $(this).css("font-size", "14px");
		 $(this).css("color", "#616161"); 
		});
 
 // Animación Enlaces
      $('#nav1 a').hover(function(){
	    $(this).css("font-size", "18px"); 
	  },
	   function (){$(this).css("font-size", "12px"); }
	  );
// Animación Entrada  
	  $("#content").hide();
	  $("#content").slideToggle("slow");
	  
// Ocultar mostrar los boxes
	$("#TituloEstadisticas").click(function(){
	      $("#estadisticas").toggle("slow"); 
	   }
	);
	$("#TituloFotos").click(function(){
	      $("#fotosAleatorias").toggle("slow"); 
		  $("#imgA1").slideToggle("fast");
	   }
	);
	
	$("#TituloMiniChat").click(function(){
	      $("#miniChat").toggle("slow"); 
	   }
	);
	$("#TituloFotosInteres").click(function(){
	      $("#fotosInteres").toggle("slow"); 
	   }
	);
	
  // Ocultar Todos Juntos menu izquierda
  $("#content_rows").toggle(Hide_Menu,Show_Menu);
  
  // Cargamos contenido inicial
  Cargar_Contenido('Inicio');
  
  CloseModalLoad();
		  
}

var menuvisible=false;
function Hide_Menu(){
	      if(!menuvisible){ Show_Menu(); return;}
	
		  menuvisible=false;
    	  $("#content_rows").hide("fast"); 
	      $("#sidebar").hide("slow");
		  $("#content").css("width","920px");
		  $("#imgA2").hide("fast");
		  $("#imgN2").hide("fast");
		  document.getElementById("flechaShowHide").src='Icons/flecha_show.jpg';
  		  $("#content_rows").show("fast"); 
		  
		  $("#wrapper").css("margin","0 auto");
		  
		   $("#ifext").css("width","900px");
   		  if(document.getElementById("ifext"))document.getElementById("ifext").scrolling="no";
	
}

function Show_Menu(){
	
  	      if(menuvisible){ Hide_Menu(); return;}
		
  		  menuvisible=true;
		  $("#content_rows").hide("fast"); 
		  $("#content").css("width","700px");
	      $("#sidebar").show("slow");
		  $("#imgA2").hide("fast");
		  $("#imgN2").hide("fast");
		  document.getElementById("flechaShowHide").src='Icons/flecha_hide.jpg';
  		  $("#content_rows").show("fast"); 
		  
		  $("#ifext").css("width","700px");
		  if(document.getElementById("ifext"))document.getElementById("ifext").scrolling="yes";
          
}

var forovisible=false;
var map;

function Cargar_Contenido(eleccion){
	eleccion=trim(eleccion);
	var subtitulo='';
    var texto='';
	forovisible=false;
	$('#content').html('<div class="post"><div class="post-bgtop"><div class="post-bgbtm"><h1 id="tituloSeccion" class="title"><a href="#">Titulo Sección </a></h1><p id="subtituloSeccion" class="meta">Subtitulo de la sección <a href="#" class="permalink"></a></p><div id="textoSeccion" class="entry"><p>Texto de la sección. </p></div></div></div></div><div style="clear: both;">&nbsp;</div>');
	if(!menuvisible&&eleccion!='DeInterés'&&eleccion!='Foro'&&eleccion!='Fotos'&&eleccion!='Gente')Show_Menu();
	$("#wrapper").css("margin","0 auto");
	$('#load').remove();
	$('#wrapper').append('<span id="load">LOADING...</span>');
	$('#load').fadeIn('normal');
	
    switch(eleccion){
	  case 'Contacto':
	    subtitulo=SubtituloContacto;
		texto=TextoContacto;
	    break;
	  case 'Enlaces':
   	    subtitulo=SubtituloEnlaces;
		texto=TextoEnlaces;
		break;
	  case 'DelasHurdes':
	    subtitulo=SubtituloDelasHurdes;
		texto=TextoDelasHurdes;
	    break;
	  case 'DeInterés':
	   if(menuvisible)Hide_Menu();
		$('#content').html('<iframe id="ifext" src="Programas/EGAnuncios/EGalery.php" scrolling="no" marginheight="0" marginwidth="0" width=900px height=800px style="border:none;" />');
	    break;
	 case 'Gente':
  	   if(menuvisible)Hide_Menu();
		$('#content').html('<iframe id="ifext" src="Programas/EGFotosGente/EGalery.php" scrolling="no" marginheight="0" marginwidth="0" width=900px height=800px style="border:none;" />');
	    break;
	  case 'Fotos':
  	  	if(menuvisible) Hide_Menu();
		$('#content').html('<iframe id="ifext" src="Programas/EGFotos/EGalery.php" scrolling="no" marginheight="0" marginwidth="0" width=900px height=800px style="border:none;" />');
	    break;
	case 'Foro':
	    if(menuvisible) Hide_Menu();
		forovisible=true;
	    $('#content').html('<iframe id="ifext" src="Programas/phpBB3/index.php" scrolling="no" marginheight="0" marginwidth="0" width=900px height=800px style="border:none;" />');
	    break;
	  case 'Inicio':
	    subtitulo=SubtituloInicio;
		texto=TextoInicio;
		break;
	   default: alert("Error en la página, no se encuentra la sección.");
	  
	}
		$('#content').fadeOut('fast');
		$('#content').fadeIn('slow');
		$('#textoSeccion').hide('slow');
		$('#tituloSeccion').text(eleccion);
		$('#subtituloSeccion').html(subtitulo);
		$('#textoSeccion').html(texto);
		$('#textoSeccion').show('slow');
		// Efecto Lupa para los contenidos
		$('#lupa').click(function() {
		 var x=$("#textoSeccion").css("font-size");
		 x=x.replace('px','');
		 x=4+parseInt(x);
		 x=x+'px';
		 $("#textoSeccion").css("font-size", x);
      });

	 // Ponemos El mensaje de carga para los iframes
  $('#ifext').load(function() {
   $('#load').fadeOut('slow');
	});
  
    if(eleccion!='Foro'&&eleccion!='Gente'&&eleccion!='Fotos'&&eleccion!='DeInterés')$('#load').fadeOut('slow');
	
	if(eleccion=='Contacto')Crear_FormContac();
	
	if(eleccion=='Inicio'){
  map = new GMap2(document.getElementById('map'));
  
var markers=[];	
	for (var i = 0; i < CoordenadasPueblos.length; i++) {
		var point = CoordenadasPueblos[i];
		marker = new GMarker(point);
		map.addOverlay(marker);
		markers[i] = marker;	
	}

	// Google maps
	   map.setCenter(CoordenadasPueblos[5], 10);
	   map.setUIToDefault();
  
     $(markers).each(function(i,marker){
					$("<li />")
						.html(NombresPueblos[i])
						.click(function(){
							displayPoint(marker, i);
						})
						.appendTo("#list");
					
					GEvent.addListener(marker, "click", function(){
						displayPoint(marker, i);
					});
				});
				
				function displayPoint(marker, index){
					$("#message").hide();
					$("#message").html(DatosPueblos[index]);
					
					var moveEnd = GEvent.addListener(map, "moveend", function(){
						var markerOffset = map.fromLatLngToDivPixel(marker.getLatLng());
					
						map.openInfoWindowHtml(CoordenadasPueblos[index],InistiloMapsWindows+DatosPueblos[index]+EndstiloMapsWindows+Empresas[index]+leyenda);
					
						GEvent.removeListener(moveEnd);
					});
					map.panTo(marker.getLatLng());
				}

	initialize();
	
	 Nifty("div#list","big fixed-height");
 //	 Nifty("#list li a","big"); 


	 
	}// Fin si Inicio
			
}

    var gdir;
    var geocoder = null;
    var addressMarker;

function initialize() {
      if (GBrowserIsCompatible()) {      
        gdir = new GDirections(map, document.getElementById("directions"));
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);
   //     setDirections("Madrid", "Nuñomoral", "es_ES");
      }
    }


function handleErrors(){
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	   
	   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
	     
	   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

	   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	     alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	    
	   else alert("An unknown error occurred.");
	   
	}
	
function onGDirectionsLoad(){ }

	
function setDirections(fromAddress, toAddress, locale) {
      gdir.load("from: " + fromAddress + " to: " + toAddress,
                { "locale": locale });
    }

function Get_Array(datos){
   var cadTroceada = datos.split (",");
  for(var i=0;i<cadTroceada.length;i++)
	 Fotos[i]=cadTroceada[i];		
}

function Foto_Aleatoria(){
	var Fotos=new Array();
	var Fotos2=new Array();

// Foto_Hurdes
$.ajax({
        type: "GET",
        url: "Functions/CrearArray.php?dir=../Programas/EGFotos/Thumb/",
		async:true,
        success: function Get_Array(datos){
   					var cadTroceada = datos.split (",");
				    for(var i=0;i<cadTroceada.length;i++)
						 Fotos[i]=cadTroceada[i];		
					},
	    complete:  function ejecuta(){
        		$("#imgA2").hide("fast");
				Show_ImagenAleatoria("Programas/EGFotos/Thumb/","imgA",Fotos);
				}
		});
// Fotos_Anuncios
$.ajax({
        type: "GET",
        url: "Functions/CrearArray.php?dir=../Programas/EGAnuncios/Thumb/",
		async:true,
        success: function Get_Array(datos){
   					var cadTroceada = datos.split (",");
				    for(var i=0;i<cadTroceada.length;i++)
						 Fotos2[i]=cadTroceada[i];		
					},
	    complete:  function ejecuta(){
        		$("#imgN2").hide("fast");
				Show_Imagenes("Programas/EGAnuncios/Thumb/","imgN",Fotos2,DescripcionesInteres, false, 0);
			
				}
		});

}


// Coge un array Fotos y lo muestra entero de forma aleatoria

function aleatorio(inferior,superior){
    numPosibilidades = superior - inferior
    aleat = Math.random() * numPosibilidades
    aleat = Math.round(aleat)
    return parseInt(inferior) + aleat
} 

function Show_ImagenAleatoria(path,id,Fotos,cambiar){

	var i=aleatorio(0,Fotos.length-1);
	if(cambiar){
		document.getElementById(id+'2').src=path+Fotos[i]; 
		 $("#"+id+'1').hide("slow");
		 $("#"+id+'2').show("slow");
		cambiar=false;
		}
	else{
	document.getElementById(id+'1').src=path+Fotos[i];
    $("#"+id+'1').show("slow");
	$("#"+id+'2').hide("slow");
	cambiar=true;
	}
	
     setTimeout(function(){ Show_ImagenAleatoria(path,id,Fotos,cambiar);},3000) ;   	
}

// Muestra las fotos ordenadamente
function Show_Imagenes(path,id,Fotos,Descripciones,cambiar,i){
	i++;
	if(i==Fotos.length||i=='')i=0;
	if(cambiar){
		document.getElementById(id+'2').src=path+Fotos[i]; 
		 $("#"+id+'1').hide("slow");
		 $("#"+id+'2').show("slow");
		 $("#TituloImagenInteres").html(Descripciones[i]);
		cambiar=false;
		}
	else{
	document.getElementById(id+'1').src=path+Fotos[i];
    $("#"+id+'1').show("slow");
	$("#"+id+'2').hide("slow");
	$("#TituloImagenInteres").html(Descripciones[i]);
	cambiar=true;
	}
	
    setTimeout(function(){ Show_Imagenes(path,id,Fotos,Descripciones,cambiar,i);},3000) ;   	
   	
}

