
/*** Funzioni Trim LTrim e RTrim, see: http://www.somacon.com/p355.php ***/
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}


/* Setto la Combo con il valore passato */
function SetValueForCombo(idCombo, valore) {
	var _obj = document.getElementById(idCombo);

	for (var i = 0; i < _obj.options.length; i++) {
		//alert(_obj.options[i].value);	         	        
		if (_obj.options[i].value == valore)
			_obj.options[i].selected = true;
	}
}


function CheckPasswordLength(id) {

	if (id.value.length >= 16)
	{
		alert('Attenzione la password non può essere più lunga di 16 caratteri');
		id.value = '';
		return false;
	}

}

function CopiaTesto(id) {
	var tempval = document.getElementById(id);   //eval("document." + theField);
	tempval.focus();
	tempval.select();
	therange = tempval.createTextRange();
	therange.execCommand("Copy");
}


function reloadCaptcha() {
	var rand = (Math.round((Math.random()*10000)+1));
	//alert(rand);
	document.getElementById("imgCaptcha").src = '/captcha.php?' + rand;
}


function CheckIDAdsense() {
	setTimeout("reallyCheckIDAdsense();", 20);
}


function reallyCheckIDAdsense() {
	obj = document.getElementById("cod_adsense");	
	if (obj == null)
		return;
	
	//alert(obj.value);

	var re = /[0123456789]+/;
	var m = re.exec(obj.value);
	
	if (obj.value.trim().length > 0)
	{
		if (m != null) {			
			var t = 'pub-' + m[0];

			if (t.length != obj.value.trim().length)
			{
				//alert(t.length);
				document.getElementById('sp_adsense').style.display = 'block';
				document.getElementById('label_adsense').style.color = 'red';
				return;
			}
			else {
				if (obj.value.trim().length != 20)
				{					
					//alert(obj.value.trim().length);
					document.getElementById('sp_adsense').style.display = 'block';
					document.getElementById('label_adsense').style.color = 'red';
					return;				
				}
				else {
					document.getElementById('sp_adsense').style.display = 'none';
					document.getElementById('label_adsense').style.color = '#17ab10';
					return;									
				}
			}
		}
		else {
			//alert(obj.value.trim().length);
			document.getElementById('sp_adsense').style.display = 'block';
			document.getElementById('label_adsense').style.color = 'red';
			return;
		}
	}
	else {
		//alert(obj.value.trim().length);
		document.getElementById('sp_adsense').style.display = 'none';
		document.getElementById('label_adsense').style.color = 'red';
		return;
	}
}


function CheckIDAnalytics() {
	obj = document.getElementById("cod_analytics");	
	if (obj == null)
		return;

	//alert(obj.value);
	var re = /^UA-\d+-\d+$/;		//RegEx per controllare il formato dell'ID Analytics 
	if (obj.value.trim().length == 0)	//Non ha inserito niente, va bene non è obbligatorio
	{
		document.getElementById('sp_analytics').style.display = 'none';
		document.getElementById('label_analytics').style.color = 'grey';
		return true;
	}
	if (!re.test(obj.value.trim()))
	{
		//alert('Attenzione, codice ID Analytics non valido.');
		document.getElementById('sp_analytics').style.display = 'block';
		document.getElementById('label_analytics').style.color = 'red';
		return false;
	}
	if (re.test(obj.value.trim()) && (obj.value.trim().length != 0))
	{
		//alert('OK');	// Tutto OK
		document.getElementById('sp_analytics').style.display = 'none';
		document.getElementById('label_analytics').style.color = 'green';
		return true;									
	}
	re.exec(obj.value);
}

function SelectLink1(e) {		
	try
	{
		document.getElementById('mv1').className = '';
		document.getElementById('mv2').className = '';
		document.getElementById('mv3').className = '';
		document.getElementById('mv4').className = '';
		e.className = 'selezionato';		
	}
	catch (Ex)
	{
		// nothing to do
	}
}


function SelectLink2(e) {		
	try
	{
		document.getElementById('mt1').className = '';
		document.getElementById('mt2').className = '';
		document.getElementById('mt3').className = '';
		document.getElementById('mt4').className = '';
		e.className = 'selezionato';		
	}
	catch (Ex)
	{
		// nothing to do
	}
}


