// mostro / nascondo il <div> delle spedizioni
function OpenCloseDivIndirizziAdmin(check, obj) {

	if(check.checked == true){
		obj.style.display = '';
	}else{
		obj.style.display = 'none';
	}

/*
	if (obj.style.display == 'block') {
		obj.style.display = 'none';
	}
	else {
		obj.style.display = 'block';
	}*/
}

// mostro / nascondo il <tr> del dettaglio acquisto
function OpenCloseDettaglio(id_obj) {
	obj = document.getElementById('dett' + id_obj);
	if (obj.style.display == 'block') {
		obj.style.display = 'none';
	}
	else {
		obj.style.display = 'block';
	}
}

// mostro / nascondo il <tr> delle provincie nel form di registrazione utente
function ShowTrProvincie(obj, num, obj_select) {

	// default value for "num"
	num = typeof(num) != 'undefined' ? num : '';

	var trp = document.getElementById('tr_provincie'+num);
	if (obj.value == 468) {
		trp.style.visibility = 'visible';
	} else {
		trp.style.visibility = 'hidden';

		if(typeof(obj_select) != 'undefined'){
			obj_select.selectedIndex = 0;
		}
	}
}

function ShowTrProvincieSpedizione(obj, num){
	// default value for "num"
	num = typeof(num) != 'undefined' ? num : '';

	var trp = document.getElementById('tr_provincie_spedizione'+num);
	if (obj.value == 468) {
		trp.style.visibility = 'visible';
	} else {
		trp.style.visibility = 'hidden';
	}
}

function ShowTrCodiceFiscale(obj, num, obj_select) {

	// default value for "num"
	num = typeof(num) != 'undefined' ? num : '';

	var trp = document.getElementById('tr_codice_fiscale'+num);
	if (obj.value == 468) {
		trp.style.visibility = 'visible';
		document.getElementById('controlla_codice_fiscale').value = 1;
	} else {
		trp.style.visibility = 'hidden';
		document.getElementById('controlla_codice_fiscale').value = 0;

		if(typeof(obj_select) != 'undefined'){
			obj_select.selectedIndex = 0;
		}
	}
}

function ShowTrEsenzioneIva(obj, num){
	// default value for "num"
	num = typeof(num) != 'undefined' ? num : '';

	var trp = document.getElementById('tr_esenzione_iva'+num);
	if (obj.value == 468) {
		trp.style.visibility = 'hidden';
	} else {
		trp.style.visibility = 'visible';
	}
}

// mostro / nascondo il <div> con l'input per i monogrammi nelle opzioni camicie
function ShowDivMonogrammi(obj) {
	var dm = document.getElementById('div_monogrammi');
	if (obj.value != 9) {
		dm.style.visibility = 'visible';
	} else {
		dm.style.visibility = 'hidden';
	}
}

// mostro / nascondo il <div> per gli indirizzi
function ShowDivIndirizzi(div) {
	var dm = document.getElementById(div);
	if (dm.style.visibility == 'hidden') {
		dm.style.visibility = 'visible';
		dm.style.height = '100%';
	} else {
		dm.style.visibility = 'hidden';
		dm.style.height = '0px';
	}
}


