//nascondi tabella o div
function showtable(idtable)
{
// mostra/nascondi tabella
	var IE=(window.navigator.userAgent.indexOf('MSIE')>-1)?1:0;
	var a=(IE)?'block':'table';
	document.getElementById(idtable).style.display=a
}
function hidetable(idtable)
{
// noascondi tabella
	document.getElementById(idtable).style.display='none'
}
//Trasposizione di alcune funzione di VB in JavaScript/////////////////////////////////////////////////////////////
function Mid(String, Start, Length)
{
    if (String == null)
        return (false);
    
    if (Start > String.length)
        return '';
    
    if (Length == null || Length.length == 0)
        return (false);
    
    return String.substr((Start - 1), Length);
}

function InStr(String1, String2)
{
    var a = 0;
    
    if (String1 == null || String2 == null)
        return (false);
    
    String1 = String1.toLowerCase();
    String2 = String2.toLowerCase();
    
    a = String1.indexOf(String2);
    if (a == -1)
        return 0;
    else
        return a + 1;
}

function Len(string)
{
    if (string == null)
        return (false);
    
    return String(string).length;
}

function Left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}

function Right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}
////////////////////////////////////////////////////////////////////////////////////////////

//Formattazione prezzi e numeri/////////////////////////////////////////////////////////////
function formatEuro(prezzo)	
{
	var sPrezzo = String(prezzo);
	sPrezzo = sPrezzo.replace(".",",");
	
	var sRight = Right(sPrezzo,3);
	
	if (InStr(sRight,",") == 0)
		return String(sPrezzo) + ",00";
	else if (InStr(sRight,",") == 2)
		return String(sPrezzo) + "0";
	else if (InStr(sRight,",") == 1)
		return String(sPrezzo);
}

//CONTROLLO SE NUMERO CON ALERT/////////////////////////////////////////////////////////////
function checkIsNaN(num, msg)
{
	var charTemp = '';
	var	icount;
	var valueTmp = num.value;
	
	for (icount = 0; icount < valueTmp.length; icount++)
	{
		if ((valueTmp.charAt(icount) != '.') && (valueTmp.charAt(icount) != ','))
		{
			charTemp += valueTmp.charAt(icount);	
		}
	}
	
	if (isNaN(charTemp))
	{
		window.alert('Il valore inserito nel campo "' + msg + '" deve essere un numero');
		num.focus();
		return false;
	}
	return true;
}

//EURO CONVERTITORE///////////////////////////////////////////////////////////////
function convLireEuro(fieldValue, fieldValue1)
{
	var icount;
	var charTemp = '';
	var charTemp1 = '';
	var charTemp2 = '';
	var result;
	var start= 'no';
	var icount1 = 0;
	var icount2 = 0;
	var pLire = fieldValue.value;
	if (pLire == '')
	{
		window.alert('attenzione il campo "prezzo in Lire" è obbligatorio');
		fieldValue.focus();
		return;
	}
	for (icount = 0; icount < pLire.length; icount++)
	{
		if (pLire.charAt(icount) != '.')
		{
			charTemp += pLire.charAt(icount);	
		}
	}
	if (isNaN(charTemp))
	{
		window.alert('Attenzione non hai scritto una cifra valida');
		fieldValue.focus();
		return;
	}
	fieldValue.value = charTemp;
	result = charTemp / 1936.27;
	result = '' + result;
	charTemp = '';
	for (icount = 0; icount < 15; icount++)
	{
		if (result.charAt(icount) == '.')
		{
			start = 'yes';
			charTemp += result.charAt(icount);
		}
		else
		{
			if (start == 'yes')
			{
				if (icount1 == 2)
					break;
				icount1++
			}
			charTemp += result.charAt(icount);
		}			
	}
	for (icount = 0; icount < charTemp.length; icount++)
	{
		if (charTemp.charAt(icount) == '.')
		{
			icount1 = 1;
			charTemp2 += ',';
		}
		else
			charTemp2 += charTemp.charAt(icount);
		
	}
	if (icount1 != 1)
		charTemp2 += ',00';
		
	if (charTemp2.length >= 7)
	{
		result = (charTemp2.length - 3) % 3;
		icount1 = 0;
		for(icount = 0; icount < charTemp2.length; icount++)
		{
			if ((charTemp2.charAt(icount) != ',') && (icount2 == 0))
			{
				if (result > 0)
				{
					if (icount == result)
					{
						charTemp1 += '.';
						result = 0;
						icount1 = 1;
					}
						charTemp1 += charTemp2.charAt(icount);
				}
				else
				{	
					
					if (icount1 == 3)
					{
						charTemp1 += '.';
						icount1 = 0;
					}
						icount1++
						charTemp1 += charTemp2.charAt(icount);	
				}
			}
			else
			{
				icount2 = 1;
				charTemp1 += charTemp2.charAt(icount);
			}
				
		}
	}
	else
		charTemp1 = charTemp2;
	
	
	fieldValue1.value = charTemp1;
	charTemp1 = ''
	charTemp = fieldValue.value + '';
	if (charTemp.length >= 4)
	{
		result = charTemp.length % 3;
		icount1 = 0;
		for(icount = 0; icount < charTemp.length; icount++)
		{
			if (result > 0)
			{
				if (icount == result)
				{
					charTemp1 += '.';
					result = 0;
					icount1 = 1;
				}
					charTemp1 += charTemp.charAt(icount);
			}
			else
			{	
				
				if (icount1 == 3)
				{
					charTemp1 += '.';
					icount1 = 0;
				}
					icount1++
					charTemp1 += charTemp.charAt(icount);	
			}
		}
	}
	else
		charTemp1 = fieldValue.value + '';
	fieldValue.value = charTemp1;
}


