﻿
//per aprire le popup di inserimento/modifica
function Apri(w, h, pagina, nome) {
    if (!nome) nome = '_blank';
    var pp = window.open(pagina, nome, 'width=' + w + ',height=' + h + ',resizable=1, scrollbars=1, status=1');
    pp.focus();
}

function PopupCentrata(url,nome,w,h,parametri) {
    var ax = window.screenLeft;
    var ay = window.screenTop;
    var aw = window.document.body.offsetWidth;
    var ah = window.document.body.offsetHeight;
    var x = ax + Math.round((aw - w) / 2);
    var y = ay + Math.round((ah - h) / 2) - 100;
    if (y < 10) y = 30;
    var xparametri = 'width=' + w + ',height=' + h + ',top=' + y + ',left=' + x;
    if (parametri) xparametri = parametri + ',' + xparametri;
    var pp = window.open('about:blank', '_blank', xparametri);
    return pp
}

function CaricaPaginaGet(pagina, dati, target, funzioneOnSuccess) {
	//debug(pagina);
	var req = new Request({
		url: pagina,
		method: 'get',
		data: dati,
		noCache: true,
		autoCancel: true,
		onSuccess: function(responseText, responseXML) {
			//debug(responseText);
			//debug(target+'<br>'+dati);
			if (target) {
				if ($(target)) $(target).innerHTML = responseText;
			}
			if (funzioneOnSuccess) setTimeout(funzioneOnSuccess, 1);
		},
		onFailure: function(xhr) {
			if (target != '') {
				if ($(target)) $(target).innerHTML = '<b>ERRORE:</b>' + xhr.responseText;
			}
			debug('<b>ERRORE:</b>' + xhr.responseText);
		}
	}).send();
}

function CaricaHTML(pagina, target, method, dati, funzioneOnSuccess) {
	if (!method) method = 'get';
	if (!dati) dati = '';
	var req = new Request({
		url: pagina,
		method: method,
		data: dati,
		noCache: true,
		autoCancel: true,
		onSuccess: function(responseText, responseXML) {
			if (target) {
				if ($(target)) $(target).innerHTML = responseText;
			}
			if (funzioneOnSuccess) setTimeout(funzioneOnSuccess, 1);
		},
		onFailure: function(xhr) {
			if (target != '') {
				if ($(target)) $(target).innerHTML = '<b>ERRORE:</b>' + xhr.responseText;
			}
		}
	}).send();
}

function SoloNumeri(evt) {
	var charCode = (evt.which) ? evt.which : event.keyCode;
	return (charCode >= 48 && charCode <= 57)
}


function strEuro(numero) {
	return numero.format({ decimal: ".", decimals: 2, group: "" });
}

function dataValida(txt) {
	var re = /^\d{1,2}[\/\.-]\d{1,2}[\/\.-]\d{4}$/
	if (re.test(txt)) {
		var xtxt = txt.replace(/[\.-]/g, '/');
		var adata = xtxt.split('/');
		var gg = parseInt(adata[0], 10);
		var mm = parseInt(adata[1], 10);
		var aaaa = parseInt(adata[2], 10);
		var xdata = new Date(aaaa, mm - 1, gg)
		if ((xdata.getFullYear() == aaaa) && (xdata.getMonth() == mm - 1) && (xdata.getDate() == gg))
			return xdata
		else return false
	} else return false
}

// funzione di controllo FORMCHECK personalizzata per la data
function dateCheck(el) {
    if (!el.value.test(/^((((0?[1-9]|[12][\d]|3[01])\/(0?[13578]|10|12)\/(\d{4}))|((0?[1-9]|[12][\d]|30)\/(0?[469]|11)\/(\d{4}))|((0?[1-9]|1[\d]|2[0-8])\/(0?2)\/(\d{4}))|((29)\/(0?2)\/([02468][048]00))|((29)\/(0?2)\/([13579][26]00))|((29)\/(0?2)\/([\d][\d]0[48]))|((29)\/(0?2)\/([\d][\d][2468][048]))|((29)\/(0?2)\/([\d][\d][13579][26]))))?$/)) {
        el.errors.push("La data deve essere in formato GG/MM/AAAA");
        return false;
    } else {
        return true;
    }
}
// funzione di controllo FORMCHECK personalizzata per numeri con la virgola, si può usare come separatore sia il punto che la virgola
function numeroDecimale(el) {
    if (!el.value.test(/^(\d+([\.\,]\d+)?)?$/)) {
        el.errors.push("numeri");
        return false;
    } else {
        return true;
    }
}

