function addEvent(obj, eventName, fn) {
    var prev = obj[eventName];
    obj[eventName] = prev ? function() { fn(); prev(); } : fn;
}

function nocookie() {
    if (!document.cookie) {
        alert("Attenzione: per poter utilizzare questo programma è necessario abilitare " + 
              "i cookie sul browser in uso.");
    }
}

/** 
 *  Costruisce il menu #controlli in alto a sinistra  per tutte le pagine 
 *  con l'eccezione di "and" e "gateway" che contengono già i controlli nell'html
 */
function getNavs(page) {
    // 'name' viene utilizzato per comporre il nome dell'immagine e dell'id di <li>
    // 'func' è l'handler registrato sull'onclick. Le funzioni vanno definite in questo
    // file 
    var BTN_STATS   = { name : 'stats',   func : new Function("doStats();return false;") };
    var BTN_LIST    = { name : 'list',    func : new Function("doForm('formList');return false;") };
    var BTN_SCHEDA  = { name : 'scheda',  func : new Function("doForm('formScheda');return false;") };
    var BTN_SEARCH  = { name : 'ricerca', func : new Function("doGateway();return false;") };
    var BTN_EXP     = { name : 'export',  func : new Function("doForm('formColumnExport');return false;") };
    var BTN_PRINT   = { name : 'stampa',  func : new Function("doForm('formColumnPrint');return false;") };

    var NAVS = new Object();
    NAVS['ricerca']  = [ BTN_STATS,  BTN_LIST,  BTN_SCHEDA, BTN_EXP,    BTN_PRINT ];
    NAVS['lista']    = [ BTN_SEARCH, BTN_STATS, BTN_SCHEDA, BTN_EXP,    BTN_PRINT ];
    NAVS['scheda']   = [ BTN_SEARCH, BTN_STATS, BTN_LIST,   BTN_EXP,    BTN_PRINT ];
    NAVS['export']   = [ BTN_SEARCH, BTN_STATS, BTN_LIST,   BTN_SCHEDA, BTN_PRINT ];
    NAVS['stampa']   = [ BTN_SEARCH, BTN_STATS, BTN_LIST,   BTN_SCHEDA, BTN_EXP ];
    NAVS['stats']    = [ BTN_SEARCH, BTN_LIST,  BTN_SCHEDA, BTN_EXP,    BTN_PRINT ];
    NAVS['statsRep'] = [ BTN_SEARCH, BTN_LIST,  BTN_SCHEDA, BTN_EXP,    BTN_PRINT ];
    
    var doc = window.top.iframe.document;
    var c = doc.getElementById('controlli');
    var count = window.top.ifooter.document.getElementById('countoperators').value;
    count == '0' ? count = 0 : count = 1;
    var arr = NAVS[page];
    var ul = window.top.iframe.document.createElement('ul');
    c.appendChild(ul);
    
    for (var i = 0; i < arr.length; i++) {
        var li = doc.createElement('li');
        var img = doc.createElement('img');
        var anchor = doc.createElement('a');

        ul.appendChild(li);
        li.id = 'sc-' + arr[i].name;
        anchor.href = '#';
        li.appendChild(anchor);
        
        if (count == 0 && (arr[i].name == 'scheda' || arr[i].name == 'list')) {
            anchor.href = "#";
            img.src = 'img/btns_search_off/btn_' + arr[i].name + '.gif';
        } else {
            anchor.onclick = arr[i].func;
            img.src = 'img/btn_' + arr[i].name + '.gif';
        } 
        anchor.appendChild(img);
    }

    // aggiorna il footer 
    // (l'immagine non mi interessa)    
    refreshFooter(page, "");

}

