/*global SISAL window showGameDetail showWFLGameDetail $*/

/**
 * La variabile rappresenta il namespace utilizzato per tutto il codice
 * javascript di giochi numerici.
 */


SISAL.GNTN = (function GNTN() {

	function setLocationHREF(formName) {

	    formName = document.getElementById(formName);    
	    
		SISAL.unsetCookie("idSession");
		SISAL.unsetCookie("username");
		
		if (!SISAL.isNullOrEmpty(formName)) {
			// recupero parametro dell'url da lanciare.
			// Facciamo cosi per il problema del passaggio tra protocollo HTTP e HTTPS
			// solo con IFRAME

			var ambiente = null;
			
			if (!SISAL.isNull(formName.ambiente))
			{
			    ambiente = formName.ambiente.value;
			}    
		    
			if (ambiente === "S")
			{    
			    formName.id_PageUrl.value = location.href.replace("http:", "http:");
			}
			else if (ambiente === "P")
			{
			    formName.id_PageUrl.value = location.href.replace("http:", "https:");    
			}
			else
			{
			    formName.id_PageUrl.value = location.href.replace("http:", "http:");
			}    
		}
	}
	
	function removeNavigationCookie()
	{
		SISAL.unsetCookie('_sezione');
		SISAL.unsetCookie('_BoxInformativo');
		SISAL.unsetCookie('_BoxPromo');
		SISAL.unsetCookie('_BoxInfoSmall');
		SISAL.unsetCookie('_assvirt');
	}
	
	function setNavigationCookie(pageName, menutop, assvirt, BoxInformativo, BoxPromo, BoxInfoSmall)
	{
		removeNavigationCookie();
		// Cookie per la gestione delle pagine del Sito Gioco		
		SISAL.setCookie('_assvirt',{ value: assvirt, days: 5});
		SISAL.unsetCookie('_sezione');
		SISAL.unsetCookie('_BoxInformativo');
		SISAL.unsetCookie('_BoxPromo');
		SISAL.unsetCookie('_BoxInfoSmall');
		SISAL.setCookie('_sezione',{ value: 'PAGE_' + pageName, days: 5});
		SISAL.setCookie('_menutop',{ value: 'MENU_' + menutop, days: 5});
		SISAL.setCookie('_BoxInformativo',{ value: BoxInformativo, days: 5});
		SISAL.setCookie('_BoxPromo',{ value: BoxPromo, days: 5});
		SISAL.setCookie('_BoxInfoSmall',{ value: BoxInfoSmall, days: 5});
	}
	
	function salvaDati(idform)
	{
		
		var formLogin = null,
			numeroconto = null,
			pin = null,
			id_salvaidati = null
			;
		
		formLogin = document.getElementById(idform);
		id_salvaidati = document.getElementById("id_salvaidati");
		
		if (!SISAL.isNull(id_salvaidati)) {
			if (formLogin.id_salvaidati.checked === true) {
				numeroconto = formLogin.id_numeroconto.value;
				pin = formLogin.id_pin.value;

				if (numeroconto !== "Errore Login" && numeroconto !== null && numeroconto !== "" && numeroconto !== "Username/N.conto")
				{
					SISAL.setCookie("numeroconto", {value: numeroconto, days: 5});
				} else {
					SISAL.unsetCookie("numeroconto");
				}
			} else {
				SISAL.unsetCookie("numeroconto");
			}
		}
		
		/*alert ("login pin vuoto => " + SISAL.isNullOrEmpty(formLogin.login_pin));
		alert ("login_numeroconto vuoto => " + SISAL.isNullOrEmpty(formLogin.login_numeroconto));
		alert ("login_numeroconto valore => " + formLogin.login_numeroconto.value);
		alert ("PIN valore => " + formLogin.login_pin.value);*/
		
		if (SISAL.isNullOrEmpty(formLogin.login_pin) || 
		    SISAL.isNullOrEmpty(formLogin.login_numeroconto) ||
		    formLogin.login_numeroconto.value === "Username/N.conto" ||
		    formLogin.login_pin.value.trim === "PIN")
		{
			if (!SISAL.isNullOrEmpty(formLogin.tipologin) && formLogin.tipologin.value === 'A')
			{
				location.href = "/portal/page/portal/SitoGioco/sitoaccessibile/registrazione/login/loginerrata"; 
			} else 
			{
				SISAL.setCookie("loginerror", {value : "parametriErrati"});   
				location.href = "/portal/page/portal/PortaleGiochiNumerici/login"; 
			}
		}    
		else
		{    
		    formLogin.submit();
		}    
	}

	// ritorna la soluzione dello schermo (versione apa)
	function getScreenResolutionApa()
	{
	    try
	    {
	        var width = null,
	            height = null
	            ;

            width = window.screen.width;
            height = window.screen.height;

	        if ((width === 800) && (height === 600))
	        {
	            document.getElementById('spazio_cuscinetto_apa').style.width = "0px";
	            document.getElementById('spazio_cuscinettoBottom_apa').style.width = "343px";
	        }
	    }
	    catch (err)
	    {
	        //alert("getScreenResolution \n"+err);
	    }
	}

	// Serve per lanciare il biglietto corretto nelle mie giocate in base al
    // tipo di gioco
    function showGame(tipogioco, giocata, pvd, conto, token) {
        // TIPO GIOCO :
        // 100 SUPERENALOTTO
        // 200 WINFORLIFE
        
        //alert("tipogioco => " + tipogioco);

        switch (tipogioco) {
        case 100:
            //alert("LANCIO showGameDetail");
            showGameDetail(giocata, pvd, conto);
            break;
        case 200:
            //alert("LANCIO showWFLGameDetail");        
            showWFLGameDetail(giocata, pvd, conto, token);
            break;
        default:
            showWFLGameDetail(giocata, pvd, conto, token);
        }
    }
    
    // serve per cambiare immagine su un elemento
	function changeimg(idimg, path) {

		var imgsel = null;

		imgsel = document.getElementById(idimg).id;
		if (idimg === imgsel) {
			document.getElementById(idimg).src = path;
		}
	}
	
	function returnUrlWithProtocol(percorso) {
	    
	    var host = null,
            hostname = null,
            port = null,
            protocol = null
	    ;
	    
        host = location.host; // dominio + porta
        hostname = location.hostname;
        
        if (!SISAL.isNullOrEmpty(host))
        {    
            port = ':' + location.port;
        }    
        else
        {    
            port = '';
        }
        
        protocol = location.protocol.substr(0, location.protocol.length - 1);

        return protocol + '://' + host + percorso;
    }
	
	function getBrowser() {
	    var element;
	    element = 'unknown';
	    if (document.all)
	    {
	        element = 'IE';
	    }
	    else if (document.layers)
	    {
	        element = 'Netscape4';
	    }
	    else
	    {
	        element = 'FireFox';
	    }
	    return element;
	}
	
	function setRss(link, titolo) {
		
		var browser,
		messaggio;

		browser = navigator.userAgent.toLowerCase();

		if (getBrowser() === 'IE')
		{	
		    window.external.AddFavorite(link, titolo);
		    location.href = link;
		} else if (browser.indexOf('safari') !== -1)
		{
		    messaggio = 'Per aggiungere RSS tra i preferiti, premre ctrl + D';
		    SISAL.FX.showOnElement_TemplatePopup('body', 'gntn.alert.buttonok.html', {"{title}" : "Attenzione", "{content}" : messaggio, "{buttonclick}" : '<hideThis>', width : '350px'});
		} else if (window.opera && window.print)
		{
		    messaggio = 'Per aggiungere RSS tra i preferiti, premre ctrl + D';
		    SISAL.FX.showOnElement_TemplatePopup('body', 'gntn.alert.buttonok.html', {"{title}" : "Attenzione", "{content}" : messaggio, "{buttonclick}" : '<hideThis>', width : '350px'});
		} else
		{
		    window.sidebar.addPanel(titolo, link, '');
		    location.href = link;
		}
	}
	
	function controlla(form, id) {
	    var flag,
	    // colore x etichetta campo compilato
	    okHex,
	    // colore x etichetta campo non compilato
	    noHex,
	    campi,
	    campiContatti,
	    k;


	    campiContatti = ['nome', 'mail', 'cognome', 'oggetto'];
	    flag = true;
	    okHex = '#ffffff';
	    noHex = '#f37d16';

	    if (id === 'contatti')
	    {
	        campi = campiContatti;
	    }


		for (k = 0; k < campi.length; k += 1) {
			if (form.elements[campi[k]].value === "" || form.elements[campi[k]].value.match(/^\s+$/)) 
			{
			    document.getElementById(campi[k]).style.backgroundColor = noHex;
				if (flag) 
				{ 
				    document.getElementById(id).style.backgroundColor = okHex;
				    flag = false;
				}
			} else {
			    document.getElementById(campi[k]).style.backgroundColor = okHex;
			}
		}
	}

	function controllamail(mail) {
		var espressione = /^[_a-z0-9+-]+(\.[_a-z0-9+-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)+$/;
		if (!espressione.test(mail)	|| (!mail.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/gi))) {
			return true;
		}
	}
	
	function contattiCheckAccept(formContatti)
	{
		var conto,
		richiesta,
		nome,
		cognome,
		email,
		oggetto,
		campiObbligatori,
		validMail,
		requestOK,
		attenzione,
		requestOKtitle,
		urlBase;

		conto = formContatti.conto.value;
		richiesta = formContatti.richiesta.value;
		nome = formContatti.nome.value;
		cognome = formContatti.cognome.value;
		email = formContatti.mail.value;
		oggetto = formContatti.oggetto.value;

		controlla(formContatti, 'contatti');

		if (parent.get_nls_language() === 'i')
		{
			campiObbligatori = "Compilare tutti i campi obbligatori";
			validMail = "Inserisci un indirizzo e-mail valido";
			requestOK = "Grazie per aver contattato il nostro call center.<br>Gestiremo la tua richiesta nel minor tempo possibile.";
			attenzione = "Attenzione";
			requestOKtitle = "Richiesta inoltrata";
		}
		if (parent.get_nls_language() === 'us')
		{
			campiObbligatori = "All fields are required";
			validMail = "Please enter a valid e-mail address";
			requestOK = "Thank you for contacting our call center.<br>Handle your request as quickly as possible.";
			attenzione = "Caution";
			requestOKtitle = "Request sent";
		}

		if (formContatti.nome.value === "" || formContatti.cognome.value === "" || formContatti.mail.value === "" || formContatti.oggetto.value === "" || formContatti.accept.checked === false)
		{
			SISAL.FX.showOnElement_TemplatePopup('body', 'gntn.alert.buttonok.html', {"{title}" : "Attenzione", "{content}" : campiObbligatori, "{buttonclick}" : '<hideThis>', width : '350px'});				
		}

		else
		{
		    if (controllamail(email))
		    {
		        SISAL.FX.showOnElement_TemplatePopup('body', 'gntn.alert.buttonok.html', {"{title}" : "Attenzione", "{content}" : validMail, "{buttonclick}" : '<hideThis>', width : '350px'});							
		        formContatti.mail.style.backgroundColor = '#f37d16';
		    }
		    else
		    {
		        urlBase = '/portal/page/portal/wfldoclib/administrator';
		        SISAL.ajax("/portal/page/portal/wfldoclib/administrator?conto=" + conto + "&nome=" + nome + "&cognome=" + cognome + "&email=" + email + "&richiesta=" + richiesta + "&oggetto=" + oggetto, {target: "contatti"});
		        formContatti.nome.style.backgroundColor = '#ffffff';
		        formContatti.cognome.style.backgroundColor = '#ffffff';
		        formContatti.mail.style.backgroundColor = '#ffffff';
		        formContatti.oggetto.style.backgroundColor = '#ffffff';
		        formContatti.nome.value = '';
		        formContatti.cognome.value = '';
		        formContatti.mail.value = '';
		        formContatti.conto.value = '';
		        formContatti.richiesta.selectedIndex = 0;
		        formContatti.oggetto.value = '';
		        SISAL.FX.showOnElement_TemplatePopup('body', 'gntn.alert.buttonok.html', {"{title}" : "Attenzione", "{content}" : requestOK, "{buttonclick}" : '<hideThis>', width : '350px'});							
		    }
		}	    
	}
	
	return {
		setLocationHREF : setLocationHREF,
		removeNavigationCookie : removeNavigationCookie,
		setNavigationCookie : setNavigationCookie,
		salvaDati : salvaDati,
		getScreenResolutionApa : getScreenResolutionApa,
		showGame : showGame,
		changeimg : changeimg,
		returnUrlWithProtocol : returnUrlWithProtocol,
		getBrowser : getBrowser,
		setRss : setRss,
		contattiCheckAccept : contattiCheckAccept
	};
}());

if (SISAL.logger.isInfoEnabled()) {
	SISAL.logger.info("SISAL.GNTN - namespace creato");
}