/*
Leonardo Service Provider S.p.A.
Tutti i diritti registrati e riservati,(R)(C) 2009.
La riproduzione parziale o totale del presente software
delle pagine generate nonchè della strutturazione dei dati,
delle tabelle e di quant'altro è ad esso inerente  è illegale 
ed è punibile secondo tutte le Leggi vigenti sulla violazione del Diritto D'Autore.
L'utilizzo del presente software senza regolare licenza d'uso
è illegale e sarà perseguito secondo tutte le Leggi vigenti applicabili
*/

var GLOBALSTValue = '4';
var GLOBALSTNavig = GLOBALSTValue;
var GLOBALcanBuyGEV = false;
$(document).ready(function(){
	gevdata = new Object({		
		init: function(){			
			this.Token;
			this.IDConto;
			this.IDRivenditore;
		},
		bind: function(xml){
			this.Token = String(xml.getElementsByTagName('TokenID')[0].firstChild.nodeValue);
			this.IDConto = String(xml.getElementsByTagName('IDContoGioco')[0].firstChild.nodeValue);
			this.IDRivenditore = String(xml.getElementsByTagName('CodiceRivenditore')[0].firstChild.nodeValue);
		}		
	});	
	gevdata.init()
	$('ul.spy').simpleSpy();
	reqWinners();
	reqTotal()
})

function enableGame(userid){
	var ui = userid
	if(ui != '' && ui != null && ui != 'undefined') {
		$.ajax({
			url: "gev/request_lit.aspx?action=getplayerinfo&userid="+ui,
			cache: false,
			success: function(xml){
				var valid = xml.getElementsByTagName('Validate')[0].firstChild.nodeValue;
				if(valid == 0){
					gevdata.bind(xml);
					var acccon = xml.getElementsByTagName('IsregisteredSCGA')[0].firstChild.nodeValue;
					if (String(GLOBALUserClass) == '5') {
						if(acccon == 'true'){
							GLOBALcanBuyGEV = true;
						}else{
						
							var msgTxt = 'In applicazione di quanto previsto dal contratto di conto di gioco, AUTORIZZO L&acute;ABILITAZIONE DEL MIO CONTO GIOCO ALL&acute;ACQUISTO DELLE LOTTERIE TELEMATICHE* si sensi dell&acute;articolo 3, comma 2 del decreto direttoriale dell&acute;amministrazione autonoma dei monopoli di stato del 21 Marzo 2006.<br /><br />* Le lotterie Telematiche sono disciplinate dai decreti dirigenziali del 13 aprile 2006 e del 28 Settembre 2006, nonch&egrave; dai regolamenti di gioco delle singole lotterie disponibili sul sito www.aams.it'
							var msgSubj = 'Abilitazione del conto di gioco all&acute;acquisto delle Lotterie Telematiche'
							var contrattoMsg = new Array($('<msg id="0" Subj="'+ msgSubj +'" Txt="'+ msgTxt +'"/>'))						
							manMsgCreate(ui,contrattoMsg)
						}
					}
				}else{
					
					var walert = $().popw({wtype:'info', wwidth:200, draggable:true})
					walert.writehtml(xml.getElementsByTagName('ErrDesc')[0].firstChild.nodeValue);
				}
			}
		});
	}
}


function pageLoggedFunction(uid) {
	GLOBALcanBuyGEV = true;
	$(".reg").hide()
	enableGame(uid);	
}

function tryGame(IDConcorso){
	tryLauncher(IDConcorso)	
}

function infoGame(IDConcorso){	
	infoLauncher(IDConcorso)
}

function buyGame(IDConcorso){
	if (GLOBALcanBuyGEV == true) {
		buyLauncher(IDConcorso, gevdata.Token, gevdata.IDConto, gevdata.IDRivenditore)
	} else {
		createLoginPopup();
	}
}

function createLoginPopup() {
	/* Devo mostrare un errore */
	var loginFormStr = ''; var loginFormStr2 = '';  var descErr = '';
	//if(descErr.indexOf('login') != -1){
		loginFormStr2 += '<div id="login_side"><p>'
		loginFormStr += '</p><p><label for="wlogin_username">Username</label><input type="text" id="wlogin_username" value="username" /></p>'
		loginFormStr += '<p><label for="wlogin_password">Password</label><input type="password" id="wlogin_password" value="password" /></p>'
		loginFormStr += '<p><button>Login</button></p>'
		loginFormStr += '</div>'
		loginFormStr += '<div id="reg_side">'
		loginFormStr += '<p>Se non sei ancora registrato apri un conto oggi stesso. E\' semplice ed immediato.</p>'
		loginFormStr += '<a href="etc.aspx?p=registrazione">Registrati</a>'						
		loginFormStr += '</div>'
		$('#tmpusr').select();
	//}
	var w = $().popw({wtype:'alert', wwidth:200, draggable:true}).writehtml(loginFormStr2 + descErr + loginFormStr);
	$('#modalew').attr('class', 'modale_login');
	if (loginFormStr != '') {
		$('#whtml #wlogin_username').focus(function() {
			if ($(this).val() == 'username') {
				$(this).val('')
			}
		})
		$('#whtml #wlogin_password').focus(function() {
			if ($(this).val() == 'password') {
				$(this).val('')
			}
		})
		$('#whtml input').keydown(function(e) {
			if (e.keyCode == 13) {
				loginLoad('post',$('#whtml #wlogin_username').val(),$('#whtml #wlogin_password').val());
			}
		});
		$('#whtml button').click(function(){
			loginLoad('post',$('#whtml #wlogin_username').val(),$('#whtml #wlogin_password').val());
		})
	}
}





