/******************************************************************************
*  NOMBRE --------->: funcVarias.js                                           *
*  AUTOR ---------->: David Trigo Pérez                                       *
*  LENGUAJE USADO ->: Javascript                                              *
*  DESCRIPCIÓN ---->: Funciones de diferente índole.                          *
******************************************************************************/

//##### FUNCIONES GENERALES GRÁFICA #####
var UltimoHash='ValorInicial';
var RelojSeguimientoHash=0;
//-------------------------------------
function Iniciar(){
//-------------------------------------
  RearrancarSeguimientoHash();
  CargarContenido();
  AjustarTamano();
}

//##### FUNCIONES GENERALES GRÁFICA #####
//-------------------------------------
function AjustarTamano(){
//-------------------------------------
  AltoCuerpoDocumento = document.body.clientHeight;
  AltoCabecera = 102+24;
  $('capaContenedor').style.height = AltoCuerpoDocumento-((Prototype.Browser.IE)?46:24) +'px';
  $('capaLateralIzq').style.height = AltoCuerpoDocumento-AltoCabecera +'px';
  $('capaCentro').style.height = AltoCuerpoDocumento-AltoCabecera-22 +'px';
  $('capaCentroIzq').style.height = AltoCuerpoDocumento-AltoCabecera-29 +'px';
  $('capaCentroDer').style.height = AltoCuerpoDocumento-AltoCabecera-29 +'px';
  $('capaContenido').style.height = AltoCuerpoDocumento-AltoCabecera-((Prototype.Browser.IE)?28:38) +'px';
  $('capaLateralDer').style.height = AltoCuerpoDocumento-AltoCabecera +'px';
  $('capaLatDer1').style.marginTop = AltoCuerpoDocumento-AltoCabecera-414+((Prototype.Browser.IE)?0:30) +'px';

  //Para evitar problemas con el overflow en IExplorer, se pone explícitamente alto a la capa del menú
  $('capaMenu').style.height = AltoCuerpoDocumento-AltoCabecera-11 +'px';

  AnchoCuerpoDocumento = document.body.clientWidth;
  AnchoCapaContenido = AnchoCuerpoDocumento - ((Prototype.Browser.IE)?321:351);
  $('capaContenido').style.width = AnchoCapaContenido;

  //Recuadro de novedades
  if($('capaPortadaNovedades')){
    $('capaPortadaNovedades').style.width = AnchoCapaContenido -((Prototype.Browser.IE)?40:1) +'px';
    $('capaPortadaRestoTituloNovedades').style.width = AnchoCapaContenido - ((Prototype.Browser.IE)?201:162) +'px';
    $('capaContenedorRecuadros').style.width = AnchoCapaContenido -((Prototype.Browser.IE)?40:3) +'px';

    //Recuadros de la portada, dentro de novedades (repartir espacios horizontales)
    MargenIzq = 10;
    NumElementos = 4;
    AnchoElemento = parseInt($('capaRecuadro1').clientWidth)+((Prototype.Browser.IE)?10:0);
    EspacioMedio = ((AnchoCapaContenido+MargenIzq) - (AnchoElemento * NumElementos)) / (NumElementos + 1) ;

    if($('capaRecuadro1')) $('capaRecuadro1').style.marginLeft = EspacioMedio - MargenIzq;
    if($('capaRecuadro2')) $('capaRecuadro2').style.marginLeft = EspacioMedio;
    if($('capaRecuadro3')) $('capaRecuadro3').style.marginLeft = EspacioMedio;
    if($('capaRecuadro4')) $('capaRecuadro4').style.marginLeft = EspacioMedio;

  }

  //AnchoCuadroEmpleo = AnchoCapaContenido - parseInt($('ImagenPortada').clientWidth) - ((Prototype.Browser.IE)?64:54);
  AnchoCuadroEmpleo = AnchoCapaContenido - 400 - ((Prototype.Browser.IE)?64:54);

  //Recuadro de empleo
  if($('capaPortadaEmpleo')){
    $('capaPortadaEmpleo').style.width = AnchoCuadroEmpleo +'px';
    $('capaPortadaRestoTituloEmpleo').style.width = AnchoCuadroEmpleo - 149 +'px';
    $('capaPortadaContenidoEmpleo').style.width = AnchoCuadroEmpleo - ((Prototype.Browser.IE)?0:30) +'px';
  }

  //Recuadro de noticias
  if($('capaPortadaNoticias')){
    $('capaPortadaNoticias').style.width = AnchoCapaContenido -((Prototype.Browser.IE)?40:1) +'px';
    $('capaPortadaRestoTituloNoticias').style.width = AnchoCapaContenido - ((Prototype.Browser.IE)?161:122) +'px';
    $('capaPortadaContenidoNoticias').style.width = AnchoCapaContenido -((Prototype.Browser.IE)?40:27) +'px';

    //Si la página es lo suficiente alta, se calcula dinámicamente el tamaño de la capa de noticias
    if((AltoCuerpoDocumento-AltoCabecera)>630){
      $('capaPortadaContenidoNoticias').style.height = AltoCuerpoDocumento-AltoCabecera-520 +'px';
      $('capaPortadaNoticias').style.height = AltoCuerpoDocumento-AltoCabecera-520-24 +'px';
      $('capaPortadaContenidoNoticias').style.overflowY = 'auto';
    }else{ //Si no, se deja un tamaño fijo
      //$('capaPortadaContenidoNoticias').style.height = 300 +'px';
      $('capaPortadaContenidoNoticias').style.height = '';
      $('capaPortadaContenidoNoticias').style.overflow = 'hidden';
      //$('capaPortadaNoticias').style.height = AltoCuerpoDocumento-AltoCabecera-520-24 +'px';
      $('capaPortadaNoticias').style.height = '';
    }
  }
}
//-------------------------------------