function refreshFooter(page, img) {
	
	var ft = window.top.ifooter;

    if (ft == null || ft == undefined) return;
    
	if (page == 'stats' || page == 'statsRep') {
        ft.$get('btns_footer').style.display='none';
        ft.$get('btns_footer_export').style.display='none';
        ft.$get('btns_footer_stampa').style.display='none';
        ft.$get('btns_footer_credits').style.display='none';
        ft.$get('btns_footer_login').style.display='none';
        ft.$get('btns_footer_stats').style.display='block';
        ft.$get('operatori').style.display='block';
        ft.$get('footer').style.backgroundImage='url(../img/footer_h.gif)';
    } else if (page == 'export') {
    	ft.$get('btns_footer').style.display='none';
    	ft.$get('btns_footer_export').style.display='block';
        ft.$get('btns_footer_stampa').style.display='none';
        ft.$get('btns_footer_credits').style.display='none';
        ft.$get('btns_footer_stats').style.display='none';
        ft.$get('btns_footer_login').style.display='none';
        ft.$get('operatori').style.display='block';
        ft.$get('footer').style.backgroundImage='url(../img/footer_h.gif)';
    } else if (page == 'stampa') {
    	ft.$get('btns_footer').style.display='none';
    	ft.$get('btns_footer_export').style.display='none';
        ft.$get('btns_footer_stampa').style.display='block';
        ft.$get('btns_footer_credits').style.display='none';
        ft.$get('btns_footer_stats').style.display='none';
        ft.$get('btns_footer_login').style.display='none';
        ft.$get('operatori').style.display='block';
        ft.$get('footer').style.backgroundImage='url(../img/footer_h.gif)';
    } else if (page == 'credits') {
    	ft.$get('btns_footer').style.display='none';
    	ft.$get('btns_footer_export').style.display='none';
        ft.$get('btns_footer_stampa').style.display='none';
        ft.$get('btns_footer_credits').style.display='block';
        ft.$get('btns_footer_stats').style.display='none';
        ft.$get('btns_footer_login').style.display='none';
        ft.$get('operatori').style.display='none';
        ft.$get('footer').style.backgroundImage='url(../img/footer_h.gif)';
    } else if (page == 'login-page') {
    	ft.$get('btns_footer').style.display='none';
    	ft.$get('btns_footer_export').style.display='none';
        ft.$get('btns_footer_stampa').style.display='none';
        ft.$get('btns_footer_credits').style.display='none';
        ft.$get('btns_footer_stats').style.display='none';
        ft.$get('btns_footer_login').style.display='block';
        ft.$get('operatori').style.display='block';
        ft.$get('footer').style.backgroundImage='url(../img/footer_h.gif)';
    } else if (page == 'emptyFooter') {
        ft.$get('operatori').style.display='none';
        ft.$get('footer').style.backgroundImage='url(' + img + ')';
        ft.$get('btns_footer').style.display='none';
    	ft.$get('btns_footer_export').style.display='none';
        ft.$get('btns_footer_stampa').style.display='none';
        ft.$get('btns_footer_credits').style.display='none';
        ft.$get('btns_footer_stats').style.display='none';
        ft.$get('btns_footer_login').style.display='none';
    } else if (page == 'setBackground') {
        ft.$get('footer').style.backgroundImage='url(' + img + ')';
    } else {
        ft.$get('btns_footer_stats').style.display='none';
        ft.$get('btns_footer_export').style.display='none';
        ft.$get('btns_footer_stampa').style.display='none';
        ft.$get('btns_footer_credits').style.display='none';
        ft.$get('btns_footer_login').style.display='none';
        ft.$get('btns_footer').style.display='block';
        ft.$get('operatori').style.display='block';
        ft.$get('footer').style.backgroundImage='url(../img/footer_h.gif)';
    }
}

/** 
 * Cerca di azzerare countoperators nel footer.
 * Si arrende dopo timeout*POLL_COUNT tentativi.
 */
var POLL_COUNT = 0;
var MAX_POLL_COUNT = 3;
var TID;

function pollFrames() {
    var timeout = 1000; // millis
    var countopr = null;;
    if(window.top.ifooter && window.top.ifooter.document){
    	countopr = window.top.ifooter.document.getElementById('countoperators');
    	if (countopr != null) {
       		countopr.value = 0;
       		window.clearTimeout(TID);
    	}
    }
    if(countopr == null && POLL_COUNT < MAX_POLL_COUNT) {
       	POLL_COUNT++;
        TID = window.setTimeout("pollFrames()", timeout);
    } 
}

/** 
 *  Chiamata dall'onload di ogni pagina che include questo js
 */