function SelectLink3(e) {		
	try
	{
		document.getElementById('tp1').className = '';
		document.getElementById('tp2').className = '';
		document.getElementById('tp3').className = '';
		document.getElementById('tp4').className = '';
		e.className = 'selezionato';		
	}
	catch (Ex)
	{
		// nothing to do
	}

}


function GetCommentoById(id_commento) {

	InitXMLDOC("ROOT","GetComment");
	AddNodeToXML('id_commento', id_commento);

	//alert(XMLDOC.xml);
	RequestHTTP(XMLDOC,'/remote_functions.php');

	if (HTTP_RESPONSE) {
		//alert(HTTPReq.responseText);		
		//eval(HTTPReq.responseText);
		//alert(id_commento);
		var tmp = HTTPReq.responseText;
		var RetArray = tmp.split('--###--');

		document.getElementById('update_comment').innerHTML = 'Modifica il Commento';	
		document.getElementById('annulla_modifica').style.visibility = 'visible';	
		
		//document.getElementById('user_comment').innerHTML = RetArray[0];	//innerHTML perchè è un <a>  
		document.getElementById('user_comment').style.display = 'none';
		document.getElementById('lbl_user_comment').innerHTML = RetArray[0];		
		document.getElementById('lbl_user_comment').style.display = 'inline';
		
		document.getElementById('commento').value = RetArray[1];			//value perchè è una <textarea>
		document.getElementById('id_commento').value = id_commento;
	}
	else  {
		alert('si è verificato un errore');
		alert(HTTPReq.responseText);	
	}	
}


function AnnullaModificaCommento() {
	document.getElementById('update_comment').innerHTML = 'Inserisci un Commento';	
	document.getElementById('annulla_modifica').style.visibility = 'hidden';	
	
	//document.getElementById('user_comment').innerHTML = RetArray[0];	//innerHTML perchè è un <a>  
	//document.getElementById('user_comment').style.display = 'none';
	//document.getElementById('lbl_user_comment').innerHTML = RetArray[0];		
	//document.getElementById('lbl_user_comment').style.display = 'inline';
	
	document.getElementById('commento').value = '';		
	document.getElementById('id_commento').disabled = true;
	document.getElementById('lbl_user_comment').innerHTML = UserName;		
	document.getElementById('lbl_user_comment').style.display = 'inline';

	//document.getElementById('id_articolo').value = null;
}


function DeleteComment(id_commento) {

	if (!confirm("Sei sicuro di voler cancellare questo commento?\nNon sarà più possibile recuperarlo."))
	{
		return;
	} 

	InitXMLDOC("ROOT","DeleteComment");
	AddNodeToXML('id_commento', id_commento);

	//alert(XMLDOC.xml);
	RequestHTTP(XMLDOC,'/remote_functions.php');

	if (HTTP_RESPONSE) {
		//alert(HTTPReq.responseText);	
		if (HTTPReq.responseText == 'OK')
		{
			//alert('Commento Cancellato con successo.');
			window.location.reload();
		}
	}
	else  {
		alert('si è verificato un errore');
		alert(HTTPReq.responseText);	
	}	
}


function SetNotificationComment(id_articolo) {
		
	//alert(document.getElementById("chk_email_notification").checked);
	//alert(id_articolo);

	var Notifica = document.getElementById("chk_email_notification").checked ? 'Y' : 'N';

	InitXMLDOC("ROOT","CommentNotification");
	AddNodeToXML('id_articolo', id_articolo);
	AddNodeToXML('notifica', Notifica);

	//alert(XMLDOC.xml);

	RequestHTTP(XMLDOC,'/remote_functions.php');

	if (HTTP_RESPONSE) {
		//alert(HTTPReq.responseText);	
		if (HTTPReq.responseText == 'OK')
		{
			if (Notifica == 'Y')
			{
				alert('D\'ora in avanti ti verrà inviata una email di notifica\nogni volta che un commento verrà registrato.');
			}
			else
			{
				alert('D\'ora in avanti NON ti verrà inviata una email di notifica\nogni volta che un commento verrà registrato.');			
			}
		}
	}
	else  {
		alert('si è verificato un errore');
		alert(HTTPReq.responseText);	
	}	
}


