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_EXP_REPO   = { name : 'export', func : new Function("doExportRepo();return false;") };
    var BTN_PRINT      = { name : 'stampa', func : new Function("doForm('formColumnPrint');return false;") };
    var BTN_EXP_SCHEDA = { name : 'scheda', func : new Function("doExportScheda();return false;") };
    var BTN_EXP_LIST   = { name : 'scheda', func : new Function("doExportList();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 ];
    NAVS['listExport']   = [ BTN_SEARCH, BTN_STATS, BTN_EXP_SCHEDA, BTN_EXP_REPO, BTN_PRINT ];
    NAVS['schedaExport'] = [ BTN_SEARCH, BTN_STATS, BTN_EXP_LIST, BTN_EXP_REPO, 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('menusedi').style.display='none';
        ft.$get('operatori').style.display='block';
        ft.$get('footer').style.backgroundImage='url(../img/footer.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('menusedi').style.display='none';
        ft.$get('operatori').style.display='block';
        ft.$get('footer').style.backgroundImage='url(../img/footer.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('menusedi').style.display='none';
        ft.$get('operatori').style.display='block';
        ft.$get('footer').style.backgroundImage='url(../img/footer.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('menusedi').style.display='none';
        ft.$get('operatori').style.display='none';
        ft.$get('footer').style.backgroundImage='url(../img/footer.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('menusedi').style.display='none';
        ft.$get('operatori').style.display='block';
        ft.$get('footer').style.backgroundImage='url(../img/footer.gif)';
    } else if (page == 'emptyFooter') {
        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';
        ft.$get('menusedi').style.display='none';
        ft.$get('operatori').style.display='none';
        ft.$get('footer').style.backgroundImage='url(' + img + ')';
    } else if (page == 'setBackground') {
        ft.$get('footer').style.backgroundImage='url(' + img + ')';
    } else if (page == 'lista' || page == 'scheda') {
        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('menusedi').style.display='none';
        ft.$get('btns_footer').style.display='block';
        ft.$get('operatori').style.display='block';
        ft.$get('footer').style.backgroundImage='url(../img/footer.gif)';
    } 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('menusedi').style.display='block';
        ft.$get('btns_footer').style.display='block';
        ft.$get('operatori').style.display='block';
        ft.$get('footer').style.backgroundImage='url(../img/footer.gif)';

        setImgSedi(window.top.sedi);
    }
}

/** 
 * 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);
    } 
}

// controlla menu a tendina di sedi

var inm=false;
var lastm=0;
function show(curr) {
   if (!document.getElementById) return;   
   inm=true;
   oldm=lastm;
   lastm=curr;
   if (oldm) erase(oldm);
  // m=document.getElementById("menu-" + curr);
   box=document.getElementById(curr);
   box.style.visibility="visible";//(non compatibile con firefox)
   box.style.display = "block";
   }
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";
   box.style.display = "none";
   }
function timeout(curr) {
   inm=false;
   window.setTimeout("erase('"+curr+"');",1000);
}

/** immagine menu sedi */
function setImgSedi(q) {
    var liPrinc = window.top.ifooter.$('sedi-principali');
    var liSecond = window.top.ifooter.$('sedi-secondarie');
    var liTutte = window.top.ifooter.$('sedi-tutte');
    var imgSedi = window.top.ifooter.$('sedi');
    
    if (q == 'principali') {
        imgSedi.style.backgroundImage = "url(../img/menubottom/sedi_principali.gif)";
        liPrinc.style.display = "none";
        liSecond.style.display = "block";
        liTutte.style.display = "block";
    }
    if (q == 'tutte') {
        imgSedi.style.backgroundImage = "url(../img/menubottom/all_sedi.gif)";
        liPrinc.style.display = "block";
        liSecond.style.display = "block";
        liTutte.style.display = "none";
    }
    if (q == 'secondarie') {
        imgSedi.style.backgroundImage = "url(../img/menubottom/sedi_secondarie.gif)";
        liPrinc.style.display = "block";
        liSecond.style.display = "none";
        liTutte.style.display = "block";
    }
	return true;
}

/** 
 *  Chiamata dall'onload di ogni pagina che include questo js
 */
function init() {
    // niente sedi in alberghi e locali ...
    /*
    if ($("btn-sedi")) {
        $("btn-sedi").onmouseover = function(){ show('elsedi'); }
    }
    if ($("btn-sedi")) {
        $("btn-sedi").onmouseout = function(){ timeout('elsedi'); }
    }
    if ($("btn-sediprincipali")) {
        $("btn-sediprincipali").onmouseover = function(){ show('elsedi'); }
    }
    if ($("btn-sediprincipali")) {
        $("btn-sediprincipali").onmouseout = function(){ timeout('elsedi'); }
    }
    if ($("btn-sedisecondarie")) {
        $("btn-sedisecondarie").onmouseover = function(){ show('elsedi'); }
    }
    if ($("btn-sedisecondarie")) {
        $("btn-sedisecondarie").onmouseout = function(){ timeout('elsedi'); }
    }
    if ($("btn-seditutte")) {
        $("btn-seditutte").onmouseover = function(){ show('elsedi'); }
    }
    if ($("btn-seditutte")) {
        $("btn-seditutte").onmouseout = function(){ timeout('elsedi'); }
    }
    */
    // azzera il risultato della COUNT sql nel footer nel caso sia presente l'id "csearch"
    if ($("csearch")) {
    
        //pollFrames();
        
        // devo aggiornare anche il footer
        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")) {
        getNavs('export');
    } else if ($("cprint")) {
        getNavs('stampa');
    } else if ($('clist-export')) {
        getNavs('listExport');
    } else if ($('cscheda-export')) {
        getNavs('schedaExport');
    } else if ($('cstatsrepository')) {
        getNavs('statsRep');
    } else if ($('csearchrepository')) {
        getNavs('ricerca');
    } else if ($('cexportRepository')) {
        getNavs('export');
    } else if ($('statlist') || $('statlistxml')) {
        getNavs('stats');
    } else if ($('credits')) {
        // l'immagine non mi interessa
        refreshFooter("credits", "");
    } else if ($('login-page')) {
        // l'immagine non mi interessa
        refreshFooter("login-page", "");
    } else if ($('main-page')) {
        // l'immagine non mi interessa
        refreshFooter("emptyFooter", "../img/hp/footer.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 = '';
        }
        
        $("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 "catg_ul_des":
                        desCatULIsPresent = true;
                        break;
                    case "catg_ul_des as CodCatUL":
                        codCatULIsPresent = true;
                        break;
                    case "attv_des":
                        desSpecAttivIsPresent = true;
                        break;
                    case "attv_des 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>"; 
                // sqlPersonal = sqlPersonal + virgola + "idSeatCodUL";

                $("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 ($("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 = '';
        }
    }

} // 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 doExportRepo() {
    alert("Not implemented: export repository");
}

function doExportScheda() {
    alert("Not implemented: export scheda");
}

function doExportList() {
    alert("Not implemented: export list");
}

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;
    }
}

addEvent(window, "onload", function() {
	setTimeout("init()", 200);
	});