function init() {
    // azzera il risultato della COUNT sql nel footer nel caso sia presente l'id "csearch"
    if ($("csearch")) {
        //pollFrames();
        refreshFooter("csearch");
    
    } else if ($('cscheda')) {
    
        $('cscheda').onselectstart = function() { return false; }
        getNavs('scheda');
        
    } else if ($("clist")) {
        $('clist').onselectstart = function() { return false; };
        getNavs('lista');

        if (window.top.isCheckAll == "checked") {
            window.top.iframe.document.getElementById('checkall').checked = true;
            window.setTimeout("spuntaAll()", 1500);
        }

    } else if ($("cexport") || $('cexportRepository')) {
        getNavs('export');
    } else if ($("cprint")) {
    	getNavs('stampa');
    } else if ($('cstatsrepository')) {
        getNavs('statsRep');
    } else if ($('csearchrepository')) {
        getNavs('ricerca');
    } else if ($('statlist') || $('statlistxml')) {
        getNavs('stats');
    } else if ($('credits')) {
        refreshFooter("credits", "");
    } else if ($('login-page')) {
        refreshFooter("login-page", "");
    } else if ($('main-page')) {
        refreshFooter("emptyFooter", "../img/hp/footer_h.jpg");
    } 

    if ($("exp-ele")) {
        $("el1").onclick = function(){ //basic    
            $("exp-opzioni").hide();
            $("exp-personalizzato").hide();
            $("exp-colonne").innerHTML = strInnerHtmlBasic;
            $("exp-colonne-ordinamento").innerHTML = strInnerHtmlBasicOrd;
            chclasse('el1');
            $("exp-basic").style.display = "block";
            tipo = "basic";
            $("exp-btipo").hide();
            $("exp-brisultati").hide();
            $("sqlOrder").value = '';
        }
        
        $("el2").onclick = function(){
            chclasse('el2');
            $("exp-basic").hide();
            $("exp-sxselcampi").innerHTML = 
                "<select name=\"expselcampi\" size=\"10\" multiple=\"multiple\" id=\"exp-selcampi\">" 
                    + optInnerHtmlPersonal + 
                "</select>";
            $("exp-personalizzato").style.display = "block";
            $("exp-pcampi").style.display = "block";
            $("exp-ordinamento").hide();
            $("exp-btipo").hide();
            $("exp-brisultati").hide();
            $("exp-opzioni").hide();
            tipo = "personal";
            $("sqlOrder").value = '';
        }
        
        $("el3").onclick = function(){ // outlook
            $("exp-opzioni").hide();
            $("exp-personalizzato").hide();
            $("exp-colonne").innerHTML = strInnerHtmlOutlook;
            $("exp-colonne-ordinamento").innerHTML = strInnerHtmlOutlookOrd;
            chclasse('el3');
            $("exp-basic").style.display = "block";
            tipo = "outlook";
            $("exp-btipo").hide();
            $("exp-brisultati").hide();
            $("sqlOrder").value = '';
        }
        
        $("btn-annulla-exp-opt").onclick = function(){
            $("exp-personalizzato").hide();
        }
        
        $("btn-ok-exp-opt").onclick = function() {
            var codCatULIsPresent = false;
            var desCatULIsPresent = false;
            var codSpecAttivIsPresent = false;
            var desSpecAttivIsPresent = false;
            for (i = 0; i < document.fesporta.expusercampi.options.length; i++) {
                switch (document.fesporta.expusercampi.options[i].value) {
                    case "idCatUL":
                        desCatULIsPresent = true;
                        break;
                    case "idCatUL as CodCatUL":
                        codCatULIsPresent = true;
                        break;
                    case "idAttivISTAT":
                        desSpecAttivIsPresent = true;
                        break;
                    case "idAttivISTAT as CodAttivIstat":
                        codSpecAttivIsPresent = true;
                        break;
                }
                
                if ((desCatULIsPresent || codCatULIsPresent) && 
                    (desSpecAttivIsPresent || codSpecAttivIsPresent)) {
                    alert("Attenzione: i parametri Categoria Seat e Attivit\u00E0 Istat non " + 
                          "possono essere utilizzati insieme");
                    return;
                }
            }
            
            if (document.fesporta.expusercampi.options.length != 0) {
                // $("exp-basic").show();
                $("exp-basic").style.display = "block";
                $("exp-pcampi").hide();
                strInnerHtmlPersonal = "";
                
				// il codice identificativo va messo all'inizio  
				// e' il primo campo da esportare.            
                sqlPersonal = "idSeatCodUL";
                
                virgola = ", ";
                
                for (var i = 0; i < document.fesporta.expusercampi.options.length; i++) {
                    if (document.fesporta.expusercampi.options[i].value != 'idSeatCodUL') {
                        strInnerHtmlPersonal = strInnerHtmlPersonal + "<p>" 
                            + document.fesporta.expusercampi.options[i].text + "</p>";
                        strInnerHtmlPersonalOrd = strInnerHtmlPersonalOrd 
                            + "<div style=\"clear:both;\"><p>" 
                            + document.fesporta.expusercampi.options[i].text 
                            + "</p><p class=\"radio\"><input type=\"radio\" name=\"ordexppersonal\" value=\"" 
                            + document.fesporta.expusercampi.options[i].value 
                            + "\" onClick=\"document.fesporta.sqlOrder.value=this.value   \"/></p></div>";
                        sqlPersonal = sqlPersonal + virgola + document.fesporta.expusercampi.options[i].value;
                    }
                }
                strInnerHtmlPersonal = strInnerHtmlPersonal + "<p>Cod. identif. record</p>";
                strInnerHtmlPersonalOrd = strInnerHtmlPersonalOrd +
                     "<div style=\"clear:both;\"><p>Cod. identif. record" + 
                     "</p><p class=\"radio\"><input type=\"radio\" name=\"ordexppersonal\" " + 
                     "value=\"idSeatCodUL\" /></p></div>"; 
                $("exp-colonne").innerHTML = strInnerHtmlPersonal;
                document.fesporta.sqlPersonal.value = sqlPersonal
                $("exp-colonne-ordinamento").innerHTML = strInnerHtmlPersonalOrd;
            
            }
            $("exp-colonne").style.display = "block";
        }
        
        $("btn-esporta-annulla").onclick = function(){
            $("exp-opzioni").hide();
        }
    }
    
    if ($("exp-ele-l")) {
        $("el1").onclick = function(){ //formato unico    
            $("exp-opzioni").hide();
            $("exp-colonne").innerHTML = strInnerHtmlBasicL;
            $("exp-colonne-ordinamento").innerHTML = strInnerHtmlBasicOrdL;
            chclasse('el1');
            $("exp-basic").style.display = "block";
            tipo = "basic";
            $("exp-btipo").hide();
            $("exp-brisultati").hide();
            $("sqlOrder").value = '';
        }
        
        $("btn-esporta-annulla").onclick = function(){
            $("exp-opzioni").hide();
        }
    }
    
    if ($("print-ele")) {
        $("el1").onclick = function(){
            chclasse('el1');
            $("print-srisultati").hide();
            $("print-schede").hide();
            $("celtoprint").innerHTML = strInnerHtmlList;
            $("print-basic").style.display = "block";
            $("print-ecampi").style.display = "block";
            $("print-srisultati").className = "print-risultati-elenco";
            $("print-stipo").className = "printElenco";
            document.fprint.stampa.value = 'elenco';
            $("sqlOrder").value = '';
        }
        $("el2").onclick = function(){
            chclasse('el2');
            $("print-basic").hide();
            $("print-srisultati").hide();
            $("print-schede").style.display = "block";
            $("print-ecampi").hide();
            $("print-srisultati").className = "print-risultati-scheda";
            $("print-stipo").className = "printScheda";
            document.fprint.stampa.value = 'schede';
            $("sqlOrder").value = '';
        }
    }
    if ($("print-ele-l")) {
        $("el1").onclick = function(){
            chclasse('el1');
            $("print-srisultati").hide();
            $("print-schede").hide();
            $("celtoprint").innerHTML = strInnerHtmlListL;
            $("print-basic").style.display = "block";
            $("print-ecampi").style.display = "block";
            $("print-srisultati").className = "print-risultati-elenco";
            $("print-stipo").className = "printElenco";
            document.fprint.stampa.value = 'elenco';
            $("sqlOrder").value = '';
        }
        $("el2").onclick = function(){
            chclasse('el2');
            $("print-basic").hide();
            $("print-srisultati").hide();
            $("print-schede").style.display = "block";
            $("print-ecampi").hide();
            $("print-srisultati").className = "print-risultati-scheda";
            $("print-stipo").className = "printScheda";
            document.fprint.stampa.value = 'schede';
            $("sqlOrder").value = '';
        }
    }
} // init

