
var websiteUrl = '';

function createXHR()
{
	var request = false;
	try
	{
		request = new ActiveXObject('Msxml2.XMLHTTP');
	}
	catch (err2)
	{
		try
		{
			request = new ActiveXObject('Microsoft.XMLHTTP');
		}
		catch (err3)
		{
			try
			{
				request = new XMLHttpRequest();
			}
			catch (err1) 
			{
				request = false;
			}
		}
	}
	return request;
}

function loadHTML(url, storage, jsAfterOpen)
{
	set_alfaDiv(storage);
	storage = document.getElementById(storage);
	var xhr = createXHR();
	xhr.onreadystatechange=function()
	{ 
		if(xhr.readyState == 4)
		{
			if(xhr.status == 200)
			{
				if (storage)
				{
					unset_alfaDiv(storage);
					storage.innerHTML = xhr.responseText;

					if (jsAfterOpen)
					{
						try
						{
							eval(jsAfterOpen);
						}
						catch (e)
						{
							if (e instanceof Error)
							{
								BugTRACK_info(e, jsAfterOpen);
							}
						}
					}
				}
				else
				{
					alert(xhr.responseText);
				}
			}
			else
			{
				alert('Si è verificato un problema tecnico di connessione.\nSe il problema persiste, contattare il webmaster.\n\nurl: ['+url+']');
			}
		}
	};
	xhr.open("GET", url , true);
	xhr.send(null);
}

function divSpinnerRefill(storage, htmlLabel)
{
	obj = document.getElementById(storage);
	if (obj)
	{
		obj.innerHTML = '<div class="zloadHTML_spinner">'+htmlLabel+'</div>';
		obj.style.display = 'block';
	}
}

function divSpinnerAdd(storage, style, label)
{
	obj = document.getElementById(storage);
	if (obj)
	{
		obj.innerHTML += '<div class="zloadHTML_spinner" style="'+style+'">'+label+'</div>';
		obj.style.display = 'block';
	}
}

function loadHTML_spinner(url, storage)
{
	divSpinnerRefill(storage, 'caricamento in corso...');
	return loadHTML(url, storage, jsAfterOpen='');
}

function sendForm_execJs(formId)
{
	url = $(formId).action + '?' + $(formId).serialize();
	loadHTML_execJs(url);
}

function loadHTML_execJs(url, callerDiv)
{
	var xhr = createXHR();
	xhr.callerDiv = callerDiv;

	xhr.onreadystatechange=function()
	{
		if(xhr.readyState == 4)
		{
			if(xhr.status == 200 || xhr.status == 0)
			{
				try
				{
					eval(xhr.responseText);
				}
				catch (e)
				{
					if (e instanceof Error)
					{
						BugTRACK_info(e, xhr.responseText);
					}
				}
			}
			else
			{
				alert('Attenzione, si è verificato un errore nel caricamento della pagina richiesta.\nPotrebbe essere dovuto ad un problema momentaneo della linea, oppure ad un effettivo errore del server.\n\nSe il problema persiste, contattare il webmaster.\n\nIndirizzo pagina:\n '+url+'\nStatus Error code: '+xhr.status+'\n\n'+xhr.responseText);
			}
		}
	}
	xhr.open("GET", url , true);
	xhr.send(null);
}

function BugTRACK_info(error, responseText)
{
	alert('Si è verificato un errore. ['+error+']\n\nPagina momentaneamente non disponibile.');
	alert(responseText);
}

function BlockScreen_custom(divName, abilita, altMessage, color, alfaDec)
{
	TheBox = document.getElementById(divName);
	if (TheBox)
	{
		if (abilita)
		{
			TheBox.style.position	= "fixed";
			TheBox.style.top		= "0px";
			TheBox.style.right		= "0px";
			TheBox.style.width		= "100%";
			TheBox.style.height		= '100%';
			TheBox.style.opacity	= "."+alfaDec;
			TheBox.style.filter		= "alpha(opacity="+(alfaDec*10)+")";
			TheBox.style.background	= color;
			TheBox.style.display	= "block";
			TheBox.title			= altMessage;
		} else {
			TheBox.style.display	= "none";
		}
	}
}