//##### FUNCIONES AJAX #####

//-------------------------------------
function PeticionAJAXaCapa(url,capa,accionPosterior){
//-------------------------------------
//  var Direccion = '<div id="direccion" style="display:none;">'+url+'</div>';
  new Ajax.Request(url, {
    method: 'post',
    onSuccess: function(transport){
//      $('CapaFondoCargando').style.display='none';
      $(capa).innerHTML = unescape(transport.responseText); // + Direccion;
//      if(Prototype.Browser.IE){
//        window.event.cancelBubble = true;
//      }
      if(accionPosterior){
        eval(accionPosterior);
      }

    },
    onFailure: function(){ alert('Error AJAX')}
  });
}
//-------------------------------------
function PeticionAJAXaFuncion(url,funcion){
//-------------------------------------
  new Ajax.Request(url, {
    method: 'post',
    onSuccess: function(transport){
      eval(funcion +"('" + transport.responseText + "')");
    },
    onFailure: function(){ alert('Error AJAX')}
  });
}
//-------------------------------------
function FormularioAJAXaFuncion(formulario,funcion){
//-------------------------------------
  $(formulario).request({
    method: 'post',
    onSuccess: function(transport){
      eval(funcion +"()");
      //eval(funcion +"('" +  unescape(transport.responseText) + "')");
    },
    onFailure: function(){ alert('Error AJAX')}
  });
}
//-------------------------------------

//##### FUNCIONES VARIAS #####

window.FormularioActivo = false; //Indica qué formulario activo actualse
window.FormularioAnterior = false; //Indica el formulario anterior
window.ActionFormulario = false; //El "action" del formulario activo
window.ContenidoCargado = false; //URL de la página cargada en la capa contenedora