// funzione di salvataggio form
function SalvaForm(ff, url) {
    // visualizzo il messaggio di salvataggio in corso
    $('boxSalva').setStyle('opacity', 0);
    $('boxSalva').setStyle('display', 'block');
    $('boxSalvaAct').setStyle('opacity', 0);
    $('boxSalvaAct').setStyle('display', 'block');
    $('boxSalva').morph({ 'opacity': 0.9 }, { duration: '1000' });
    $('boxSalvaAct').morph({ 'opacity': 1 }, { duration: '1000' });
    $('boxSalvaAct').set('html', '<img src="/img/progress.gif" alt="progress" /><br /><br />Salvataggio in corso...');

    var req = new Request({
    	url: url,
    	method: 'post',
    	noCache: true,
    	data: leggiFormEscape(ff.id),
    	autoCancel: true,
    	onSuccess: function(responseText, responseXML) {
    		//debug(responseText);
    		responseXML = responseXML.documentElement;
    		if (responseXML != null) {
    			// leggo la variabile "reload" - se 1 faccio il reload della pagina sottostante
    			var reload = responseXML.getElementsByTagName("reload")[0].childNodes[0].nodeValue + '';
    			if (reload == '1') {
    				if (window.opener) window.opener.location.reload();
    			}
    			
    			// leggo le variabili "var" - se presenti nel form imposto i valori corrispondenti
    			var valori = responseXML.getElementsByTagName("var");
    			for (i = 0; i < valori.length; i++) {
    				var nomeinput = valori[i].attributes.getNamedItem("name").nodeValue;
    				var valoreinput = '';
    				if (valori[i].childNodes[0]) valoreinput = valori[i].childNodes[0].nodeValue;
    				if (ff.elements[nomeinput]) {
    					ff.elements[nomeinput].value = valoreinput;
    				}
    			}
    		}

    		// nascondo il messaggio di salvataggio effettuato
    		var fx = new Fx.Morph($('boxSalva'), { duration: 1500, transition: Fx.Transitions.Quart.easeOut });
    		fx.start({
    	}).chain(function() {
    		this.start.delay(1500, this, { 'opacity': 0 });
    	}).chain(function() {
    		$('boxSalva').style.display = 'none';
    		this.start.delay(0100, this, { 'opacity': 1 });
    	});

    	var fx2 = new Fx.Morph($('boxSalvaAct'), { duration: 1500, transition: Fx.Transitions.Quart.easeOut });
    	fx2.start({
    }).chain(function() {
    	$('boxSalvaAct').set('html', '<img src="/img/ok.png" alt="ok" /><br /><br />Dati salvati!');
    	this.start.delay(1500, this, { 'opacity': 0 });
    }).chain(function() {
    	$('boxSalvaAct').style.display = 'none';
    	this.start.delay(0100, this, { 'opacity': 1 });
    });
    if (typeof (afterSave) == 'function') {
    	afterSave();
    }

   },
   onFailure: function(xhr) {

   	debug(xhr.responseText);

   	// nascondo il messaggio di errore
   	var fx = new Fx.Morph($('boxSalva'), { duration: 1500, transition: Fx.Transitions.Quart.easeOut });
   	fx.start({
   }).chain(function() {
   	this.start.delay(3500, this, { 'opacity': 0 });
   }).chain(function() {
   	$('boxSalva').style.display = 'none';
   	this.start.delay(0100, this, { 'opacity': 1 });
   });

   var fx2 = new Fx.Morph($('boxSalvaAct'), { duration: 1500, transition: Fx.Transitions.Quart.easeOut });
   fx2.start({
  }).chain(function() {
  	$('boxSalvaAct').set('html', '<img src="/img/ko.png" alt="ko" /><br /><br />Si è verificato un errore.<br />I dati non sono stati salvati.');
  	this.start.delay(3500, this, { 'opacity': 0 });
  }).chain(function() {
  	$('boxSalvaAct').style.display = 'none';
  	this.start.delay(0100, this, { 'opacity': 1 });
  });
 }
}).send();
}

function urlEncode(str){
	str = escape(str).replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\\/g, '%2F').replace(/@/g, '%40')
	return str;
}