function setFocusToObjId(idObject)
{
	var obj = document.getElementById(idObject);
	if (obj)
	{
		obj.focus();
	}
}

function displayBox(idName, value)
{
	obj = document.getElementById(idName);
	if (obj)
	{
		if (value == 'switch')
		{
			obj.style.display = (obj.style.display == 'none' ? 'block' : 'none');
		}
		else 
		{
			obj.style.display = (value == true ? 'block' : 'none');
		}
	}
}

function redirectCountdown(idName, seconds, url)
{
	if (seconds <= 0)
	{
		document.location = url;
	}
	else
	{
		seconds--;

		obj = document.getElementById(idName);
		if (obj)
		{
			if (seconds == 0)
			{
				obj.innerHTML = '... redirect in corso...';
			}
			else if (seconds == 1)
			{
				obj.innerHTML = seconds+' secondo';
			}
			else
			{
				obj.innerHTML = seconds+' secondi';
			}
		}
		setTimeout("redirectCountdown('"+ idName +"', "+ (seconds) +", '"+(url)+"');", 1000);
	}
}

function set_alfaDiv(objId)
{
	var obj = document.getElementById(objId);
	if (obj)
	{
		if (obj.style.opacity == "0.50")
		{
			obj.style.filter = "alpha(opacity=100)";
			obj.style.opacity = "1.00";
		}
		else
		{
			obj.style.filter = "alpha(opacity=50)";
			obj.style.opacity = "0.50";
		}
	}
}

function unset_alfaDiv(obj)
{
	if (obj)
	{
		obj.style.filter = "";
		obj.style.opacity = "";
	}
}

function controllaPartitaIva_noCF(objId)
{
	document.getElementById(objId).value = trim(document.getElementById(objId).value.toUpperCase());
	obj = document.getElementById(objId).value;

	if( obj.length != 11 )
	{
		return new Array(false, "La lunghezza della partita IVA non è corretta.");
	}
	
	validi = "0123456789";
	for( i = 0; i < 11; i++ )
	{
		if( validi.indexOf( obj.charAt(i) ) == -1 ) 
			return new Array(false, "La partita IVA contiene un carattere non valido: " + obj.charAt(i));
	}
	
	s = 0;
	for( i = 0; i <= 9; i += 2 ) 
		s += obj.charCodeAt(i) - '0'.charCodeAt(0);
	
	for( i = 1; i <= 9; i += 2 )
	{
		c = 2*( obj.charCodeAt(i) - '0'.charCodeAt(0) );
		if( c > 9 ) c = c - 9; s += c; 
	}

	if( ( 10 - s%10 )%10 != obj.charCodeAt(10) - '0'.charCodeAt(0) )
		return new Array(false, "La partita IVA non è valida");

	return new Array(true);
}


function controllaPartitaIva(objId)
{
	document.getElementById(objId).value = trim(document.getElementById(objId).value.toUpperCase());
	obj = document.getElementById(objId).value;

	if( obj.length != 11 )
	{
		if( obj.length == 16)
		{
			return controllaCodiceFiscale(objId);
		}

		return new Array(false, "La lunghezza della partita IVA non è corretta.");
	}
	
	validi = "0123456789";
	for( i = 0; i < 11; i++ )
	{
		if( validi.indexOf( obj.charAt(i) ) == -1 ) 
			return new Array(false, "La partita IVA contiene un carattere non valido: " + obj.charAt(i));
	}
	
	s = 0;
	for( i = 0; i <= 9; i += 2 ) 
		s += obj.charCodeAt(i) - '0'.charCodeAt(0);
	
	for( i = 1; i <= 9; i += 2 )
	{
		c = 2*( obj.charCodeAt(i) - '0'.charCodeAt(0) );
		if( c > 9 ) c = c - 9; s += c; 
	}

	if( ( 10 - s%10 )%10 != obj.charCodeAt(10) - '0'.charCodeAt(0) )
		return new Array(false, "La partita IVA non è valida");

	return new Array(true);
}