// verifico i campi della form di registrazione (/registrazione-utente)
function RegUtenteCheckForm() {

	var errori = new Array();
	var frm = document.forms['registrazione'];

	if (frm.f400_nome.value == '') {
		errori.push('inserire il nome');
	}
	if (frm.f400_cognome.value == '') {
		errori.push('il cognome non pu\u00F2 essere vuoto');
	}
	if(typeof(frm.f401_codice_fiscale) != 'undefined' && document.getElementById('controlla_codice_fiscale').value == 1){
		if(typeof(frm.tipo_persona) != 'undefined'){
			if(frm.tipo_persona.options[frm.tipo_persona.selectedIndex].value == 1){
				if (frm.f401_codice_fiscale.value == '') {
					errori.push('inserire il codice fiscale');
				}else if(ControllaCF(frm.f401_codice_fiscale.value) == false){
					errori.push('il codice fiscale non \u00E8 valido');
				}
			}
		}else{
			if (frm.f401_codice_fiscale.value == '') {
				errori.push('inserire il codice fiscale');
			}else if(ControllaCF(frm.f401_codice_fiscale.value) == false){
				errori.push('il codice fiscale non \u00E8 valido');
			}
		}
	}
	if(typeof(frm.tipo_persona) != 'undefined'){
		if(frm.tipo_persona.options[frm.tipo_persona.selectedIndex].value == 2){
			if (frm.f401_partita_iva.value == '') {
				errori.push('inserire la partita iva');
			}else if(frm.f401_r451_id_nazioni.options[frm.f401_r451_id_nazioni.selectedIndex].value == 468){
				if(ControllaPIVA(frm.f401_partita_iva.value) == false){
					errori.push('la partita iva non \u00E8 valida');
				}
			}
		}
	}
	if(typeof(frm.f401_citta) != 'undefined'){
		if (frm.f401_citta.value == '') {
			errori.push('inserire la localit\u00E0');
		}
	}
	if(typeof(frm.f401_via) != 'undefined'){
		if (frm.f401_via.value == '') {
			errori.push('inserire l\' indirizzo');
		}
	}
	if(typeof(frm.f401_cap) != 'undefined'){
		if (frm.f401_cap.value == '') {
			errori.push('inserire il cap');
		}
	}
	if (frm.f400_mail.value == '') {
		errori.push('inserire l\u00B4 email');
	}

	if (frm.f400_password) {
		if (frm.f400_password.value == '') {
			errori.push('indicare una password');
		}
		if (frm.f400_password.value.length < 6) {
			errori.push('indicare una password lunga almeno 6 caratteri');
		}
		if (frm.f400_password.value == frm.f400_username.value) {
			errori.push('indicare una password diversa dallo username');
		}
	}

	if(frm.check_spedizione_diversa.checked == true){
		if (frm.f400_nome_spedizione.value == '') {
			errori.push('inserire il nome');
		}
		if (frm.f400_cognome_spedizione.value == '') {
			errori.push('il cognome non pu\u00F2 essere vuoto');
		}
		if(typeof(frm.f401_citta_spedizione) != 'undefined'){
			if (frm.f401_citta_spedizione.value == '') {
				errori.push('inserire la localit\u00E0');
			}
		}
		if(typeof(frm.f401_via_spedizione) != 'undefined'){
			if (frm.f401_via_spedizione.value == '') {
				errori.push('inserire l\' indirizzo');
			}
		}
		if(typeof(frm.f401_cap_spedizione) != 'undefined'){
			if (frm.f401_cap_spedizione.value == '') {
				errori.push('inserire il cap');
			}
		}
	}

	if (frm.f400_username.value == '') {
		alert('lo username non pu\u00F2 essere vuoto');
	}
	else if (frm.f400_username.value.length < 6) {
		alert('lo username deve essere lungo almeno 6 caratteri');
	}
	else {

		if (errori.length == 0) {
			// lo username è già in uso ?
			RegUtenteCheckUsernameAvailable(frm.f400_username.value, frm.f400_id_utenti.value);
		} else {
			txt_alert = 'Per completare la registrazione occorre:\n\n';
			for (x=0; x<errori.length; x++) {
				txt_alert = txt_alert + ' - ' + errori[x] + '\n';
			}
			txt_alert = txt_alert + '\n';
			alert(txt_alert);
			return false;
		}
	}
}
function RegUtenteCheckForm2() {

	var errori = new Array();
	var frm = document.forms['registrazione'];

	if (frm.f400_nome.value == '') {
		errori.push('inserire il nome');
	}
	if (frm.f400_cognome.value == '') {
		errori.push('il cognome non puo\u00F2 essere vuoto');
	}
	if(frm.tipo_persona.options[frm.tipo_persona.selectedIndex].value == 1 && document.getElementById('controlla_codice_fiscale').value == 1){
		if (frm.f401_codice_fiscale.value == '') {
			errori.push('inserire il codice fiscale');
		}else if(!ControllaCF(frm.f401_codice_fiscale.value)){
			errori.push('il codice fiscale non \u00E8 valido');
		}
	}
	if(frm.tipo_persona.options[frm.tipo_persona.selectedIndex].value == 2){
		if(frm.f401_r451_id_nazioni.options[frm.f401_r451_id_nazioni.selectedIndex].value == 468){
			if (frm.f401_partita_iva.value == '') {
				errori.push('inserire la partita iva');
			}else if(ControllaPIVA(frm.f401_partita_iva.value) == false){
				errori.push('la partita iva non \u00E8 valida');
			}
		}
	}
	if (frm.f401_r451_id_nazioni.value == '') {
		errori.push('inserire la nazione');
	}
	if (frm.f401_citta.value == '') {
		errori.push('inserire la localit\u00E0');
	}
	if (frm.f401_via.value == '') {
		errori.push('inserire l\u00B4indirizzo');
	}
	if (frm.f401_cap.value == '') {
		errori.push('inserire il cap');
	}
	if (frm.f400_mail.value == '') {
		errori.push('inserire l\u00B4email');
	}
	if (frm.accetta.checked != true) {
		errori.push('dare il consenso al trattamento dei dati personali');
	}

	if (frm.f400_password) {
		if (frm.f400_password.value == '') {
			errori.push('indicare una password');
		}
		if (frm.f400_password.value.length < 6) {
			errori.push('indicare una password di almeno 6 caratteri');
		}
		if (frm.f400_password.value == frm.f400_username.value) {
			errori.push('indicare una password diversa dallo username');
		}
	}

	if (errori.length == 0) {
		frm.submit();
		return false;
	} else {
		txt_alert = 'Per completare la registrazione occorre:\n\n';
		for (x=0; x<errori.length; x++) {
			txt_alert = txt_alert + ' - ' + errori[x] + '\n';
		}
		txt_alert = txt_alert + '\n';
		alert(txt_alert);
		return false;
	}


}

