/*********************************************************************************/
/*********************************************************************************/
/*********************************************************************************/
/****************************  GESTIONE DOM  *************************************/
/*********************************************************************************/
/*********************************************************************************/
/*********************************************************************************/
/*********************************************************************************/
//! classe per la definizione del tipo di browser
function _BrowserDetails()
{
	// Browser check
	var ua = navigator.userAgent;
	this.isMSIE = (navigator.appName == "Microsoft Internet Explorer");
	this.isMSIE5 = this.isMSIE && (ua.indexOf('MSIE 5') != -1);
	this.isMSIE5_0 = this.isMSIE && (ua.indexOf('MSIE 5.0') != -1);
	this.isMSIE7 = this.isMSIE && (ua.indexOf('MSIE 7') != -1);
	this.isGecko = ua.indexOf('Gecko') != -1; // Will also be true on Safari
	this.isSafari = ua.indexOf('Safari') != -1;
	this.isOpera = window['opera'] && opera.buildNumber ? true : false;
	this.isMac = ua.indexOf('Mac') != -1;
	this.isNS7 = ua.indexOf('Netscape/7') != -1;
	this.isNS71 = ua.indexOf('Netscape/7.1') != -1;
	// Fake MSIE on Opera and if Opera fakes IE, Gecko or Safari cancel those
	if (this.isOpera) {
		this.isMSIE = true;
		this.isGecko = false;
		this.isSafari =  false;
	}

	this.isIE = this.isMSIE;
	this.isRealIE = this.isMSIE && !this.isOpera;
}
//! definisco un oggetto per la classe _BrowserDetails
var USERbrowser = new _BrowserDetails();



//! restituisce l'handle all'elemento DOM indicato
/*! @param	nome	identificativo dell'oggetto
	@return			puntatore all'oggetto specificato, NULL altrimenti */
function getElement(nome)
{
	//NN6 ed Opera
	if (document.getElementById) return document.getElementById(nome);
	// IE
	else if (document.all) return document.all[nome];
	// NN4
	else if (document.layers) return document.layers[nome];
	// invalid browser
	else return null;
}



//! elimina un elemento dall'elenco DOM
/*! @param	n		nome dell'elemento da eliminare
	@return			{ TRUE | FALSE } esito dell'operazione */
function deleteElement(n)
{
	var nodo = getElement(n);
	if (nodo)
	{
		try { delete nodo.parentNode.removeChild(nodo); }
		catch(e) { return false; }
	}
	return true;
}




//! restituisce l'handle all'elemento FLASH indicato
/*! @param	nome	identificativo dell'oggetto FLASH
	@return			puntatore all'oggetto specificato, NULL altrimenti */
function getMovie(nome)
{
	if(document.embeds[nome]) return document.embeds[nome];
	if(window.document[nome]) return window.document[nome];
	if(window[nome]) return window[nome];
	if(document[nome]) return document[nome];
	
	return null;
}




/*********************************************************************************/
/*********************************************************************************/
/*********************************************************************************/
/***************************  GESTIONE POPUP  ************************************/
/*********************************************************************************/
/*********************************************************************************/
/*********************************************************************************/
/*********************************************************************************/
//! apre il popup del gioco
/*!
la funzione tenta di aprire la finestra popup in cui è contenuto il gioco.

@param	to		[OPZIONALE] pagina da caricare nel popup
@return			puntatore alla finestra, NULL in caso di errore

@note			se viene tornato NULL potrebbe essere attivo un blocco popup sul
				browser dell'utente.
*/
function popOpen()
{
	// verifico se è stato specificato un indirizzo
	var url = (arguments[0]) ? arguments[0] : '';
	
	var USERpopup = null;
	if (url!='')
	{
		USERpopup = window.open(	url,
									'ppstar',
									'directories=no,hotkeys=no,location=no,menubar=no,resizable=no,scrollbars=no,'+
									'status=no,toolbar=no,height=660,innerHeight=660,innerWidth=980,width=980'	);
	}
	
	return USERpopup;
}




