﻿//Evitaremos realizar acciones si el resultado obtenido no ha cambiado.
var disponibilidad = null;
//Numero de milisegundos entre comprobaciones
var timeout = 60000;
//Idioma de la página
var idioma = jQuery('html').attr('lang');

//Al terminar la carga de la página, comprobamos la disponibilidad del servicio
jQuery(document).ready(function() {
	comprobarDisponibilidadServicio();
});

//Se envia una petición ajax para comprobar si responde
function comprobarDisponibilidadServicio() {
    var fecha = new Date();
    var params = 'URL=/servlet/fhoLogin%3Faccion=listar%26opcion=status%26fecha='+fecha;
    jQuery.ajax({
        type: "POST",
        url: "/WTNWEB/servlet/central",
        data: params,
        dataType:"json",
        success: successHandler,
        error: errorHandler
    });
}

function successHandler(response, status) {
    if ('success' == status) {
        if (disponibilidad != true) {
            //Si ha cambiado a DISPONIBLE, mostramos los forms
            disponibilidad = true;
            mostrarServicioDisponible();
        }
        //Volveremos a comprobar pasado el tiempo indicado en "timeout"
        setTimeout('comprobarDisponibilidadServicio()',timeout);
    } else {
    	//Otros status se procesa como erroneo.
        errorHandler(response, status);
    }
}

function errorHandler(response, status) {
    if (disponibilidad != false) {
        //Si ha cambiado a NO DISPONIBLE, mostramos error
        disponibilidad = false;
        mostrarServicioNoDisponible();
    }
    //Volveremos a comprobar pasado el tiempo indicado en "timeout"
    setTimeout('comprobarDisponibilidadServicio()',timeout);
}

function mostrarServicioDisponible() {
	//Eliminamos los DIV de errores que existan.
    jQuery('div[id^="servNoDisp"]').remove();
    
	//Recargamos los forms.
    jQuery('iframe').each(function(ndx, elemento){
        if ( this.id.indexOf('loginFrame') >= 0 ) {
            //si es el form de Login (loginFrame, ALMloginFrame, etc) establezco SRC para cargar el contenido.
            var urlLoginForm = '/WTNWEB/servlet/central?URL=/servlet/fhPublicAjaxRequest%3Faccion=form%26opcion=webForm%26formAlias=formLogin%26zona=EUR%26locale=' + idioma;
            if (this.id == 'CPRloginFrame' || document.title.indexOf('Wtransnet Corporate') >= 0) {
            	//Compatibilidad se comprueba por titulo (antes) y también por id del Iframe (nuevo)
                urlLoginForm = urlLoginForm + "%26source=cpr"
            } else if (this.id == 'ALMloginFrame') {
                urlLoginForm = urlLoginForm + "%26source=alm"
            }
            this.src = (urlLoginForm + '%26fecha='+ new Date());
        } else if (this.src.indexOf('/WTNWEB/')!=-1 ) {
            //si es otro form de app, quito y vuelvo a establecer el mismo SRC para recargar el contenido 
            var iframeSrc = this.src;
            this.src='';
            this.src=iframeSrc;
        }
    });
}

function mostrarServicioNoDisponible() {
    jQuery('iframe').each(function(ndx, elemento){
        var iframeObj = jQuery(this);
        var src = iframeObj.attr('src');
        if (src.indexOf('/WTNWEB/')!=-1 || iframeObj.attr('id').indexOf('loginFrame') >= 0 ) {
            var divObj = crearTapaIframe(ndx,this);
            iframeObj.parent().css("position","relative");
            iframeObj.parent().append(divObj);
        }
    });
}

function crearTapaIframe(numElemento, iframeObj) {

	var idDiv = 'servNoDisp' + numElemento;

    var divObj = jQuery('<div />').attr('id',idDiv).css({
        'position':'absolute',
        'text-align':'left',
        'background':'white',
        'width':'100%',
        'height':'100%',
        'top':'0px',
        'left':'0px'
    });

    var esCorporate = (iframeObj.id == 'CPRloginFrame' || document.title.indexOf('Wtransnet Corporate') >= 0);
    var esAlmacenaje = (iframeObj.id.substring(0,3) == 'ALM');

    //Construimos el título del mensaje
    var tituloObj = jQuery('<h5/>').html(tituloMensajeIdiomas()).css({
    	'margin':'0px',
        'padding':'0px',
        'text-align':'center',
        'font': 'normal normal bold 11px Arial, Helvetica, sans-serif',
        'color': '#1280B1'
    });
    //Cambiamos algunos estilos según la página de origen
	if (esCorporate) {
		divObj.css({'background':'url(/img-web/background.jpg) repeat-x top left'});
        tituloObj.css({'color': '#FFF'});
	} else if (esAlmacenaje) {
    	divObj.css({'padding':'10px','height':'85%'});
        tituloObj.css({'color': '#F29222'});
	}
    //Agregamos el titulo al div
	tituloObj.appendTo(divObj);

    //Construimos los párrafos del mensaje
    jQuery.each(mensajesIdiomas(), function(index, value) {
    	//Construimos un párrafo
    	var parrafoObj = jQuery('<p/>').html(value).css({
        	'margin'  : '0px',
            'padding' : '0px',
            'text-align':'center',
            'font'    : 'normal normal normal 11px Arial, Helvetica, sans-serif',
            'color'   : '#1280B1'
        });
    	//Cambiamos algunos estilos según la página de origen
    	if (esCorporate) {
    		parrafoObj.css({'color' : '#FFF'});
    	} else if (esAlmacenaje) {
    		parrafoObj.css({'color' : '#666'});    		
    	}
    	//Agregamos el párrafo al div
    	parrafoObj.appendTo(divObj);
    });

    return divObj;
}