function RegUtenteCheckForm3() {

	var errori = new Array();
	var frm = document.forms['registrazione'];

	if (frm.f400_nome.value == '') {
		errori.push('inserire il nome');
	}
	if (frm.f400_cognome.value == '') {
		errori.push('il cognome non puo\' essere vuoto');
	}
	if (frm.f400_mail.value == '') {
		errori.push('inserire l\'email');
	}

	if (errori.length == 0) {
		frm.submit();
		return false;
	} else {
		txt_alert = 'Per completare la registrazione occorre:\n\n';
		for (x=0; x<errori.length; x++) {
			txt_alert = txt_alert + ' - ' + errori[x] + '\n';
		}
		txt_alert = txt_alert + '\n';
		alert(txt_alert);
		return false;
	}


}

// verifico la validità dello username, via AJAX
function RegUtenteCheckUsernameAvailable(username, f400_id_utenti) {

  // variabili di funzione
  var
    // assegnazione oggetto XMLHttpRequest
    ajax = assegnaXMLHttpRequest();

  // se l'oggetto XMLHttpRequest non è nullo
  if(ajax) {

    // impostazione richiesta asincrona in GET
    // del file specificato
    ajax.open("post", "/ecommerce/utenti_registrazione_check_username.php", true);
    ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded");
    ajax.setRequestHeader("connection", "close");

    // impostazione controllo e stato della richiesta
    ajax.onreadystatechange = function() {

      // verifica dello stato
      if(ajax.readyState === readyState.COMPLETATO) {
        // verifica della risposta da parte del server
        if(statusText[ajax.status] === "OK") {
          // operazione avvenuta con successo, ritorno al chiamante un ok / ko
          //alert(ajax.responseText);
          user_available = ajax.responseText;
          if (user_available == 'ok1') {
          	RegUtenteCheckForm2();
          } else if (user_available == 'ok2') {
          	RegUtenteCheckForm3();
          }
          else {
          	alert('Lo username che hai scelto \u00E8 gi\u00E0 in uso\nPer favore scegline uno diverso.');
          }
        }
      }
    }

    // invio richiesta
    ajax.send("username="+username+"&f400_id_utenti="+f400_id_utenti);
  }

}

/*id della checkBox attualmente selezionata*/
var checkBoxSelected = '';

function SelectProdottoForActions(idProdotto,sessGet){
	// variabili di funzione
  var
    // assegnazione oggetto XMLHttpRequest
    ajax = assegnaXMLHttpRequest();

  // se l'oggetto XMLHttpRequest non è nullo
  if(ajax) {

    // impostazione richiesta asincrona in GET
    // del file specificato
    ajax.open("post", "/ecommerce/admin/prodotti_elenco_check.php", true);
    ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded");
    ajax.setRequestHeader("connection", "close");

    // impostazione controllo e stato della richiesta
    ajax.onreadystatechange = function() {

      // verifica dello stato
      if(ajax.readyState === readyState.COMPLETATO) {
        // verifica della risposta da parte del server
        if(statusText[ajax.status] === "OK") {
          // operazione avvenuta con successo, ritorno al chiamante un ok / ko
          //alert(ajax.responseText);
          if (ajax.responseText != 'ko') {
          	/*inserire funzione di selezione unica checkbox e aggiornamento get actions*/
          	SetValueIdProdotto(idProdotto, ajax.responseText);
          }
          else {
          	alert('Il prodotto che hai scelto non &egrave; presente nella lista.');
          }
        }
      }
    }
    // invio richiesta
    if(checkBoxSelected != '')
		document.getElementById(checkBoxSelected).checked = false;
	if(checkBoxSelected != 'selProdotto'+idProdotto)
    	ajax.send("id_prodotti="+idProdotto+"&s="+sessGet);
   	else
   	{
   		checkBoxSelected = '';
   		SetNoneValueProdotto(sessGet);
	}
  }
}

function SelectCategoryForActions(idCat, sessGet){
	// variabili di funzione
  var
    // assegnazione oggetto XMLHttpRequest
    ajax = assegnaXMLHttpRequest();

  // se l'oggetto XMLHttpRequest non è nullo
  if(ajax) {

    // impostazione richiesta asincrona in GET
    // del file specificato
    ajax.open("post", "/ecommerce/admin/categorie_elenco_check.php", true);
    ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded");
    ajax.setRequestHeader("connection", "close");

    // impostazione controllo e stato della richiesta
    ajax.onreadystatechange = function() {

      // verifica dello stato
      if(ajax.readyState === readyState.COMPLETATO) {
        // verifica della risposta da parte del server
        if(statusText[ajax.status] === "OK") {
          // operazione avvenuta con successo, ritorno al chiamante un ok / ko
          if (ajax.responseText != 'ko') {
          	/*split stringa se sub_cat o sub_prod e passaggio caso a  funzione che setta i link*/
          	arrTmp = ajax.responseText.split('#');
           	if(arrTmp.length == 1)
          		SetValueIdCategoria(idCat, arrTmp[0], 1);
       		else if(arrTmp[1] == 'sub_cat'){
       			SetValueIdCategoria(idCat, arrTmp[0], 2);
       		}else if(arrTmp[1] == 'sub_prod')
       			SetValueIdCategoria(idCat, arrTmp[0], 3);
          }
          else {
          	alert('Categoria inesistente.');
          }
        }
      }
    }
    // invio richiesta
    if(checkBoxSelected != '')
		document.getElementById(checkBoxSelected).checked = false;
	if(checkBoxSelected != 'selCategoria'+idCat)
    	ajax.send("id_categorie="+idCat+"&s="+sessGet);
   	else
   	{
   		checkBoxSelected = '';
   		SetNoneValueCategoria();
	}
  }
}