//EURO CONVERTITORE///////////////////////////////////////////////////////////////
function convEuroLire(fieldValue, fieldValue1)
{
	var icount;
	var charTemp = '';
	var charTemp1 = '';
	var result;
	var start= 'no';
	var icount1 = 0;
	var icount2 = 0;
	var pEuro = fieldValue.value;
	if (pEuro == '')
	{
		window.alert('Attenzione il campo "prezzo in Euro" è obbligatorio');
		fieldValue.focus();
		return;
	}
	for (icount = 0; icount < pEuro.length; icount++)
	{
		if (pEuro.charAt(icount) == ',')
		{
			charTemp += '.'
		}
		else
			charTemp += pEuro.charAt(icount);
	}
	if (isNaN(charTemp))
	{
		window.alert('Attenzione non hai scritto una cifra valida, usa uno di questi formati 1500.23 - 1500,23');
		fieldValue.focus();
		return;
	}
	result = charTemp * 1936.27;
	pEuro = charTemp;
	result = '' + result;
	charTemp = '';
	for (icount = 0; icount < 15; icount++)
	{
		if (result.charAt(icount) != '.')
		{
			charTemp += result.charAt(icount);
		}
		else
			break;					
	}
	if (charTemp.length >= 4)
	{
		result = charTemp.length % 3;
		icount1 = 0;
		for(icount = 0; icount < charTemp.length; icount++)
		{
			if (result > 0)
			{
				if (icount == result)
				{
					charTemp1 += '.';
					result = 0;
					icount1 = 1;
				}
					charTemp1 += charTemp.charAt(icount);
			}
			else
			{	
				
				if (icount1 == 3)
				{
					charTemp1 += '.';
					icount1 = 0;
				}
					icount1++;
					charTemp1 += charTemp.charAt(icount);	
			}
		}
	}
	else
		charTemp1 = charTemp;
	fieldValue1.value = charTemp1;
	charTemp1 = '';
	charTemp2 = '';
	
	for (icount = 0; icount < pEuro.length; icount++)
	{
		if (pEuro.charAt(icount) == '.')
		{
			icount1 = 1;
			charTemp2 += ',';
		}
		else
			charTemp2 += pEuro.charAt(icount);
		
	}
	if (icount1 != 1)
		charTemp2 += ',00';
		
	if (charTemp2.length >= 7)
	{
		
		result = (charTemp2.length - 3) % 3;
		icount1 = 0;
		for(icount = 0; icount < charTemp2.length; icount++)
		{
			if ((charTemp2.charAt(icount) != ',') && (icount2 == 0))
			{
				if (result > 0)
				{
					if (icount == result)
					{
						charTemp1 += '.';
						result = 0;
						icount1 = 1;
					}
						charTemp1 += charTemp2.charAt(icount);
				}
				else
				{	
					
					if (icount1 == 3)
					{
						charTemp1 += '.';
						icount1 = 0;
					}
						icount1++
						charTemp1 += charTemp2.charAt(icount);	
				}
			}
			else
			{
				icount2 = 1;
				charTemp1 += charTemp2.charAt(icount);
			}
				
		}
	}
	else
		charTemp1 = charTemp2;
	
	
	fieldValue.value = charTemp1;
	
}