function spuntaAll() {
    window.top.iframe.document.getElementById('checkall').checked = true;
}

//
// azioni collegate ai controlli di navigazione
//
function doForm(formName) {

    var w = window.top;
    if (w.searchKeyCounter <= 0) {
        return;
    }

    for (var i = 0; i < w.searchKeyCounter; i++) {
        if (w.arrQueries[i].status == "on") {
            //creaMsgWait();
            w.contaObj.putObjectsToForm(formName);
            w.contaObj.document[formName].submit();
            return;   
        }   
    }                
}

function doGateway() {
    window.top.iframe.location = window.top.ROOT + '/gatewayframe.do?z=' + window.top.where();
}

function doStats() {
   window.top.iframe.location = window.top.ROOT + '/statsinit.do?z=' + window.top.where();
}

function doStatsList() {
    window.top.iframe.location = window.top.ROOT + '/statslist.do?z=' + window.top.where();
}

function creaMsgWait(tipo){
    var corpo = document.getElementsByTagName('body')[0];
    var box = document.createElement('div');
    if (tipo == 'scontro') {
        box.setAttribute('id', 'msg-wait-scontro');
    } else if (!tipo) {
        box.setAttribute('id', 'msg-wait-generico');
    }
    box.innerHTML = "<div><h1>Elaborazione dati in corso.</h1><p>" + 
                    "Il sistema sta elaborando i dati inseriti, vi preghiamo " + 
                    "di attendere qualche istante...</p></div>";
    corpo.appendChild(box);
}