function SetValueIdCategoria(idCat, strGet, intCase){
	checkBoxSelected = 'selCategoria'+idCat;
	document.getElementById('linkEdit').onclick = function(){location.href='categorie_elenco_modifica.php'+strGet;};
	document.getElementById('linkCategories').onclick = function(){location.href='categorie_elenco.php'+strGet;};
	document.getElementById('linkLanguages').onclick = function(){location.href='categorie_lingue_testi.php'+strGet;};

	switch(intCase){
		case 1:
			document.getElementById('linkDelete').onclick = function(){if (confirm('Confermi l\u00B4 eliminazione ?')) { location.href='categorie_elenco_elimina.php'+strGet; } else { return false; }};
			break;
		case 2:
			document.getElementById('linkDelete').onclick = function(){alert('la categoria selezionata contiene sotto-categorie non \u00E8 possibile procedere all\u00B4 eliminazione')};
			break;
		case 3:
			document.getElementById('linkDelete').onclick = function(){if (confirm('la categoria contiene prodotti che verranno disassociati confermi l\u00B4 eliminazione ?')) { location.href='categorie_elenco_elimina.php'+strGet; } else { return false; }};
			break;
	}
}

function SetNoneValueCategoria(){
	document.getElementById('linkEdit').onclick = function(){alert('Nessuna categoria selezionata');};
	document.getElementById('linkDelete').onclick = function(){alert('Nessuna categoria selezionata');};
	document.getElementById('linkCategories').onclick = function(){alert('Nessuna categoria selezionata');};
}

function SetValueIdProdotto(idProdotto, strGet){
	//if(checkBoxSelected != '')
		//document.getElementById(checkBoxSelected).checked = false;
	checkBoxSelected = 'selProdotto'+idProdotto;
	document.getElementById('linkCopy').onclick = function(){location.href='prodotti_clona.php'+strGet;};
	document.getElementById('linkPrices').onclick = function(){location.href='prodotti_attributi_check.php'+strGet+'&page=prezzi';};
	document.getElementById('linkStorage').onclick = function(){location.href='prodotti_attributi_check.php'+strGet+'&page=magazzino';};
	document.getElementById('linkView').onclick = function(){location.href='prodotti_attributi.php'+strGet;};
	document.getElementById('linkFavorites').onclick = function(){location.href='prodotti_preferiti_utenti.php'+strGet;};
	document.getElementById('linkFavorites').title = 'preferiti';
	document.getElementById('linkLanguages').onclick = function(){location.href='prodotti_lingue_testi.php'+strGet;};
	document.getElementById('linkAttachments').onclick = function(){location.href='prodotti_allegati.php'+strGet;};
	document.getElementById('linkCorrelates').onclick = function(){location.href='prodotti_correlati_elenco.php'+strGet;};
	document.getElementById('linkEdit').onclick = function(){location.href='prodotti_modifica.php'+strGet;};
	document.getElementById('linkDelete').onclick = function(){if (confirm('Confermi l\u00B4 eliminazione? Questa operazione non \u00E8 reversibile!')) { location.href='prodotti_elimina.php'+strGet; } else { return false; }};
}

function SetNoneValueProdotto(sessGet){
	document.getElementById('linkCopy').onclick = function(){alert('Nessun prodotto selezionato');};
	document.getElementById('linkPrices').onclick = function(){alert('Nessun prodotto selezionato');};
	document.getElementById('linkStorage').onclick = function(){alert('Nessun prodotto selezionato');};
	document.getElementById('linkView').onclick = function(){alert('Nessun prodotto selezionato');};
	document.getElementById('linkFavorites').onclick = function(){location.href='prodotti_preferiti_utenti.php'+sessGet;};
	document.getElementById('linkFavorites').title = 'tutti i preferiti';
	document.getElementById('linkLanguages').onclick = function(){alert('Nessun prodotto selezionato');};
	document.getElementById('linkAttachments').onclick = function(){alert('Nessun prodotto selezionato');};
	document.getElementById('linkCorrelates').onclick = function(){alert('Nessun prodotto selezionato');};
	document.getElementById('linkEdit').onclick = function(){alert('Nessun prodotto selezionato');};
	document.getElementById('linkDelete').onclick = function(){alert('Nessun prodotto selezionato');};
}

