







var cargado = 0;
Element.addMethods({
   closest: function closest (element, cssRule) {
      var $element = $(element);
      // Return if we don't find an element to work with.
      if(!$element) {
         return;
      }
      return $element.match(cssRule) ? $element : $element.up(cssRule);
   }
});

document.observe("dom:loaded", function() {
    navegadores();
        
    var galeria1 = new Carrusel();
        galeria1.inicia();
        
    var nav1 = new desplegablesMenu();
        nav1.inicia();
        
    var indice = new ejeZ();
        indice.inicia();
        
    if($("mapa-lateral")){
    gmaps_iniciar_lateral();
    }
    if($("mapa-principal")){
    gmaps_iniciar();
    }
    
    textoBuscador ();
    
    var desplegables1 = new desplegables();
        desplegables1.inicia();
        
    var pestanas1 = new pestanas();
        pestanas1.inicia();
    
});

function navegadores () {

    //if(/MSIE 6.0/i.test(navigator.userAgent)) {$$('body')[0].addClassName('ie6');}
    //if(/MSIE 7.0/i.test(navigator.userAgent)) {$$('body')[0].addClassName('ie7');}
    //if(/MSIE 8.0/i.test(navigator.userAgent)) {$$('body')[0].addClassName('ie8');}
    //if(/Firefox\/1.5/i.test(navigator.userAgent)) {$$('body')[0].addClassName('ff15');console.log('Firefox 1.5');}
    if(/Firefox\/2.0/i.test(navigator.userAgent)) {$$('body')[0].addClassName('ff2');}
    if(/Firefox\/3.0/i.test(navigator.userAgent)) {$$('body')[0].addClassName('ff30');}
    //if(/Firefox\/3.5/i.test(navigator.userAgent)) {$$('body')[0].addClassName('ff35');console.log('Firefox 3.5');}
    //if(/Firefox\/3.6/i.test(navigator.userAgent)) {$$('body')[0].addClassName('ff3');console.log('Firefox 3.6');}
}

function textoBuscador () {
    campo = document.getElementById('busqueda');
    valorCampo = campo.value;

    campo.onfocus = function () {
        if (this.value == valorCampo) {this.value = '';}
    }
    campo.onblur = function () {
        if (this.value == '') {this.value = valorCampo;}
    }
    
}

function gmaps_iniciar () {
    var map,geocoder;
    // Iniciar Google Maps
   var coordenada1= document.getElementById('coordenada1');
   var coordenada2= document.getElementById('coordenada2');
   var browser=navigator.appName;
   //geocoder = new google.maps.Geocoder();
   // var myOptions = {
       // zoom: 15,
       // mapTypeId: google.maps.MapTypeId.ROADMAP
   // };
    if ($('mapa-principal-alternativo')) {$('mapa-principal-alternativo').remove();}
    //map = new google.maps.Map(document.getElementById("mapa-principal"), myOptions);
    
     if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("mapa-principal"));
    //map.setUIToDefault();
   var center = new GLatLng(coordenada1.value,coordenada2.value); 
    map.setCenter(center, 15);
                     
               
       var marker = new GMarker(center, {draggable: true});

       


     map.addOverlay(marker);
     if(browser.toLowerCase().indexOf ( 'explorer')!=-1)
     {
     //map.setUIToDefault();
     map.addControl(new GSmallMapControl());
     map.addControl(new GMapTypeControl());


     
     }
     else
     {
      map.addControl(new GSmallMapControl());
       map.addControl(new GMapTypeControl());

     
     }
        
                      
          } 
          
          

        }

function gmaps_iniciar_lateral () {
    var map,geocoder;
       // Iniciar Google Maps
    geocoder = new google.maps.Geocoder();
    var myOptions = {
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    if ($('mapa-lateral-alternativo')) {$('mapa-lateral-alternativo').remove();}
    
    
    
    
    
    
    map = new google.maps.Map(document.getElementById("mapa-lateral"), myOptions);
        
    gmaps_ubicar("mapa-lateral-ubicacion",geocoder,map);
    //setTimeout('gmaps_teclado("mapa-lateral");',6000);
}

function gmaps_ubicar(ubicacion,geocoder,map) {
   var coordenada1= document.getElementById('coordenada1');
   var coordenada2= document.getElementById('coordenada2');
    var address = $(ubicacion).innerHTML.stripTags().replace(/[\n\r]/,"").replace(/[\n\r]/,"");
        //alert(address);
    if (geocoder) {
        var latlng = new google.maps.LatLng(coordenada1.value,coordenada2.value); 
	geocoder.geocode( {'latLng': latlng}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                        position: latlng, 
			map: map 
                });
            } else {
                alert("Error en la localización: " + status);
            }
        });
    }
}

