/* ----------------------------- */
function apriFinestra(name, larghezza, altezza){
	var x = (screen.width - larghezza)/2;
	var y = (screen.height - altezza)/2;
	var finestra = window.open(name, 'ingrandimento', 'width=' + larghezza +',height=' + altezza + ', toolbar=no, directories=no, location=no, status=no, menubar=no, copyhistory=no, scrollbars=no, resizable=no');
	finestra.moveTo(x,y);
	finestra.focus();
}// fine funzione
/* ----------------------------- */
function login_accedi(){
	with(document.forms['login']){
		//alert(UNAME.value.length);
		if(UNAME.value.length<=2){
			alert('Username non valido!');
			UNAME.focus();
			return;
		}//fine if
		if(PASSWD.value.length<=2){
			alert('Password non valida!');
			PASSWD.focus();
			return;
		}//fine if
		submit();
	}// fine with
}// fine funzione
/* ----------------------------- */
function registra_registra(linguaSito){

	switch(linguaSito){
		case 3:
			msgUsername='Username non valido!';
			msgNome='Nome non valido!';
			msgCognome='Cognome non valido!';
			msgRagioneSociale='Nome impresa non valida!';
			msgCodiceImpresa='Codice identificativo impresa non valido!';
			msgDescrLavoro='Inserire la descrizione del lavoro!';
			msgEmail="L'indirizzo di e-mail deve essere nel formato nome@dominio.!";
			msgDomanda='Selezionare una domanda!';
			msgRisposta='Risposta non valida!';
			msgLegge="Non avete dato il consenso alla Legge 196/2003";
		break;
		case 2:
			msgUsername='Username non valido!';
			msgNome='Nome non valido!';
			msgCognome='Cognome non valido!';
			msgRagioneSociale='Nome impresa non valida!';
			msgCodiceImpresa='Codice identificativo impresa non valido!';
			msgDescrLavoro='Inserire la descrizione del lavoro!';
			msgEmail="L'indirizzo di e-mail deve essere nel formato nome@dominio.!";
			msgDomanda='Selezionare una domanda!';
			msgRisposta='Risposta non valida!';
			msgLegge="Non avete dato il consenso alla Legge 196/2003";

		break;
		default:
			msgUsername='Username non valido!';
			msgNome='Nome non valido!';
			msgCognome='Cognome non valido!';
			msgRagioneSociale='Nome impresa non valida!';
			msgCodiceImpresa='Codice identificativo impresa non valido!';
			msgDescrLavoro='Inserire una breve descrizione del lavoro!';
			msgEmail="L'indirizzo di e-mail deve essere nel formato nome@dominio.!";
			msgDomanda='Selezionare una domanda!';
			msgRisposta='Risposta non valida!';
			msgLegge="Non avete dato il consenso alla Legge 196/2003";
		break;
	}//end switch

	with(document.forms['registra']){

		if(utenUsername.value==''){
			alert(msgUsername);
			utenUsername.focus();
			return;
		}//fine if

		if(utenNome.value==''){
			alert(msgNome);
			utenNome.focus();
			return;
		}//fine if

		if(utenCognome.value==''){
			alert(msgCognome);
			utenCognome.focus();
			return;
		}//fine if

		if(utenRagioneSociale.value==''){
			alert(msgRagioneSociale);
			utenRagioneSociale.focus();
			return;
		}//fine if

		if(utenCodiceImpresa.value==''){
			alert(msgCodiceImpresa);
			utenCodiceImpresa.focus();
			return;
		}//fine if

		if (utenEmail.value.search(/^\w+([\.\-]\w+)*@\w+([\.\-]\w+)*\.\w+$/) == -1) {
			alert(msgEmail);
			utenEmail.focus();
			return;
		}//fine if

		if(utenDescrLavoro.value==''){
			alert(msgDescrLavoro);
			utenDescrLavoro.focus();
			return;
		}//fine if
		
		if(utenDomanda.selectedIndex == 0){
			alert(msgDomanda);
			utenDomanda.focus();
			return;
		}//fine if

		if(utenRisposta.value==''){
			alert(msgRisposta);
			utenRisposta.focus();
			return;
		}//fine if
		// legge
		if (!legge.checked){
			alert(msgLegge);
			legge.focus();
			return;
		}//end if

		submit();
	}// fine with
}// fine funzione