function SetValueIdGruppo(idGruppo, strSess){
	if(checkBoxSelected != '')
		document.getElementById(checkBoxSelected).checked = false;
	if(checkBoxSelected != 'selGruppo'+idGruppo)
	{
		checkBoxSelected = 'selGruppo'+idGruppo;
		document.getElementById('idGruppo').value = idGruppo;
		document.getElementById('linkModifica').onclick = function(){document.gruppi_mod.submit();};
		document.getElementById('linkUtenti').onclick = function(){location.href='gruppi_utenti.php?f402_id_gruppi_utenti='+idGruppo+'&amp;'+strSess;};
		document.getElementById('linkElimina').onclick = function(){if (confirm('Confermi l\u00B4 eliminazione ?')) {location.href='gruppi_elimina.php?f402_id_gruppi_utenti='+idGruppo+'&amp;'+strSess;} else {return false;}};
	}
	else
	{
		checkBoxSelected = '';
		document.getElementById('idGruppo').value = '';
		document.getElementById('linkModifica').onclick = '';
		document.getElementById('linkUtenti').onclick = function(){alert('Nessun gruppo selezionato');};
		document.getElementById('linkElimina').onclick = function(){alert('Nessun gruppo selezionato');};
	}
}

function SetValueIdMail(idMail, strSess){
	if(checkBoxSelected != '')
		document.getElementById(checkBoxSelected).checked = false;
	if(checkBoxSelected != 'selMail'+idMail)
	{
		checkBoxSelected = 'selMail'+idMail;
		document.getElementById('linkAdmin').onclick = function(){location.href="send_email.php?id_email="+idMail+"&gruppo=0&off_mail=0&"+strSess;};
		document.getElementById('linkUsers').onclick = function(){location.href="send_email.php?id_email="+idMail+"&gruppo=1&off_mail=0&"+strSess;};
		document.getElementById('linkModifica').onclick = function(){location.href="send_email_form.php?id_email="+idMail+"&"+strSess;};
		document.getElementById('linkElimina').onclick = function(){if (confirm('Confermi l\u00B4 eliminazione ?')) {location.href="send_email_elimina.php?id_email="+idMail+"&"+strSess;} else {return false}};
	}
	else
	{
		checkBoxSelected = '';
		document.getElementById('linkAdmin').onclick = function(){alert('Nessuna mail selezionata');};
		document.getElementById('linkUsers').onclick = function(){alert('Nessuna mail selezionata');};
		document.getElementById('linkModifica').onclick = function(){alert('Nessuna mail selezionata');};
		document.getElementById('linkElimina').onclick = function(){alert('Nessuna mail selezionata');};
	}
}

function EnabledTextBox(){
	blnUtenteRegistrato = document.getElementById('chkUtenteRegistrato').checked;
	txtUsername = document.getElementById('txtUsername');
	txtPassword = document.getElementById('txtPassword');
	lblUtenteRegistrato = document.getElementById('lblUtenteRegistrato');
	if(blnUtenteRegistrato){
		txtUsername.disabled = false;
		txtUsername.style.color = '#000000';
		txtPassword.disabled = false;
		txtPassword.style.color = '#000000';
		lblUtenteRegistrato.innerHTML = "Utente registrato";
	}else{
		txtUsername.disabled = true;
		txtUsername.style.color = '#ebe9d8';
		txtPassword.disabled = true;
		txtPassword.style.color = '#ebe9d8';
		lblUtenteRegistrato.innerHTML = "Utente non registrato";
	}
}

function SubmitUtente(){
	txtUsername = document.getElementById('txtUsername').value;
	txtPassword = document.getElementById('txtPassword').value;
	txtPasswordOld = document.getElementById('password_old').value;
	blnUtenteRegistrato = document.getElementById('chkUtenteRegistrato').checked;
	if(blnUtenteRegistrato){
		if(txtUsername == '' || (txtPassword == '' && txtPasswordOld == '')){
			alert('Per registrare un utente inserire Username e Password');
		}else{
			document.utente_modifica_profilo.submit();
		}
	}else{
		document.utente_modifica_profilo.submit();
	}
}

function SubmitPromo(intCase, idPromo){
	switch(intCase){
		case 1:
			document.getElementById('action').value = "insert";
			document.scegli_stato_promozioni.submit();
			break;
		case 2:
			document.getElementById('action').value = "update";
			document.getElementById('id_promo').value = idPromo;
			document.scegli_stato_promozioni.submit();
			break;
		case 3:
			document.getElementById('action').value = "delete";
			document.getElementById('id_promo').value = idPromo;
			document.scegli_stato_promozioni.submit();
			break;
	}
}