function gmaps_teclado(mapa) {
    var capaMapa = mapa; // cambiar por id de la capa en la que se inserta el mapa
    var button, button_style = 'width:100%;height:100%;padding:2px;margin:2px;background:transparent;border-width:0px;border-style:solid;cursor:pointer;overflow:hidden;text-indent:-100em;position:absolute;top:-2px;left:-2px;';
    var divs = document.getElementById(capaMapa).getElementsByTagName('div');
    for (var i = 0; i < (divs.length); i++) {
        if ( divs[i].getAttribute('title')) {
            // Se genera el button
            button = document.createElement("BUTTON");
            button.setAttribute('id','boton-mapa-'+i);
            button.setAttribute('value',divs[i].getAttribute('title'));
            
            // estilos...
            button.setAttribute('style',button_style); // Para navegadores de verdad
            button.style.cssText = button_style; // Para IE
            
            // Se añade el button
            divs[i].appendChild(button);
        }
    }
}

function ejeZ() {
    this.datos ={
        selector: 'p.fecha'
        ,indice: 900
    }
    
    this.inicia = function() {
        var elementos = $$(this.datos.selector);
        var numero = elementos.length;
        var i = 0;
        while (i<numero){
            elementos[i].setStyle({zIndex: this.datos.indice});
            this.datos.indice--;
            i++;
        }
    }
}



function desplegablesMenu () {
    this.datos = {
        capa: '#menu'
        ,claseEnlace: 'mostrar'
        ,elementoSuperior: 'nivel-superior'
        ,idActivo: 'nivel-activo'
        ,idContenedorEnlaceActivo: 'contenedor-enlace-activo'
        ,nivelFinal: 'div.desplegable'
    }
    
    this.inicia = function () {
        var that = this;
        that.ocultarSubniveles();
        that.mostrarSubnivel();
        
    }
    
    this.ocultarSubniveles = function () {
        var that = this;
        $$(that.datos.capa+' '+that.datos.nivelFinal).each(function (el) {
            el.id='';
            el.previous().id = '';
            el.hide();
            if(/MSIE 6.0/i.test(navigator.userAgent)) {alternarSelect('mostrar');}
        });
    }
    
    this.mostrarSubnivel = function () {
        var that = this;
        $$(that.datos.capa+' '+that.datos.nivelFinal).each(function (el) {
            el.up().addClassName(that.datos.elementoSuperior);
            el.previous().select('a')[0].addClassName(that.datos.claseEnlace);
        });
        
        $$(that.datos.capa+' a.'+that.datos.claseEnlace).each(function (el) {
            el.observe('click',function (ev) {
                Event.stop(ev);
                var contenedorEnlace = Element.closest(el, ".bg-nivel1");
                if (contenedorEnlace.next().style.display != 'none') {
                    that.ocultarSubniveles();
                } else {
                    that.ocultarSubniveles();
                    contenedorEnlace.id = that.datos.idContenedorEnlaceActivo;
                    contenedorEnlace.next().id = that.datos.idActivo;
                    contenedorEnlace.next().show();
                    contenedorEnlace.next().style.display = 'block';
                    if(/MSIE 6.0/i.test(navigator.userAgent)) {alternarSelect('ocultar');}
                    that.condicionCierre();
                }
                
            });
        });
    }

    this.condicionCierre = function () {
        var that = this;
        
        document.onclick = function (e) {
        e = e || event;
        var target = e.target || e.srcElement;
        var element = document.getElementById(that.datos.idActivo);
        do {
            if (element == target) {
             return;
            }
            target = target.parentNode;
        } while (target)
        if ($(that.datos.idActivo)) {
            that.ocultarSubniveles();
        }
         
        }

    }
    
}