/* ----------------------------- */
function persa_controllo(){
	with(document.forms['persa']){

		if(utenUsername.value==''){
			alert('Username non valido!');
			utenUsername.focus();
			return;
		}//fine if

		if(utenDomanda.selectedIndex == 0){
			alert('Selezionare una domanda!');
			utenDomanda.focus();
			return;
		}//fine if

		if(utenRisposta.value==''){
			alert('Risposta non valida!');
			utenRisposta.focus();
			return;
		}//fine if

		submit();
	}// fine with
}// fine funzione
/*-----------------------------------------*/
function profilo_registra(){
	with(document.forms['profilo']){

		if (utenEmail.value.search(/^\w+([\.\-]\w+)*@\w+([\.\-]\w+)*\.\w+$/) == -1) {
			alert("L'indirizzo di e-mail deve essere nel formato nome@dominio.");
			utenEmail.focus();
			return;
		}//fine if

		if(utenRisposta.value==''){
			alert('Risposta non valida!');
			utenRisposta.focus();
			return;
		}//fine if
		if(eval('document.forms[0].mailingList') != undefined){
		if (mailingList.checked == true){
			var selezionato = false;
			var i=0;
			for (i=0;i<elements.length;i++){
				if (elements[i].name.substring(0,11)=="mailingTemi" && elements[i].checked){
					selezionato = true;
				}// fine if
			}// fine for
			if (selezionato == false) {
				alert('Non risulta essere stato specificato alcun tema!');
				return;
			}// fine if
		}//end if
		}//end if

		submit();
	}// fine with
}// fine funzione

/* ----------------------------- */
var ajax = null; // il problema con IE sta qui ;)

function chg_psw(comando, lingua){
	switch(lingua){
		default:
		msgOldPassword='Devi inserire la vecchia password!';
		msgNewPassword='Devi inserire la nuova password!';
		msgNewPassword2='Devi inserire la conferma della nuova password!';
		msgConfrontoPassword='La nuova password e la conferma non coincidono';
		msg_password_wrong="Vecchia Password errata!";
		msgAttesa="Attendere un attimo...";
		break;
	}//end switch

	with(document.forms[0]){

	if(old_password.value==''){
			alert(msgOldPassword);
			old_password.focus();
			return;
		}//fine if
	if(new_password1.value==''){
			alert(msgNewPassword);
			new_password1.focus();
			return;
		}//fine if
	if(new_password2.value==''){
			alert(msgNewPassword2);
			new_password2.focus();
			return;
		}//fine if
	if(new_password1.value!=new_password2.value){
			alert(msgConfrontoPassword);
			new_password1.value="";
			new_password2.value="";
			new_password1.focus();
			return;
		}//fine if



		// l'oggetto per comunicare con il server
	 	ajax = assegnaXMLHttpRequest();
	    var elemento = prendiElementoDaId("idOldPassword");

	    elemento.innerHTML = "";
	    loader=document.createElement("img");
	    loader.setAttribute("src","./imm_struttura/gira.gif");
	    elemento.appendChild(loader);

	    // data di inizio interazione
	    dataChiamata = new Date(),
	    // tempo in millisecondi dell'inizio
	    inizioChiamata = dataChiamata.getTime(),
	    // secondi di attesa prima di fermare l'interazione
	    massimaAttesa = 5;
	    // variabile cui assegnare la funzione di verifica

	    // verificaTempoTrascorso;
	    if(ajax){
	    	ajax.open("GET","./common/cerca_username.php?uten_seriale=" + id.value+"&uten_psw=" + old_password.value,true);
	    	//ajax.setRequestHeader("connection", "close");
	    	ajax.onreadystatechange = function() {
			  // verifica dello stato
		      if(ajax.readyState == 4){
		        // annulliamo la funzione di verifica tempo
        		verificaTempoTrascorso = function(){};
		        // verifica della risposta da parte del server
		        if(statusText[ajax.status] === "OK"){
			        if(ajax.responseText!="1"){
				          elemento.innerHTML = ajax.responseText;
				          ///elemento.removeChild(loader);
				          alert(msg_password_wrong);
				          old_password.focus();
				          return;
			        }else{
			        	elemento.innerHTML = msgAttesa;
			        	//elemento.removeChild(loader);
	        	   		frm_op.value = 'change';
						submit();
						//alert('ok');
			        }//end if username esistente
			     }else{
			       	// errore di caricamento
			       	///elemento.removeChild(loader);
			       	elemento.innerHTML = "Impossibile effettuare l'operazione richiesta.<br />";
			       	elemento.innerHTML += "Errore riscontrato: " + statusText[ajax.status];
			       	alert('error');
			       	return;
			     }//end if else

				elemento.removeChild(loader);

		      }else if(massimaAttesa < 2000){
          		// conversione di massimaAttesain millisecondi
          		massimaAttesa = massimaAttesa * 2000;

          			verificaTempoTrascorso = function() {
		            	dataChiamata = new Date();
		         		if((dataChiamata.getTime() - inizioChiamata) > massimaAttesa) {
		              		ajax.onreadystatechange = function(){return;};
		              		ajax.abort();
		              		//ajax = document.createElement("p");
		              		elemento.innerHTML ="<br>Spiacente, richiesta fallita. <br>La prego di ritentare tra qualche istante...";
		              		old_password.value="";
		              		new_password1.value="";
							new_password2.value="";
		              		//elemento.appendChild(ajax);
		              		//link.clicked = false;
		            	}else
		              		setTimeout(verificaTempoTrascorso, 100);
		          	};
            		verificaTempoTrascorso();

		      }//end if completato
		    }//end function
	    // invio richiesta
	    ajax.send(null);

	    }else{
			alert('Problemi con il controllo ajax!');
		}//end if ajax



	}// fine with
}//end function

