/* Controlla se una stringa e' vuota o contiene caratteri non visibili come
 * lo spazio e il ritorno a capo.
 * Input:
 *   La stringa da controllare.
 * Output:
 *   true se la stringa e' vuota, false altrimenti.
 */
function stringa_vuota(s) {
	if (s.length == 0)
		return true;
	for (var i = 0; i < s.length; i++) {
		var c = s.charAt(i);
		if ((c != ' ') && (c != '\r') && (c != '\n') && (c != '\t'))
			return false;
	}
	return true;
}


/* Aggiunge un campo nascosto al form e non è già presente. */
function aggiungi_campo_form(f, nome, valore) {
	var presente = false;
	var child;

	child = f.firstChild;
	while (child != null) {
		if (child.name == nome) {
			presente = true;
			break;
		}
		child = child.nextSibling;
	}

	if (presente)
		return;

	var campo_form;

	if (ie) {
		campo_form = document.createElement("<INPUT TYPE=\"hidden\" NAME=\"" + nome + "\" VALUE=\"" + valore + "\" >");
	}
	else {
		campo_form = document.createElement("input");
		campo_form.setAttribute("type", "hidden");
		campo_form.setAttribute("name", nome);
		campo_form.setAttribute("value", valore);
	}

	f.appendChild(campo_form);
}


/* Aggiorna i valori di un form leggendoli dagli item specificati.
 * Input:
 *   f: Il form da aggiornare.
 *   prefisso:  Il prefisso dato agli ID degli item, ad esempio "utente_"
 *   campi: Un array con gli ID (a meno del prefisso) degli item.
 * Output:
 *   Nessuno.
 */
function aggiorna_campi_form(f, prefisso, campi) {
	for (var i = 0; i < campi.length; i++) {
		var item = document.getElementById(prefisso + campi[i]);
		if (item == null) {
			/*alert("campo assente: " + prefisso+campi[i]);*/
			continue;
		}

		var form_items = document.getElementsByName(campi[i]) || [];
		for (var j = 0; j < form_items.length; j++) {
			var fitem = form_items[j];

			if ((fitem == null) || (fitem.tagName.toLowerCase() != "input")) {
				// alert("campo form assente: " + campi[i]);
				continue;
			}

			if ((item.type.toLowerCase() == "checkbox") || (item.type.toLowerCase() == "radio")) {
				if (item.checked)
					fitem.value = "1";
				else
					fitem.value = "0";
			}
			else
				fitem.value = item.value;
		}
	}
}


function aggiungi_parametri_ajax(a, prefisso, campi) {
	for (var i = 0; i < campi.length; i++) {
		var item = document.getElementById(prefisso + campi[i]);
		if (item == null)
			continue;

		var valore = "";
		if ((item.type.toLowerCase() == "checkbox") || (item.type.toLowerCase() == "radio")) {
			if (item.checked)
				valore = "1";
			else
				valore = "0";
		}
		else
			valore = item.value;

		a.aggiungi_parametro(campi[i], valore);
	}
}


/* Controlla la correttezza dei valori in una serie di item.
 * Input:
 *   prefisso:  Il prefisso dato agli ID degli item, ad esempio "utente_"
 *   campi: Un array con gli ID (a meno del prefisso) degli item da controllare.
 *   nomi_campi: Un array con i nomi descrittivi degli item.
 *   scheda_campi: (opzionale) il numero di scheda in cui si trova il campo
 * Output:
 *   TRUE se i valori dei campi sono corretti, FALSE altrimenti.
 */