/*** Chiamata Asincrona Ajax per recuperare gli articoli più visitate, più votati e top users ***/
function GetArticlesAsync(tipo, categoria, periodo) {
	
	InitXMLDOC("ROOT","GetArticles");
	AddNodeToXML('tipo', tipo);
	AddNodeToXML('categoria', categoria);
	AddNodeToXML('periodo', periodo);
	
	//Bug Fix - 13/01/2012 se non esiste un div (esempio 'topusers') esco
	if (document.getElementById(tipo) == null)
	{
		return;
	}

	// Loading.gif
	document.getElementById(tipo).innerHTML = '<center><img src="/images/loading.gif" class="nodef"></center>';	
	
	//funzione anonima di Callback
	var f = function() { 	
		if (HTTPReq && HTTPReq.readyState == 4) {
			if (HTTPReq.status == 200) {
				//alert(tipo);
				document.getElementById(tipo).innerHTML = HTTPReq.responseText;
			}
			else {
				alert(HTTPReq.statusText);		
			}
		}	
	}
	AsyncRequestHTTP(XMLDOC, '/ajaxgetarticles.php', f);
}



/*** Chiamata Sincrona Ajax per recuperare gli articoli più visitate e più votati ***/
function GetArticles(tipo, categoria, periodo) {
	
	InitXMLDOC("ROOT","GetArticles");
	AddNodeToXML('tipo', tipo);
	AddNodeToXML('categoria', categoria);
	AddNodeToXML('periodo', periodo);
	
	//Bug Fix - 24/01/2012 se non esiste un div (esempio 'topusers') esco
	if (document.getElementById(tipo) == null)
	{
		return;
	}

	// Loading.gif
	document.getElementById(tipo).innerHTML = '<center><img src="/images/loading.gif" class="nodef"></center>';	

	//alert(XMLDOC.xml);
	RequestHTTP(XMLDOC,'/ajaxgetarticles.php');

	if (HTTP_RESPONSE) {
		//alert(HTTPReq.responseText);	
		var Risultato = null;		
		document.getElementById(tipo).innerHTML = HTTPReq.responseText;
	}
	else  {
		alert('si è verificato un errore');
		alert(HTTPReq.responseText);	
	}
}


function deleteAvatar() {

	InitXMLDOC("ROOT","DeleteAvatar");
	
	//alert(XMLDOC.xml);
	RequestHTTP(XMLDOC,'/deleteavatar.php');

	if (HTTP_RESPONSE) {
		//alert(HTTPReq.responseText);
		if (HTTPReq.responseText == 'OK')
		{
			reloadAvatar();
			HideDeleteAvatar();
		}
	}
	else  {
		alert('si è verificato un errore');
		alert(HTTPReq.responseText);	
	}
}

function HighLight(v) {
	
	//reset
	for (var i=1;i<=5;i++ ) {
		document.getElementById('V'+i).style.fontWeight  = 'normal';
		document.getElementById('V'+i).style.color  = '#646464';	
	}
	
	//set bold
	document.getElementById(v).style.fontWeight  = 'bold';
	document.getElementById(v).style.color  = '#d27514';	
}


function get_radio_value() {
 var rad_val = null;
	for (var i=0; i < document.FormVoto.votazione.length; i++) {
	   if (document.FormVoto.votazione[i].checked) {
		  rad_val = document.FormVoto.votazione[i].value;
	   }
	}
 return rad_val;
}


function SaveVote(id_articolo, voto) {	
	//alert(id_articolo + ' ' + get_radio_value());
	//if (get_radio_value() == null)
	//	return;


	InitXMLDOC("ROOT","SaveVote");
	AddNodeToXML('voto', voto);
	AddNodeToXML('id_articolo', id_articolo);

	
	//alert(XMLDOC.xml);	//questo funziona solo su IE
	RequestHTTP(XMLDOC,'/savevote.php');

	if (HTTP_RESPONSE) {
		//alert(HTTPReq.responseText);	
		var Risultato = null;
		var XMLDOM = getDOMfromString(_serializeXML(HTTPReq.responseXML));
		//var _ver = XMLDOM.documentElement.firstChild.firstChild;
		
		if (XMLDOM.getElementsByTagName('RISULTATO')[0] != null)  {
			Risultato = XMLDOM.getElementsByTagName('RISULTATO')[0];

			if (Risultato.firstChild.nodeValue == 'OK') {
				//document.getElementById('TableVoto').style.visibility = 'hidden';
				return true;
			}
			else {
				return false; 
			}
				
		}        
		else {
			Risultato = XMLDOM.getElementsByTagName('ERRORE')[0];
			alert(Risultato.firstChild.nodeValue);
			//return "Error";
			return '';									
		}        
		//alert(HTTPReq.responseText);
	}
	else  {
		alert('si è verificato un errore');
		alert(HTTPReq.responseText);	
	}
}