function pestanas () {
    this.datos = {
        capa: '.js-pestanas'
        ,selectorPestana: '.pestana'
        ,clasePredeterminado: 'predeterminado'
        ,selectorEnlace: '.opciones a'
        ,claseSeleccionado: 'selected'
    }
    
    this.inicia = function () {
        var that = this;
        that.pestanasInicial();
    }
    
    this.pestanasInicial = function () {
        var that = this;
        $$(that.datos.capa).each(function (el) {
            el.select(that.datos.selectorPestana).each(function (el) {
                if (!el.hasClassName(that.datos.clasePredeterminado)) {
                    el.hide();
                }
            });
        that.alternarPestanas(el);
        });
    }
    
    this.alternarPestanas = function (capa) {
        var that = this;
        capa.select(that.datos.selectorEnlace).each(function (el) {
            el.observe('click',function (ev) {
                Event.stop(ev);
                var marcador = el.href.split('#'); marcador = marcador[(marcador.length-1)];
                capa.select(that.datos.selectorPestana).each(function (el) {
                    el.hide();
                });
                that.variarSeleccionado(el);
                $(marcador).show();
                // Oscar Porcar - 01/04/2011
                // 
                // recargar el mapa de google al seleccionar la pestaña que contiene el mapa
                // debido a un error de maquetación.
                if (marcador == 'pestana05' && cargado == 0)
                {
                    cargado = 1;
                    gmaps_iniciar();
                }                
                
            });
        });
    }
    
    this.variarSeleccionado = function (elemento) {
        var that = this;
        var pestana = Element.closest(elemento,"li");
        pestana.siblings().each(function (el) {
            el.removeClassName(that.datos.claseSeleccionado);
            //if (el.match(that.datos.selectorElementoLista+':first-child')) {el.removeClassName(that.datos.claseSeleccionadoPrimera);}
        });
        pestana.addClassName(that.datos.claseSeleccionado);
        //if (pestana.match(that.datos.selectorElementoLista+':first-child')) {pestana.addClassName(that.datos.claseSeleccionadoPrimera);}
    }

}

function desplegables () {
    this.datos = {
        capa: '.contenedor-desplegables'
        ,clasePredeterminado: 'predeterminado'
        ,titulo: '.titulo-desplegables'
        ,clasePlegado: 'plegado'
        ,claseDesplegado: 'desplegado'
    }
    
    this.inicia = function () {
        var that = this;
        $$(this.datos.capa).each(function(el) {
            var titulo = el.select(that.datos.titulo);
            that.ocultarInicial(titulo);
            that.alternarCapas(titulo);
        });
    }
    
    this.ocultarInicial = function (titulo) {
        var that = this;
        titulo.each(function(el) {
            if(!el.hasClassName(that.datos.claseDesplegado)){
                el.next().hide();
            }
        });
    }
    
    this.alternarCapas = function (titulo) {
        var that = this;
        titulo.each(function(el) {
            var enlace = el.select('a')[0];
            enlace.observe('click', function(ev){
                Event.stop(ev);
                el.next().toggle();
                el.toggleClassName(that.datos.clasePlegado);
                el.toggleClassName(that.datos.claseDesplegado);
            });
        });
    }
}