function controlla_campi(prefisso, campi, nomi_campi, scheda_campi) {
	if (typeof nomi_campi == "undefined")
		nomi_campi = campi;
	if (typeof scheda_campi == "undefined")
		scheda_campi = null;
	for (var i = 0; i < campi.length; i++) {
		var item = document.getElementById(prefisso+campi[i]);
		if ((item == null) || (item.name == null) || (item.name == ""))
			continue;

		if (item.name.indexOf("*") != -1)
			if (stringa_vuota (item.value)) {
				if (scheda_campi != null)
					mostra_vtab(scheda_campi[i]);
				item.focus();
				alert("Il campo " + nomi_campi[i] + " e' obbligatorio");
				return false;
			}

		if (item.value == "")
			continue;

		if (item.name.indexOf("U") != -1)
			item.value = item.value.toUpperCase();

		if (item.name.indexOf("E") != -1)
			item.value = item.value.replace(/"/g, "&quot;");

		var a_codice = [
                        "_id",            "^[a-z0-9]*$",                                          " puo' contenere solo numeri e lettere",
                        "aa",             "^[a-z]*$",                                             " puo' contenere solo lettere",
                        "an",             "^[a-z0-9()' _]*$",                                     " puo' contenere solo numeri, lettere, lo spazio e i caratteri: ( ) _ '",
                        "nn",             "^[0-9]*$",                                             " puo' contenere solo numeri",
                        "euro",           "^[0-9\.]*$",                                           " non contiene un valore corretto",
                        "tel",            "^[0-9 /-]*$",                                          " puo' contenere solo numeri e i caratteri: / -",
                        "c.a.p.",         "^[0-9]{5}$",                                           " non contiene un c.a.p. corretto",
                        "e-mail",         "^[a-z0-9._%-]+@[a-z0-9.-]+\.[a-z]{2,4}$",              " non contiene un indirizzo e-mail corretto",
                        "codice_fiscale", "^[A-Z]{6}[A-Z0-9]{10}$",                               " non contiene un codice fiscale corretto",
                        "nomefile",       "^[A-Za-z0-9_\.]+$",                                    " non contiene un nome di file corretto"
                       ];

		for (var k = 0; k < a_codice.length; k = k + 3)  {
			if (item.name.indexOf(a_codice[k]) != -1) {
				var reg = new RegExp(a_codice[k + 1], "i");
				if (!item.value.match(reg)) {
					if (scheda_campi != null)
						mostra_vtab(scheda_campi[i]);
					item.focus();
					alert("Il campo " + nomi_campi[i] + a_codice[k + 2]);
					return false;
				}
			}
		}
	}
	return true;
}


// Ritorna la data attuale nel formato YYYY-MM-DD
function oggi(d) {
	if (typeof d == "undefined")
		d = new Date();
	var y = d.getFullYear();
	var m = d.getMonth() + 1;
	if (m < 10)
		m = "0" + m;
	var d = d.getDate();
	if (d < 10)
		d = "0" + d;
	return  y + "-" + m + "-" + d;
}


function oggi_anno(d) {
	if (typeof d == "undefined")
		d = new Date();
	return d.getFullYear();
}


// Ritorna l'ora attuale nel formato HH:MM:SS
function ora(d) {
	if (typeof d == "undefined")
		d = new Date();
	var h = d.getHours();
	var m = d.getMinutes();
	var s = d.getSeconds();
	if (h < 10)
		h = "0" + h;
	if (m < 10)
		m = "0" + m;
	if (s < 10)
		s = "0" + s;
	return  h + ":" + m + ":" + s;
}


function valore_data(id_controllo) {
	var o_anno = document.getElementById(id_controllo + "_anno");
	if (o_anno == null)
		return "";
	var anno = o_anno.value;
	var mese = document.getElementById(id_controllo + "_mese").value;
	var giorno = document.getElementById(id_controllo + "_giorno").value;
	if (anno == "" || mese == "" || giorno == "")
		return "";
	else
		return anno + "-" + mese + "-" + giorno;
}


function imposta_data(id_controllo, valore) {
	if (valore == "oggi")
		valore = oggi();
	var s_g = valore.substr(8, 2);
	var s_m = valore.substr(5, 2);
	var s_a = valore.substr(0, 4);
	document.getElementById(id_controllo + "_giorno").value = s_g;
	document.getElementById(id_controllo + "_mese").value = s_m;
	document.getElementById(id_controllo + "_anno").value = s_a;
}


function valore_ora(id_controllo) {
	var hh = document.getElementById(id_controllo + "_hh").value;
	var mm = document.getElementById(id_controllo + "_mm").value;
	var ss = document.getElementById(id_controllo + "_ss");
	if (ss == null)
		ss = "00";
	else
		ss = ss.value;
	if (hh == "" || mm == "" || ss == "")
		return "";
	else
		return hh + ":" + mm + ":" + ss;
}


function imposta_ora(id_controllo, valore) {
	if (valore == "ora")
		valore = ora();
	var hh = valore.substr(0, 2);
	var mm = valore.substr(3, 2);
	var ss = valore.substr(5, 2);
	document.getElementById(id_controllo + "_hh").value = hh;
	document.getElementById(id_controllo + "_mm").value = mm;
	var o_ss = document.getElementById(id_controllo + "_ss");
	if (o_ss != null)
		o_ss.value = ss;
}


function valore_radio(nome_gruppo) {
	var aInput = document.getElementsByName(nome_gruppo);
	for (var i = 0; i < aInput.length; i++) {
		var oInput = aInput[i];
		if (oInput.checked)
			return oInput.value;
	}
	return '';
}


function con_zero_iniziale(v) {
	if (v < 10)
		return "0" + v;
	else
		return v;
}


function controllo_data(id, data, inizio, fine, onchange) {
	if (typeof inizio == "undefined")
		inizio = 1930;
	if (typeof fine == "undefined")
		fine = 2005;
	if (typeof onchange == "undefined")
		onchange = "";

	var a_data = [ '', '', '' ];
	if (data != "") {
		a_data = data.split('-');
		for (var i = 0; i < a_data.length; i++)
			a_data[i] = parseInt(a_data[i]);
	}

	if (onchange != "")
		onchange = "onchange=\"" + onchange + "\"";

	var h = new Array();
	h.push("<select id=\"" + id + "_giorno\" " + onchange + ">");
	h.push("  <option value=\"\"> -- </option>");
	for (var d = 1; d <= 31; d++) {
		var opt = "<option value=\"" + con_zero_iniziale(d) + "\"";
		if (a_data[2] == d)
			opt += " selected=\"selected\"";
		opt += ">" + con_zero_iniziale(d) + "</option>";
		h.push(opt);
	}
	h.push("</select> ");

	h.push("<select id=\"" + id + "_mese\" " + onchange + ">");
	h.push("  <option value=\"\"> -- </option>");
	for (var d = 1; d <= 12; d++) {
		var opt = "<option value=\"" + con_zero_iniziale(d) + "\"";
		if (a_data[1] == d)
			opt += " selected=\"selected\"";
		opt += ">" + con_zero_iniziale(d) + "</option>";
		h.push(opt);
	}
	h.push("</select> ");

	h.push("<select id=\"" + id + "_anno\" " + onchange + ">");
	h.push("  <option value=\"\"> ---- </option>");
	for (var d = inizio; d <= fine; d++) {
		var opt = "<option value=\"" + con_zero_iniziale(d) + "\"";
		if (a_data[0] == d)
			opt += " selected=\"selected\"";
		opt += ">" + con_zero_iniziale(d) + "</option>";
		h.push(opt);
	}
	h.push("</select> ");

	return h.join("\n");
}


function aggiorna_select_valori(id, a_oggetti, valore_vuoto) {
	if (typeof valore_vuoto == "undefined")
		valore_vuoto = "( scegli )";

	var o_select = document.getElementById(id);
	var a_id = [];
	var a_valori = [];
	var selezionato = null;
	for (var i = 0; i < a_oggetti.length; i++) {
		var oggetto = a_oggetti[i];
		if (oggetto == null)
			continue;
		if (oggetto.attivo == "1")
			selezionato = a_oggetti[i].id;
		a_id.push(a_oggetti[i].id);
		a_valori.push(a_oggetti[i].nome);
	}
	if (selezionato == null) {
		selezionato = parseInt(o_select.value);
		if (isNaN(selezionato))
			selezionato = null;
	}
	imposta_lista_select(o_select, a_id, a_valori, selezionato, valore_vuoto);
}


function memorizza_valore_associato_da_select(id, a_oggetti) {
	var o_select = document.getElementById(id);
	var selezionato = o_select.value;
	for (var i = 0; i < a_oggetti.length; i++) {
		var oggetto = a_oggetti[i];
		if (oggetto == null)
			continue;
		oggetto.attivo = (oggetto.id == selezionato) ? "1" : "0";
	}
}


function distanza_giorni_aggiorna_data(o_input) {
	var n_giorni = parseInt(o_input.value);
	if (isNaN(n_giorni))
		n_giorni = 0;
	o_input.value = n_giorni;

	var id_controllo_data = o_input.id.substr(0, o_input.id.length - "_n_giorni".length);
	var nuova_data = new Date(new Date().getTime() + (n_giorni * (1000 * 60 * 60 * 24)));
	imposta_data(id_controllo_data, oggi(nuova_data));
}


function distanza_giorni_aggiorna_da_data(id_controllo_data) {
	var d = new Date();
	d.setFullYear(parseInt(document.getElementById(id_controllo_data + "_anno").value, 10),
		      parseInt(document.getElementById(id_controllo_data + "_mese").value, 10) - 1,
		      parseInt(document.getElementById(id_controllo_data + "_giorno").value, 10));
	d.setHours(0);
	d.setMinutes(0);
	d.setSeconds(0);
	d.setMilliseconds(0);

	var o = new Date();
	o.setHours(0);
	o.setMinutes(0);
	o.setSeconds(0);
	o.setMilliseconds(0);

	var n_giorni = parseInt(Math.floor((d.getTime() - o.getTime()) / (1000 * 60 * 60 * 24)), 10);
	if (! isNaN(n_giorni))
		document.getElementById(id_controllo_data + "_n_giorni").value = n_giorni;
	else
		document.getElementById(id_controllo_data + "_n_giorni").value = "";
}


function get_attribute(o, a) {
	if (!ie)
		return o.getAttribute(a);
	for (var i = 0; i < o.attributes.length; i++)
		if (o.attributes[i].nodeName.toLowerCase() == a)
			return o.attributes[i].nodeValue;
}


function disabilita_campo(id, v) {
	var o = document.getElementById(id);
	if (o == null)
		return;
	o.disabled = v;
	var labels = document.getElementsByTagName("label");
	if (labels == null)
		return;
	for (var i = 0; i < labels.length; i++) {
		var o_label = labels[i];
		if (get_attribute(o_label, "for") == id) {
			o_label.className = v ? "disabled" : "";
			break;
		}
	}
}


function modifica_valori(tipo_oggetto) {
	apri_dialogo_html("/amministrazione/modifica_elenco_valori/" + tipo_oggetto + ".htpl", 400, 500, tipo_oggetto);
	return false;
}


function onchange_elenco_predefiniti(s, id_input) {
	var v = s.value;
	if (v != "")
		document.getElementById(id_input).value = v;
	s.value = "";
}