var testoInizialeRicerca = '';
function VerificaSelectProdotti(strNomeProdotto){
	if(strNomeProdotto.length < 3){
		NascondiProdottiCercati();
	}else if(strNomeProdotto.length >= 3){
		SelectProdotti(strNomeProdotto);
		return;
	}
	/*
	if(strNomeProdotto.length >= 1){
		if(strNomeProdotto != testoInizialeRicerca){
			testoInizialeRicerca = strNomeProdotto;
		}else{
			SelectProdotti(strNomeProdotto);
			return;
		}
		setTimeout("VerificaSelectProdotti('"+strNomeProdotto+"')", 30);
	}
	*/
}

function SelectProdotti(strNomeProdotto){
	// variabili di funzione
  var
    // assegnazione oggetto XMLHttpRequest
    ajax = assegnaXMLHttpRequest();

  // se l'oggetto XMLHttpRequest non è nullo
  if(ajax){

    // impostazione richiesta asincrona in GET
    // del file specificato
    ajax.open("post", "/ecommerce/admin/prodotti_correlati_check.php", true);
    ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded");
    ajax.setRequestHeader("connection", "close");

    // impostazione controllo e stato della richiesta
    ajax.onreadystatechange = function() {

      // verifica dello stato
      if(ajax.readyState === readyState.COMPLETATO) {
        // verifica della risposta da parte del server
        if(statusText[ajax.status] === "OK") {
          // operazione avvenuta con successo, ritorno al chiamante un ok / ko
          if (ajax.responseText != 'ko') {
          	/*restituzione corretta dell'html*/
          	VisualizzaProdottiCercati(ajax.responseText);
          } else {
          	alert('La ricerca del prodotto non sta avvenendo correttamente.');
          }
        }
      }
    }
  }
    // invio richiesta
   	ajax.send("f100_nome_prodotto="+strNomeProdotto);
}

function VisualizzaProdottiCercati(htmlToPaste){
	document.getElementById('resProdotti').style.display = '';
	document.getElementById('elenco_prodotti').innerHTML = htmlToPaste;
}

function NascondiProdottiCercati(){
	document.getElementById('elenco_prodotti').innerHTML = '';
	document.getElementById('resProdotti').style.display = 'none';
}

function SceltaProdottoCorrelato(idProdotto, nomeProdotto){
	document.getElementById('ricerca_prodotto').value = nomeProdotto;
	//document.getElementById('id_prodotti').value = idProdotto;
	arr_str_id = document.getElementById('id_prodotti').value;
	arr_id = arr_str_id.split(',');
	document.getElementById('id_prodotti').value = '';
	prodotto_selezionato = false;
	for(i = 0; i < arr_id.length; i++){
		if(arr_id[i] != ''){
			if(arr_id[i] == idProdotto)
				prodotto_selezionato = true;
			document.getElementById('id_prodotti').value += arr_id[i]+',';
		}
	}
	if(!prodotto_selezionato){
		document.getElementById('id_prodotti').value += idProdotto;
		document.getElementById('correlati_sel').innerHTML += '<div id="div_nome'+idProdotto+'" style="width:360px;float:left;border-bottom:1px solid #999999;clear:both;">'+nomeProdotto+'</div><div id="div_'+idProdotto+'" style="width:20px;float:left;"><img style="cursor:pointer" onclick="DeselezionaProdottoCorrelato('+idProdotto+', \''+nomeProdotto+'\')" src="/ecommerce/admin/img/ico_delete.png"  /></div>';
	}else{
		alert('Prodotto precedentemente selezionato');
	}
}

function DeselezionaProdottoCorrelato(idProdotto, nomeProdotto){
	arr_str_id = document.getElementById('id_prodotti').value;
	arr_id = arr_str_id.split(',');
	document.getElementById('id_prodotti').value = '';
	for(i = 0; i < arr_id.length; i++){
		if(arr_id[i] != ''){
			if(arr_id[i] != idProdotto)
				document.getElementById('id_prodotti').value += arr_id[i]+',';
		}
	}
	div_ico = document.getElementById('div_'+idProdotto);
	div_nome = document.getElementById('div_nome'+idProdotto);
	document.getElementById('correlati_sel').removeChild(div_ico);
	document.getElementById('correlati_sel').removeChild(div_nome);
}

// funzione usata per cambiare l'ordine delle categorie dalla pagine dell'elenco tramite le freccette
function SpostaCategoria(id_categoria, id_categoria_madre, flag){
	// variabili di funzione
  var
    // assegnazione oggetto XMLHttpRequest
    ajax = assegnaXMLHttpRequest();

  // se l'oggetto XMLHttpRequest non è nullo
  if(ajax){

    // impostazione richiesta asincrona in GET
    // del file specificato
    ajax.open("post", "/ecommerce/admin/cambia_ordine_categorie.php", true);
    ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded");
    ajax.setRequestHeader("connection", "close");

    // impostazione controllo e stato della richiesta
    ajax.onreadystatechange = function() {

      // verifica dello stato
      if(ajax.readyState === readyState.COMPLETATO) {
        // verifica della risposta da parte del server
        if(statusText[ajax.status] === "OK") {
          // operazione avvenuta con successo, ritorno al chiamante un ok / ko
          if (ajax.responseText == 'OK') {
          	/*Operazione andata a buon fine*/
			location.href = location.href;
          } else {
          	/*Errore*/
          	alert('Impossibile aggiornare le categorie.');
          }
        }
      }
    }
  }
    // invio richiesta
   	ajax.send("id_categoria="+id_categoria+"&id_categoria_madre="+id_categoria_madre+"&flag="+flag);
}