function Carrusel () {
    this.datos = {
        listaPestanas: '.componenteGaleria>.lista'
        ,correccionPosicionIzquierda: 1
        ,correccionAnchoPestanas: 24
        ,claseCarrusel: 'carrusel'
        ,htmlNavegacion: '<ul class="navegacion-carrusel clear"><li class="anterior"><a href="#"><img src="/export/system/modules/es.servigroup/resources/recursos/ico-carrusel-nav-anterior.gif" alt="Mover a la izquierda" /></a></li><li class="siguiente"><a href="#"><img src="/export/system/modules/es.servigroup/resources/recursos/ico-carrusel-nav-siguiente.gif" alt="Mover a la derecha" /></a></li></ul>'
        ,claseListaNavegacion: 'navegacion-carrusel'
        ,claseIcoActivo: 'activo'
        ,claseIcoAnterior: 'anterior'
        ,icoAnterior: '/export/system/modules/es.servigroup/resources/recursos/ico-carrusel-nav-anterior.gif'
        ,icoAnteriorHover: '/export/system/modules/es.servigroup/resources/recursos/ico-carrusel-nav-anterior-hover.gif'
        ,claseIcoSiguiente: 'siguiente'
        ,icoSiguiente: '/export/system/modules/es.servigroup/resources/recursos/ico-carrusel-nav-siguiente.gif'
        ,icoSiguienteHover: '/export/system/modules/es.servigroup/resources/recursos/ico-carrusel-nav-siguiente-hover.gif'
        ,claseIcoDesplegar: 'desplegar'
        //,icoDesplegar: 'ficheros/AP_IMG_control_carrusel_03_desplegar.gif'
        //,icoDesplegarHover: 'ficheros/AP_IMG_control_carrusel_03_desplegar_hover.gif'
        //,htmlListaSecundaria: '<ul class="lista-secundaria"></ul>'
        ,listaSecundaria: '.lista-secundaria'
        ,claseSeleccionado: 'seleccionado'
        ,selectorComponente: '.componenteGaleria'
        ,distanciaIndividual: 96
        ,movimientoIndividual: 1
        ,distanciaGrupo: 576
        ,movimientoGrupo: 6
        ,claseMovimientoIndividual: 'movimiento-individual'
        ,htmlNumeracion: '<p class="numeracion"><span class="indentado">Viendo </span><em class="numeracion-parcial-inicio"></em> a <em class="numeracion-parcial-final"></em> de <em class="numeracion-total"></em></p>'
        ,numeracion: '.numeracion'
        ,numeracionParcialInicio: '.numeracion-parcial-inicio'
        ,numeracionParcialFinal: '.numeracion-parcial-final'
        ,numeracionTotal: '.numeracion-total'
        ,listaImagenes: '.imagenes li'
        ,imagenSeleccionada: '.imagen-seleccionada'
        ,claseCarruselConImagenSeleccionada: 'carrusel-con-imagen-seleccionada'
        ,htmlImagenSeleccionada: '<p></p>'
    }
    
    this.inicia = function () {
        var that = this;
        
        $$(that.datos.listaPestanas).each(function (el) {
            that.imagenSeleccionada(el.up());
            var pestanas = el.select('li');
            var anchoComponente = el.getWidth();
            
            var anchoLista = 0;
            var i=0; while (i<pestanas.length) {
                anchoLista = anchoLista+pestanas[i].getWidth()+that.datos.correccionAnchoPestanas;//alert(i+' de '+pestanas.length+' - '+anchoLista);
                i++;
            }
            
            var anchoPestanas = anchoLista;
            if (anchoPestanas>anchoComponente) {
                el.addClassName(that.datos.claseCarrusel);
                el.down('ul').setStyle({
                     width: (anchoPestanas/10)+'em'
                });
                Element.wrap(el.down('ul'),'div');
                that.navegacion(el);
                
            }
            
            // temporal
            that.mostrar(el);
        });
        
    }
    
    this.mostrar = function (elemento) {
        var that = this;
        elemento.select(that.datos.listaImagenes+' a').each(function (el) {
            el.observe('click',function (ev) {
                Event.stop(ev);
                el.up().siblings().each(function (el2) {
                    el2.removeClassName(that.datos.claseSeleccionado);
                });
                el.addClassName(that.datos.claseSeleccionado);
                var imagen = el.select('img')[0];
                var texto = imagen.alt.split(':')[0];
                var componente = Element.closest(el,that.datos.selectorComponente);
                var enlaceSeleccionada = componente.select('.enlace-imagen-seleccionada a')[0];
                var imagenSeleccionada = componente.select('.imagen-seleccionada img')[0];
                
                imagenSeleccionada.src = el.href;
                
                imagenSeleccionada.alt = texto;
                enlaceSeleccionada.select('span')[0].update(texto);
                enlaceSeleccionada.href = el.rel;
            });
        });
    }
    
    this.imagenSeleccionada = function (el) {
        var that = this;
        if (el.select(that.datos.imagenSeleccionada).length==1) {
            el.addClassName(that.datos.claseCarruselConImagenSeleccionada);
        }
    }
    
    this.navegacion = function (el) {
        var that = this;
        Element.insert(el,{bottom: that.datos.htmlNavegacion});
        var lista = el.select('.'+that.datos.claseListaNavegacion)[0];
        
        
        var anterior = lista.select('li.'+that.datos.claseIcoAnterior+' a')[0];if (el.up().style.left==0) {anterior.hide();}
        var siguiente = lista.select('li.'+that.datos.claseIcoSiguiente+' a')[0];
        
        
        that.rollover(anterior,that.datos.icoAnterior,that.datos.icoAnteriorHover);
        that.rollover(siguiente,that.datos.icoSiguiente,that.datos.icoSiguienteHover);
        
        this.numeracion(el.up());
        
        that.mover(siguiente,-1);
        that.mover(anterior,1);
        
    }
    
    this.numeracion = function (el) {
        var that = this;
        
        var primero = 1;
        var ultimo = that.datos.movimientoGrupo;
        var total = el.select(that.datos.listaImagenes).length;
        
        Element.insert(el,{top:that.datos.htmlNumeracion});
        el.select(that.datos.numeracionParcialInicio)[0].update(primero);
        el.select(that.datos.numeracionParcialFinal)[0].update(ultimo);
        el.select(that.datos.numeracionTotal)[0].update(total);
    }
    
    this.variarNumeracion = function (elemento,signo) {
        var that = this;
        
        var componente = Element.closest(elemento,that.datos.selectorComponente);
        var movimiento = that.datos.movimientoGrupo; if (componente.hasClassName(that.datos.claseMovimientoIndividual)) {movimiento = that.datos.movimientoIndividual;}
        
        var numeracion = componente.select(that.datos.numeracion)[0];
        var numPrimero = numeracion.select(that.datos.numeracionParcialInicio)[0];
        var numUltimo = numeracion.select(that.datos.numeracionParcialFinal)[0];
        
        var primero = (parseInt(numPrimero.firstChild.nodeValue))+(movimiento*signo*(-1));
        numPrimero.update(primero);
        
        var ultimo = (parseInt(numUltimo.firstChild.nodeValue))+(movimiento*signo*(-1));
        numUltimo.update(ultimo);
    }
    
    this.mover = function (elemento,signo) {
        var that = this;
        elemento.observe('click',function (ev) {
            that.variarNumeracion(elemento,signo);
            Event.stop(ev);
            if (signo>0) {
                Element.closest(elemento,'.'+that.datos.claseListaNavegacion).select('.'+that.datos.claseIcoSiguiente+' a')[0].show();
            } else {
                Element.closest(elemento,'.'+that.datos.claseListaNavegacion).select('.'+that.datos.claseIcoAnterior+' a')[0].show();
            }
            var listaPestanas = elemento.up(1).previous().down('ul');
            var componente = Element.closest(elemento,that.datos.selectorComponente);
            var distancia = that.datos.distanciaGrupo; if (componente.hasClassName(that.datos.claseMovimientoIndividual)) {distancia = that.datos.distanciaIndividual;}
            var anchoListaPestanas = listaPestanas.getWidth();
            var capaPestanas = elemento.up(2);
            var diferencia = parseInt(capaPestanas.getStyle('padding-right').split('px')[0]);
            if(/MSIE /i.test(navigator.userAgent)) {diferencia = parseFloat(capaPestanas.getStyle('padding-right').split('em')[0])*10;}
            
            var anchoCapaPestanas = capaPestanas.getWidth();
            //var anchoCapaSuperior = anchoCapaPestanas+diferencia+(signo*that.datos.correccionAnchoPestanas);console.log(anchoCapaSuperior);
            var anchoCapaSuperior = anchoCapaPestanas+(signo*that.datos.correccionAnchoPestanas);
            
            //var posicionIzquierdaMaxima = (anchoListaPestanas-anchoCapaSuperior)*signo;
            var posicionIzquierdaMaxima = (anchoListaPestanas-anchoCapaSuperior+diferencia+that.datos.correccionPosicionIzquierda)*signo;
            var posicionIzquierdaActual = parseInt(listaPestanas.getStyle('left').split('px')[0]);//alert(posicionIzquierda);
            var posicionIzquierdaProxima = posicionIzquierdaActual+(signo*distancia);
            
            if (posicionIzquierdaProxima<posicionIzquierdaMaxima && signo<0) {
                posicionIzquierdaProxima=posicionIzquierdaMaxima;
                Element.closest(elemento,'.'+that.datos.claseListaNavegacion).select('.'+that.datos.claseIcoSiguiente+' a')[0].hide();
            }
            if (posicionIzquierdaProxima>0 && signo>0) {
                posicionIzquierdaProxima=0;
                Element.closest(elemento,'.'+that.datos.claseListaNavegacion).select('.'+that.datos.claseIcoAnterior+' a')[0].hide();
            }
            //console.log(posicionIzquierdaProxima+'>'+posicionIzquierdaMaxima)
            listaPestanas.setStyle({left: ((posicionIzquierdaProxima)/1)+'px'});
        });
    }
    
    this.rollover = function (elemento,imagen,imagenHover) {
        elemento.observe('mouseenter',function () {
            elemento.down('img').src = imagenHover;
        });
        elemento.observe('mouseout',function () {
            elemento.down('img').src = imagen;
        });
    }
    
    
    
}

function alternarSelect (accion) {
    var visibilidad = '';
    if (accion=='ocultar') {visibilidad='hidden';}
    $$('select').each(function (el) {
        el.style.visibility = visibilidad;
    });
}