//-------------------------------------
function EvaluarPulsacion(tecla){
//-------------------------------------
  switch (tecla){
    case 27: //Escape
      if($('calendarDiv')){ //Si el calendario está abierto
        if($('calendarDiv').style.display == 'block'){
          closeCalendar();
        }
      }
/*      if(window.actualPopupSuperior){ //Si está el pop superior abierto
        esconderPopupSuperiorActual();
      }else{*/
        CerrarPop();
//      }
      break;
    case 13: //Intro
/*      if (window.accionEnterPopupSuperior){
        eval(window.accionEnterPopupSuperior);
      }else{*/
        if(window.FormularioActivo != ''){ //Si hay definido un formulario como activo
          $(window.FormularioActivo).submit();
        }
        break;
//      }
  }
}
//-------------------------------------
function AbrirPop(url,titulo,parametros,formulario,action,campoFocus,script){
//-------------------------------------
//  abrirIbox(url+'?Curso="'+titulo+'"',titulo,parametros,campoFocus,script); //Ñapa temporal
  abrirIbox(url,titulo,parametros,campoFocus,script);
  if (formulario){
    window.FormularioAnterior = window.FormularioActivo;
    window.FormularioActivo = formulario;
    window.ActionFormulario = action;
  }
}
//-------------------------------------
function CerrarPop(){
//-------------------------------------
/*    if(window.actualPopupSuperior){ //Si está el pop superior abierto
    esconderPopupSuperiorActual();
  }*/
  hideIbox();
  window.FormularioActivo = window.FormularioAnterior;
  window.FormularioAnterior = '';
  window.ActionFormulario = '';
}
//-------------------------------------
function CargarContenido(){
//-------------------------------------
  if(Prototype.Browser.IE){
    //Comprueba si existe el IFRAME para la gestión de historial del IExplorer
    ComprobarIFRAME();
  }
  //Se analiza si la URL viene con un HASH, lo que indicaría que debería haber contenido distinto del de la página de inicio
  //Los parámetros: c --> Tiene contenido (0=no, 1=sí), i --> Imagen, t --> Título, d --> Documento
  Cadena = window.location.hash.gsub('#', '');
  if(Cadena.length >= 1){
//    $(capaContenido).innerHTML = '<img border="0" style="margin-top: 80px;" src="imagenes/cargando3.gif"/>';
    Parametros = Cadena.toQueryParams();
    if(Parametros.c == 0){ //Caso especial (0) para cuando no hay contenido expecífico
      PeticionAJAXaCapa (('contenidos/Generico.php?Titulo='+Parametros.t.gsub('-', ' ')+'&Imagen='+Parametros.i),'capaContenido','SeguimientoAnalytics()');
    }else{ //Caso normal
      PeticionAJAXaCapa (('contenidos/'+Parametros.d),'capaContenido','SeguimientoAnalytics()');
    }
    window.FormularioActivo = 'FormularioPeq'; //Para que el enter ataque este formulario
  }else{ //Si no hay parámetros
    if(!$('capaPortadaNovedades')){  //Por si se vuelve de hacer atrás con el botón y hay que recargar el contenido de inicio. Se fija en la existencia de cierto contenido de la portada
      PeticionAJAXaCapa('indexContenido.php','capaContenido','AjustarTamano();CargarFlash();CargarNoticias();SeguimientoAnalytics();');
    }else{
      CargarFlash();
      CargarNoticias();
    }
  }
//  $(capaContenido).style.display = (Prototype.Browser.IE)?'inline':'block';
  if(Prototype.Browser.IE){
    if($(capaContenido).style.display != 'inline'){
      $(capaContenido).style.display = 'inline';
    }
  }else{
    if($(capaContenido).style.display != 'block'){
      $(capaContenido).style.display = 'block';
    }
  }
}
//-------------------------------------
function ComprobarIFRAME(){
//-------------------------------------
  //Comprueba si existe el IFRAME para la gestión de historial del IExplorer. Si no, lo crea.
  if(!$('IFHistoria')){
    var IFHistoria = document.createElement("IFRAME");
    IFHistoria.id = "IFHistoria";
    IFHistoria.width = 0;
    IFHistoria.height = 0;
    IFHistoria.src = "historia.php#";
    document.body.appendChild(IFHistoria);
  }
}
//-------------------------------------
function ponerHash(parametros){
//-------------------------------------
  window.location.hash = parametros;
  if(Prototype.Browser.IE){ //Si es IExplorer
    UltimoHash = window.location.hash.gsub('#', '');
    if($('IFHistoria')){
      //$('IFHistoria').src = "historia.php?"+parametros+window.location.hash;
      $('IFHistoria').contentWindow.document.location = "historia.php?"+parametros+window.location.hash;
      RearrancarSeguimientoHash(); //Esto es para darle tiempo a que se cargue el IFRAME
    }
  }else{
    UltimoHash = window.location.hash;
  }
}
//-------------------------------------
function comprobarCambioHash(){
//-------------------------------------
  if(Prototype.Browser.IE){ //Si es IExplorer
    if(UltimoHash == 'ValorInicial'){
      $('IFHistoria').contentWindow.document.location.hash = window.location.hash;
      UltimoHash = window.location.hash.gsub('#', '');
      return;
    }
    if ((window.location.hash.gsub('#', '') == UltimoHash && $('IFHistoria').contentWindow.document.location.hash.gsub('#', '') == UltimoHash)) { //Si no ha cambiado el HASH o es la primera vez que se entra en la página
      window.location.hash = $('IFHistoria').contentWindow.document.location.hash;
      UltimoHash = window.location.hash.gsub('#', '');
    }else{
      window.location.hash = $('IFHistoria').contentWindow.document.location.hash;
      UltimoHash = window.location.hash.gsub('#', '');
      // La URL ha cambiado, se actualiza el contenido
      cerrarTodas(MenuVertical);
      CargarContenido();
    }
  }else{ //Si es otro explorador
    if (window.location.hash==UltimoHash || UltimoHash == 'ValorInicial') { //Si no ha cambiado el HASH o es la primera vez que se entra en la página
      UltimoHash = window.location.hash;
    }else{
      UltimoHash = window.location.hash;
      // La URL ha cambiado, se actualiza el contenido
      cerrarTodas(MenuVertical);
      CargarContenido();
    }
  }
}
//-------------------------------------
function PararSeguimientoHash(){
//-------------------------------------
  if(RelojSeguimientoHash != 0){ //Está arrancado
    clearInterval(RelojSeguimientoHash); //Se destruye
  }
}
//-------------------------------------
function RearrancarSeguimientoHash(){ //Se utiliza está función para que el reloj parta siempre de cero al hacer click
//-------------------------------------
  if(RelojSeguimientoHash != 0){ //Está arrancado
    clearInterval(RelojSeguimientoHash); //Se destruye
    RelojSeguimientoHash = setInterval(comprobarCambioHash, 1000); //Se vuelve a crear
  }else{
    RelojSeguimientoHash = setInterval(comprobarCambioHash, 1000); //Se crea
  }
}
//-------------------------------------
function CargarFlash(){
//-------------------------------------
   PeticionAJAXaCapa('adjuntos/php/inc.Flash.php','capaFlashCentro'); 
}
//-------------------------------------
function CargarNoticias(){
//-------------------------------------
  PeticionAJAXaCapa ('noticias.php','capaPortadaContenidoNoticias');
}
//-------------------------------------
function MarcarCampo(Campo){
//-------------------------------------
  $(Campo).focus();
  if ($(Campo).select){ //Si existe la función select
    $(Campo).select();
  }
}
//-------------------------------------
function SeguimientoAnalytics(){
//-------------------------------------
  Cadena = window.location.hash.gsub('#', '');
  if(Cadena.length >= 1){
    Parametros = Cadena.toQueryParams();
    pageTracker._trackPageview("/"+Parametros.t);
  }else{
    pageTracker._trackPageview("/Inicio");
  }
}
//-------------------------------------