//funzione che passato l'id di un form ne restituisce il valore degli elementi come se inviato con un get
function leggiFormEscape(id){
	var ff = $(id);
	var str = '';
	var valore = '';
	var sep = '';
	for (i = 0; i < ff.elements.length; i++) {
		valore = LeggiValoreCampo(ff.elements[i]);
		if (!(ff.elements[i].type == 'checkbox' && valore == '')) {
			str += sep + ff.elements[i].name + '=' + urlEncode(valore);
			sep = '&';
		}
	}
	return str;
}

function leggiForm(id) {
	var ff = $(id);
	var str = '';
	var valore = '';
	var sep = '';
	for (i = 0; i < ff.elements.length; i++) {
		valore = LeggiValoreCampo(ff.elements[i]);
		if (!(ff.elements[i].type == 'checkbox' && valore == '')) {
			str += sep + ff.elements[i].name + '=' + valore;
			sep = '&';
		}
	}
	return str;
}

function LeggiValoreCampo(obj) {
    var xvalore, valore = obj.value;
    var ff = obj.form;

    if (obj.type == 'hidden') {
        valore = obj.value;
    }

    if (obj.type == 'radio') {
        var rr = ff.elements[obj.name]
        if (rr.length) {
            for (var i = 0; i < rr.length; i++)
                if (rr[i].checked) xvalore = rr[i].value;
                if (xvalore != '')
                    valore = xvalore;
                else
                    valore = '';
        } else {
        if (obj.checked)
            valore = obj.value;
        else
            valore = '';
        }
    }
    if (obj.type == 'checkbox') valore = (obj.checked ? obj.value : '');
    if (obj.type == 'select-one') {
        if (obj.options.length)
            valore = obj.options[obj.selectedIndex].value;
        else
            valore = '';
    }
    //alert(obj.name+' '+valore)
    return valore
}

function HTMLEncode(str) {
    var div = document.createElement('div');
    var text = document.createTextNode(str);
    div.appendChild(text);
    text = div.innerHTML;
    text = str;
    text = text.replace(/\"/g, "&quot;");

    // Lettere accentate ------------- 
    text = text.replace(/à/g, "&agrave;");
    text = text.replace(/è/g, "&egrave;");
    text = text.replace(/é/g, "&eacute;");
    text = text.replace(/ì/g, "&igrave;");
    text = text.replace(/ù/g, "&ugrave;");
    text = text.replace(/ò/g, "&ograve;");
    //--------------------------------
    //-------Fix Safari problem-------
    text = text.replace(/</g, "&lt;");
    text = text.replace(/>/g, "&gt;");
    //--------------------------------
    return text;
}

function debug(str) {
	if ($('divDebug')) {
		var txt = $('divDebug').innerHTML;
		if (txt != '') txt += '<br />'
		$('divDebug').innerHTML = txt + (new Date()).toLocaleTimeString() + ' | ' + str;
	}
}

function NoTagAndSpace(html) {
	var str = html.replace(/<\/?[^>]+(>|$)/g, '');
	str = str.replace(/[ ]{2,}/g, '');
	str = str.replace(/\t*/g, '');

	str = str.replace(/&quot;/g, '"');

	// Lettere accentate -------------
	str = str.replace(/&agrave;/g, 'à');
	str = str.replace(/&egrave;/g, 'è');
	str = str.replace(/&eacute;/g, 'é');
	str = str.replace(/&igrave;/g, 'ì');
	str = str.replace(/&ugrave;/g, 'ù');
	str = str.replace(/&ograve;/g, 'ò');
	// Minore / maggiore -------------
	str = str.replace(/&lt;/g, "<");
	str = str.replace(/&gt;/g, ">");
	
	return str;
}

function CheckAll(selettore,checked) {
	if (checked == undefined) checked = event.srcElement.checked;
	$$(selettore).each(function(el) { if (el.type == 'checkbox') el.checked = checked });
}

function upload(percorso, subFolders, strJs, strFileType) {
	if (!strJs) strJs = '';
	if (!strFileType) strFileType = '';
	pp = window.open('/file_manager/upload.aspx?CreateSubFolders=' + subFolders + '&RootFolder=' + percorso + '&strJs=' + strJs + '&strFileType=' + strFileType, 'Upload', 'width=750,height=550,scrollbars=0,resizable=1')
	pp.focus();
}

function EstendiSessione() {
	var req = new Request({
		url: '/mngarea/EstendiSessione.asp',
		method: 'get',
		noCache: true,
		autoCancel: true
	}).send();
}