//VERIFICA CAMPI OBBLIGATORI IN MODULI CON UN SOLO PULSANTE SUBMIT////////////////////
function controlloCampi(nomeform, testo, valore)  
{
	if (nomeform.value == valore)
	{
		window.alert('Attenzione il campo "'+ testo +'" è obbligatorio');
		nomeform.focus();
		return false;
	}
	return true;
}


//VERIFICA CAMPI OBBLIGATORI IN MODULI CON PIU' BUTTONS///////////////////////////////
function controlloCampiButton(nomeform, testo, nomeformSubmit, formAzione)   
{
	nomeformSubmit.azione.value = formAzione;
	if (nomeform.value == '')
	{
		window.alert('Attenzione il campo "'+ testo +'" è obbligatorio');
		return false;
	}
	nomeformSubmit.submit();
}

//VERIFICA FORMATO E-MAIL/////////////////////////////////////////////////////////////
//'obbligatorio' è un valore booleano che indica se il cap è obbligatorio
function controlloEmail(nomeform, obbligatorio) 
{
	var sEmail= nomeform.value;
	
	if (obbligatorio == true && sEmail.length==0)
	{
			alert ('Attenzione il campo "E-mail" è obbligatorio');
			nomeform.focus();
			return false;
	
	}
	
	if ((sEmail.indexOf("@")== -1 || sEmail.indexOf(".")== -1) && sEmail != "") 
	{
		window.alert ('Il campo "E-mail" è stato compilato in modo errato');
		nomeform.focus();
		return false;
						
	}
	return true;
}

//VERIFICA FORMATO CAP/////////////////////////////////////////////////////////////
//'obbligatorio' è un valore booleano che indica se il cap è obbligatorio
function controlloCap(nomeform, obbligatorio) 
{
	var sCap= nomeform.value;
	
	if (obbligatorio == true && sCap.length==0)
	{
		alert ('Attenzione il campo "Cap" è obbligatorio');
		nomeform.focus();
		return false;
	
	}
	
	if ((sCap.length > 0 && sCap.length <5) || isNaN(sCap))
	{
		alert ('Il campo "Cap" è stato compilato in modo errato');
		nomeform.focus();
		return false;
	}
	return true;
}
//VERIFICA FORMATO PARTITA IVA
function ControlloPIVA(pi)
{
	if( pi == '' )  return '';
	if( pi.length != 11 ) 
	{
		alert('La lunghezza della partita IVA non è corretta: la partita IVA dovrebbe essere lunga esattamente 11 caratteri');
		return false;
	}
	validi = "0123456789";
	for( i = 0; i < 11; i++ ){
		if( validi.indexOf( pi.charAt(i) ) == -1 )
		{
			alert('La partita IVA contiene un carattere non valido')
			return false;
		}
	}
	s = 0;
	for( i = 0; i <= 9; i += 2 )
		s += pi.charCodeAt(i) - '0'.charCodeAt(0);
	for( i = 1; i <= 9; i += 2 ){
		c = 2*( pi.charCodeAt(i) - '0'.charCodeAt(0) );
		if( c > 9 )  c = c - 9;
		s += c;
	}
	if( ( 10 - s%10 )%10 != pi.charCodeAt(10) - '0'.charCodeAt(0) )
	{
		alert('Partita IVA non valida')
		return false;
	}
	return true;
}