function controllaCodiceFiscale(objId, isRequired)
{
	document.getElementById(objId).value = trim(document.getElementById(objId).value.toUpperCase());
	obj = document.getElementById(objId).value;

	if (obj == '')
	{
		if (isRequired)
		{
			return new Array(false, "Campo obbligatorio");
		}
		return new Array(true);
	}

	var validi, i, s, set1, set2, setpari, setdisp;
	if( obj.length != 16 )
	{
		return new Array(false, "La lunghezza del codice fiscale non è corretta");
	}

	validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	for( i = 0; i < 16; i++ )
	{
		if( validi.indexOf( obj.charAt(i) ) == -1 ) 
		{
			return new Array(false, "Il codice fiscale contiene un carattere non valido: " + obj.charAt(i)); 
		}
	}

	set1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	set2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
	setpari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	setdisp = "BAKPLCQDREVOSFTGUHMINJWZYX";
	s = 0;
	for( i = 1; i <= 13; i += 2 ) 
	{
		s += setpari.indexOf( set2.charAt( set1.indexOf( obj.charAt(i) )));
	}

	for( i = 0; i <= 14; i += 2 ) 
	{
		s += setdisp.indexOf( set2.charAt( set1.indexOf( obj.charAt(i) )));
	}

	if( s%26 != obj.charCodeAt(15)-'A'.charCodeAt(0) ) 
	{
		return new Array(false, "Il codice fiscale non è corretto");
	}

	return new Array(true);
}

function trim(stringa)
{
	while (stringa.substring(0,1) == ' ')
	{
		stringa = stringa.substring(1, stringa.length);
	}
	while (stringa.substring(stringa.length-1, stringa.length) == ' ')
	{
		stringa = stringa.substring(0,stringa.length-1);
	}
	return stringa;
}

function forceInt(obj)
{
	obj.value  = parseInt(obj.value);
}

function jq_blink(objId)
{
	$('#'+objId).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);
}

function jq_blinkObj(obj)
{
	$(obj).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);
}

function checkCAP(objId, isRequired)
{
	document.getElementById(objId).value = trim(document.getElementById(objId).value);
	obj = document.getElementById(objId).value;

	if (obj == '')
	{
		if (isRequired)
		{
			return new Array(false, "Campo obbligatorio");
		}
		return new Array(true);
	}

	if (obj.length != 5)
	{
		return new Array(false, 'Il CAP è composto da 5 cifre');
	}

	var isOk = true;
	for (i=0; i<obj.length; i++)
	{
		isOk_i = (parseInt(obj.charAt(i)) == obj.charAt(i));
		if (!isOk_i)
		{
			obj = obj.substring(0, i)+'?'+obj.substring(i+1);
		}
		isOk &= isOk_i;
	}
	if (!isOk)
	{
		document.getElementById(objId).value = obj;
		return new Array(false, 'Il CAP è composto da soli numeri');
	}

	return new Array(true);
}

function checkEmail(objId, isRequired)
{
	document.getElementById(objId).value = trim(document.getElementById(objId).value);
	obj = document.getElementById(objId).value;

	var emailPat=/^(.+)@(.+)$/
	var specialChars1="\\(\\)<>@,;:\\\\\\\"\\[\\]"
	var specialChars2="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	var validChars1="\[^\\s" + specialChars1 + "\]"
	var validChars2="\[^\\s" + specialChars2 + "\]"
	var quotedUser="(\"[^\"]*\")"
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	var atom1=validChars1 + '+'
	var atom2=validChars2 + '+'
	var word="(" + atom1 + "|" + quotedUser + ")"
	var userPat=new RegExp("^" + word + "$")
	var domainPat=new RegExp("^" + atom2 + "(\\." + atom2 +")*$")

	if (obj=='')
	{
		if (isRequired)
		{
			return new Array(false, "campo obbligatorio");
		}
		return new Array(true);
	}

	var matchArray = obj.match(emailPat)
	if (matchArray==null)
	{
		return new Array(false, "controllare '@' e '.'");
	}

	var user=matchArray[1]
	var domain=matchArray[2]
	if (user.match(userPat)==null) {
		return new Array(false, "username prima di '@' non valido");
	}

	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				return new Array(false, "Indirizzo IP di destinazione non valido");
			}
		}
		return("");
	}

	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		return new Array(false, "dominio dopo di '@' non valido");
	}

	var atomPat=new RegExp(atom2,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	if (domArr[domArr.length-1].length<2)
	{
		return new Array(false, "l'indirizzo inserito deve terminare con l'estenzione del dominio di minimo 2 lettere");
	}

	if (len<2) {
		return new Array(false, 'hostname prima del dominio non inserito');
	}

	return new Array(true);
}