function CheckTagScript(testo) {
	
		var re = /&lt;script\b[^>]*&gt;(.*?)&lt;\/script&gt;/i;
		if (re.exec(testo))
			return false;
		else
			return true;
	}

function CheckTagScript2(testo) {

	var re = /<script\b[^>]*>(.*?)<\/script>/i;
	if (re.exec(testo))
		return false;
	else
		return true;
}

function CheckCaptcha()  {
	
	InitXMLDOC("ROOT","CheckCaptcha");
	AddNodeToXML('captcha', document.getElementById('codcap').value);
	
	//alert(XMLDOC.xml);
	RequestHTTP(XMLDOC,'/checkcaptcha.php');

	if (HTTP_RESPONSE) {
		//alert(HTTPReq.responseText);	
		var Risultato = null;
		var XMLDOM = getDOMfromString(_serializeXML(HTTPReq.responseXML));
		//var _ver = XMLDOM.documentElement.firstChild.firstChild;
		
		if (XMLDOM.getElementsByTagName('RISULTATO')[0] != null)  {
			Risultato = XMLDOM.getElementsByTagName('RISULTATO')[0];

			if (Risultato.firstChild.nodeValue == 'OK')
				return true;
			else {
				return false; 
			}
				
		}        
		else {
			Risultato = XMLDOM.getElementsByTagName('ERRORE')[0];
			alert(Risultato.firstChild.nodeValue);
			//return "Error";
			return '';									
		}        
		//alert(HTTPReq.responseText);
	}
	else  {
		alert('si è verificato un errore');
		alert(HTTPReq.responseText);	
	}
}

function CheckUserByEmail() {

	InitXMLDOC("ROOT","CheckUserByEmail");
	//alert(document.getElementById('user_email').value);
	AddNodeToXML('email', document.getElementById('user_email').value);
	
	//alert(XMLDOC.xml);
	RequestHTTP(XMLDOC,'/checkuseremail.php');

	if (HTTP_RESPONSE) {
		//alert(HTTPReq.responseText);	
		var Risultato = null;
		var XMLDOM = getDOMfromString(_serializeXML(HTTPReq.responseXML));
		//var _ver = XMLDOM.documentElement.firstChild.firstChild;
		
		if (XMLDOM.getElementsByTagName('RISULTATO')[0] != null)  {
			Risultato = XMLDOM.getElementsByTagName('RISULTATO')[0];

			if (Risultato.firstChild.nodeValue == 'NO') {
				document.getElementById('sp_email').style.display = 'block';
				document.getElementById('sp_email').focus();
				return false;
			}
			else {
				document.getElementById('sp_email').style.display = 'none';
				return true;				
			}
				
		}        
		else {
			Risultato = XMLDOM.getElementsByTagName('ERRORE')[0];
			alert(Risultato.firstChild.nodeValue);
			//return "Error";
			return '';									
		}        
		//alert(HTTPReq.responseText);
	}
	else  {
		alert('si è verificato un errore');
		alert(HTTPReq.responseText);	
	}
}


function VerifyComment(oForm, szCap) {
	
	if (!checkForm2(oForm, true))
	{
		return false;
	}

	if (szCap == 'true')
	{
		if (!CheckCaptcha())
		{
			alert('Attenzione, il codice di controllo inserito non è corretto');
			reloadCaptcha();
			return false;
		}
	}
	
	//Se tutto OK
	return true;
}