//VERIFICA FORMATO CODICE FISCALE /////////////////////////////////////////////////////////////
//'obbligatorio' è un valore booleano che indica se il cap è obbligatorio
function controlloCodiceFiscale(nomeform, obbligatorio) 
{
	var sCodiceFiscale= nomeform.value;
	var bControllo = false;
	
	if (obbligatorio == true && sCodiceFiscale.length==0)
	{
		alert ('Attenzione il campo "Codice Fiscale" è obbligatorio');
		nomeform.focus();
		return false;
	
	}
	
	sCodiceFiscale = sCodiceFiscale.toUpperCase();	
   	var regex = /^[A-Z]{6}\d{2}[A-Z]\d{2}[A-Z]\d{3}[A-Z]$/;
	
	// Controllo i 15 carastteri
   	if (regex.test(sCodiceFiscale))
    {
		// Verifico il 16° carattere	
	   	var set1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	  	var set2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
	   	var setpari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	   	var setdisp = "BAKPLCQDREVOSFTGUHMINJWZYX";
	   	var s = 0;
	   
	   	for(i = 1; i <= 13; i += 2)
			s += setpari.indexOf(set2.charAt(set1.indexOf(sCodiceFiscale.charAt(i))));
	   	for(i = 0; i <= 14; i += 2)
			s += setdisp.indexOf(set2.charAt(set1.indexOf(sCodiceFiscale.charAt(i))));
	   	if (s%26 == sCodiceFiscale.charCodeAt(15)-'A'.charCodeAt(0))
			bControllo = true;
	 
	}

	if (!bControllo)
	{
		alert ('Il campo "Codice Fiscale" è stato compilato in modo errato');
		nomeform.focus();
		return false;
	}	
	
   	return true;
}

//CONFERMA CANCELLAZIONE DA FORM//////////////////////////////////////////////////////
function controlloCancellazione(nomeform, testo, nomeformSubmit, formAzione) 
{
	nomeformSubmit.azione.value = formAzione
	if (confirm('Attenzione hai scelto di cancellare "'+ testo +'"'))
	{
		nomeformSubmit.submit();
	}
}

//CONFERMA CANCELLAZIONE DA BUTTON////////////////////////////////////////////////////
function controlloCancButton(actionRedirect, testo)
{
	if (confirm('Attenzione hai scelto di cancellare "'+ testo +'"'))
	{
		document.location.href = actionRedirect;
	}
}

//ROLLOVER SULLE RIGHE ON CHECKBOX////////////////////////////////////////////////////
function changeColor(Rows) 
{
	if (Rows.checked)
	{
		while (Rows.tagName != 'TR')
		{
			Rows = Rows.parentNode;
		}
	Rows.className = 'H';
	}
	else
	{
		while (Rows.tagName != 'TR')
		{
			Rows = Rows.parentNode;
		}
		Rows.className = "";
	}
}

//ROLLOVER SULLE RIGHE ON MOUSEOVER///////////////////////////////////////////////////
function changeColor1(Rows, set) 
{
				
	if ((set == 1) || (set == 3))
	{
		while (Rows.tagName != 'TR')
		{
			Rows = Rows.parentNode;
		}
		Rows.className = 'H';
	}
	else if (set == 2)
	{
		while (Rows.tagName != 'TR')
		{
			Rows = Rows.parentNode;
		}
		Rows.className = "";
	}
}

//FUZIONE  CHE INSERISCE I TAG HTML IN UN CAMPO DI TESTO /////////////////////////
//per gli URL --> code = 'URL'
//per le e-mail --> code = '@'
//per il tag <BR> --> code = 'BR'
//per le immagini --> code = 'IMG'
//per il tag <B> ----> code = 'B'
//per il tag <div align="center"> ---> 'DIV' 
//Per il TAG <FONT> si utilizza la funzione AddColorCode()
function AddColorCode(code, sForm) {
	sString = '<font color="' + code + '">'
	formatText(sForm, sString, '</font>');	
}