function checkNotEmpty(objId)
{
	document.getElementById(objId).value = trim(document.getElementById(objId).value);
	obj = document.getElementById(objId).value;

	if (obj == '')
	{
		return new Array(false, "Campo obbligatorio");
	}
	return new Array(true);
}

function checkAll_onchange(obj)
{
	isOk = true;
	if (obj)
	{
		if (!obj.childNodes)
		{
			obj = document.getElementById(obj);
		}

		if (obj && obj.hasChildNodes())
		{
			var children = obj.childNodes;
			for (var i = 0; i < children.length; i++) 
			{
				if (children[i].nodeName == 'INPUT')
				{
					// alert('id: '+children[i].id+'\nname: '+children[i].name+'\nvalue: '+children[i].value+'\nnodeName: '+children[i].nodeName+'\nnodeType: '+children[i].nodeType);
					if (children[i].onchange != undefined)
					{
						isOk |= fireEvent(children[i], 'change');
					}
				}
				else if (children[i].nodeType == 1)
				{
					isOk |= checkAll_onchange(children[i]);
				}
			}
		}
	}
	return isOk;
}

function fireEvent(element,event)
{
	if (document.createEventObject)
	{
		// dispatch for IE
		var evt = document.createEventObject();
		var isOk = element.fireEvent('on'+event,evt)
	}
	else
	{
		// dispatch for firefox + others
		var evt = document.createEvent("HTMLEvents");
		evt.initEvent(event, true, true); // event type,bubbling,cancelable
		var isOk = element.dispatchEvent(evt);
	}
	// alert('element:'+element+' / event:'+event+' = '+isOk);
	return isOk;
}

function addPopup_fadeout(obj, className, htmlMessage, timeFadeout, timeSpeddFade)
{
	var newId = make_uniqueId('z_pfb_');
	if (obj)
	{
		var newObj = document.createElement('div');
		newObj.setAttribute('id',newId);
		newObj.setAttribute('class',className);
		newObj.innerHTML = htmlMessage;
		obj.appendChild(newObj);
		if (timeFadeout)
		{
			setTimeout("$('#"+newId+"').fadeOut("+timeSpeddFade+");", timeFadeout);
			newObj.onclick = new Function('$("#'+newId+'").fadeOut('+timeSpeddFade+')');
		}
	}
	return newId;
}

function nl2br(str, is_xhtml)
{
	var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '' : '<br>';
	return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}

function make_uniqueId(baseName)
{
	do
	{
		var newId = baseName+Math.floor(Math.random()*100000);
		var newObj = document.getElementById(newId);
	}
	while (newObj);

	return newId;
}

function isset(e)
{
	var isOk = (e!=undefined);
	try
	{
		if (eval(e)) {}
	}
	catch(err)
	{
		return false;
	}
	return isOk;
}