function VerifyLogin() {
	var obj = new C_UTIL_CLASS();
	var u = document.getElementById('user_login').value.trim();
	var p = document.getElementById('pass1').value.trim();
	
	if (obj.isBlank(u) || obj.isBlank(p)) {
		alert("Attenzione compilare tutti i campi obbligatori.");
		document.getElementById('user_login').focus();
		return false;
	}
}

function checkChangePassword(oForm) {
	
	if (!checkForm2(oForm, true))
	{
		return false;
	}

	return true;
}

function checkLostPasswordForm(oForm) {
	
	if (!checkForm(oForm))
	{
		return false;
	}

	if (!CheckCaptcha())
	{
		alert('Attenzione, il codice di controllo inserito non è corretto');
		return false;
	}

	//Controllo che esista la mail in Tabella
	InitXMLDOC("ROOT","CheckUserByEmail");
	AddNodeToXML('email', document.getElementById('user_email').value);	
	RequestHTTP(XMLDOC,'/checkuseremail.php');

	if (HTTP_RESPONSE) {
		//alert(HTTPReq.responseText);	
		var Risultato = null;
		var XMLDOM = getDOMfromString(_serializeXML(HTTPReq.responseXML));
		
		if (XMLDOM.getElementsByTagName('RISULTATO')[0] != null)  
		{
			Risultato = XMLDOM.getElementsByTagName('RISULTATO')[0];
			if (Risultato.firstChild.nodeValue == 'OK') {
				//alert('Attenzione l\'email inserita non è presente in archivio.');
				document.getElementById('msg_emaillost').style.display = 'block';
				return false;
			}				
		}        
	}
	else  {
		alert('si è verificato un errore');
		alert(HTTPReq.responseText);
		return false;
	}

	return true;
}


function CheckMainForm(oForm, IsProfile)  {
	
	/*
	if (IsProfile && document.getElementById('pass1').value.length > 0) {
		document.getElementById('pass2').setAttribute('inputfield', 'password');
	}
	else {
		document.getElementById('pass2').setAttribute('inputfield', 'text');
	}
	*/

	// se referrer valorizzato controllo formale
	if (document.getElementById('user_referrer').value.length > 0) {
		if (document.getElementById('user_login').value.trim() == document.getElementById('user_referrer').value.trim())
		{
			alert('Attenzione, il nome di chi ti ha invitato non può coincidere con il tuo Username');
			return;
		}
		
		//Controllo che il referrer sia un nome presente nel DB
		
		if (!CheckUserNameInDB(document.getElementById('user_referrer').value.trim()))
		{
			if (document.getElementById('sp_user_referrer'))
			{
				document.getElementById('sp_user_referrer').style.display = 'block';
				document.getElementById('sp_user_referrer').focus();
			}
			else {
				alert("Attenzione, il nome di chi ti ha invitato non esiste");
			}
			return;
		} 
		else 
		{
			if (document.getElementById('sp_user_referrer'))
			{
				document.getElementById('sp_user_referrer').style.display = 'none';
			}
		}
		document.getElementById('user_referrer').setAttribute('inputfield', 'username');	

	} else {
		document.getElementById('user_referrer').setAttribute('inputfield', 'text');		
	}

	
	if (!checkForm(oForm))
	{
		return;
	}

	if (!IsProfile) {	//se profilo non c'è il captcha
		if (!CheckCaptcha())
		{
			alert('Attenzione, il codice di controllo inserito non è corretto');
			return;
		}
	}

	
	InitXMLDOC("ROOT","CheckUserName");
	AddNodeToXML('username', document.getElementById('user_login').value);
	
	//alert(XMLDOC.xml);
	RequestHTTP(XMLDOC,'/checkusername.php');

	if (HTTP_RESPONSE) {
		//alert(HTTPReq.responseText);	
		var Risultato = null;
		var XMLDOM = getDOMfromString(_serializeXML(HTTPReq.responseXML));
		//var _ver = XMLDOM.documentElement.firstChild.firstChild;
		
		if (XMLDOM.getElementsByTagName('RISULTATO')[0] != null)  {
			Risultato = XMLDOM.getElementsByTagName('RISULTATO')[0];

			if (Risultato.firstChild.nodeValue == 'NO') {
				document.getElementById('sp_username').style.display = 'block';
				document.getElementById('sp_username').focus();
				return;
			} else {
				document.getElementById('sp_username').style.display = 'none';
			}				

		}        
		else {
			Risultato = XMLDOM.getElementsByTagName('ERRORE')[0];
			alert(Risultato.firstChild.nodeValue);
			//return "Error";
			return '';									
		}        
		//alert(HTTPReq.responseText);
	}
	else  {
		alert('si è verificato un errore');
		alert(HTTPReq.responseText);	
	}

	if (!CheckUserByEmail())
	{
		return;
	}

	//Controllo email conferma = email
	if (!IsProfile) {
		if (document.getElementById('user_email').value != document.getElementById('repeat_email').value)
		{
			alert('Attenzione, l\'email di conferma non coincide con l\'email');
			return;
		}
	}

	if (IsProfile) {				
		var ads = document.getElementById('cod_adsense').value;
		var re = /[0123456789]+/;
		var m = re.exec(ads);
		
		if (ads.trim().length > 0)
		{
			if (m != null) {			
				var t = 'pub-' + m[0];

				if (t.length != 20)
				{
					document.getElementById('sp_adsense').style.display = 'block';
					return;
				}
			}
			else {
				document.getElementById('sp_adsense').style.display = 'block';
				return;
			}
		}

		//Controllo codice ID Analytics
		if(!CheckIDAnalytics())
			return;

	}

	// se tutto OK abilito il campo email e submit
	document.getElementById('user_email').disabled = false;
	oForm.submit();				
}


