/*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');
		
		SISAL.unsetCookie('_sezionewfl');
		SISAL.unsetCookie('_BoxInformativowfl');
		SISAL.unsetCookie('_BoxPromowfl');
		SISAL.unsetCookie('_BoxInfoSmallwfl');
		SISAL.unsetCookie('_assvirtwfl');
	}
	
	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});
		
		SISAL.setCookie('_assvirtwfl', { value: assvirt, days: 5});
		SISAL.unsetCookie('_sezionewfl');
		SISAL.unsetCookie('_BoxInformativowfl');
		SISAL.unsetCookie('_BoxPromowfl');
		SISAL.unsetCookie('_BoxInfoSmallwfl');
		SISAL.setCookie('_sezionewfl', { value: 'PAGE_' + pageName, days: 5});
		SISAL.setCookie('_menutopwfl', { value: 'MENU_' + menutop, days: 5});
		SISAL.setCookie('_BoxInformativowfl', { value: BoxInformativo, days: 5});
		SISAL.setCookie('_BoxPromowfl', { value: BoxPromo, days: 5});
		SISAL.setCookie('_BoxInfoSmallwfl', { value: BoxInfoSmall, days: 5});
	}
	
	function salvaDati(idform)
	{
		
		var formLogin = null,
			numeroconto = null,
			login_pin = null,
			id_salvaidati = null,
			buttonLogin = null,
			cssImg = null
			;
		
		formLogin = document.getElementById(idform);
		id_salvaidati = $("#id_salvaidati", formLogin).attr('checked');
		login_pin = $("#id_pin", formLogin).val();
		numeroconto = $("#id_numeroconto", formLogin).val();
		buttonLogin = $('#id_entra', formLogin);
		
		cssImg =
		{
			'background-image' : 'url("/gntn-docs/cross/sitogioco/immagini/login_no_buttonLoginSel.png")',
			'cursor' : 'default'
		};
		
		if (!SISAL.isNull(id_salvaidati))
		{
			if (id_salvaidati === true)
			{
				if (numeroconto !== "Errore Login" && numeroconto !== null && numeroconto !== "" && numeroconto !== "Numero conto")
				{
					SISAL.setCookie("numeroconto", {value: numeroconto, days: 5});
				} else
				{
					SISAL.unsetCookie("numeroconto");
				}
			} else
			{
				SISAL.unsetCookie("numeroconto");
			}
		}
		
		if (SISAL.isNullOrEmpty(login_pin) || SISAL.isNullOrEmpty(numeroconto) || numeroconto === "Numero conto" || login_pin.trim === "Pin/Password")
		{
			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 = "/GiochiNumerici/login"; 
			}
		}    
		else
		{    
		    formLogin.submit();
		    buttonLogin.removeAttr('onclick');
			buttonLogin.css(cssImg);
		}    
	}

	// 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);
        
        tipogioco = tipogioco * 1;

        switch (tipogioco) {
        case 100:
            //alert("LANCIO showGameDetail");
            showGameDetail(giocata, pvd, conto, token);
            break;
        case 102:
            //alert("LANCIO showWFLGoldGameDetail");        
            showSVTGameDetail(giocata, pvd, conto, token);
            break;
        case 200:
            //alert("LANCIO showWFLGameDetail");        
            showWFLGameDetail(giocata, pvd, conto, token);
            break;
        case 300:
            //alert("LANCIO showWFLGoldGameDetail");        
            showWFLGoldGameDetail(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 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;

		conto = $('#ob_conto').attr('value');
		richiesta = $('#ob_richiesta').attr('value');
		nome = $('#ob_nome').attr('value');
		cognome = $('#ob_cognome').attr('value');
		email = $('#ob_mail').attr('value');
		oggetto = $('#ob_oggetto').attr('value');
		
        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";
        }
		
        $('#idformContatti input, textarea').each(function(i, el){
            if($(el).attr('id').substr(0,3) === 'ob_')
            {
                if (SISAL.isNullOrEmpty($(el).val()))
                { 
                    $(el).css('background-color','#f37d16');
                }
                else
                {
                    $(el).css('background-color','#FFFFFF');
                }
            }
        });
        
        $('#idformContatti input, textarea').each(function(i, el){
            if($(el).attr('id').substr(0,3) === 'ob_')
            {
                if(SISAL.isNullOrEmpty($(el).val()) || !$('#ob_accept').attr('checked'))
                {
                   SISAL.FX.showOnElement_TemplatePopup('body', 'gntn.alert.buttonok.html', {"{title}" : "Attenzione", "{content}" : campiObbligatori, "{buttonclick}" : '<hideThis>', width : '350px'});
                   return false;
                } else
                {
                    if (controllamail(email))
                    {
                        SISAL.FX.showOnElement_TemplatePopup('body', 'gntn.alert.buttonok.html', {"{title}" : "Attenzione", "{content}" : validMail, "{buttonclick}" : '<hideThis>', width : '350px'});                         
                        $('#ob_mail').css('background-color', '#f37d16');
                        return false;
                    } else
                    {
                        SISAL.ajax("/portal/page/portal/wfldoclib/administrator?conto=" + conto + "&nome=" + nome + "&cognome=" + cognome + "&email=" + email + "&richiesta=" + richiesta + "&oggetto=" + oggetto, {target: "contatti"});
                       
                        $('#idformContatti input, textarea').each(function(i, el){
                            if($(el).attr('id').substr(0,3) === 'ob_')
                            {
                                $(el).css('background-color','#FFFFFF');
                                $(el).attr('value', '');
                            }
                        });
                        formContatti.richiesta.selectedIndex = 0;
                        SISAL.FX.showOnElement_TemplatePopup('body', 'gntn.alert.buttonok.html', {"{title}" : "Attenzione", "{content}" : requestOK, "{buttonclick}" : '<hideThis>', width : '350px'});
                        return false;
                    }
                }
            }
        });
	}
	
	function changeImg(idImg, src, idDiv)
	{
	    $('#containerImg img').each(function (i, el)
	    {
	        var srcIn = $('#' + el.id).attr('src');
	        $(el).hide();
	        if (idImg !== idDiv)
	        {
	            $('#' + idDiv).show();      
	            $('#' + idImg).hide();
	        }
	        
	        if (src !== srcIn)
	        {
	            $(el).show();
	        }
	    });
	}

	function pngfix() 
	{
	    if (getBrowser() === 'IE')
	    {   
	        var ii = 0;
	        var imageArray = new Array;
	        imageArray[ii++] = "star.png";
	        imageArray[ii++] = "assvirt_nascondi.png";
	        imageArray[ii++] = "pagePath_separator.png";
	        imageArray[ii++] = "frecciaUp.png";
	        imageArray[ii++] = "frecciaDown.png";
	        imageArray[ii++] = "frecciaRight.png";
	        imageArray[ii++] = "frecciaLeft.png";
	        imageArray[ii++] = "loginBg.png";
	        imageArray[ii++] = "logoutBg.png";
	        imageArray[ii++] = "giocaIlGiusto.png";
	        imageArray[ii++] = "giocoSicuro.png";
	        imageArray[ii++] = "aams.png";
	        imageArray[ii++] = "MyPage.png";
	        imageArray[ii++] = "sfRegistrazioneBottom.png";
	        imageArray[ii++] = "refresh_saldo.png";
	        imageArray[ii++] = "vinciteCombVincente.png";
	        imageArray[ii++] = "circle.png";
	        //imageArray[ii++] = "logo_nolog.png";
	        imageArray[ii++] = "loginBg.png";
	        imageArray[ii++] = "rotella.png";
	        
	        var els=document.getElementsByTagName('*');
	        var ip=/\.png/i;
	        var i=els.length;

	        while(i-- >0)
	        {
	            var el=els[i];
	            var es=el.style;
	            
	            if (el.src !== undefined)
	            {
	                var elb=el.src;
	                var type='src';
	            } else
	            {
	                var elb=el.currentStyle.backgroundImage;
	                var type='bg';
	            }
	            
	            if (elb != undefined)
	            {
	                var indiceArray = 0;
	                do
	                {
	                    var ricerca = elb.search(imageArray[indiceArray]);
	                    indiceArray++;
	                } while (indiceArray != imageArray.length && ricerca == -1);
	            }
	            else
	                var ricerca = -1;
	                
	            // -1 => NON TROVATO
	            if (ricerca != -1)
	            {
	                if(elb.match(ip))
	                {
	                    if (type == 'src')
	                        elb = '"' + elb + '"';
	                        
	                    var path=elb.split('"');
	                    var rep=(el.currentStyle.backgroundRepeat=='no-repeat')?'crop':'scale';
	                    es.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+path[1]+"',sizingMethod='"+rep+"')";
	                    
	                    es.height=el.clientHeight+'px';
	                    es.backgroundImage='none';
	                    if (el.src != undefined)
	                        el.src='/sitogioco/Immagini/Top/empty.gif';
	                    var elkids=el.getElementsByTagName('*');
	                    
	                    if (elkids)
	                    {
	                        var j=elkids.length;
	                        if(el.currentStyle.position!="absolute")es.position='static';
	                            while (j-- >0)
	                                if(!elkids[j].style.position)elkids[j].style.position="relative";
	                    }
	                }
	            }
	        }
	    }
	}
	
	return {
		setLocationHREF : setLocationHREF,
		removeNavigationCookie : removeNavigationCookie,
		setNavigationCookie : setNavigationCookie,
		salvaDati : salvaDati,
		getScreenResolutionApa : getScreenResolutionApa,
		showGame : showGame,
		changeimg : changeimg,
		returnUrlWithProtocol : returnUrlWithProtocol,
		getBrowser : getBrowser,
		setRss : setRss,
		contattiCheckAccept : contattiCheckAccept,
		changeImg : changeImg,
		pngfix : pngfix
	};
}());

if (SISAL.logger.isInfoEnabled()) {
	SISAL.logger.info("SISAL.GNTN - namespace creato");
}