/* ----------------------------- */
function cercaCliente(){
	with(document.forms[0]){

		if(eval('document.forms[0].idAgente') == undefined){
			agente = '';
		}
		else{
			agente = eval('document.forms[0].idAgente.value');
		}// fine else/if

		name = 'scheda_SelCliente.php?ID=' + idCliente.value + '&AGENTE=';

		if(agente!=''){
			name += agente;
		}// fine if

		apriFinestra(name, 600, 600);

	}// fine with
}// fine funzione
/* ----------------------------- */
function CaricaCliente(IdAgente){
	with(document.forms[0]){
		with (opener.document.forms[0]){
			idCliente.value = IdAgente;	//id agente
		}// fine with
		window.close();
	}// fine with
}// fine funzione
/* ----------------------------- */
function preventivoTesta(){
	with(document.forms[0]){
		if(idCliente.value.length!=10){
			alert('Codice cliente non valido!');
			idCliente.focus();
			return;
		}//fine if
		if(VerificaData(dataPreventivo.value) == false){
			alert('Data non valida!');
			dataPreventivo.focus();
			return;
		}//fine if
		//action='ric_articoli.php';
		op_pag.value = 'testata';
		submit();
	}// fine with
}// fine funzione
/* ----------------------------- */
function listaProd(){
	with(document.forms[0]){
		name = 'scheda_sel_articoli.php?id=' + idProd.value
		apriFinestra(name, 600, 500);
	}// fine if
}// fine funzione
/* ----------------------------- */
function artSel(idArticolo, descr){
	with(document.forms[0]){
		with (opener.document.forms[0]){
			idProd.value = idArticolo;
			prodDescr.value = descr;
		}// fine with
		window.close();
	}// fine with
}// fine funzione
/* ----------------------------- */
function aggiungiProd(){
	with(document.forms[0]){
		if(idProd.value==''){
			alert('Codice prodotto non valido!');
			idProd.focus();
			return;
		}// fine if
		if(isNaN(quantita.value) || quantita.value<=0){
			alert('Quantita\' non valida!');
			quantita.focus();
			return;
		}//fine if
		document.getElementById('idControllo').src = "ric_articoli_iframe.php?idProd=" +idProd.value;
		//alert('ok-');
	}// fine with
}// fine funzione
/* ----------------------------- */
function eliminaProd(idPrevProd){
	with(document.forms[0]){
		op_pag.value = 'eliPrevProd';
		seriale.value = idPrevProd;
		submit();
	}// fine with
}// fine funzione
/* ----------------------------- */
function eliminaPrev(idPrev){
	with(document.forms[0]){
		if(confirm('Vuoi veramente eliminare questo preventivo?')){
			op_pag.value = 'eliPrev';
			seriale.value = idPrev;
			submit();
		}//fine if
	}// fine with
}// fine funzione
/* ----------------------------- */
// richiesta modifica prodotto preventivo
function modificaProd(idPrevProd){
	with(document.forms[0]){
		op_pag.value = 'modPrevProd';
		seriale.value = idPrevProd;
		submit();
	}// fine with
}// fine funzione
/* ----------------------------- */
// modifica prodotto preventivo
function modificaProdDef(idPrevProd){
	with(document.forms[0]){
		op_pag.value = 'modPrevProdDef';
		seriale.value = idPrevProd;
		submit();
	}// fine with
}// fine funzione
/* ----------------------------- */
function confermaPrev(idPrev){
	with(document.forms[0]){
		if(confirm('Vuoi veramente confermare questo preventivo?')){
			op_pag.value = 'confPrev';
			seriale.value = idPrev;
			submit();
		}//fine if
	}// fine with
}// fine funzione
/* ----------------------------- */
function salvaPar(){
	with(document.forms[0]){

		if(!VerificaMail(destinatario.value)){
			return;
		}// fine if

		op_pag.value = 'ins';
		submit();

	}// fine with
}// fine funzione
/* ----------------------------- */
function VerificaDataNoObg(g,m,a){
	var data;
	if(g.value!='' || m.value!='' || a.value!=''){
		data = g.value + "/" + m.value + "/" + a.value;
		if(!VerificaData(data)){
			alert('la data '+data+' non risulta essere in un formato accettabile!');
			g.value='';
			m.value='';
			a.value='';
			g.focus();
			return 0;
		}
	}
	return 1;
}//end function
/* ----------------------------- */
function VerificaDataObg(g,m,a){
	var data;
	if(g.value==''){
		alert('Inserire il giorno!');
		g.focus();
		return 0;
	}
	if(m.value==''){
		alert('Inserire il mese!');
		m.focus();
		return 0;
	}
	if(a.value==''){
		alert('Inserire l\'anno!');
		a.focus();
		return 0;
	}

	data = g.value + "/" + m.value + "/" + a.value;
	if(!VerificaData(data)){
		alert('la data '+data+' non risulta essere in un formato accettabile!');
		g.value='';
		m.value='';
		a.value='';
		g.focus();
		return 0;
	}
	return 1;
}//end function
/* ----------------------------- */
function VerificaData(Valore) {
	var     ValoriData;
	var Giorni = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

	// verifica la validita' della data
	if (Valore.search(/^([12]\d|3[01]|0?[1-9])\/(1[0-2]|0?[1-9])\/(19|20|)\d\d$/) != -1) {
		// imposta il vettore dei valori
		ValoriData = Valore.split("/");

		// verifica se l'anno e' bisestile
		if (ValoriData[2] % 4 == 0) Giorni[1]++;
		return (ValoriData[0] <= Giorni[ValoriData[1] - 1]);
	}

	// in caso di errore ritorna false
	return false;
}//end function
/* ----------------------------- */
function VerificaMail(Valore) {
	if (Valore.search(/^\w+([\.\-]\w+)*@\w+([\.\-]\w+)*\.\w+$/) == -1) {
		alert("L'indirizzo di e-mail deve essere nel formato nome@dominio.");
		return false;
	}
	return true;
}// end function
/* ----------------------------- */
function SalvaGuestbook() {
    with (document.forms[0]) {
        // Controllo i campi obbligatori
        if (!VerificaCampi(document.forms[0], "Nome:Cognome:Email:Titolo:Messaggio:check")){
            return;
        }
		COMANDO.value="salva";
     	submit();
    }//end with
}// end function
/* ----------------------------- */
function VerificaCampi(NomeForm, ListaCampi) {
	var CampiOb;
	// crea il vettore dei campi da controllare
	CampiOb = ListaCampi.split(":");
	// se uno dei campi e' vuoto visualizza l'errore e torna falso
	for (i=0; i < CampiOb.length; i++) {
		if (NomeForm[CampiOb[i]].value == "" &&
		NomeForm[CampiOb[i]].type != "submit" &&
		NomeForm[CampiOb[i]].type != "reset" &&
		NomeForm[CampiOb[i]].type != "button" &&
		NomeForm[CampiOb[i]].type != "hidden") {
			alert("Il campo " + NomeForm[CampiOb[i]].name + " � vuoto!");
			NomeForm[CampiOb[i]].focus();
			return false;
		}//end if
		//controllo forma della mail
		if ((NomeForm[CampiOb[i]].name == "Email") && (!VerificaMail(NomeForm[CampiOb[i]].value))){
					NomeForm[CampiOb[i]].focus();
					return false;
		}//end if
		//controllo check legge consenso
		if (NomeForm[CampiOb[i]].type == "checkbox" && NomeForm[CampiOb[i]].name == "check" &&
		!NomeForm[CampiOb[i]].checked){
			alert("Non avete dato il consenso alla Legge 196/2003");
			return false;
		}//end if
	}//end for
	return true;
}// end function
/* ----------------------------- */
/* DETTAGLIO PER PHOTOGALLERY */
function apriDettaglio(id){
	var pagina = 'gallery.php?pgSeriale=' + id;
	var larghezza = 580;
	var altezza = 450;
	var x = (screen.width -larghezza)/2;
	var y = (screen.height - altezza)/2;
	var finestra = window.open(pagina, 'ingrandimento', 'width=' + larghezza +',height=' + altezza + ',toolbar=no,directories=no,location=no,status=no,menubar=no,copyhistory=no,scrollbars=yes,resizable=yes');
	finestra.moveTo(x,y);
	finestra.focus();
}// fine funzione