// funzione chiamata al cambio di stato dell'ordine per decidere se creare la riga di spedizione o cancellarla
function CheckSpedizione(id_stato_vecchio, id_prossimo_stato){
	// variabili di funzione
  var
    // assegnazione oggetto XMLHttpRequest
    ajax = assegnaXMLHttpRequest();

  // se l'oggetto XMLHttpRequest non è nullo
  if(ajax){

    // impostazione richiesta asincrona in GET
    // del file specificato
    ajax.open("post", "/ecommerce/admin/acquisti_riga_spedizione.php", true);
    ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded");
    ajax.setRequestHeader("connection", "close");

    // impostazione controllo e stato della richiesta
    ajax.onreadystatechange = function() {

      // verifica dello stato
      if(ajax.readyState === readyState.COMPLETATO) {
        // verifica della risposta da parte del server
        if(statusText[ajax.status] === "OK") {
          // operazione avvenuta con successo, ritorno al chiamante un ok / ko
          if (ajax.responseText != 'KO') {
          	/*Operazione andata a buon fine*/
			if(ajax.responseText == 'CREA'){
				document.cambia_stato_acquisti.riga_spedizione.value = 1; // riga spedizione da creare
			}else if(ajax.responseText == 'CANCELLA'){
				if(confirm('Sospendere la relativa spedizione ?')){
					document.cambia_stato_acquisti.riga_spedizione.value = 2; // riga spedizione da sospendere
				}
			}

			//alert(ajax.responseText);
			document.cambia_stato_acquisti.submit();

          } else {
          	/*Errore*/
          	alert('Errore nella gestione della riga di spedizione.');
          }
        }
      }
    }
  }
    // invio richiesta
   	ajax.send("id_stato_vecchio="+id_stato_vecchio+"&id_prossimo_stato="+id_prossimo_stato);
}

// funzione chiamata dal check-out per salvare il testo del pacchetto regalo
function SalvaPacchettoRegalo(id_acquisto, testo){
	// variabili di funzione
  var
    // assegnazione oggetto XMLHttpRequest
    ajax = assegnaXMLHttpRequest();

  // se l'oggetto XMLHttpRequest non è nullo
  if(ajax){

    // impostazione richiesta asincrona in GET
    // del file specificato
    ajax.open("post", "/ecommerce/check_out_pacchetto_regalo_salva.php", true);
    ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded");
    ajax.setRequestHeader("connection", "close");

    // impostazione controllo e stato della richiesta
    ajax.onreadystatechange = function() {

      // verifica dello stato
      if(ajax.readyState === readyState.COMPLETATO) {
        // verifica della risposta da parte del server
        if(statusText[ajax.status] === "OK") {
          // operazione avvenuta con successo, ritorno al chiamante un ok / ko
          if (ajax.responseText === 'OK') {
			document.metodo_pagamento.pacchetto_regalo_default.value = testo;
          } else {
          	/*Errore*/
          	alert('Errore nel salvataggio del testo del pacchetto regalo.');
          }
        }
      }
    }
  }
    // invio richiesta
   	ajax.send("id_acquisti="+id_acquisto+"&testo="+testo);
}

// funzione chiamata dal check-out per salvare le note per il venditore
function SalvaNoteVenditore(id_acquisto, testo){
	// variabili di funzione
  var
    // assegnazione oggetto XMLHttpRequest
    ajax = assegnaXMLHttpRequest();

  // se l'oggetto XMLHttpRequest non è nullo
  if(ajax){

    // impostazione richiesta asincrona in GET
    // del file specificato
    ajax.open("post", "/ecommerce/check_out_note_venditore_salva.php", true);
    ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded");
    ajax.setRequestHeader("connection", "close");

    // impostazione controllo e stato della richiesta
    ajax.onreadystatechange = function() {

      // verifica dello stato
      if(ajax.readyState === readyState.COMPLETATO) {
        // verifica della risposta da parte del server
        if(statusText[ajax.status] === "OK") {
          // operazione avvenuta con successo, ritorno al chiamante un ok / ko
          if (ajax.responseText === 'OK') {
			document.metodo_pagamento.note_venditore_default.value = testo;
          } else {
          	/*Errore*/
          	alert('Errore nel salvataggio delle note per il venditore.');
          }
        }
      }
    }
  }
    // invio richiesta
   	ajax.send("id_acquisti="+id_acquisto+"&testo="+testo);
}