function closeMsgWait() {
    var corpo = document.getElementsByTagName('body')[0];
    var box_generico = document.getElementById('msg-wait-generico');
    var box_scontro = document.getElementById('msg-wait-scontro');
    if (box_generico) {
        corpo.removeChild(box_generico)
    } else if (box_scontro) {
        corpo.removeChild(box_scontro)
    }
}

// ML: commentati. La gestione dei link è da rivedere ...
function nolink() {
    //    window.top.iframe.$get('nolinkgateway').style.zIndex = '3';
    //    window.top.itop.$get('nolink').style.zIndex = '2';
    //    window.top.ifooter.$get('nolinkfooter').style.zIndex = '2';
}

function resetLink() {
//    try {
//        window.top.iframe.$get('nolinkgateway').style.zIndex = '-1';
//        window.top.itop.$get('nolink').style.zIndex = '-1';
//        window.top.ifooter.$get('nolinkfooter').style.zIndex = '-1';
//    } catch (err) {
//        window.setTimeout('resetLink()', 2000);
//    }
}

/** cambio classe css delle liste nelle maschere di ricerca */
var inmenu = false;
var lastmenu = 0;

function chclasse(current) {
    inmenu = true;
    oldmenu = lastmenu;
    lastmenu = current;
    if (oldmenu) {
        nascondi(oldmenu);
    }
    if (oldmenu == current) return;
    var m = document.getElementById(current);
    if (m == null) {
        alert('chclasse: impossibile trovare elemento con id ' + current);
    } else { 
        m.className = "elon";
    }
}

function nascondi(current){
    if (lastmenu == current) {
        m = document.getElementById(current);
        m.style.className = "off";
    } else {
        m = document.getElementById(current);
        m.className = "off";
    }
}

// Funzioni per nascondere e visualizzare gli elementi
// (usati dalla pagina di export)
function appare(elemento){
	var obj = $(elemento);
	if(obj) {
		obj.style.display = "block";
	}
}

function disappare(elemento){
	var obj = $(elemento);
	if(obj) {
		obj.style.display = "none";
	}
}

function showType() {
	if(tipo == "outlook") {
		$('exp-tab').style.display = "none";
		$('csvexcel_tab').checked = false;
		$('exp-comma').style.display = "inline";
		$('csvexcel_com').checked = true;
		$('exp-excel').style.display = "none";
		$('csvexcel_xls').checked = false;
	}
	if(tipo == "basic" || tipo == "personal") {
		$('exp-tab').style.display = "inline";
		$('csvexcel_tab').checked = true;
		$('exp-comma').style.display = "inline";
		$('csvexcel_com').checked = false;
		$('exp-excel').style.display = "inline";
		$('csvexcel_xls').checked = false;
	}
}

// controlla menu a tendina di sedi
/*
var inm = false;
var lastm = 0;
function show(curr){
    inm = true;
    oldm = lastm;
    lastm = curr;
    if (oldm) 
        erase(oldm);
    box = document.getElementById(curr)
    box.style.visibility = "visible";
}

function erase(curr){
    if (!document.getElementById) 
        return;
    if (inm && lastm == curr) {
        return;
    }
    m = document.getElementById("menu-" + curr);
    box = document.getElementById(curr);
    box.style.visibility = "hidden";
}

function timeout(curr){
    inm = false;
    window.setTimeout("erase('" + curr + "');", 1000);
}
*/

addEvent(window, "onload", function() {
	setTimeout("init()", 100);
	});