/*********************************************************************************/
/*********************************************************************************/
/*********************************************************************************/
/***************************  GESTIONE TEMPO  ************************************/
/*********************************************************************************/
/*********************************************************************************/
/*********************************************************************************/
/*********************************************************************************/
//! ritorna il timestamp UNIX (alla data 01/01/1970) in millisecondi
/**
se viene passato un timestamp questo viene convertito in UNIX timestamp,
altrimenti viene tornato il timestamp NOW.
@param	t		[OPZIONALE] timestamp in formato stringa YYYYMMDDHHMMSS
@return			timestamp in millisecondi
*/
function msec()
{
	if (arguments.length==1)
	{
		arguments[0]+='';
		if (arguments[0]=='0') return 0;
		var t = new Date(	arguments[0].substr(0,4),
							arguments[0].substr(4,2),
							arguments[0].substr(6,2),
							arguments[0].substr(8,2),
							arguments[0].substr(10,2),
							arguments[0].substr(12) );
	}
	else var t = new Date();
	return t.getTime();
}



/*********************************************************************************/
//! verifica se la variabile indicata è valorizzata o meno
/*! @param	x		variabile da verificare
	@return			{ TRUE | FALSE } se la variabile è definita e non è vuota o nulla
					o pari a zero ritorna TRUE, FALSE altrimenti
*/
function empty(x)
{
	if (typeof(x)=="undefined") return true;
	else if (typeof(x)=="object")
	{
		try { if ( x.length === 0 ) return true; } catch(e) { /* NOP */ }
		return false;
	}
	else return ( x == "" || x == 0 || x == null || x === false );
}



/*********************************************************************************/
//! verifica la validità dell'indirizzo mail immesso
/** @param o	stringa sulla quale applicare il controllo
	@param n	[OPZIONALE] 0 specifica nessun alert, 1 mostra un avviso
	@return		TRUE in caso di controllo passato, FALSE altrimenti */
function checkMail(o) {
	if (checkMail.arguments.length==1) return checkMail(o,1);
	
	if (o!='')
	{
		var errore = false;
		var x = o.toLowerCase();
		var i;
		var espressione = /^[^@]{1,64}@[^@]{1,255}$/;
		// First, we check that there's one @ symbol, and that the lengths are right
		if (espressione.test(x))
		{
			// Split it into sections to make life easier
			var email_array = x.split('@');
			var local_array = email_array[0].split(".");
			// check user part
			espressione = /^([a-z0-9_~-]*[a-z0-9]+)$/;
			for (i = 0; i < local_array.length; i++)
			{
				if (!espressione.test(local_array[i]))
				{
					errore = true;
					break;
				}
			}

			// check domain part
			espressione = /^\[?[0-9\.]+\]?$/;
			if (!espressione.test(email_array[1]))
			{	// Check if domain is IP. If not, it should be valid domain name
				var domain_array = email_array[1].split(".");
				if (domain_array.length >= 2)
				{
					espressione = /^(([a-z0-9][a-z0-9-]{0,61}[a-z0-9])|([a-z0-9]+))$/;
					for (i = 0; i < domain_array.length; i++)
					{
						if (!espressione.test(domain_array[i]))
						{
							errore = true;
							break;
						}
					}
				}
				else errore = true;
			}
		}
		else errore = true;
		
		
		if (errore)
		{
			if (checkMail.arguments[1]) alert('Indirizzo e-mail non valido...');
			return false;
		}
	}
	
	return true;
}


/*********************************************************************************/
/*********************************************************************************/
/*********************************************************************************/
/********************************  AJAX  *****************************************/
/*********************************************************************************/
/*********************************************************************************/
/*********************************************************************************/

//! assegna l'oggetto XMLHttpRequest compatibile con i browsers
/*! @return	ritorna il puntatore all'oggetto AJAX */
function getXMLHttpRequest()
{
	// Mozilla, FireFox
	try { return new XMLHttpRequest(); } catch (e) {}
	// IE
	try{ return new ActiveXObject("MSXML3.XMLHTTP"); } catch(e){}
	try{ return new ActiveXObject("MSXML2.XMLHTTP.3.0"); }catch(e){}
	try{ return new ActiveXObject("Msxml2.XMLHTTP"); }catch(e){}
	try{ return new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){}
	
	return false;
}

//! restituisce il valore di un TAG XML specificato
/**
@param	obj			XML sorgente
@param	nomeNodo	nome del TAG
@return				stringa contenente il valore del nodo, NULL in caso di errore
*/
function getXMLValue(obj, nomeNodo)
{
	try {
		var t = obj.getElementsByTagName(nomeNodo).item(0);
		if(t.hasChildNodes()) return t.firstChild.nodeValue;
		else return null;
	}
	catch(e) { return null; }
}

