//
// AJAX
//
function requestHtml(action, params, f) {
    var url = formatUrl(action, params);
    var httpRequest;
    if (window.XMLHttpRequest) {
        // Mozilla, Safari, ...
        httpRequest = new XMLHttpRequest();
        if (httpRequest.overrideMimeType) httpRequest.overrideMimeType('text/xml');
    } else if (window.ActiveXObject) {
        // IE
        try {
            httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) { }
        }
    }
    if (httpRequest) {
        httpRequest.onreadystatechange = function() {
            if (httpRequest.readyState == 4 && httpRequest.status == 200) f(httpRequest.responseText);
        };
        httpRequest.open('GET', url, true);
        httpRequest.send(null);
    }
}
function ajaxRequest(action, params, f) { 
    requestHtml(action, params, f);
}
function formatUrl(action, params) {
    var url = phpmain + ".php?action=" + action;
    if (params) url += "&" + params;
    return url;
}
function gotoAction(action, params, popup) {
    if (popup == 1) window.open(formatUrl(action, params));
    else window.location = formatUrl(action, params);
}
function submitAction(action) {
    if (typeof(ajaxStartWait) !== "undefined") ajaxStartWait();
    var form = window.document.forms[0];
    form.action.value = action;
    form.submit();
}
function onSubmitAction(form) { 
    return (form.action.value != "");
}
//
// DATE
//
var calendarDateShortName = "";
var calendarDate = getCurrentDate();
var calendarDayClick = "";
var calendarSelStart = calendarDate;
var calendarSelEnd = calendarDate;
var calendarSelDow = [1,1,1,1,1,1,1];
var monthNames = ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"];
function displayCalendar() {
    // oggi
    var today = getCurrentDate();
    // giorni del mese precedente
    var firstDay = new Date(calendarDate.getFullYear(), calendarDate.getMonth(), 1);
    var w = firstDay.getDay();
    if (w != 1) firstDay.setDate(firstDay.getDate() - (w > 0 ? w - 1 : 6));
    // giorni del mese successivo
    var lastDay = new Date(calendarDate.getFullYear(), calendarDate.getMonth() + 1, 0);
    w = lastDay.getDay();
    if (w != 0) lastDay.setDate(lastDay.getDate() + 7 - w);
    // html calendario
    var html = '<table class="calendar">';
    html += '<tr class="month"><td><img class="link" src="/condiviso/images/sx.gif" onclick="onClickCalendarPrev()" /></td>';
    html += '<td colspan="5">' + monthNames[calendarDate.getMonth()] + " " + calendarDate.getFullYear() + '</td>';
    html += '<td><img class="link" src="/condiviso/images/dx.gif" onclick="onClickCalendarNext()" /></td></tr>';
    html += '<tr class="dow"><td>L</td><td>M</td><td>M</td><td>G</td><td>V</td><td>S</td><td>D</td></tr>';
    // crea tabella giorni
    while (firstDay.getTime() <= lastDay.getTime()) {
        // nuova riga
        w = firstDay.getDay();
        if (w % 7 == 1) html += '</tr><tr class="day">';
        // aggiunge td per il giorno
        html += '<td class="';
        html += (firstDay >= today) ? "active" : "old";
        if (firstDay >= calendarSelStart && firstDay <= calendarSelEnd && calendarSelDow[w])
            html += " selected";
        html += '"';
        // evento click sul giorno
        var clickDate = dateObject2dateString(firstDay);
        html += " onclick=\"onClickCalendarDay('" + clickDate + "')\"";
        html += '>' + firstDay.getDate() + '</td>';
        // prossimo giorno
        firstDay.setDate(firstDay.getDate() + 1);
    }
    html += "</table>";
    // visualizza calendario
    return html;
}
function onClickCalendarDay(value) {
    updateDateShortValue(calendarDateShortName, dateString2dateObject(value));
    onChangeDateShort(calendarDateShortName, calendarDayClick);
    var div = document.getElementById("calendar");
    if (div) div.style.display = "none";
}
function onClickCalendarNext() {
    var div = document.getElementById("calendar");
    if (div) {
        calendarDate.setDate(1);
        calendarDate.setMonth(calendarDate.getMonth() + 1);
        div.innerHTML = displayCalendar();
    }
}
function onClickCalendarPrev() {
    var div = document.getElementById("calendar");
    if (div) {
        calendarDate.setDate(1);
        calendarDate.setMonth(calendarDate.getMonth() - 1);
        div.innerHTML = displayCalendar();
    }
}
function displayCalendarSimple(sender, name, func) {
    var div = document.getElementById("calendar");
    if (div == null) {
        div = document.createElement("div");
        div.setAttribute("id", "calendar");
        document.body.appendChild(div);
        div.style.position = "absolute";
        div.style.background = "#FFFFFF";
        div.style.padding = "0";
        div.style.zIndex = "1000";
    }
    if (calendarDateShortName == name && div.style.display == "block") {
        // nascondi
        div.style.display = "none";
    } else {
        // posiziona
        var pos = getAbsolutePosition(sender);
        div.style.display = "block";
        div.style.top = (pos.y + sender.offsetHeight + 2) + "px";
        div.style.left = (pos.x) + "px";
        // visualizza calendario
        var value = getDateShortValue(name);
        var anno = new Date(2009, 1, 1);
        calendarDateShortName = name;
        calendarDate = value < anno ? getCurrentDate() : value;
        calendarDayClick = func;
        calendarSelStart = calendarDate;
        calendarSelEnd = calendarDate;
        div.innerHTML = displayCalendar();
    }
}
function dateDiff(dataa, datab) {
    var diffMilli = dataa.getTime()-datab.getTime()
    divisore = 86400000
    return Math.round(diffMilli/divisore)
}
function getDateControlValue(frm, prefix, name) {
    if (!frm) frm = window.document.forms[0];
    var y = frm[prefix + '_y_' + name].value;
    var m = frm[prefix + '_m_' + name].value;
    var d = frm[prefix + '_d_' + name].value;
    if (y > 0 && m > 0 && d > 0) {
        m = parseInt((m.substring(0, 1) == "0") ? m.substring(1) : m);
        d = parseInt((d.substring(0, 1) == "0") ? d.substring(1) : d);
        return new Date(y, m - 1, d);
    }
    else return null;
}
function getDateShortValue(name, frm) { 
    return getDateControlValue(frm, 'dateShort', name);
}
function updateDateShortValue(n, v, frm) {
    if (!frm) frm = window.document.forms[0];
    var yd = v.getFullYear();
    var md = v.getMonth() + 1;
    if (md < 10) md = "0" + md;
    var gd = v.getDate();
    if (gd < 10) gd = "0" + gd;
    frm['dateShort_y_' + n].value = yd;
    frm['dateShort_m_' + n].value = md;
    frm['dateShort_d_' + n].value = gd;
    var h = frm[n];
    h.value = yd + '-' +  md + '-' + gd;
}
function setDateShortValue(name, frm) {
    if (!frm) frm = window.document.forms[1];
    var y = frm['dateShort_y_' + name].value;
    var m = frm['dateShort_m_' + name].value;
    var d = frm['dateShort_d_' + name].value;
    var h = frm[name];
    h.value = y + '-' +  m + '-' + d;
}
function clearDateShortValue(name, frm) {
    if (!frm) frm = window.document.forms[0];
    frm[name].value = '0000-00-00';
    frm['dateShort_y_' + name].value = '0000';
    frm['dateShort_m_' + name].value = '00';
    frm['dateShort_d_' + name].value = '00';
}
function onChangeDateShort(name, func, frm) {
    if (!frm) frm = window.document.forms[0];
    var data = getDateShortValue(name, frm);
    if (data != null) updateDateShortValue(name, data, frm);
    else frm[name].value = '0000-00-00';
    if (arguments.length > 1 && self[func] != null) eval(func + '()');
}
function toDateYmd(name, frm) {
    if (!frm) frm = window.document.forms[0];
    var h = frm[name].value;
    var y = h.substr(0, 4);
    var m = h.substr(5, 2);
    var d = h.substr(8, 2);
    return y + m + d;
}
function fromDateToYmd(v) {
    var yd = v.getFullYear();
    var md = v.getMonth() + 1;
    if (md < 10) md = "0" + md;
    var gd = v.getDate();
    if (gd < 10) gd = "0" + gd;
    return yd + "" + md + "" + gd;
}
function onChangeOra(n) {
    var a = window.document.getElementById(n);
    var b = window.document.getElementById(n + "_ora");
    var c = window.document.getElementById(n + "_min");
    a.value = b.value + ":" + c.value;
}
function datestring2ymd(v) {
    if (v.length < 10) return "        ";
    else {
        var d = v.substring(0, 2);
        var m = v.substring(3, 5);
        var y = v.substring(6, 10);
        return y + m + d;
    }
}
function getCurrentDate() {
    var today = new Date();
    today.setHours(0);
    today.setMinutes(0);
    today.setSeconds(0);
    today.setMilliseconds(0);
    return today;
}
function dateString2dateObject(v) {
    if (v.length < 10) return new Date()
    else {
        var d = v.substring(0, 2);
        var m = v.substring(3, 5) - 1;
        var y = v.substring(6, 10);
        return new Date(y, m, d);
    }
}
function dateObject2dateString(d) {
    var cd = d.getDate();
    var cm = (d.getMonth() + 1);
    var cy = d.getFullYear();
    if (cd < 10) cd = "0" + cd;
    if (cm < 10) cm = "0" + cm;
    return cd + "/" + cm + "/" + cy;
}
function onChangeDateInterval(name, check) {
    if (!check) check = 0;
    // crea la formula
    var exprData = /\d{2}[/\-]\d{2}[/\-]\d{4}/;
    var from = window.document.getElementById("dateInterval_from_" + name);
    var to = window.document.getElementById("dateInterval_to_" + name);
    if (!exprData.test(from.value) || !exprData.test(to.value)) {
        // date non valide
        alert("La data inserita non e' valida");
    } else {
        // date valide
        var selStart = dateString2dateObject(from.value);
        var selEnd = dateString2dateObject(to.value);
        var today = getCurrentDate();
        if (typeof(maxDate)=="undefined") maxDate = new Date(today.getFullYear() + 1, 0, 31);
        // if (selStart < today) { from.value = dateObject2dateString(today); selStart = today; }
        if (selStart > maxDate) { 
            from.value = dateObject2dateString(maxDate); selStart = maxDate;
        }
        // if (selEnd < today) { to.value = dateObject2dateString(today); selEnd = today; }
        if (selEnd > maxDate) { 
            to.value = dateObject2dateString(maxDate); selEnd= maxDate;
        }
        if (selEnd < selStart) {
            if (check == 0) { 
                to.value = from.value; selEnd = selStart;
            }
            else { 
                from.value = to.value; selStart = selEnd;
            }
        }
        var dataInterval = datestring2ymd(from.value) + datestring2ymd(to.value);
        for (var i=0; i<7; i++) {
            var dow = window.document.getElementById("dateInterval_dow_" + i + "_" + name);
            dataInterval += dow.checked ? "1" : "0";
        }
        // imposta il campo hidden
        window.document.forms[0][name].value = dataInterval;
        // aggiorna il calendario
        var selDow = new Array(
            (window.document.getElementById("dateInterval_dow_0_" + name)).checked,
            (window.document.getElementById("dateInterval_dow_1_" + name)).checked,
            (window.document.getElementById("dateInterval_dow_2_" + name)).checked,
            (window.document.getElementById("dateInterval_dow_3_" + name)).checked,
            (window.document.getElementById("dateInterval_dow_4_" + name)).checked,
            (window.document.getElementById("dateInterval_dow_5_" + name)).checked,
            (window.document.getElementById("dateInterval_dow_6_" + name)).checked
            );
        displayCalendarInterval("dateInterval_calendar_from_" + name, selStart, selStart, selEnd, selDow, "onClickCalendar('" + name + "', 'from', '%1')");
        displayCalendarInterval("dateInterval_calendar_to_" + name, selEnd, selStart, selEnd, selDow, "onClickCalendar('" + name + "', 'to', '%1')");
    }
}
function onDateIntervalAction(name, type, a) {
    // imposta prossimo mese
    var c = window.document.getElementById("dateInterval_" + type + "_" + name);
    var d = dateString2dateObject(c.value);
    d.setMonth(d.getMonth() + a);
    // aggiorna campo data
    c.value = dateObject2dateString(d);
    // visualizza calendario
    onChangeDateInterval(name, type == "to" ? 1 : 0);
}
function onClickCalendar(name, type, value) {
    var c = window.document.getElementById("dateInterval_" + type + "_" + name);
    c.value = value;
    onChangeDateInterval(name, type == "to" ? 1 : 0);
}
function displayCalendarInterval(id, myDay, selStart, selEnd, selDow, onClickFunc) {
    var today = getCurrentDate();
    // giorni del mese precedente
    var firstDay = new Date(myDay.getFullYear(), myDay.getMonth(), 1);
    var w = firstDay.getDay();
    if (w != 1) firstDay.setDate(firstDay.getDate() - (w > 0 ? w - 1 : 6));
    // giorni del mese successivo
    var lastDay = new Date(myDay.getFullYear(), myDay.getMonth() + 1, 0);
    w = lastDay.getDay();
    if (w != 0) lastDay.setDate(lastDay.getDate() + 7 - w);
    // html calendario
    var html = '<table class="calendar">';
    html += '<tr class="month"><td colspan="7">' + monthNames[myDay.getMonth()] + " " + myDay.getFullYear() + '</td></tr>';
    html += '<tr class="dow"><td>L</td><td>M</td><td>M</td><td>G</td><td>V</td><td>S</td><td>D</td></tr>';
    // crea tabella giorni
    while (firstDay.getTime() <= lastDay.getTime()) {
        // nuova riga
        w = firstDay.getDay();
        if (w % 7 == 1) html += '</tr><tr class="day">';
        // aggiunge td per il giorno
        html += '<td class="';
        html += (firstDay >= today) ? "active" : "old";
        if (firstDay >= selStart && firstDay <= selEnd && selDow[w]) html += " selected";
        html += '"';
        if (firstDay >= today && onClickFunc) {
            // evento click sul giorno
            var clickDate = dateObject2dateString(firstDay);
            html += ' onclick="' + onClickFunc.replace('%1', clickDate) + '"';
        }
        html += '>' + firstDay.getDate() + '</td>';
        // prossimo giorno
        firstDay.setDate(firstDay.getDate() + 1);
    }
    html += "</table>";
    // visualizza calendario
    var d = window.document.getElementById(id);
    d.innerHTML = html;
}
//
// FORMS
//
function setFocus(name) {
    if (name) {
        var form = window.document.forms[0];
        var control = form[name];
        if (control) control.focus();
    }
}
function isCampoVuoto(controllo) { 
    return (controllo == null || controllo.value == "");
}
function isCampoNumero(controllo) { 
    return !isCampoVuoto(controllo) && !isNaN(controllo.value);
}
function strFormat(s, p) { 
    return s.replace("$1", p);
}
function controllaCampoVuoto(controllo, campo) {
    if (isCampoVuoto(controllo)) {
        alert(strFormat("Il campo $1 non puo' essere vuoto", campo));
        controllo.focus();
        return false;
    }
    return true;
}
function controllaCampoNumero(controllo, campo, obbligatorio) {
    if (!obbligatorio && isCampoVuoto(controllo)) return true;
    else if (controllaCampoVuoto(controllo, campo)) {
        if (!isNaN(controllo.value)) return true;
        else {
            alert(strFormat("Il campo $1 contiene un numero non valido", campo));
            controllo.focus();
        }
    }
    return false;
}
function controllaCampoEmail(controllo, campo, obbligatorio) {
    if (!obbligatorio && isCampoVuoto(controllo)) return true;
    else if (controllaCampoVuoto(controllo, campo)) {
        var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if (filter.test(controllo.value)) return true;
        else {
            alert(strFormat("Il campo $1 contiene un indirizzo email non valido", campo));
            controllo.focus();
        }
    }
    return false;
}
function controllaCampoRadio(controllo, campo) {
    for (i=0; i<controllo.length; i++) if (controllo[i].checked) return true;
    alert(strFormat("Devi selezionare almeno un'opzione per il campo $1", campo));
    controllo[0].focus();
    return false;
}
//
// GFX
//
function ajaxStartWait() {
    var div = window.document.getElementById("content");
    if (div) {
        div.style.opacity = "0.25";
        div.style.filter = "alpha(opacity=25)";
    }
}
function ajaxStopWait() {
    var div = window.document.getElementById("content");
    if (div) {
        div.style.opacity = "1";
        div.style.filter = "alpha(opacity=100)";
    }
}
function onMouseOverTr(t, c) { 
    t.style.background = c;
}
function onMouseOutTr(t, c) { 
    t.style.background = c;
}
function Point(x, y) { 
    this.x = x; this.y = y;
}
function getAbsolutePosition(o) {
    var objParent = o;
    var x = 0;
    var y = 0;
    while (objParent){
        y += objParent.offsetTop;
        x += objParent.offsetLeft - objParent.scrollLeft;
        objParent = objParent.offsetParent;
    }
    return new Point(x, y);
}
function showTooltip(s, m, w) {
    if (m) {
        var t = window.document.getElementById("tooltip");
        if (t) {
            var tx = window.document.getElementById("tooltipContent");
            if (tx) tx.innerHTML = m;
            if (t.className != "tooltipshow") {
                t.className = "tooltipshow";
                if (w) t.style.width = w + "px";                
                var p = getAbsolutePosition(s);
                var x = (p.x - t.offsetWidth + 2);
                t.style.top = (p.y + s.offsetHeight - 2) + "px";
                t.style.left = x + "px";
            }
        }
    }
}
function hideTooltip() {
    var t = document.getElementById("tooltip");
    if (t) t.className = "tooltiphide";
}