function CheckUserNameInDB(username) {
	
	InitXMLDOC("ROOT","CheckUserName");
	AddNodeToXML('username', username);
	
	//alert(XMLDOC.xml);
	RequestHTTP(XMLDOC,'/checkusername.php');

	if (HTTP_RESPONSE) {
		//alert(HTTPReq.responseText);	
		var Risultato = null;
		var XMLDOM = getDOMfromString(_serializeXML(HTTPReq.responseXML));
		//var _ver = XMLDOM.documentElement.firstChild.firstChild;
		
		if (XMLDOM.getElementsByTagName('RISULTATO')[0] != null)  {
			Risultato = XMLDOM.getElementsByTagName('RISULTATO')[0];

			if (Risultato.firstChild.nodeValue == 'OK') 		//username non trovata
				return false;
			else
				return true;						
		}        
		else {
			Risultato = XMLDOM.getElementsByTagName('ERRORE')[0];
			alert(Risultato.firstChild.nodeValue);
			//return "Error";
			return '';									
		}        
		//alert(HTTPReq.responseText);
	}
	else  {
		alert('si è verificato un errore');
		alert(HTTPReq.responseText);	
	}
}


function ShowEsitoOperazione(Esito) {
    if (Esito == '1')
        alert(WBX_MSG_ESITO_OPERAZIONE[0]);
}

function sendForm(objForm) {

    var objValidator = new C_UTIL_CLASS;    
        
    if (objValidator.CheckForm(objForm, false))
		objForm.submit();
}

function checkForm(objForm) {

    var objValidator = new C_UTIL_CLASS;        
    return (objValidator.CheckForm(objForm, false));
}

function checkForm2(objForm, bln) {

    var objValidator = new C_UTIL_CLASS;        
    return (objValidator.CheckForm(objForm, bln));
}

function CheckBlankInString(s)  {
	var re = /\s/;         //Match any single space character. Equivalent to [ \t\r\n\v\f].
	return !re.test(s);
}