function tituloMensajeIdiomas() {
    // Consulto el attributo "lang" del tag HTML
    if ( idioma.toLowerCase() == 'de' )
        return "Zurzeit sind unsere Dientsleistungen nicht verf&uuml;gbar.";
    if ( idioma.toLowerCase() == 'en' )
        return "Right now the service is not accessible.";
    if ( idioma.toLowerCase() == 'fr' )
        return "Le service est momentan&eacute;ment indisponible.";
    if ( idioma.toLowerCase() == 'it' )
        return "In questo momento il servizio non &egrave; disponibile.";
    if ( idioma.toLowerCase() == 'pl' )
        return "Strona jest chwilowo niedost&#281;pna.";
    if ( idioma.toLowerCase() == 'pt' )
        return "Actualmente o servi&ccedil;o encontra-se indispon&iacute;vel.";
    if ( idioma.toLowerCase() == 'pt-br' )
        return "Atualmente o servi&ccedil;o n&atilde;o est&aacute; dispon&iacute;vel.";
    /* ELSE ( idioma.toLowerCase() == 'es' ) */
    return "En estos momentos el servicio no est&aacute; accesible.";
}

function mensajesIdiomas() {
    // Consulto el attributo "lang" del tag HTML
    if ( idioma.toLowerCase() == 'de' )
        return [
            "Der Grund daf&uuml;r ist, dass &Auml;nderungen in der Applikation vorgenommen werden",
            "(&Auml;nderungen: Jeden Donnerstag von 14h bis 15h spanischer Zeit GMT+1).",
        "<a href='Empfehlungen.html' target='_blank'>WICHTIG: Ausserhalb diesen Uhrzeiten: KLICKEN SIE HIER</a>"
        ] ;
    if ( idioma.toLowerCase() == 'en' )
        return [
            "The reason may be that changes are being made in the application",
            "(this takes place every Thursday from 14:00 to 15:00 hours from Spain GMT+1).",
            "<a href='Advices.html' target='_blank'>IMPORTANT: Out of this hours CLICK HERE</a>"
        ] ;
    if ( idioma.toLowerCase() == 'fr' )
        return [
            "Des op&eacute;rations de maintenance sont peut-&ecirc;tre en cours de r&eacute;alisation",
            "(ces changements sont r&eacute;alis&eacute;s chaque jeudi de 14:00 &agrave; 15:00).",
        "<a href='Conseils.html' target='_blank'>IMPORTANT: en dehors de cet horaire, veuillez cliquer ICI</a>"
        ] ;
    if ( idioma.toLowerCase() == 'it' )
        return [
            "Il motivo pu&ograve; essere dovuto a cambi che si stanno realizzando nell'applicazione",
            "(questi cambi sono realizzati ogni Gioved&iacute; dalle ore 14.00 alle 15.00).",
            "<a href='Consigli.html' target='_blank'>IMPORTANTE: Fuori da quest&#39;orario CLICCHI QUI</a>"
        ] ;
    if ( idioma.toLowerCase() == 'pl' )
        return [
            "Przeprowadzamy zmiany w aplikacji",
            "(zmiany te przeprowadzane s&#261; w ka&#380;dy czwartek w godzinach 14:00 i 15:00).",
            "<a href='Instrukcje.html' target='_blank'>UWAGA: Poza podanymi godzinami: KLIKNIJ TUTAJ</a>"
        ] ;
    if ( idioma.toLowerCase() == 'pt' )
        return [
	        "O motivo poder&aacute; estar relacionado com a realiza&ccedil;&atilde;o de modifica&ccedil;&otilde;es na aplica&ccedil;&atilde;o",
	        "(modifica&ccedil;&otilde;es: &agrave;s 5&ordf; feiras entre as 14h e as 15h, hor&aacute;rio de Espanha GMT+1).",
        "<a href='Conselhos.html' target='_blank'>IMPORTANTE: Fora deste hor&aacute;rio CLIQUE AQUI</a>"
	    ] ;
    if ( idioma.toLowerCase() == 'pt-br' )
        return [
	        "O motivo poder&aacute; estar relacionado com a realiza&ccedil;&atilde;o de modifica&ccedil;&otilde;es na aplica&ccedil;&atilde;o",
	        "(realizado todas as 5&ordf; feiras das 14:00 &agrave;s 15:00 hs, hor&aacute;rio de Espanha GMT+1).",
            "<a href='conselhos.html' target='_blank'>IMPORTANTE: Fora deste hor&aacute;rio CLIQUE AQUI</a>"
	    ] ;
    /* ELSE ( idioma.toLowerCase() == 'es' ) */
    return [
        "El motivo puede ser que se est&eacute;n realizando cambios en la aplicaci&oacute;n",
        "(esto se realiza cada Jueves de 14:00 a 15:00 horario de Espa&ntilde;a GMT+1).",
        "<a href='consejos.html' target='_blank'>IMPORTANTE: Fuera de este horario CLICK AQU&Iacute;</a>"
    ] ;
}