/* ----------------------------- */
/*#######################################################################*/
/** FUNZIONI AJAX */
/*#######################################################################*/
	// funzione per prendere un elemento con id univoco
		function prendiElementoDaId(id_elemento) {
			var elemento;
			if(document.getElementById)
				elemento = document.getElementById(id_elemento);
			else
				elemento = document.all[id_elemento];
			return elemento;
		};


	// funzione per assegnare un oggetto XMLHttpRequest

		function assegnaXMLHttpRequest() {
			var
				XHR = null,
				browserUtente = navigator.userAgent.toUpperCase();

			if(typeof(XMLHttpRequest) === "function" || typeof(XMLHttpRequest) === "object" || window.XMLHttpRequest){
				XHR = new XMLHttpRequest();
			}else if(window.ActiveXObject && browserUtente.indexOf("MSIE 4") < 0) {
				if(browserUtente.indexOf("MSIE 5") < 0)
					XHR = new ActiveXObject("Msxml2.XMLHTTP");
				else
					XHR = new ActiveXObject("Microsoft.XMLHTTP");
			}
			return XHR;
		};



/** OGGETTI / ARRAY */

	// oggetto di verifica stato
		var readyState = {
			INATTIVO:	0,
			INIZIALIZZATO:	1,
			RICHIESTA:	2,
			RISPOSTA:	3,
			COMPLETATO:	4
		};

	// array descrittivo dei codici restituiti dal server
	// [la scelta dell' array � per evitare problemi con vecchi browsers]
		var statusText = new Array();
		statusText[100] = "Continue";
		statusText[101] = "Switching Protocols";
		statusText[200] = "OK";
		statusText[201] = "Created";
		statusText[202] = "Accepted";
		statusText[203] = "Non-Authoritative Information";
		statusText[204] = "No Content";
		statusText[205] = "Reset Content";
		statusText[206] = "Partial Content";
		statusText[300] = "Multiple Choices";
		statusText[301] = "Moved Permanently";
		statusText[302] = "Found";
		statusText[303] = "See Other";
		statusText[304] = "Not Modified";
		statusText[305] = "Use Proxy";
		statusText[306] = "(unused, but reserved)";
		statusText[307] = "Temporary Redirect";
		statusText[400] = "Bad Request";
		statusText[401] = "Unauthorized";
		statusText[402] = "Payment Required";
		statusText[403] = "Forbidden";
		statusText[404] = "Not Found";
		statusText[405] = "Method Not Allowed";
		statusText[406] = "Not Acceptable";
		statusText[407] = "Proxy Authentication Required";
		statusText[408] = "Request Timeout";
		statusText[409] = "Conflict";
		statusText[410] = "Gone";
		statusText[411] = "Length Required";
		statusText[412] = "Precondition Failed";
		statusText[413] = "Request Entity Too Large";
		statusText[414] = "Request-URI Too Long";
		statusText[415] = "Unsupported Media Type";
		statusText[416] = "Requested Range Not Satisfiable";
		statusText[417] = "Expectation Failed";
		statusText[500] = "Internal Server Error";
		statusText[501] = "Not Implemented";
		statusText[502] = "Bad Gateway";
		statusText[503] = "Service Unavailable";
		statusText[504] = "Gateway Timeout";
		statusText[505] = "HTTP Version Not Supported";
		statusText[509] = "Bandwidth Limit Exceeded";

/*#######################################################################*/
/** FINE FUNZIONI AJAX */
/*#######################################################################*/

/* ----------------------------- */
/* -- NON UTILIZZATA 20070525 -- */
function countChars(campo, caratteri, contatore){
	var theForm = document.forms[0];
	var campoControllo = eval ('theForm.' + campo);
	var campoContatore = eval ('theForm.' + contatore);
	var textLength = campoControllo.value.length;
	var arrValue = campoControllo.value.split("?");
	var adjustedLength = (arrValue.length - 1) + textLength;
	var returnValue;

	if (adjustedLength > caratteri){
		alert("Puoi inserire solo " + caratteri + " caratteri per questo campo!");
		returnValue = campoControllo.value.substr(0, caratteri-1);
		campoControllo.value = returnValue;
	}

	campoContatore.value = caratteri - adjustedLength;

}
/* ----------------------------- */