/*********************************************************************************/
/*********************************************************************************/
/*********************************************************************************/
/*************************  controllo stringhe  **********************************/
/*********************************************************************************/
/*********************************************************************************/
/*********************************************************************************/
//! esegue la ripetizione della stringa indicata
/*
il metodo estende la classe String di sistema, quindi deve essere invocato direttamente
sull'oggetto (ad esempio t = "abc"; t.repeat(10);)
@param	n		numero di ripetizioni
@return			stringa di ingresso ripetuta n volte
*/
function str_repeat(n)
{
   var s = "", t = this.toString();
   while (--n >= 0) s += t;
   return s;
}
String.prototype.repeat = str_repeat;


//! esegue il trim della stringa
/*! @param	stringToTrim	stringa di partenza
	@return	stringa di ritorno senza spazi iniziali e finali */
function trim(stringToTrim)
{
	var t = ""+stringToTrim; // conversione in stringa
	return t.replace(/^\s+|\s+$/g,"");
}


//! esegue il ltrim della stringa
/*! @param	stringToTrim	stringa di partenza
	@return	stringa di ritorno senza spazi iniziali */
function ltrim(stringToTrim)
{
	var t = ""+stringToTrim; // conversione in stringa
	return t.replace(/^\s+/,"");
}


//! esegue il rtrim della stringa
/*! @param	stringToTrim	stringa di partenza
	@return	stringa di ritorno senza spazi finali */
function rtrim(stringToTrim)
{
	var t = ""+stringToTrim; // conversione in stringa
	return t.replace(/\s+$/,"");
}


//! converte le entità HTML in una stringa
/** (vedi documentazione PHP) */
function htmlspecialchars(string)
{
    // http://kevin.vanzonneveld.net
    // +   original by: Mirek Slugen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: htmlspecialchars("<a href='test'>Test</a>", 'ENT_QUOTES');
    // *     returns 1: '&lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;'
    var quote_style = (htmlspecialchars.arguments.length==2) ? htmlspecialchars.arguments[1] : 'ENT_COMPAT';
    
	var s = string+'';
    
    // Always encode
    s = s.replace(/&/g, '&amp;');
    s = s.replace(/</g, '&lt;');
    s = s.replace(/>/g, '&gt;');
    
    // Encode depending on quote_style
    if (quote_style == 'ENT_QUOTES') {
        s = s.replace(/"/g, '&quot;');
        s = s.replace(/'/g, '&#039;');
    } else if (quote_style != 'ENT_NOQUOTES') {
        // All other cases (ENT_COMPAT, default, but not ENT_NOQUOTES)
        s = s.replace(/"/g, '&quot;');
    }
    
    return s;
}


/*********************************************************************************/
/*********************************************************************************/
/*********************************************************************************/
/**********************  controllo valori numerici  ******************************/
/*********************************************************************************/
/*********************************************************************************/
/*********************************************************************************/
//! genera un numero casuale compreso nell'intervallo indicato
/**
@param	l		limite inferiore
@param	u		limite superiore
@return			numero casuale tra i limiti (compresi uguali)
*/
function rand(l,u)
{
	return Math.floor((Math.random() * (u-l+1))+l);
}


//! accetta l'inserimento esclusivamente di numeri
/** la funzione va invovata sull'evento onKeyDown="return onlyNumber(event)" */
function onlyNumber(e)
{
	var evt = e || window.event;
	var charCode = (evt.which) ? evt.which : evt.keyCode;
	
	if(	(charCode == 13 || charCode == 9) ||
	   	(charCode == 46 || charCode == 8) ||
		(charCode >= 37 && charCode <= 40) ||
		(charCode == 189 || charCode == 109) ||
		(charCode >= 96 && charCode <= 105) ||
		(charCode >= 48 && charCode <= 57) )
	return true;
	else return false;
}

function almenouno(idfrm,name)
{
	var frm = getElement(idfrm);
	var bool = false;
	
	for(var i=0; i < frm.elements.length; i++)
	{		
		if(frm.elements[i].name==name)
		{
			
			if(frm.elements[i].checked==true)
			{
				bool = true;
				break;
			}
		}
	}
	return bool;	
}