(function ($) {
    
$.fn.simpleSpy = function (limit, interval) {
    limit = limit || 4;
    interval = interval || 4000;
    
    return this.each(function () {
     
        var $list = $(this),
            items = [], // uninitialised
            currentItem = limit,
            total = 0, // initialise later on
            height = $list.find('> li:first').height();            
       
        $list.find('> li').each(function () {
            items.push('<li>' + $(this).html() + '</li>'); 
        });
        
        total = items.length;
        
        $list.wrap('<div class="spyWrapper" />').parent().css({ height : height * limit });
       
        $list.find('> li').filter(':gt(' + (limit - 1) + ')').remove();
          
        function spy() {           
            var $insert = $(items[currentItem]).css({ 
                height :0,
                opacity : 0,
                display : 'none'
            }).prependTo($list); 
            $list.find('> li:last').animate({ opacity : 0}, 1000, function () {               
                $insert.animate({ height : height }, 1000).animate({ opacity : 1 }, 1000);                 
                $(this).remove();                
            });
            
            currentItem++;
            if (currentItem >= total) {
                currentItem = 0;
            }            
            setTimeout(spy, interval)
        }
        
        spy();
    });
};
    
})(jQuery);

function gotoGev(gevId){			
	var gevTop = $('#gev'+gevId).offset().top;
	$('html,body').animate({scrollTop:gevTop-20}, 500);
}

function reqWinners(){	
	$.ajax({
		url: "gev/request_lit.aspx?action=ListWinners",
		cache: false,
		success: function(xml){
			var valid = xml.getElementsByTagName('Validate')[0].firstChild.nodeValue;
			if(valid == 0){				
				var winners = xml.getElementsByTagName('BetWinersResponse');
				if(winners.length>0){
					showWinners(winners, 0)
				}
			}else{
				var walert = $().popw({wtype:'info', wwidth:200, draggable:true})
				walert.writehtml(xml.getElementsByTagName('ErrDesc')[0].firstChild.nodeValue);
			}
		}
	});	
}

function showWinners(winners, counter){
	
	var user = '<span class="capitalize">' + $(winners[counter]).attr('UserID').toLowerCase() + '</span>';
	
	var game = $(winners[counter]).attr('NameGame');
	
	var w = $(winners[counter]).attr('Win'); w = w.substr(0, w.length-2);
	var win = '<span class="gevcurrentwin">'+ w + ' &euro;</span>';	
	
	var c = $(winners[counter]).attr('City').toLowerCase()	
	var city = '<span class="capitalize">'+c+'</span>';
	
	$('#lastWinner').css('opacity',0);
	
	$('#lastWinner').html(user+' da'+' '+city+' ha appena vinto '+win+' <span style="display:block;">'+' giocando a '+game+'!</span>');
	
	var winSize = $('#lastWinner').css("font-size")
	$('.gevcurrentwin').css("font-size", parseInt(winSize)+4+"px"); 
	$('#lastWinner').animate({opacity:1},1000)
	
	counter = (counter == winners.length-1) ? 0 : counter+1;
	
	var winnersTime = setTimeout(function(){showWinners(winners, counter)}, 5000)	
}

function reqTotal(){	
	$.ajax({
		url: "gev/request_lit.aspx?action=totalWin",
		cache: false,
		success: function(xml){
			var valid = xml.getElementsByTagName('Validate')[0].firstChild.nodeValue;
			if(valid == 0){				
				var total = xml.getElementsByTagName('Win')[0].firstChild.nodeValue;
				showTotal(total)
			}else{
				var walert = $().popw({wtype:'info', wwidth:200, draggable:true})
				walert.writehtml(xml.getElementsByTagName('ErrDesc')[0].firstChild.nodeValue);
			}
		}
	});	
}

function showTotal(tot){	
	 
	$('.totvincite').html(tot + " &euro;")
	
}