// DEFINISCO UNA CLASSE VUOTA 
function C_UTIL_CLASS() {

	//AGGIUNGO I METODI ALLA CLASSE
	//Stringa vuota 	
	this.isBlank = function(s)  {
		var isBlank_re = /\S/;
		return !(String (s).search (isBlank_re) != -1);
	}

    //Check if string is a whole number (digits only)
	this.soloNumeriInteri = function(s) {
	   var isWhole_re = /^\s*\d+\s*$/;	   
       return String(s).search (isWhole_re) != -1;
    }
	
    //Valid Number
    //A valid number value should contain only an optional minus sign, followed by digits, followed by an optional dot (.) to signal decimals, and if it's present, additional digits. 
	this.onlyNumbers = function(s) {
	   var isWhole_re = /(^-*\d+$)|(^-*\d+\.\d+$)/;	   
       return String(s).search (isWhole_re) != -1;
    }
        
	
	//Data in formato dd/mm/yyyy oppure dd-mm-yyyy (formato Italiano)
	this.CheckEuroDate = function(szDate)  {
		 var regex = /^(?:(?:0?[1-9]|1\d|2[0-8])(\/|-)(?:0?[1-9]|1[0-2]))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(?:(?:31(\/|-)(?:0?[13578]|1[02]))|(?:(?:29|30)(\/|-)(?:0?[1,3-9]|1[0-2])))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(29(\/|-)0?2)(\/|-)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]|[2468][048]|[13579][26]))$/  			
		 //alert(regex.test(data_avviso));

		 if (regex.test(szDate))	 
			 return true;
		 else
			 return false;
	}
    
    //Importo in euro (punto come separatore dei centesimi)
    this.CheckEuroCurrency = function(cImp) {
		 var regex =  /^\s*-?((\d{1,3}(\.(\d){3})*)|\d*)(,\d{1,2})?\s?(\u20AC)?\s*$/; 			
		 //alert(regex.test(cImp));

	     if (regex.test(cImp))	 
		     return true;
	     else
		     return false;
	}
    
    //Controllo email
	this.CheckEmail = function(szEmail)	{	
		var regex = /^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$/
		if (regex.test(szEmail))
			return true
		else
			return false
	}

	//Controllo campi password e conferma password
	this.CheckPassword = function(p1, p2) {
		if (p1 != p2) {
			return false;
		}
		else {
			return true;
		}
	}

	//Controllo campi password e conferma password
	this.CheckLengthPassword = function(p1) {
		if (p1.length < 8) {
			return false;
		}
		else {
			return true;
		}
	}
	
	//Controllo campo login(username): tutti i caratteri alphanumerici + numerici e carattere _
	this.CheckUserName = function(s) {
		var regex =/^([a-zA-Z0-9_-]+)$/; 
		if (regex.test(s))
			return true
		else
			return false
	}

	//Controllo campo Nome(username): tutti i caratteri alphanumerici + numerici e carattere _ e anche lo spazio
	this.CheckNameWithSpace = function(s) {
		var regex =/^([\sa-zA-Z0-9_-]+)$/; 
		if (regex.test(s))
			return true
		else
			return false
	}	

	this.isIE = function()	{
		return (navigator.appName.toLowerCase().indexOf("explorer") != -1) ? true : false;
	}

	this.isFF = function()	{
		return (navigator.appName.toLowerCase().indexOf("explorer") != -1) ? false: true;
	}
	
	
	//Funzione di controllo del Form: CheckForm
	this.CheckForm = function CheckForm(ObjForm, blnSummary) {
	    
	    var _szSummary = "";

		//ciclo su ogni elemento del form
		for(var i = 0; i < ObjForm.elements.length; i++) {
				var _obj = ObjForm.elements[i];

				//alert("Nome del campo: " + ObjForm.elements[i].name + " and its value is: " + ObjForm.elements[i].value);
												    								
				//controllo se campi obbligatori valorizzati
				if (_obj.getAttribute('mandatory') == 'yes') {
					if (this.isBlank(_obj.value)) {
						alert("Attenzione compilare tutti i campi obbligatori.");
						_obj.focus();
						return false;
					}
					//se una checkbox obbligatoria devo verificare che sia checked
					if (_obj.getAttribute('type') == 'checkbox' && _obj.checked == false) {
						alert("Attenzione è obbligatorio selezionare la checkbox.");
						return false;					
					}
				}
				
				//controllo input utente
				switch (_obj.getAttribute('inputfield'))
				{
					case 'email':
						if (!this.isBlank(_obj.value) && !this.CheckEmail(_obj.value)) {
							if (blnSummary)  {
								alert('Valore non corretto per il campo: ' + _obj.getAttribute('label') + ' Valore: ' + _obj.value + '\n'); 
								_obj.focus();
								return false;
							}
							else  {
								_szSummary += 'Campo email non corretto.\n';
							}						    	    							    
						}
						break;
						
					case 'number':					    		
						if (!this.isBlank(_obj.value) && !this.onlyNumbers(_obj.value)) {
							if (blnSummary) {
								alert('Valore non corretto per il campo: ' + _obj.getAttribute('label') + ' Valore: ' + _obj.value + '\n');
								 _obj.focus();
								return false;
							}
							else {
								_szSummary += 'Valore non corretto per il campo: ' + _obj.getAttribute('label') + ' Valore: ' + _obj.value + '\n';
							
							}
						}
						break;

					case 'integer':
						if (!this.isBlank(_obj.value) && !this.soloNumeriInteri(_obj.value)) {
							if (blnSummary) {
								alert('Valore non corretto per il campo: ' + _obj.getAttribute('label') + ' Valore: ' + _obj.value + '\n');
								_obj.focus();
								return false;
							}
							else {
								_szSummary += 'Valore non corretto per il campo: ' + _obj.getAttribute('label') + ' Valore: ' + _obj.value + '\n';

							}
						}
						break;
						
					case 'euro':
						if (!this.CheckEuroCurrency(_obj.value))  {
							if (blnSummary) {
								alert('Valore non corretto per il campo: ' + _obj.getAttribute('label') + ' Valore: ' + _obj.value + '\n');
								 _obj.focus();
								return false;
							}    
							else  {
								_szSummary += 'Valore non corretto per il campo: ' + _obj.getAttribute('label') + ' Valore: ' + _obj.value + '\n';
							}
						}					
						break;
						
					case 'text':						
						//nessun controllo
						break;
						
					case 'date':					    
						if (!this.isBlank(_obj.value) && !this.CheckEuroDate(_obj.value)) {
							if (blnSummary) {
								alert('Valore non corretto per il campo: ' + _obj.getAttribute('label') + ' Valore: ' + _obj.value + '\n');
								_obj.focus();
								return false;
							}    
							else {
								_szSummary += 'Valore non corretto per il campo: ' + _obj.getAttribute('label') + ' Valore: ' + _obj.value + '\n';

							}							
						}
						break;
					
					case 'textarea':
						if (_obj.getAttribute('maxlength')) {
							if (_obj.value.length >= parseInt(_obj.getAttribute('maxlength'))) {
								if (blnSummary) {
									alert('Il testo non può superare i ' + _obj.getAttribute('maxlength').toString() + ' caratteri');
									_obj.focus();
									return false;
								}    
								else  {
									_szSummary += 'Il testo non può superare i ' + _obj.getAttribute('maxlength').toString() + ' caratteri\n';
								}							    
							}
						}
						break;

					case 'password':
						if (!this.CheckPassword(ObjForm['pass1'].value,ObjForm['pass2'].value))
						{
							if (blnSummary) {
								alert('La password di conferma deve coincidere con la password');
									_obj.focus();
									return false;
							}    
							else  {
									_szSummary += 'La password di conferma deve coincidere con la password\n';
							}							    
						}

						if (!this.CheckLengthPassword(ObjForm['pass1'].value))
						{
							if (blnSummary) {
								alert('La password deve essere almeno di 8 caratteri');
									_obj.focus();
									return false;
							}    
							else  {
									_szSummary += 'La password deve essere almeno di 8 caratteri\n';
							}							    
						}
						break;

					case 'username':
						if (!this.CheckUserName(_obj.value))
						{
							if (blnSummary) {
								alert('I campi Username e Referrer possono contenere solo lettere, numeri e il segno unsderscore _ ma nessuno spazio\n');
									_obj.focus();
									return false;
							}    
							else  {
									_szSummary += 'I campi Username e Referrer possono contenere solo lettere, numeri e il segno unsderscore _ ma nessuno spazio\n';
							}							    
						}

						break;

					case 'nome':
						if (!this.CheckNameWithSpace(_obj.value))
						{
							if (blnSummary) {
								alert('Attenzione: caratteri non permessi nel campo nome\n');
									_obj.focus();
									return false;
							}    
							else  {
									_szSummary += 'Attenzione: caratteri non permessi nel campo nome\n';
							}							    
						}

						break;

					default:
						break;
				}   //end switch		
		    }   //end for
            //Tutto OK, submit del form
		    
		if (_szSummary == '')  {		
		    return true;
		}
		else  {
		    alert("Attenzione, correggere i seguenti problemi:\n\n" + _szSummary);
		    _szSummary = '';
		    return false;
	    }
	}
}