// Per gli altri TAG
function AddCode(code, sForm) {

	//Per i link
	if (code == "URL") {
		insertText = prompt("Inserisci il testo del collegamento:", "");
							
			if ((insertText != null) && (insertText != "") && (code == "URL")){
				insertCode = prompt("Inserisci l'indirizzo del sito:", "http://");
									
					if ((insertCode != null) && (insertCode != "") && (insertCode != "http://")){
						if (confirm("Il link è esterno al sito?")){
							sString= '<a class="linkDesc" href="' + insertCode + '" target="_blank">' + insertText + '</a>';				
						}
						else {
							sString= '<a class="linkDesc" href="' + insertCode + '">' + insertText + '</a>';
						}
						formatText(sForm, '', sString);
					}
			}
	}
	
	//Per le e-mail
	if (code == "@") {
		insertCode = prompt("Inserisci l' e-mail:", "");
			
		if ((insertCode != null) && (insertCode != "")){					
			sString = '<a href="mailto:' + insertCode + '">' + insertCode + '</a>';
			formatText(sForm, '', sString);
		}
		
	}
	
	//Per il TAG <BR>
	if ((code == "BR") || (code == 13)) {
		formatText(sForm, '', '<br>');	
	}
		
	//Per inserire una foto di un prodotto
	if (code == "PRO") {	
		insertCode = prompt("Inserisci il nome della foto del prodotto con l'estensione:", "");
					
			if ((insertCode != null) && (insertCode != "")){					
				sString = '<img src="http://www.sardagrossoffice.com/fotopiccola/'+insertCode+'" align="left" border="0">';
				formatText(sForm, '', sString);
			}			
	}
	
	//Per il TAG <B>
	if (code == "B") {
		formatText(sForm, '<b>', '</b>');	
	}
	//Per il TAG <I>
	if (code == "I") {
		formatText(sForm, '<i>', '</i>');	
	}
	//Per il TAG <DIV align="right">
	if (code == "DIVR") {
		formatText(sForm, '<p class=FONT12TIT align=right>', '</p>');	
	}
	//Per il TAG <DIV align="center">
	if (code == "DIV") {
		formatText(sForm, '<div align=center>', '</div>');	
	}
	
	//Per inserire la barra nelle Newsletter
	if (code == "BARRA") {	
		sString = '<br><br><br><img src="http://www.sardagrossoffice.com/immagini/barra_news.gif" align="left" border="0"><br><br>';
		formatText(sForm, '', sString);
	}			
		
}

//inserisce i tags specificati all'inizio e alla fine del testo selezionato
function formatText(textEl, tagstart, tagend) {
	if (textEl.createTextRange && textEl.caretPos) {
	var caretPos = textEl.caretPos;
	caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? tagstart + textE1 + tagend : tagstart + textE1 + tagend;
	textEl.focus();		
	}
}

//ottiene la posizione di una porzione di testo selezionato
function getActiveText(textEl) {
	if (textEl.createTextRange)
	textEl.caretPos = document.selection.createRange().duplicate();
	textE1 = (document.all) ? document.selection.createRange().text : document.getSelection();
}

//funzione per creare il campo per i suggerimenti
function suggerimento(div, page, str) 
{
	if (str.length==0) {   
		
		div.style.visibility="hidden"; 
		div.visible = false; 
		return false;  
	}
	else {
		
		if (window.XMLHttpRequest) {
			http_request = new XMLHttpRequest();
		} else if(window.ActiveXObject) {
			http_request = new ActiveXObject("Microsoft.XMLHTTP");
		} else {
			return false;
		}
		
		var url= page +"?q="+ str;
		url=url+"&sid="+Math.random();
					
		http_request.open('GET', url, true);						
		http_request.send(null);
		
		http_request.onreadystatechange = function() {
			
			if (http_request.readyState == 4 && http_request.status == 200) {	
	
				if(http_request.responseText != ""){
						
					div.style.visibility="visible";
					div.innerHTML=http_request.responseText;					
											
				}	
				else {
					
					div.style.visibility="hidden"; 
					div.visible = false; 
				
				}
				
			}
			else
			{
				div.style.visibility="visible";
				div.innerHTML= "<img src='immagini/loading.gif'>";
			}			
			
		};
	}	
}
//////////////////////////////////////////////////////////////////////////////////