var callBack_addCount = 0;
function callBack_add(url)
{
	if (isIE_old())
	{
		document.location = '#'+url;
		return false;
	}

	//----------
	// in fase di testing
	//----------
	if (websiteUrl[websiteUrl.length-1] != '/')
	{
		websiteUrl += '/';
	}

	var base = new String(document.location);

	base = base.replace(websiteUrl, '');
	url = url.replace(websiteUrl, '');

	i=-1;
	do
	{
//		if (i>50)
//		{
//			messageInfo_add('', 
//				base[i]+' - '+
//				url[i]+' - '+
//				(base[i] != url[i])+' - '+
//				(base[i] == '#')+' - '+
//				(url[i] == '#')+' - '+
//				''
//				, 999, 'XX'+i, '');
//		}

		i++;
		found = (base[i] != url[i]);
		found |= (base[i] == '?');
		found |= (url[i] == '?');
		found |= (base[i] == '#');
		found |= (url[i] == '#');

		var lunghezzaSuperata = false;
		lunghezzaSuperata |= (i > base.length);
		lunghezzaSuperata |= (i > url.length);
	}
	while (!found || lunghezzaSuperata);

	if (found)
	{
		var key = url.substr(i);
		if (key[0]=='?')
		{
			key = key.substr(1);
		}
		document.location = '#'+key;
	}

//	messageInfo_add('', 'ok', 10, 'callBack_'+(callBack_addCount++), '');
//	messageInfo_add('', base, 999, 'XX_A', '');
//	messageInfo_add('', url, 999, 'XX_B', '');
//	messageInfo_add('', key, 999, 'XX_C', '');
}

function callBack_restore()
{
	var url = new String(document.location);
	var pos = url.indexOf('#');
	if (pos>0)
	{
		var key = url.substr(pos+1);
		// alert('key: '+key);

		var newUrl = new String(document.location);
		pos_A = newUrl.indexOf('?');
		pos_B = newUrl.indexOf('#');
		pos_C = (pos_A>0 && (pos_A < pos_B) ? pos_A : pos_B);
//		alert(pos_A +'\n'+ pos_B+'\n'+ pos_C);
		if (pos_C > 0)
		{
			newUrl = newUrl.substr(0, pos_C);
// 			alert('newUrl = '+newUrl);
		}
		newUrl += '?'+key;
		document.location = newUrl;
	}
}
callBack_restore();


function viewHide(IdName)
{
	TheBox = document.getElementById(IdName);
	if (TheBox.style.display == 'none') {
		TheBox.style.display = 'block';
	} else {
		TheBox.style.display = 'none';
	}
}

function parseEuro(obj)
{
	obj.value = obj.value.replace(',', '.');
	obj.value = (parseInt(parseFloat(obj.value*100)+0.00)/100)+0.00;

	if (obj.value == 'NaN')
	{
		obj.value = '';
		jq_blinkObj(obj);
		return false;
	}
}

//--------
function messageInfo_add(className, htmlMessage, messageDelaySeconds, divName, titleText)
{
	var isParent = false;
	var obj = document.getElementById(divName);
	if (obj)
	{
		obj.parentNode.removeChild(obj);
	}

	var messageInfo = document.getElementById('messageInfo');
	if (messageInfo == null)
	{
		var _body = document.getElementsByTagName('body')[0];
		var messageInfo = document.createElement('div');
		messageInfo.setAttribute('id','messageInfo');
		messageInfo.setAttribute('class','messageInfoBox');
		_body.appendChild(messageInfo);
	}

	htmlMessage = '<input type="button" value="x" onclick="$(\'#'+divName+'\').fadeOut(\'slow\')" class="btnClose" title="chiudi il messaggio" />' + htmlMessage;

	var newObj = document.createElement('div');
	newObj.setAttribute('id',divName);
	newObj.setAttribute('class', 'itemBox '+className);
	newObj.setAttribute('title', titleText);
	newObj.innerHTML = htmlMessage;
	messageInfo.appendChild(newObj);

	if (messageDelaySeconds)
	{
		setTimeout('$("#'+divName+'").fadeOut();', messageDelaySeconds*600);
	}

	return divName;
}

function isIE_old()
{
	var result = (BrowserDetect.browser == 'Explorer') && (BrowserDetect.version <= 7);
	return result;
}