// funzione chiamata al momento della stampa di un ordine
function AggiornaStampa(elenco){
	// variabili di funzione
  var
    // assegnazione oggetto XMLHttpRequest
    ajax = assegnaXMLHttpRequest();

  // se l'oggetto XMLHttpRequest non è nullo
  if(ajax){

    // impostazione richiesta asincrona in GET
    // del file specificato
    ajax.open("post", "/ecommerce/admin/aggiorna_stato_stampato.php", true);
    ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded");
    ajax.setRequestHeader("connection", "close");

    // impostazione controllo e stato della richiesta
    ajax.onreadystatechange = function() {

      // verifica dello stato
      if(ajax.readyState === readyState.COMPLETATO) {
        // verifica della risposta da parte del server
        if(statusText[ajax.status] === "OK") {
          // operazione avvenuta con successo, ritorno al chiamante un ok / ko
          if (ajax.responseText != 'OK') {
			alert('Errore nel salvataggio dello stato stampato.');
          }
        }
      }
    }
  }
    // invio richiesta
   	ajax.send("elenco="+elenco);
}

function ControllaCF(cf)
{
    var validi, i, s, set1, set2, setpari, setdisp;
    if( cf == '' )  return '';
    cf = cf.toUpperCase();
    if( cf.length != 16 )
        return false;
    validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    for( i = 0; i < 16; i++ ){
        if( validi.indexOf( cf.charAt(i) ) == -1 )
            return false;
    }
    set1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    set2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
    setpari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    setdisp = "BAKPLCQDREVOSFTGUHMINJWZYX";
    s = 0;
    for( i = 1; i <= 13; i += 2 )
        s += setpari.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
    for( i = 0; i <= 14; i += 2 )
        s += setdisp.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
    if( s%26 != cf.charCodeAt(15)-'A'.charCodeAt(0) )
        return false;
    return true;
}

function ControllaPIVA(pi)
{
	if( pi == '' )  return '';
	if( pi.length != 11 )
		return false;
	validi = "0123456789";
	for( i = 0; i < 11; i++ ){
		if( validi.indexOf( pi.charAt(i) ) == -1 )
			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) )
		return false;
	return true;
}

function IdentificaBrowser(){
	var BrowserDetect = {
		init: function () {
			this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
			this.version = this.searchVersion(navigator.userAgent)
				|| this.searchVersion(navigator.appVersion)
				|| "an unknown version";
			this.OS = this.searchString(this.dataOS) || "an unknown OS";
		},
		searchString: function (data) {
			for (var i=0;i<data.length;i++)	{
				var dataString = data[i].string;
				var dataProp = data[i].prop;
				this.versionSearchString = data[i].versionSearch || data[i].identity;
				if (dataString) {
					if (dataString.indexOf(data[i].subString) != -1)
						return data[i].identity;
				}
				else if (dataProp)
					return data[i].identity;
			}
		},
		searchVersion: function (dataString) {
			var index = dataString.indexOf(this.versionSearchString);
			if (index == -1) return;
			return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
		},
		dataBrowser: [
			{
				string: navigator.userAgent,
				subString: "Chrome",
				identity: "Chrome"
			},
			{ 	string: navigator.userAgent,
				subString: "OmniWeb",
				versionSearch: "OmniWeb/",
				identity: "OmniWeb"
			},
			{
				string: navigator.vendor,
				subString: "Apple",
				identity: "Safari",
				versionSearch: "Version"
			},
			{
				prop: window.opera,
				identity: "Opera",
				versionSearch: "Version"
			},
			{
				string: navigator.vendor,
				subString: "iCab",
				identity: "iCab"
			},
			{
				string: navigator.vendor,
				subString: "KDE",
				identity: "Konqueror"
			},
			{
				string: navigator.userAgent,
				subString: "Firefox",
				identity: "Firefox"
			},
			{
				string: navigator.vendor,
				subString: "Camino",
				identity: "Camino"
			},
			{		// for newer Netscapes (6+)
				string: navigator.userAgent,
				subString: "Netscape",
				identity: "Netscape"
			},
			{
				string: navigator.userAgent,
				subString: "MSIE",
				identity: "Explorer",
				versionSearch: "MSIE"
			},
			{
				string: navigator.userAgent,
				subString: "Gecko",
				identity: "Mozilla",
				versionSearch: "rv"
			},
			{ 		// for older Netscapes (4-)
				string: navigator.userAgent,
				subString: "Mozilla",
				identity: "Netscape",
				versionSearch: "Mozilla"
			}
		],
		dataOS : [
			{
				string: navigator.platform,
				subString: "Win",
				identity: "Windows"
			},
			{
				string: navigator.platform,
				subString: "Mac",
				identity: "Mac"
			},
			{
				   string: navigator.userAgent,
				   subString: "iPhone",
				   identity: "iPhone/iPod"
		    },
			{
				string: navigator.platform,
				subString: "Linux",
				identity: "Linux"
			}
		]
	};

	BrowserDetect.init();

	return BrowserDetect.browser;
}

function Stampa(){
	var browser = IdentificaBrowser();
	if(browser != 'Chrome'){
		window.print();
	}else{
		alert('Attenzione! Google Chrome ha noti problemi di stampa.\nSi consiglia di usare un altro browser.');
		return false;
	}
}
