//------------------------------------------------------------------------------
// CLASS Stru
//------------------------------------------------------------------------------
//
	function Stru(id,titolo,start,stop,url) {
            this.id = id ;
            this.titolo = titolo ;
            this.start = start ;
            this.stop = stop ;
            this.url = url ;
            this.type = 1 ;
	}
//
//------------------------------------------------------------------------------


//------------------------------------------------------------------------------
// CLASS Visualizzatore (v1.3)
//
// Modulo visualizzatore di risorse digitali
// Utilizza ancora componenti legati alla vecchia versione (slider e pulsanti)
//
// Francesco Gabbrielli, 2006
//------------------------------------------------------------------------------
//
	function Visualizzatore(percorso, imagePath, rid, sid, imagePrefix, staticPage, maxIllust, choose) {

	    this.PAGE = 1 ;
	    this.ILLUSTRATION = 2 ;
	    this.TRANSCRIPTION = 4 ;
	    this.TRANSCRIPTION_LOADED = 16 ;

	    this.base = Sfogliatore ;

	    this.base(percorso, imagePrefix, imagePath, rid, sid) ;

	    //sezioni
	    this.tipoSX = "" ;
	    this.tipoDX = "" ;

	    //vecchie sezioni (importanti x l'attivazione globale)
	    this.oldSX = "" ;
	    this.oldDX = "" ;

	    //pagine
	    this.pagSX = 0 ;
	    this.pagDX = 1 ;
	    this.pages = new Array() ;

	    this.thumb = 1 ;
	    this.oldThumb = 1 ;
	    this.thumbs = new Array() ;

	    this.thumbsPage = 1 ;
	    this.thumbsTotpag = 1 ;
	    this.thumbsXPage = parseInt(maxIllust) ;

	    this.struid = -1 ;
	    this.expandedStrus = new String(document.modulo[this.path+'@struEspansi'].value).split(',') ;
	    this.newStruCounter = 1000 ;//indice fittizio (i primi 1000 sono riservati)

	    this.staticPage = staticPage ;
            
            this.choose = choose ;

	    this.btns = new Array(
                "bdv_lista","bdv_ricerca",
                "bdv_prima","bdv_prec","bdv_succ","bdv_ultima",
                "bdv_curs",
                "bdv_note", "bdv_note_sx", "bdv_note_dx"
	    ) ;

	    this.sections = new Array('pagina','indice','illust','trascr') ;
            
	    this.serverActive = false ;
	    this.serverCallsNumber = 0 ;

	    //preload e impostazioni varie (funzionera'?)
	    this.preloadOn = new Array() ;
	    this.preloadOver = new Array() ;
	    this.preloadOut = new Array() ;
	    this.preloadOff = new Array() ;
	    var i,ip = 0 ;
	    for(i=0;i<this.btns.length;i++) {
                var img = document.images[this.btns[i]] ;
                if(img) {//&& img.src.substring(img.src.length-5)=='1.gif') {
                    img.onload = null ;
                    //img.onclick = function() {
                    //	instance.clicking(this.name) ;
                    //}
                    var pre = new Image() ;
                    pre.src = img.src.substring(0,img.src.length-5)+'0.gif' ;
                    this.preloadOff[this.btns[i]] = pre ;
                    pre = new Image() ;
                    pre.src = img.src.substring(0,img.src.length-5)+'1.gif' ;
                    this.preloadOut[this.btns[i]] = pre ;
                    pre = new Image() ;
                    pre.src = img.src.substring(0,img.src.length-5)+'2.gif' ;
                    this.preloadOver[this.btns[i]] = pre ;
                    pre = new Image() ;
                    pre.src = img.src.substring(0,img.src.length-5)+'3.gif' ;
                    this.preloadOn[this.btns[i]] = pre ;
                    if(img.src.substring(img.src.length-5)=='1.gif')
                        this.addButtonEvents(img) ;
                }
	    }
	    this.preload = new Array() ;
	    this.preload['tr.gif'] = new Image() ;
	    this.preload['tr.gif'].src = 'tr.gif' ;
	    this.preload['blankpage.jpg'] = new Image() ;
	    this.preload['blankpage.jpg'].src = this.imagePrefix+'?special=blankpage.jpg' ;
		
	    var v = this ;
	    if(!window.XMLHttpRequest)
                window.XMLHttpRequest = function() { return new ActiveXObject('Microsoft.XMLHTTP') }

	    //eventi sulle immagini
	    document.images["bdv_sx"].onload = function(){v.imageLoaded(this.name.substring(4));}
	    document.images["bdv_sx"].onerror = function(){v.imageError(this,this.name.substring(4));}
	    document.images["bdv_sx"].onabort = function(){v.imageAbort(this);}
	    document.images["bdv_dx"].onload = function(){v.imageLoaded(this.name.substring(4));}
	    document.images["bdv_dx"].onerror = function(){v.imageError(this,this.name.substring(4));}
	    document.images["bdv_dx"].onabort = function(){v.imageAbort(this);}

            this.txtSelManSX = new TextSelectionManager() ;
            this.txtSelManDX = new TextSelectionManager() ;
	    
	    //handler testi ajax
	    this.txtClientSX = new XMLHttpRequest() ;
	    this.txtClientHandlerSX = function() {
                var ajax = v.txtClientSX ;
                if(ajax.readyState==4 && ajax.status==200) {
                    ajax.loading=false ;
                    var layer = document.getElementById("layer_bdv_trascr_sx") ;
                    layer.innerHTML = ajax.responseText ;
                    v.txtSelManSX.setLayer(layer.firstChild) ;
                    v.showWait('sx','hidden') ;
                    if(v.searchWord)
                        v.enboss('sx',v.searchWord) ;
                }
	    }
	    this.txtClientDX = new XMLHttpRequest() ;
	    this.txtClientHandlerDX = function() {
                var ajax = v.txtClientDX ;
                if(ajax.readyState==4 && ajax.status==200) {
                    ajax.loading=false ;
                    var layer = document.getElementById("layer_bdv_trascr_dx") ;
                    layer.innerHTML = ajax.responseText ;
                    v.txtSelManDX.setLayer(layer.firstChild) ;
                    v.txtSelManDX.addSelectionListener(function(source,evtType,zid) {
                        if(v.tipoSX=='pagina') {
                            v.imgSelManSX.highlightById(source,evtType,zid) ;
                        }
                        if(evtType=='links') {
                            var z = v.imgSelManSX.getZoneById(zid) ;
                            v.links(z.rid) ;
                        }
                    }) ;
                    v.showWait('dx','hidden') ;
                    if(v.searchWord)
                        v.enboss('dx',v.searchWord) ;
                }
	    }
	    /*
            this.txtClientDX = new XMLHttpRequest() ;
	    this.txtClientDX.onreadystatechange = function() {
                var ajax = v.txtClientDX ;
                if(ajax.readyState==4 && ajax.status==200) {
                    document.getElementById("layer_bdv_trascr_dx").innerHTML = ajax.responseText ;
                    v.showWait('dx','hidden') ;
                }
	    }
            */

	    //document.images["bdv_lens"].onmousemove = this.moveLens() ;
	    //onMouseOver="viewer.showLens()" onMouseOut="viewer.hideLens()"

            this.magLoadClient = new AjaxRequest() ;

            //this.magClient = new XMLHttpRequest() ;
            this.magSaveClient = new AjaxRequest() ;
            //inizializzazione variabili utilizzate nella richiesta
            this.magSaveClient.addHandler(function(req) {
                v.zoneCounter = 0 ;
                v.endsave = false ;
                return false ;
            }) ;
            //salvataggio strutture
            this.magSaveClient.addHandler(function(req) {
                
                var ret = false ;
                
                if(req.getStatus()==200) {
                    
                    var node ;

                    //ripristino id nell'albero
                    var xml = req.getResponseXML() ;
                    var retid = xml.getElementsByTagName("return") ;
                    if(retid.length) {
                        var retval = retid.item(0) ;
                        node = v.index.getNode(retval.getAttribute("old-id")) ;
                        if(node) {
                            node.setId(retval.getAttribute("new-id")) ;
                            node.value.id = retval.getAttribute("new-id") ;
                        }
                    }

                    //invocazione asincrona successiva
                    var stack = v.saveMAGStack ;
                    if(stack) {
                        ret = false ;
                        while(stack.length) {
                            node = stack.shift() ;
                            for(i=0;i<node.figli.length;i++)
                                    stack.push(node.figli[i]) ;
                            var stru = node.value ;
                            if(node.modified) {
                                if(!v.saveSections.contains('indice'))
                                    v.saveSections.push('indice') ;
                                req.changeURL(
                                    "mag?sid="+v.savingID+
                                    "&op=save-stru&struid="+node.id+
                                    "&tipo="+stru.type+
                                    "&titolo="+escape(stru.titolo)+
                                    "&start="+stru.start+
                                    "&stop="+stru.stop+
                                    "&risorsa="+v.rid+
                                    (node.padre ? "&madre="+node.padre.id : "")+
                                    (node.info ? "&info="+node.info : "")
                                ) ;
                                ret = true ;
                                break ;
                            }
                        }
                    }
                
                } else
                    alert("Errore di comunicazione nel salvataggio STRU") ;
                
                return ret ;
            }) ;
            //salvataggio immagini
            this.magSaveClient.addHandler(function(req) {
                var ret = false ;
                if(req.getStatus()==200) {
                    var img = v.saveImage ? v.saveImage : 1 ;
                    while(img<v.pages.length) {
                        var pag = v.pages[img++] ;
                        v.saveImage = img ;
                        if(pag.modified) {
                            if(!v.saveSections.contains('pagine'))
                                v.saveSections.push('pagine') ;
                            req.changeURL("mag?sid="+v.savingID+"&op=save-img&pagid="+pag.rid+"&titolo="+pag.titolo+((pag.pitflag&2)==2?"&illust=true":"")) ;
                            ret = true ;
                            break ;
                        }
                    }
                } else
                    alert("Errore di comunicazione nel salvataggio IMG") ;
                return ret ;
            }) ;
            //eliminazione fisica STRU cancellati
            this.magSaveClient.addHandler(function(req) {
                var ret = false ;
                if(req.getStatus()==200) {
                    var toDel = new Array() ;
                    var i ;
                    if(v.index) {
                        for(i=0;i<v.index.removed.length;i++)
                            toDel.push(v.index.removed[i].id) ;
                        v.index.resetModified() ;
                    }
                    if(toDel.length && !v.saveSections.contains('indice'))
                        v.saveSections.push('indice') ;

                    if(toDel.length) {
                        req.changeURL("mag?sid="+v.savingID+"&op=del-stru&ids="+toDel.join()) ;
                        ret = true ;
                    }
                }
                return ret ;
            }) ;
            //salvataggio zone (pagina SX e DX)
            /*this.magSaveClient.addHandler(function(req) {
                var ret = false ;
                if(req.getStatus()==200) {
                    do {
                        var dx = v.zoneCounter >= v.imgSelManSX.selections.length ;
                        var selman = dx ? v.imgSelManDX : v.imgSelManSX ;
                        var counter = dx ? v.zoneCounter-v.imgSelManSX.selections.length : v.zoneCounter ;
                        ret = selman.saveHandler(counter,req,"mag?sid="+v.savingID+"&op=save-zone") ;
                        v.zoneCounter++ ;
                        if(v.zoneCounter >= v.imgSelManDX.selections.length+v.imgSelManSX.selections.length)
                            break ;
                    } while(!ret) ;
                } else
                    alert("Errore di comunicazione nel salvataggio zone") ;
                return ret ;
            }) ;
            //eliminazione zone cancellate (pagina SX e DX)
            this.magSaveClient.addHandler(function(req) {
                var ret = false ;
                if(req.getStatus()==200) {
                    ret = v.imgSelManSX.deleteHandler(req,"mag?sid="+v.savingID+"&op=del-zone") ;//sx
                    ret = ret || v.imgSelManDX.deleteHandler(req,"mag?sid="+v.savingID+"&op=del-zone") ;//altrimenti dx
                } else
                    alert("Errore di comunicazione nell'eliminazione zone") ;
                return ret ;
            }) ;*/
            //finalizzazione
            this.magSaveClient.addHandler(function(req) {
                var ret = false ;
                if(req.getStatus()==200) {
                     if(!v.endsave) {
                        req.changeURL("mag?sid="+v.savingID+"&op=endsave") ;
                        ret = true ;
                        v.endsave = true ;
                    }
                } else
                    alert("Errore di comunicazione nella finalizzazione del salvataggio") ;
                return ret ;
            }) ;
            this.magSaveClient.addHandler(function(req) {
                v.loadMAG(v.saveSections) ;
                return false ;
            }) ;

	    //ajax thumbnails
	    this.thumbsClient = new XMLHttpRequest() ;

	    //abilitazione rotazione
	    this.rotation = 0 ;
	    if(navigator.appName.indexOf('Microsoft')<0) {
                this.changeImage('bdv_rotate',0) ;
                this.rotation = -1 ;
	    }

	}

	// DISPLAY
	//----------------------------------------------------------------------
	Visualizzatore.prototype.display = function(p,s,t1,t2,l,w,extend) {

            this.changeListener = function(val) {this.showPages(val);}//il change cambia la visualizzazione x intero
            this.dragListener = function(val) {this.checkPages(val);}//il drag agisce solo sulle intestazioni di pagina
            this.renumberListener = function(val) {this.changeRenumberStart()} ;
            document.getElementById('bdv_stru_edit_bar').onmousedown = function(evt) {
                evt = evt ? evt : window.event ;
                var layer = document.getElementById('bdv_stru_edit') ;
                this.offsetPopupDragX = evt.clientX - parseInt(layer.style.left) ;
                this.offsetPopupDragY = evt.clientY - parseInt(layer.style.top) ;
                this.popupDragging = true ;
            }
            document.getElementById('bdv_stru_edit_bar').onmousemove = function(evt) {
                if(this.popupDragging) {
                    evt = evt ? evt : window.event ;
                    var layer = document.getElementById('bdv_stru_edit') ;
                    layer.style.left = evt.clientX - this.offsetPopupDragX ;
                    layer.style.top = evt.clientY - this.offsetPopupDragY ;
                }
            }
            document.getElementById('bdv_stru_edit_bar').onmouseup = function(evt) {
                evt = evt ? evt : window.event ;
                this.popupDragging = false ;
            }

            this.titSX = document.getElementById("bdv_tit_sx") ;
            this.titDX = document.getElementById("bdv_tit_dx") ;

            this.level = l ;//livello di pubblicazione????

            this.searchWord = w ;

            //creazione sliders
            var i ;
            var curs = document.getElementById('bdv_cursor') ;
            var slid = document.getElementById('bdv_slider') ;
            if(this.pages.length) {
                this.slider1 = new Slider(curs,slid,8,8) ;
                for(i=1;i<this.pages.length;i++) {
                    if(!this.pages[i])
                        this.pages[i] = new Page(i,'???','') ;
                    this.slider1.addValue(i,this.pages[i].titolo) ;
                }

                this.slider1.deactivate() ;
                this.slider1.addChangeListener(this.changeListener,this) ;
                this.slider1.addDragListener(this.dragListener,this) ;
                this.slider1.addChangeListener(this.renumberListener,this) ;
                this.slider2 = new Slider(curs,slid,8,8) ;
                var tit ;
                this.slider2.addValue(1,this.pages[1].titolo) ;
                for(i=2;i<this.pages.length-1;i+=2) {
                    tit = this.pages[i].titolo+this.pages[i+1].titolo ;
                    this.slider2.addValue(i,tit) ;
                }
                if(this.pages.length>2)
                    this.slider2.addValue(this.pages.length-1,this.pages[this.pages.length-1].titolo) ;
                this.slider2.deactivate() ;
                this.slider2.addChangeListener(this.changeListener,this) ;
                this.slider2.addDragListener(this.dragListener,this) ;
                this.slider2.addChangeListener(this.renumberListener,this) ;
            }

            if(this.hasThumbnails())
                this.rebuildSliderT() ;

            //if(!t1 && !t2)
            //	alert("Opera senza dati") ;


            var v = this ;

            //attivazione editing vari
            if(document.getElementsByName(this.name+"_saveindex").length) {

                //menu contestuale sull'indice
                document.getElementById('layer_bdv_indice_sx').oncontextmenu = function(evt) {
                    var layer = document.getElementById('bdv_context_menu') ;
                    evt = evt ? evt : window.event ;
                    if(layer.style.visibility!='visible')
                        v.showIndexContextMenu(evt) ;
                    return false ;
                }

                for(i=1;i<this.pages.length;i++) {
                    document.modulo['/bdviewer/popup/inizio'].options[i-1] = new Option(this.pages[i].titolo,i) ;
                    document.modulo['/bdviewer/popup/fine'].options[i-1] = new Option(this.pages[i].titolo,i) ;
                }

                //menu contestuale sulle immagini
                document.getElementById('layer_bdv_pagina_sx').oncontextmenu = function(evt) {
                    evt = evt ? evt : window.event ;
                    v.showImgContextMenu(evt,'sx') ;
                    return false ;
                }
                document.getElementById('layer_bdv_pagina_dx').oncontextmenu = function(evt) {
                    evt = evt ? evt : window.event ;
                    v.showImgContextMenu(evt,'dx') ;
                    return false ;
                }

                //menu contestuale sulle trascrizioni
                document.getElementById('layer_bdv_trascr_sx').oncontextmenu = function(evt) {
                    evt = evt ? evt : window.event ;
                    v.showTxtContextMenu(evt,'sx') ;
                    return false ;
                }
                document.getElementById('layer_bdv_trascr_dx').oncontextmenu = function(evt) {
                    evt = evt ? evt : window.event ;
                    v.showTxtContextMenu(evt,'dx') ;
                    return false ;
                }

            }

            //onload
            window.onload = function() {

                //this.activateServer(true) ;

                if(extend)
                    setTimeout(v.name+".extend()",100) ;

                //zone sensibili
                v.imgSelManSX = new ImageSelectionManager(
                    document.getElementById("layer_bdv_pagina_sx"),
                    document.images["bdv_img_sx"],
                    document.getElementById("bdv_pag_sx").offsetLeft,
                    document.getElementById("bdv_header").offsetHeight + document.getElementById("bdv").offsetTop,
                    document.modulo[v.path+"@zoneid"].value
                ) ;
                v.imgSelManSX.addSelectionListener(function(source,evtType,zid) {
                    if(v.tipoDX=='pagina') {
                        v.imgSelManDX.selectOver() ;
                    } else if(v.tipoDX=='trascr' && v.txtSelManDX) {
                        v.txtSelManDX.highlightByZone(source,evtType,zid) ;
                    }
                    if(evtType=='links')
                        v.links(zid) ;
                }) ;
                v.imgSelManDX = new ImageSelectionManager(
                    document.getElementById("layer_bdv_pagina_dx"),
                    document.images["bdv_img_dx"],
                    document.getElementById("bdv_pag_dx").offsetLeft,
                    document.getElementById("bdv_header").offsetHeight + document.getElementById("bdv").offsetTop,
                    document.modulo[v.path+"@zoneid"].value
                ) ;
                v.imgSelManDX.addSelectionListener(function(source,evtType,zid) {
                    if(evtType=='links')
                        v.links(zid) ;
                }) ;
                
                v.setSections(t1,t2) ;
                
                v.setZoneEdit() ;
                
                //finalizzazione display
                if(v.index) {
                    var tempstru = s ;
                    if(!tempstru && v.index.root.figli[0])
                        tempstru = v.index.root.figli[0].id ;
                    v.currentStruRoot = v.index.getNode(tempstru) ;
                }

                if(s)
                    if(!v.index.getNode(s))
                        s = 0 ;

                if(s)
                    v.showStru(s) ;
                else
                    v.showPages(p) ;

            }

            //attivazione tools
            /*if(this.index || this.hasTranscriptions())
                    this.changeButtonState('bdv_cerca',1) ;
            if(this.pages.length>0 && this.imagePath) {
                    this.changeButtonState('bdv_lente',1) ;
                    this.changeButtonState('bdv_pdf',1) ;
            }*/

	}
	//----------------------------------------------------------------------


	Visualizzatore.prototype.rebuildSliderT = function() {
	    if(!this.sliderT) {
                var curs = document.getElementById('bdv_cursor') ;
                var slid = document.getElementById('bdv_slider') ;
                this.sliderT = new Slider(curs,slid,8,8) ;

                //inizializzazione layer delle illustrazioni
                for(i=0;i<this.thumbsXPage;i++) {
                    var pos = i+1 ;
                    var layer = document.getElementById("layer_bdv_illust_sx") ;
                    var div = document.createElement("div") ;
                    div.id = this.name+"_thumb_layer_"+pos ;
                    div.className = "bdv_thumb_layer" ;
                    div.innerHTML =
                        "<div><a href='javascript:"+this.name+".showPageThumb("+pos+")'><img name='bdv_thumb_"+pos+"' class='bdv_thumb_img' src='tr.gif'/></a></div>"+
                        "<div><span id='"+this.name+"_thumb_text_"+pos+"'>&#160;</span></div>" ;
                    layer.appendChild(div) ;
                }
	    }
	    this.sliderT.reset() ;
	    for(i=0;i<this.thumbs.length;i++)
                this.sliderT.addValue(i+1,this.thumbs[i].titolo) ;
	    this.sliderT.deactivate() ;
	    this.sliderT.addChangeListener(this.showThumb,this) ;
	    this.sliderT.addDragListener(this.dragListener,this) ;
	}


	// ACTIVATE
	//----------------------------------------------------------------------
	// Attiva tutti gli oggetti globali che devono esserlo dopo che tutte 
	// le impostazioni sono state effettuate:
	// - lo slider
	//----------------------------------------------------------------------
	Visualizzatore.prototype.activate = function() {
	
            if(this.oldSX!=this.tipoSX || this.oldDX!=this.tipoDX) {

                var illust = this.tipoSX=='illust'  ;
                var oldIllust = this.oldSX=='illust' ;
                var dopp = this.tipoSX==this.tipoDX ;
                var oldDopp = this.oldSX==this.oldDX ;

                if(!illust && !this.imagePath && this.tipoDX=='pagina') {
                    illust = true ;
                    oldIllust = false ;
                }

                //se si cambia da doppia pag a singola o viceversa o si cambia verso le illustrazioni...
                if(dopp!=oldDopp || !this.oldSX || illust!=oldIllust) {

                    if(this.slider) {
                        this.slider.deactivate() ;
                        this.slider = null ;//superfluo???
                    }

                    if(illust)
                        this.slider = this.sliderT ;
                    else if(dopp)
                        this.slider = this.slider2 ;
                    else
                        this.slider = this.slider1 ;

                    //if(illust) {
                        //alert("THUMB SELECTED: "+(this.thumb)+" -> P."+this.pagSX+"-> T."+this.findThumb(this.pagSX)) ;
                        //alert("PAG="+this.pagSX+"/THUMB="+this.thumb) ;
                        //this.showThumb(this.findThumb()) ;
                        //alert("PAG="+this.pagSX+"/THUMB="+this.thumb) ;
                        //alert("THUMB "+this.thumb+" DA PAG "+this.pagSX) ;
                    //} else

                    if(this.slider) {
                        //alert(this.tipoSX + " - " + (illust ? this.thumb : this.pagSX)) ;
                        this.slider.setValue(illust ? this.thumb : this.pagSX) ;
                        this.slider.activate() ;
                        this.slider.redraw() ;
                    } else
                        this.slider = null ;

                    //if(illust)
                    //	alert("PAG="+this.pagSX+"/THUMB="+this.thumb) ;
                }
            }


            //aggiustamento slider
            //alert("AGGIUSTAMENTO SLIDER") ;
            //this.slider.setValue(this.pagDX) ;
		
	}
	//----------------------------------------------------------------------


	// ACTIVATE SERVER
	//----------------------------------------------------------------------
	Visualizzatore.prototype.activateServer = function(state) {
            this.serverActive = state ;
	}
	//----------------------------------------------------------------------


	// ADD PAGE
	//----------------------------------------------------------------------
	// Aggiunge una pagina per la visualizzazione in tendina
	// (metodo da chiamare in fase di inizializzazione)
	//----------------------------------------------------------------------
	Visualizzatore.prototype.addPage = function(nr,title,rid,id,zid,pit,server,ref) {
            if(!this.pages[nr]) {
                if(!server)
                    server = 1 ;
                this.pages[nr] = new Page(nr,decode(title),id,zid,pit,server,ref) ;
                this.pages[nr].rid = rid ;
                if((pit & this.ILLUSTRATION) == this.ILLUSTRATION)
                    this.addThumb(nr,decode(title),id,zid,null,server) ;
            }
	}
	//----------------------------------------------------------------------

	// ADD THUMB
	//----------------------------------------------------------------------
	Visualizzatore.prototype.addThumb = function(pag,tit,id,zid,path,server) {
            if(!server)
                server = 1 ;
            this.insertThumb(this.thumbs.length,new Thumb(pag,tit,id,zid,path,server)) ;
	}

	Visualizzatore.prototype.insertThumb = function(index,thumb) {
	    this.thumbs.splice(index,0,thumb) ;
	    //this.refreshThumbs() ;
	}

	Visualizzatore.prototype.removeThumb = function(index) {
	    this.thumbs.splice(index,1) ;
	}
	//----------------------------------------------------------------------

	// HAS THUMBNAILS
	//----------------------------------------------------------------------
	Visualizzatore.prototype.hasThumbnails = function() {
            return this.thumbs.length>0 ;
	}
	//----------------------------------------------------------------------

	// HAS TRANSCRIPTIONS
	//----------------------------------------------------------------------
	Visualizzatore.prototype.hasTranscriptions = function() {
            var i ;
            var ret = false ;
            for(i=1;!ret && i<=this.pages.length;i++)
                if((this.pages[i].pitflag & this.TRANSCRIPTION)==this.TRANSCRIPTION)
                    ret = true ;
            return ret ;
	}
	//----------------------------------------------------------------------


	// SET INDEX
	//----------------------------------------------------------------------
	// Imposta l'albero da usare come struttura/indice del libro
	//----------------------------------------------------------------------
	Visualizzatore.prototype.setIndex = function(tree) {

            var instance = this ;

            tree.addSelectListener(function(val){
                if(this.index.selected.value.id!=val.id)
                    this.showStru(val.id);
            },this) ;
            tree.addExpandListener(this.expandStru,this) ;
            tree.addInfoListener(function(val) {
                //var w = window.open('http://fermi.imss.fi.it/riviste/GetRecordByAN.jsp?rivista=all&an='+val+'&lingua=ITA&dig=no','bibinfo','width=600,height=400,scrollbars=yes') ;
                instance.info(val) ;
                //w.focus() ;
                //invia(this.nome+'/struinfo',val,false,'bibinfo','width=300,height=300,scrollbars=yes') ;
            },this) ;
            tree.addLinkListener(function(url) {
                instance.links(url) ;
                //pagina.call(this.path,'link',url,'collegate','links','width=640,height=480,scrollbars=yes') ;
            },this) ;
            tree.ui = new TreeUI(
                function(node) {return node.value.titolo},
                function(node) {
                    return "---" ;
                    /*var r = intance.computeStruRoot(node) ;
                    var start = node.value.start ;
                    var stop = node.value.stop ;
                    //alert("ROOT di "+r.value.titolo+ " = "+ r.value.id) ;
                    switch(r.value.id) {
                        case 1:
                            return instance.pages[start].titolo+(start!=stop && stop ? " - "+instance.pages[stop].titolo : "") ;
                        case 2:
                            return instance.thumbs[start-1].titolo+(start!=stop && stop ? " - "+instance.thumbs[stop-1].titolo : "") ;
                        default:
                            return '---' ;
                    }*/
                },
                function(node) {
                    alert(node.value.titolo) ;
                    return false ;
                },
                document.getElementById('layer_bdv_indice_sx'),
                'css/roberta/it.fi.imss.dig.form/visualizzatore/tree_piu.gif',
                'css/roberta/it.fi.imss.dig.form/visualizzatore/tree_piu_l.gif',
                'css/roberta/it.fi.imss.dig.form/visualizzatore/tree_meno.gif',
                'css/roberta/it.fi.imss.dig.form/visualizzatore/tree_meno_l.gif',
                'css/roberta/it.fi.imss.dig.form/visualizzatore/tree_chiuso.gif',
                'css/roberta/it.fi.imss.dig.form/visualizzatore/tree_aperto.gif',
                'css/roberta/it.fi.imss.dig.form/visualizzatore/tree_pagina.gif',
                'css/roberta/it.fi.imss.dig.form/visualizzatore/bt_info_1.gif',
                'css/roberta/it.fi.imss.dig.form/visualizzatore/bt_note_1.gif',
                'css/roberta/it.fi.imss.dig.form/visualizzatore/tree_linea.gif',
                'css/roberta/it.fi.imss.dig.form/visualizzatore/tree_giunzione.gif',
                'css/roberta/it.fi.imss.dig.form/visualizzatore/tree_giunzione_l.gif'
            ) ;
            tree.redraw() ;

            this.index = tree ;

            //impostazione strutture principali
            var i ;
            for(i=0;i<tree.root.figli.length;i++)
                tree.root.figli[i].value.type = 2 ;
	}
	//----------------------------------------------------------------------

	/*Visualizzatore.prototype.setTranscriptionPages = function(psx,pdx) {
		this.trascrSX = parseInt(psx) ;
		this.trascrDX = parseInt(pdx) ;
	}*/

	// Metodi di controllo pagine
	//----------------------------------------------------------------------
	//
	Visualizzatore.prototype.isGoodPage = function(p) {
            return p>=this.getMinPage() && p<=this.getMaxPage() ;
	}

	/** Restituisce la pagina corrente in base alla sezione impostata */
	Visualizzatore.prototype.getPage = function(dx) {
            var ret = -1 ;
            if(this.tipoSX==this.tipoDX) {
                ret = this.pagSX >= this.getMinPage() ? this.pagSX : this.pagDX ;
                if(dx)
                    ret += 1 ;
            } else if(this.tipoSX=='illust') {
                ret = this.thumb ;
            } else
                ret = this.pagDX ;//xk la sez. destra non contiene mai cose strane...
            return ret ;
	}
	
	Visualizzatore.prototype.getMinPage = function() {
            return 1 ;
	}

	Visualizzatore.prototype.getMaxPage = function() {
            return this.tipoSX=='illust' || !this.pages.length ? this.thumbs.length : this.pages.length-1 ;
	}
	//
	//----------------------------------------------------------------------


	// Metodi di scorrimento, settaggio e visualizzazione pagine
	//----------------------------------------------------------------------
	//
	Visualizzatore.prototype.firstPage = function() {
            this.slider.goFirst() ;
	}
	Visualizzatore.prototype.previousPage = function() {
            this.slider.previous() ;
            //this.showPages(this.tipoSX==this.tipoDX ? this.getPage()-2 : this.getPage()-1) ;
	}
	Visualizzatore.prototype.nextPage = function() {
            this.slider.next() ;
            //this.showPages(this.tipoSX==this.tipoDX ? this.getPage()+2 : this.getPage()+1) ;
	}
	Visualizzatore.prototype.lastPage = function() {
            this.slider.goLast() ;
	}

	// SET PAGES FROM THUMB
	//----------------------------------------------------------------------
	// Imposta la pagina o entrambe (a seconda del tipo di visualizzazione) a 
	// partire dalla thumbnail
	//----------------------------------------------------------------------	
	Visualizzatore.prototype.setPagesFromThumb = function(thumbIndex) {
	    var ret = false ;
	    var thumb = this.thumbs[thumbIndex-1] ;
	    if(thumb && thumb.pag) {
                this.setPagesImpl(thumb.pag) ;
                ret = true ;
	    }
	    return ret ;
	}

	// SET PAGES FROM STRU
	//----------------------------------------------------------------------
	// Imposta la pagina o entrambe (a seconda del tipo di visualizzazione) a 
	// partire dallo stru (se si trova nella sez. galleria imposta la thumb)
	//----------------------------------------------------------------------
	Visualizzatore.prototype.setPagesFromStru = function(stru) {
            if(stru) {
                switch(this.currentStruRoot.id) {

                    //GALLERIA
                    case 200:
                        this.setAbsoluteThumbImpl(stru.start) ;
                        break ;

                    default:
                        this.setPagesImpl(stru.start) ;
                        this.setThumbFromPag(stru.start) ;
                        //this.setThumbImpl(this.thumb) ;

                }
            }
	}

	// SET PAGES IMPL
	//----------------------------------------------------------------------
	Visualizzatore.prototype.setPagesImpl = function(p) {
            if(this.tipoSX==this.tipoDX) {
                this.pagSX = p - p%2 ;
                this.pagDX = this.pagSX < this.getMaxPage() ? this.pagSX + 1 : -1 ;
            } else {
                this.pagSX = p ;
                this.pagDX = p ;
            }
            document.modulo[this.path+'@pagsx'].value = this.pagSX ;
            document.modulo[this.path+'@pagdx'].value = this.pagDX ;
	}

	// SET PAGES
	//----------------------------------------------------------------------
	// Imposta la pagina o entrambe (a seconda del tipo di visualizzazione) a 
	// partire da un solo valore. L'impostazione non genera un cambio di visua_
	// lizzazione
	//----------------------------------------------------------------------
	Visualizzatore.prototype.setPages = function(p,noEvents) {
		/*if(!p)
			p = this.tipoSX=='illust' ? this.thumb : this.pagSX ;
		//la setPage sullo slider non deve rilanciare eventi! (ci sara' il metodo setValue che lo fa)
		if(this.tipoSX==this.tipoDX) {
			this.pagSX = p - p%2 ;
			this.pagDX = this.pagSX < this.getMaxPage() ? this.pagSX + 1 : -1 ;
			this.refreshThumbFromPage() ;
		} else if(this.tipoSX=='illust') {
			this.setThumb(p - this.thumbsXPage*(this.thumbsPage-1)) ;
		} else {
			this.pagSX = p ;
			this.pagDX = p ;
			this.refreshThumbFromPage() ;
		}*/

		if(p) {
		    this.setPagesImpl(p) ;
                    //alert("SET PAGES IMPL") ;
		    this.setThumbFromPag(p) ;
                    //alert("SET THUMB FROM PAG") ;
		    this.setStruFromPag(p) ;
		}

		/*//aggiornamento indice
		if(this.index) {
			if(!this.index.clicked) {
				this.index.deactivate() ;
				this.setStru(this.getStru().id) ;
				this.index.activate() ;
			} else
				this.index.clicked = false ;
		}

		//aggiornamento slider
		if(!noEvents && this.slider)
			this.slider.setValue(this.pagSX) ;*/

		//document.modulo[this.path+'@thumb'].value = this.thumb ;
	}

	/*Visualizzatore.prototype.refreshThumbFromPage = function() {
		var i = 0 ;
		for(i=0;i<this.thumbs.length;i++) {
			var tp = this.thumbs[i].pag ;
			if(tp==this.pagSX || tp==this.pagDX) {
				this.setAbsoluteThumb(i+1) ;
				//this.thumb = i+1 ;
				//document.images['bdv_thumb_'+this.oldThumb].className = 'bdv_thumb_img' ;
				//this.oldThumb = this.thumb ;
				//document.images['bdv_thumb_'+this.thumb].className = 'bdv_thumb_img_selected' ;
				break ;
			}
		}
	}

	Visualizzatore.prototype.refreshPageFromThumb = function() {
		var t = this.thumbs[this.thumb-1] ;
		if(t) {
			this.pagSX = t.pag ;
			this.pagDX = t.pag ;
		}
	}*/


	// SHOW PAGES
	//----------------------------------------------------------------------
	// Settaggio + propagazione del cambio di visualizzazione impostato
	//----------------------------------------------------------------------
	Visualizzatore.prototype.showPages = function(p) {
            this.setPages(p) ;
            this.serverAction() ;
            this.loadPages() ;
	}

	// SERVER ACTION
	//----------------------------------------------------------------------
	// Controlla se c'e' bisogno di caricare nuovi dati dal server.
	// In caso di esito positivo lancia un timer per bufferizzare le operazioni
	// ripetute troppo velocemente
	//----------------------------------------------------------------------
	Visualizzatore.prototype.serverAction = function() {
            if(this.serverActive) {
                //quando nelle trascrizioni si arriva a una pagina non caricata
                if(this.tipoSX=='trascr' && this.trascrSX!=this.pagSX && this.isGoodPage(this.pagSX)) {
                    this.serverCallsNumber++ ;
                    setTimeout(this.name+".serverCallBuffer('trascrizione')",500) ;//sistema provvisorio...
                } else if(this.tipoDX=='trascr' && this.trascrDX!=this.pagDX && this.isGoodPage(this.pagDX)) {
                    this.serverCallsNumber++ ;
                    setTimeout(this.name+".serverCallBuffer('trascrizione')",500) ;
                }
            }
	}

	// SERVER CALL BUFFER
	//----------------------------------------------------------------------
	Visualizzatore.prototype.serverCallBuffer = function(act) {
            if(this.serverCallsNumber==1)
                pagina.call(this.path,act) ;
            if(this.serverCallsNumber>0)
                this.serverCallsNumber-- ;
	}

	// LOAD PAGES
	//----------------------------------------------------------------------
	// Caricamento lato client della visualizzazione correntemente impostata
	//----------------------------------------------------------------------
	Visualizzatore.prototype.loadPages = function() {
            this.activate() ;//attiva la sezione corrente, poi imposta le pagine
            this.loadPage('sx') ;
            this.loadPage('dx') ;
	}

	// LOAD PAGE
	//----------------------------------------------------------------------
	// Caricamento lato client di una singola pagina
	//----------------------------------------------------------------------
	Visualizzatore.prototype.loadPage = function(p,side) {

            if(!side)
                side = p ;
            var tipo = eval("this.tipo"+side.toUpperCase()) ;
            var illust = this.tipoSX=='illust' || !this.pages.length || (this.tipoSX=='indice' && this.currentStruRoot && this.currentStruRoot.id==2) ;
            if(!parseInt(p)) {
                p = illust ? this.thumb : eval("this.pag"+side.toUpperCase()) ;
                if(this.tipoSX==this.tipoDX)
                    p = parseInt(p/2)*2 + (side=='dx'?1:0) ;
            }

            this.checkPage(p,side) ;
            if(this.isGoodPage(p)) {

                this.showWait(side,'visible') ;
                var pp = null ;
                switch(tipo) {

                    case 'pagina':
                        //var url = "tr.gif" ;
                        //if(p>0 && p<=pmax) {
                            //if(this.pages[p].livello>=this.level)
                            //	url = tmb==null ? this.imagePrefix+this.percorso+'/'+this.percorso+'_'+this.formatPage(p)+'r.jpg' : tmb.indirizzo ;
                            //else
                            //	url = this.imagePrefix+'restricted_page.jpg' ;
                            //this.imagePrefix+this.percorso+'/'+this.percorso+'_'+this.formatPage(tmb.nrpag)+'r.jpg';
                        //}
                        //document.images["bdv_"+side].src = this.imagePrefix+this.imagePath+'/'+this.imagePath+'_'+Sfogliatore.prototype.formatPage(p)+(this.extendedView ? 'z' : 'r')+'.jpg' ;
                        pp = this.pages[p] ;
                        var tt = null ;
                        if(illust) {
                            pp = null ;
                            var t = this.thumbs[p-1] ;
                            if(t) {
                                //if(t.pag)
                                //	pp = this.pages[t.pag] ;
                                //else
                                    tt = t ;
                            }
                        }
                        if(pp) {
                            document.images["bdv_"+side].src = this.imagePrefix+"?fid="+(this.extendedView ? pp.zid : pp.id)+"&sid="+this.sid+"&archid="+pp.server ;
                            this.changeImage("bdv_zoom",pp.zid?1:0) ;
                            this.changeImage("bdv_lente",pp.zid?1:0) ;
                        } else if(tt) {
                            document.images["bdv_"+side].src = this.imagePrefix+"?fid="+tt.id+"&sid="+this.sid+"&archid="+tt.server ;
                            this.changeImage("bdv_zoom",tt.zid?1:0) ;
                            this.changeImage("bdv_lente",tt.zid?1:0) ;
                        } else
                            alert("Errore caricamento pagina: "+p) ;

                        this.changeButtonState("bdv_note_"+side,pp && pp.ref ? 1 : 0) ;
                        break ;

                    case 'illust':
                        this.showWait(side,'hidden') ;
                        document.getElementById(this.name+'_thumb_layer_'+(this.thumb-(this.thumbsXPage*(this.thumbsPage-1)))).className = 'bdv_thumb_layer bdv_thumb_layer_selected' ;
                        break ;

                    case 'indice':
                        this.showWait(side,'hidden') ;
                        break ;

                    case 'trascr':
                        pp = this.pages[p] ;
                        if(pp) {
                            var ajax = eval('this.txtClient'+side.toUpperCase()) ;
                            if(ajax.readyState!=1)
                                try {
                                    ajax.open("POST", "text?sid="+this.sid+"&fid="+pp.id+"&rid="+pp.rid+"&rnd="+Math.random(), true) ;
                                    ajax.setRequestHeader("Content-Type","plain/text; charset=UTF-8") ;
                                    ajax.onreadystatechange = eval('this.txtClientHandler'+side.toUpperCase()) ;
                                    ajax.send(null) ;
                                } catch(exc) {
                                    var lay = document.getElementById("layer_bdv_trascr_"+side) ;
                                    lay.innerHTML = "SERVER ERROR: "+exc ;
                                    this.showWait(side,'hidden') ;
                                }
                        }
                        break ;
                }
            } else {
                switch(tipo) {
                    case 'pagina':
                    case 'trascr':
                        //document.images["bdv_"+side].src = this.preload['tr.gif'].src ;
                        break ;
                }
            }
	}

	// CHECK PAGES
	//----------------------------------------------------------------------
	// Controlla e visualizza le intestazioni di pagina correntemente impostate.
	// Utilizzato come handler per lo scorrimento dello slider
	//----------------------------------------------------------------------
	Visualizzatore.prototype.checkPages = function(p) {
            this.setPages(p,true) ;
            this.checkPage(this.getPage(),'sx') ;
            this.checkPage(this.getPage(true),'dx') ;
	}

	// CHECK PAGE
	//----------------------------------------------------------------------
	// Visualizza l'intestazione di una pagina, controllando lo stato dei bottoni
	// per la pagina scelta. Non cambia la sezione in caso di incongruenze...
	//----------------------------------------------------------------------
	Visualizzatore.prototype.checkPage = function(p,side) {

		var tipo = eval("this.tipo"+side.toUpperCase()) ;
		var tit = eval("this.tit"+side.toUpperCase()) ;

		//aggiustamento stato bottoni sezioni
		var i ;
		for(i=0;i<this.sections.length;i++) {
			var s = this.sections[i] ;
			var newSez = this.checkPageSection(p,s) ;
			if(tipo!=s)
				this.changeButtonState("bdv_"+s+"_"+side,newSez==s ? 1 : 0) ;
		}

		//aggiustamento stato bottoni slider
		this.changeButtonState("bdv_prima",	this.getPage()>this.getMinPage() ? 1 : 0) ;
		this.changeButtonState("bdv_prec",	this.getPage()>this.getMinPage() ? 1 : 0) ;
		this.changeButtonState("bdv_succ",	this.getPage(true)<this.getMaxPage() ? 1 : 0) ;//uso true x sapere la pagina + grande!
		this.changeButtonState("bdv_ultima",	this.getPage(true)<this.getMaxPage() ? 1 : 0) ;//uso true x sapere la pagina + grande!
                
                document.getElementById("bdv_link_sx").style.visibility = 'hidden' ;
                document.getElementById("bdv_link_dx").style.visibility = 'hidden' ;

		if(this.isGoodPage(p)) {
                    
                      if(this.tipoSX=='pagina' && this.pages[this.pagSX] && this.pages[this.pagSX].ref)
                          document.getElementById("bdv_link_sx").style.visibility = 'visible' ;
                      if(this.tipoDX=='pagina' && this.pages[this.pagDX] && this.pages[this.pagDX].ref)
                          document.getElementById("bdv_link_dx").style.visibility = 'visible' ;

			//visualizzazione titolo
			var t ;
			tit.title = null ;
			switch(tipo) {

				case 'pagina':
					if(this.tipoSX=='illust')
						tit.innerHTML = this.thumbs[p-1].titolo ;
					else if(this.pages[p])
						tit.innerHTML = this.pages[p].titolo ;
					else if(this.thumbs[p-1])
						tit.innerHTML = this.thumbs[p-1].titolo ;
					else
						tit.innerHTML = " " ;
					break ;

				case 'indice':
					tit.innerHTML = '' ;
					break ;

				case 'illust':
					tit.innerHTML = "Illustrazione "+p ;
					break ;

				case 'trascr':
					if(this.pages[p])
						tit.innerHTML = this.pages[p].titolo+" [Trascrizione]" ;
					else
						tit.innerHTML = " " ;
					break ;
			}
			
		} else {

			tit.title = null ;
			tit.innerHTML = " " ;

		}
	}

	// SET THUMB
	//----------------------------------------------------------------------
	Visualizzatore.prototype.setThumb = function(thumbIndex) {
		this.setAbsoluteThumbImpl(thumbIndex) ;
		if(this.setPagesFromThumb(thumbIndex))
		    this.setStruFromPag(this.pagSX) ;
	}

	// SET THUMB FROM PAG
	//----------------------------------------------------------------------
	Visualizzatore.prototype.setThumbFromPag = function(p) {
	    var i ;
	    var ok = false ;
	    for(i=1;i<=this.thumbs.length && !ok;i++)
		    if(this.thumbs[i-1].pag==p) {
			    this.setAbsoluteThumbImpl(i) ;
			    ok = true ;
		    }
	    //if(!ok)
		//this.setAbsoluteThumbImpl(p) ;
	}

	// SET THUMB IMPL
	//----------------------------------------------------------------------
	// Imposta la thumbnail relativamente alla pagina corrente
	//----------------------------------------------------------------------
	Visualizzatore.prototype.setThumbImpl = function(thumbIndex) {

            this.setAbsoluteThumbImpl(thumbIndex-(this.thumbsPage-1)*this.thumbsXPage) ;
            /*
            this.thumb = thumbIndex + offset ;
            //alert(this.thumb+"->"+thumbIndex+" da "+this.oldThumb) ;

            var oldimgLayer = document.getElementById(this.name+'_thumb_layer_'+(this.oldThumb-offset)) ;
            if(oldimgLayer)
                    oldimgLayer.className = 'bdv_thumb_layer' ;
            this.oldThumb = this.thumb ;
            var newimgLayer = document.getElementById(this.name+'_thumb_layer_'+thumbIndex) ;
            if(newimgLayer)
                    newimgLayer.className = 'bdv_thumb_layer bdv_thumb_layer_selected' ;

            if(this.thumbsXPage>0 && (thumbIndex<=0 || thumbIndex>this.thumbsXPage)) {
                    //alert(parseInt((thumbIndex+this.thumbsXPage*(this.thumbsPage-1)-1)/this.thumbsXPage)+1) ;
                    this.setThumbsPage(parseInt((thumbIndex+this.thumbsXPage*(this.thumbsPage-1)-1)/this.thumbsXPage)+1) ;
            }*/
	}

	// SET ABSOLUTE THUMB IMPL
	//----------------------------------------------------------------------
	// Imposta la thumbnail in senso assoluto (reimpostando la pagina)
	//----------------------------------------------------------------------
	Visualizzatore.prototype.setAbsoluteThumbImpl = function(thumbIndex) {

		//this.setThumbImpl(thumbIndex - this.thumbsXPage*(this.thumbsPage-1)) ;

		this.thumb = thumbIndex ;

		var offset = (this.thumbsPage-1)*this.thumbsXPage ;
		
		var oldimgLayer = document.getElementById(this.name+'_thumb_layer_'+(this.oldThumb-offset)) ;
		if(oldimgLayer)
			oldimgLayer.className = 'bdv_thumb_layer' ;
		this.oldThumb = this.thumb ;

		var newOffset = 0 ;
		if(this.thumbsXPage) {
		    var newPage = parseInt((thumbIndex-1) / this.thumbsXPage) + 1 ;
		    if(newPage!=this.thumbsPage)
			this.setThumbsPage(newPage) ;
		    newOffset = (this.thumbsPage-1)*this.thumbsXPage ;
		}

		var newimgLayer = document.getElementById(this.name+'_thumb_layer_'+(thumbIndex-newOffset)) ;
		if(newimgLayer)
			newimgLayer.className = 'bdv_thumb_layer bdv_thumb_layer_selected' ;

		/*if(this.thumbsXPage>0 && (thumbIndex<=0 || thumbIndex>this.thumbsXPage)) {
			//alert(parseInt((thumbIndex+this.thumbsXPage*(this.thumbsPage-1)-1)/this.thumbsXPage)+1) ;
			this.setThumbsPage(parseInt((thumbIndex+this.thumbsXPage*(this.thumbsPage-1)-1)/this.thumbsXPage)+1) ;
		}*/
	}

	Visualizzatore.prototype.showPageThumb = function(thumb) {
	    var thumbIndex = thumb+(this.thumbsPage-1)*this.thumbsXPage ;
	    if(thumbIndex>0 && thumbIndex<=this.thumbs.length)
		this.showThumb(thumbIndex) ;
	    else
		alert("Errore thumb: "+thumbIndex) ;
	}

	// SHOW THUMB
	//----------------------------------------------------------------------
	Visualizzatore.prototype.showThumb = function(thumbIndex) {
	    this.setThumb(thumbIndex) ;
	    this.loadPages() ;
	}

	// SHOW ABSOLUTE THUMB (handler per il change)
	//----------------------------------------------------------------------
	/*Visualizzatore.prototype.showAbsoluteThumb = function(thumbIndex) {
		//thumbIndex = parseInt(thumbIndex) ;
		//alert(thumbIndex) ;
		this.showThumb(thumbIndex - this.thumbsXPage*(this.thumbsPage-1)) ;
	}*/

	Visualizzatore.prototype.loadThumbsPage = function() {
		var i ;
		var start = 0 ;
		var stop = this.thumbs.length ;
		if(this.thumbsXPage>0) {
			start = (this.thumbsPage-1)*this.thumbsXPage ;
			stop = Math.min(start+this.thumbsXPage,stop) ;
		}

		var count = 0 ;
		for(i=start;i<stop;i++) {
			document.getElementById(this.name+"_thumb_layer_"+(count+1)).className = "bdv_thumb_layer" ;
			var img = document.images['bdv_thumb_'+(count+1)] ;
			if(img) {
				if(img.src.substr(img.src.length-6,6)=='tr.gif') {
					img.src = this.imagePrefix+'?fid='+this.thumbs[i].id+'&sid='+this.sid+'&height=90'+'&archid='+this.thumbs[i].server ;
					img.title = this.thumbs[i].titolo ;
					var txt = this.thumbs[i].titolo ;
					if(txt && txt.length>32)
						txt = txt.substring(0,32)+"..." ;
					document.getElementById(this.name+'_thumb_text_'+(count+1)).innerHTML = txt ;
				}
			} else {
				alert("ERRORE IMG "+i+"/"+this.thumbs.length) ;
				break ;
			}
			count++ ;
		}
		for(i=stop-start;i<this.thumbsXPage;i++)
		    document.getElementById(this.name+"_thumb_layer_"+(i+1)).className = "bdv_thumb_layer bdv_thumb_layer_void" ;
		var paginaz = document.getElementById(this.name+'_thumbs_pag') ;
		if(paginaz) {
			paginaz.innerHTML = ''+this.thumbsPage ;
			document.getElementById(this.name+'_thumbs_totpag').innerHTML = ''+(parseInt(this.thumbs.length/this.thumbsXPage)+1) ;
		}
	}

	Visualizzatore.prototype.clearThumbSelection = function() {
		var i ;
		for(i=0;i<this.thumbsXPage;i++) {
			var imgLayer = document.getElementById(this.name+'_thumb_layer_'+(i+1)) ;
			imgLayer.className='bdv_thumb_layer' ;
		}
	}

	Visualizzatore.prototype.clearThumbsPage = function() {
		var i ;
		for(i=0;i<this.thumbsXPage;i++) {
			var img = document.images['bdv_thumb_'+(i+1)] ;
			if(img) {
			    img.src="tr.gif" ;
			    document.getElementById(this.name+'_thumb_text_'+(i+1)).innerHTML = "" ;
			}
		}
		this.clearThumbSelection() ;
	}

	Visualizzatore.prototype.setThumbsPage = function(p) {
		this.thumbsPage = p ;
		this.clearThumbsPage() ;
		this.loadThumbsPage() ;
	}

	Visualizzatore.prototype.prevThumbsPage = function() {
		if(this.thumbsPage>1) {
			this.thumbsPage-- ;
			this.clearThumbsPage() ;
			this.loadThumbsPage() ;
			this.showPageThumb(this.thumbsXPage) ;
		}
	}

	Visualizzatore.prototype.nextThumbsPage = function() {
		if(this.thumbsPage<parseInt((this.thumbs.length-1)/this.thumbsXPage)+1) {
			this.thumbsPage++ ;
			this.clearThumbsPage() ;
			this.loadThumbsPage() ;
			this.showPageThumb(1) ;
		}
	}
	//
	//------------------------------------------------------------------------------


	// CHECK PAGE SECTION
	//--------------------------------------------------------------------------
	// Controlla che la sezione passata sia compatibile con la pagina
	// Restituisce la sezione compatibile: in caso di esito positivo e'
	// la stessa di quella passata, altrimenti restituisce un'altra sezione
	//--------------------------------------------------------------------------
	Visualizzatore.prototype.checkPageSection = function(p,sez) {
		var ret = null ;
		if(sez=="indice" && this.index) {
			ret = sez ;
		} else if(sez=="illust" && this.hasThumbnails()) {
			ret = sez ;
		//sezioni che dipendono dalla pagina
		} else if(this.isGoodPage(p)) {
			var pag = this.pages[p] ;
			if(pag)
				switch(sez) {
					case "pagina":
						if((pag.pitflag & this.PAGE) == this.PAGE)
							ret = sez ;
						break ;
					/*case "illust":
						if((pag.pitflag & this.ILLUSTRATION) == this.ILLUSTRATION)
							ret = sez ;
						break ;*/
					case "trascr":
						if((pag.pitflag & this.TRANSCRIPTION) == this.TRANSCRIPTION)
							ret = sez ;
						break ;
				}

			if(!ret)
				ret = this.getDefaultPageSection(p) ;
		}
		return ret ;
	}

	// GET DEFAULT PAGE SECTION
	//----------------------------------------------------------------------
	// Restituisce la sezione di default per la pagina corrente
	//----------------------------------------------------------------------
	Visualizzatore.prototype.getDefaultPageSection = function(p) {
		var ret = null ;
		var pag = this.pages[p] ;
		if(pag) {
			if((pag.pitflag & this.PAGE) == this.PAGE)
				ret = "pagina" ;
			else if((pag.pitflag & this.TRANSCRIPTION) == this.TRANSCRIPTION)
				ret = "trascr" ;
			/*else if((pag.pitflag & this.ILLUSTRATION) == this.ILLUSTRATION)
				ret = "illust" ;*/
		}
		return ret ;
	}


	// Metodi per la gestione dell'indice
	//----------------------------------------------------------------------
	//

	// COMPUTE STRU ROOT
	//----------------------------------------------------------------------
	// Calcola la radice corrente dell'indice in base al nodo passato
	//----------------------------------------------------------------------
	Visualizzatore.prototype.computeStruRoot = function(node) {
	    var ret = node ;
	    if(ret) {
			while(true) {
				var padre = ret.padre ;
				if(padre && padre.id)
				ret = padre ;
				else
				break ;
			}
	    } else
			ret = this.index && this.index.figli ? this.index.figli[0] : null ;
	    return ret ;
	}

	// SET STRU FROM PAG
	//----------------------------------------------------------------------
	// Imposta la struttura corrente a partire dalla pagina, rimanendo all'
	// interno della radice corrente
	//----------------------------------------------------------------------
	Visualizzatore.prototype.setStruFromPag = function(p) {
	    if(this.index) {
                var n = this.index.selected ;
                if(!n || n.espanso || n.value.start>p || p>n.value.stop) {
                    var temp = this.currentStruRoot ;
                    while(temp) {
                        var f = null ;
                        if(temp.espanso && temp.figli && temp.figli.length) {
                            var i ;
                            for(i=0;!f && i<temp.figli.length;i++) {
                                var figlio = temp.figli[i] ;
                                if(figlio.value.start<=p && figlio.value.stop>=p)
                                    f = figlio ;
                            }
                        }
                        if(f)
                            temp = f ;
                        else
                            break ;
                    }
                    if(temp)
                        this.setStruImpl(temp.id) ;
                }
	    }
	}

	// SET STRU
	//----------------------------------------------------------------------
	// Imposta lo stru corrente.
	// calcola la pagina corrente e la thumb corrente se esistono, senza lanciare eventi.
	//----------------------------------------------------------------------
	Visualizzatore.prototype.setStru = function(s) {
            if(this.struid!=s) {
                this.setStruImpl(s) ;
                this.currentStruRoot = this.computeStruRoot(this.index.selected) ;
                var stru = this.index.getNode(s).value ;
                this.setPagesFromStru(stru) ;
            }
	}

	Visualizzatore.prototype.setStruImpl = function(s) {
	    this.struid = s ;
	    document.modulo[this.path+'@struid'].value = s ;
	    this.index.selectNode(s,true) ;
	    this.index.expandPathToNode(s,true) ;
	}

	// GET STRU
	//----------------------------------------------------------------------
	// Restituisce la struttura corrispondente alla pagina corrente
	//----------------------------------------------------------------------
	Visualizzatore.prototype.getStru = function() {
            var sel = this.index.root.figli[0] ;//parto dal primo figlio (ovvero il nodo INDICE)
            var oldsel = null ;
            while(!sel.equals(oldsel)) {
                oldsel = sel ;
                if(sel.espanso)
                    for(i=0;i<sel.figli.length;i++)
                        if(sel.figli[i].value.start<=this.pagDX && sel.figli[i].value.stop>=this.pagDX) {
                            //alert(this.stru+","+sel.figli[i].id) ;
                            sel = sel.figli[i] ;
                            break ;
                        }
            }
            return sel.value ;
	}

	// SHOW STRU
	//----------------------------------------------------------------------
	// Imposta la visualizzazione per la struttura specificata 
	// (utilizzato anche come handler per eventi tree selection)
	//----------------------------------------------------------------------
	Visualizzatore.prototype.showStru = function(s) {
            this.hidePopups() ;
            this.setStru(s) ;
            /*
                var stru = this.index.selected.value ;
                var p = this.getPage() ;
                this.index.clicked = true ;
                var pag = stru.start ;
                if(!this.pages.length) {
                    do {
                        var figli = this.index.getChildren(stru.id) ;
                        if(figli.length)
                            stru = figli[0].value ;
                    } while(figli.length) ;
                    pag = 0 ;
                    var i ;
                    for(i=0;i<this.thumbs.length && pag==0;i++)
                        if(this.thumbs[i].pag==stru.start)
                            pag = i+1 ;
                }
                this.showPages(pag) ;
            */
            this.serverAction() ;
            this.loadPages() ;

            //else 
            //  this.showThumbById(stru.id) ;
	}

	// EXPAND STRU
	//----------------------------------------------------------------------
	// Handler espansione dell'indice
	//----------------------------------------------------------------------
	Visualizzatore.prototype.expandStru = function(node) {
	    var id = node ? node.value.id : 0 ;
	    if(id) {
                var espanso = node.espanso ;
                if(espanso) {
                    if(!this.expandedStrus.contains(id)) {
                        this.expandedStrus.push(id) ;
                        document.modulo[this.path+'@struEspansi'].value = this.expandedStrus.join(",") ;
                    }
                } else
                    this.expandedStrus.remove(id) ;

                if(node.value.start<=this.pagSX && node.value.stop>=this.pagSX) {
                    this.index.selectNode(node.id,true) ;
                    this.currentStruRoot = this.computeStruRoot(this.index.selected) ;
                    this.setStruFromPag(this.pagSX) ;
                }
	    }
	}

	//
	//----------------------------------------------------------------------


	// Metodi di caricamento, settaggio e visualizzazione sezioni
	//----------------------------------------------------------------------
	//
	// SET SECTION
	//----------------------------------------------------------------------
	// Impostazione della sezione in uno dei due lati
	//----------------------------------------------------------------------
	Visualizzatore.prototype.setSection = function(sez,side) {
            this.setSectionImpl(sez,side) ;
	}

	Visualizzatore.prototype.setSectionImpl = function(sez,side) {
	
            this.oldSX = ""+this.tipoSX ;
            this.oldDX = ""+this.tipoDX ;

            if(side=='sx') {
                this.tipoSX = sez ;
                document.modulo[this.path+"@tiposx"].value = sez ;
            } else if(side=='dx') {
                this.tipoDX = sez ;
                document.modulo[this.path+"@tipodx"].value = sez ;
            }
            this.changeButtonState("bdv_"+sez+"_"+side,3) ;

            //alert("CAMBIO "+side+": SX="+this.oldSX+"->"+this.tipoSX+"; DX="+this.oldDX+"->"+this.tipoDX) ;

            //attivazione layer
            var i ;
            for(i=0;i<this.sections.length;i++) {
                var lay = document.getElementById('layer_bdv_'+this.sections[i]+'_'+side) ;
                if(lay)
                    lay.style.visibility = 'hidden' ;
            }
            var lay = document.getElementById('layer_bdv_'+sez+'_'+side) ;
            if(lay)
                document.getElementById('layer_bdv_'+sez+'_'+side).style.visibility='visible' ;

            if(sez=='illust') {
                this.setSection('pagina','dx') ;
                this.loadThumbsPage() ;
            }
	}

	// SET SECTIONS
	//----------------------------------------------------------------------
	// Stessa cosa di prima, solo che non cacha due volte il vecchio valore
	// come succederebbe con due chiamate delle precedenti
	//----------------------------------------------------------------------
	Visualizzatore.prototype.setSections = function(sezSX,sezDX) {
            var oldSX = ""+this.tipoSX ;
            var oldDX = ""+this.tipoDX ;
            this.setSection(sezSX,'sx') ;
            this.setSection(sezDX,'dx') ;
            this.oldSX = oldSX ;
            this.oldDX = oldDX ;
	}
        
        Visualizzatore.prototype.showSections = function(sezSX,sezDX) {
            this.setSections(sezSX,sezDX) ;
            this.showPages() ;
        }

	//Caricamento
	Visualizzatore.prototype.loadSection = function() {
	}

	// SHOW SECTION
	//----------------------------------------------------------------------
	// Impostazione + caricamento
	//----------------------------------------------------------------------
	Visualizzatore.prototype.showSection = function(sez,side) {
            this.setSection(sez,side) ;
            this.showPages() ;
	}

	//
	//----------------------------------------------------------------------


	// Handlers per il caricamento delle immagini
	//----------------------------------------------------------------------
	//

	// SHOW WAIT
	//--------------------------------------------------------------------------
	// Visualizza l'avvertimento di attendere il caricamento della pagina
	//--------------------------------------------------------------------------
	Visualizzatore.prototype.showWait = function(pos,state) {
            if(!state) state = 'visible' ;
            document.getElementById("bdv_wait_"+pos).style.visibility=state ;
	}

	// IMAGE LOADED
	//--------------------------------------------------------------------------
	// Chiude l'avvertimento di attesa caricamento immagine
	//--------------------------------------------------------------------------
	Visualizzatore.prototype.imageLoaded = function(side) {
            //alert("LOADED IMG "+side+": "+document.images["bdv_"+side].src) ;
            this.showWait(side,'hidden') ;
            this.refreshSelections(side) ;
            //aggiornamento image selection manager (se presente)
            //var selman = eval('this.imgSelMan'+side.toUpperCase()) ;
            //if(selman)
            //    selman.imageChanged('this.pages[this.pag'+side.toUpperCase()+']') ;
	}

	// IMAGE ERROR
	//--------------------------------------------------------------------------
	// Visualizza l'avvertimento di errore caricamento immagine (ovvero pagina bianca!!!)
	//--------------------------------------------------------------------------
	Visualizzatore.prototype.imageError = function(img,side) {
            //alert(this+": Error "+img.name) ;
            //img.onerror 
            //this.disableEvents = true ;
            //img.src = this.preload['blankpage.jpg'].src ;//risolvere meglio...
            //this.disableEvents = false ;
            //this.showWait(side,'hidden') ;
            //window.status = "Errore immagine: "+img.src ;
	}
	
	Visualizzatore.prototype.imageAbort = function(img) {
            alert("ABORT: "+img.src) ;
	}

	// THUMB LOADED
	//----------------------------------------------------------------------
	// Chiude l'avvertimento di attesa caricamento immagine
	//----------------------------------------------------------------------
	Visualizzatore.prototype.thumbLoaded = function(side) {
            //this.showWait(side,'hidden') ;
	}

	// THUMB ERROR
	//----------------------------------------------------------------------
	// Visualizza l'avvertimento di errore caricamento immagine (ovvero pagina bianca!!!)
	//----------------------------------------------------------------------
	Visualizzatore.prototype.thumbError = function(img) {
            this.breakThumbsLoad = true ;
	}
	//
	//----------------------------------------------------------------------

	Visualizzatore.prototype.refreshSelections = function(side) {
            if(side=='sx' && this.imgSelManSX)
                this.imgSelManSX.imageChanged(this.pages[this.pagSX].rid,"mag?op=load-zones") ;
            if(side=='dx' && this.imgSelManDX)
                this.imgSelManDX.imageChanged(this.pages[this.pagDX].rid,"mag?op=load-zones") ;
        }


	// Rollover, gestione grafica e interazione bottoni
	//----------------------------------------------------------------------
	//
	// GET BUTTON STATE
	//----------------------------------------------------------------------
	Visualizzatore.prototype.getButtonState = function(imgName) {
            return document.images[imgName].src.substr(img.src.length-5,1) ;
	}

	// CHANGE BUTTON STATE
	//----------------------------------------------------------------------
	Visualizzatore.prototype.changeButtonState = function(imgName,state) {
            var img = document.images[imgName] ;
            if(img) {
                //alert(imgName+": "+state) ;
                var prefix = img.src.substring(0,img.src.length-5) ;
                var old = img.src.substr(img.src.length-5,1) ;
                if(old!=state && (old!=2 || state!=1)) {
                    var instance = this ;
                    //if(img.className=='bdv_button bdv_button_pressed')
                    //	img.className='bdv_button' ;
                    if(state==1) {
                        this.addButtonEvents(img) ;
                        img.src = instance.preloadOut[imgName].src ;
                        //if(this.style.cursor)
                            img.style.cursor = 'default' ;
                    } else if(state==3) {
                        img.onmouseover = null ;
                        img.onmouseout = null ;
                        //img.className='bdv_button bdv_button_pressed' ;

                        //tolgo i listener tranne ai pulsanti che si possono ripremere anche da premuti
                        if(imgName!='bdv_lente' && imgName!='bdv_estesa') {
                            img.onclick = null ;
                            img.style.cursor = 'default' ;
                        }

                        img.src = instance.preloadOn[imgName].src ;

                    } else {
                        if(img.src.indexOf('bt_')>=0) {
                            img.onmouseover = null ;
                            img.onmouseout = null ;
                            img.onclick = null ;
                        }
                        img.src = instance.preloadOff[imgName].src ;
                        //if(img.style.cursor)
                            img.style.cursor = 'default' ;
                    }
                }
            } else {
                //alert("Errore! Immagine non esistente: "+imgName) ;
            }
	}

	Visualizzatore.prototype.changeImage = function(imgName,state) {
            var img = document.images[imgName] ;
            if(img) {
                var prefix = img.src.substring(0,img.src.length-5) ;
                var old = img.src.substr(img.src.length-5,1) ;
                img.src = prefix+state+".gif" ;
            }
	}

	Visualizzatore.prototype.getImageState = function(imgName) {
            var ret = 0 ;
            var img = document.images[imgName] ;
            if(img) {
                var prefix = img.src.substring(0,img.src.length-5) ;
                ret = img.src.substr(img.src.length-5,1) ;
            }
            return parseInt(ret) ;
	}

	Visualizzatore.prototype.addButtonEvents = function(img) {
            var instance = this ;
            img.onmouseover = function() {
                this.src = instance.preloadOver[this.name].src ;
                //if(this.style.cursor)
                    this.style.cursor = 'pointer' ;
                    if(this.className.substring(0,10)=='bdv_button')
                        this.className = 'bdv_button bdv_button_pressed' ;
            }
            img.onmouseout = function() {
                this.src = instance.preloadOut[this.name].src ;
                //if(this.style.cursor)
                    this.style.cursor = 'default' ;
                    if(this.className.substring(0,10)=='bdv_button')
                        this.className = 'bdv_button' ;
            }
            if(img.src.indexOf('bt_')>=0)
                img.onclick = function() {
                    instance.clicking(this.name);
                }
	}

	// ROLL OVER
	//----------------------------------------------------------------------
	Visualizzatore.prototype.rollOver = function() {
            var prefix = this.src.substring(0,this.src.length-5) ;
            this.src = prefix+'2.gif' ;
            if(this.style.cursor) {
                this.style.cursor = 'pointer' ;
                this.className = 'bdv_button bdv_button_pressed' ;
            }
	}

	// ROLL OUT
	//----------------------------------------------------------------------
	Visualizzatore.prototype.rollOut = function() {
            var prefix = this.src.substring(0,this.src.length-5) ;
            this.src = prefix+'1.gif' ;
            if(this.style.cursor) {
                this.style.cursor = 'default' ;
                this.className = 'bdv_button' ;
            }
	}
	//
	//----------------------------------------------------------------------


	// Handlers click vari
	//----------------------------------------------------------------------
	//
	// CLICKING
	//----------------------------------------------------------------------
	// Handle per il click sui vari bottoni dell'interfaccia
	//----------------------------------------------------------------------
	Visualizzatore.prototype.clicking = function(btn) {
		
            switch(btn) {

                case 'bdv_info':
                    pagina.call(this.path,'info','','','bibinfo','width=600,height=400,scrollbars=yes') ;
                    break ;
                case 'bdv_note':
                    pagina.call(this.path,'links','','','links','width=600,height=400,scrollbars=yes') ;
                    break ;
                case 'bdv_note_sx':
                    var p = this.pages[this.pagSX] ;
                    var nrlinks = parseInt(p.ref) ;
                    var props = 'width=600,height=400,scrollbars=yes' ;
                    if(nrlinks==1)
                        props = 'width=1024,height=768,scrollbars=yes' ;
                    pagina.call(this.path,'links',p.rid+'#'+nrlinks,'','links',props) ;
                    break ;
                case 'bdv_note_dx':
                    var p = this.pages[this.pagDX] ;
                    var nrlinks = parseInt(p.ref) ;
                    var props = 'width=600,height=400,scrollbars=yes' ;
                    if(nrlinks==1)
                        props = 'width=1024,height=768,scrollbars=yes' ;
                    pagina.call(this.path,'links',p.rid+'#'+nrlinks,'','links',props) ;
                    break ;

                //bottoni slider
                case 'bdv_prima':
                    this.firstPage() ;
                    break ;
                case 'bdv_prec':
                    this.previousPage() ;
                    break ;
                case 'bdv_succ':
                    this.nextPage() ;
                    break ;
                case 'bdv_ultima':
                    this.lastPage() ;
                    break ;

                //bottoni sezioni
                case 'bdv_pagina_sx':
                    this.showSection('pagina','sx') ;
                    break ;
                case 'bdv_indice_sx':
                    this.showSection('indice','sx') ;
                    break ;
                case 'bdv_illust_sx':
                    this.showSection('illust','sx') ;
                    break ;
                case 'bdv_trascr_sx':
                    this.showSection('trascr','sx') ;
                    break ;

                case 'bdv_pagina_dx':
                    this.showSection('pagina','dx') ;
                    break ;
                case 'bdv_trascr_dx':
                    this.showSection('trascr','dx') ;
                    break ;

                case 'bdv_estesa':
                    this.extend() ;
                    break ;

                case 'bdv_cerca':
                    pagina.call(this.path,'search','','','search','width=500,height=620,scrollbars=yes',true) ;
                    break ;
                case 'bdv_lente':
                    this.toggleLens() ;
                    break ;
                case 'bdv_pdf':
                    pagina.call(this.path,'pdf','','','pdf','width=300,height=300,scrollbars=yes',true) ;
                    break ;
            }

	}

	Visualizzatore.prototype.zoomSingle = function() {
            if(this.getImageState("bdv_zoom")) {
                var sez = this.tipoSX=='pagina' ? 'sx' : (this.tipoDX=='pagina' ? 'dx' : '') ;
                if(sez)
                    this.zoom(sez) ;
            } else
                alert("Zoom non disponibile") ;
	}

	Visualizzatore.prototype.back = function(codice) {
            pagina.call(this.path,'back') ;
	}

	Visualizzatore.prototype.info = function(codice) {
            pagina.call(this.path,'info',codice,'','info') ;
	}
	
	Visualizzatore.prototype.links = function(url) {
            pagina.call(this.path,'links',url,'','links','width=750,height=500,scrollbars=yes') ;
	}

	Visualizzatore.prototype.search = function() {
            pagina.call(this.path,'search','','','search','width=450,height=750,resizable=no,scrollbars=yes') ;
	}

	Visualizzatore.prototype.download = function() {
            pagina.call(this.path,'download','','','download','width=360,height=240,resizable=no,scrollbars=yes') ;
	}

	// ZOOM
	//----------------------------------------------------------------------
	// Apre lo zoom di un'immagine in una nuova finestra
	//----------------------------------------------------------------------
	Visualizzatore.prototype.zoom = function(side) {
            if(this.staticPage)
                pagina.call(this.path,'zoom',eval('this.pag'+side.toUpperCase()),this.staticPage+'_zoom.html','zoom','width=900,height=750,scrollbars=yes,resizable=yes') ;
            else
                pagina.call(this.path,'zoom',eval('this.pag'+side.toUpperCase()),'','zoom','width=900,height=750,scrollbars=yes,resizable=yes') ;
	}

	// EXTEND
	//----------------------------------------------------------------------
	// Estende/ripristina la vista
	//----------------------------------------------------------------------
	Visualizzatore.prototype.extend = function() {

	    if(this.getImageState("bdv_estesa")) {

		this.extendedView = !this.extendedView ;
		document.images['bdv_estesa'].title = this.extendedView ? 'Vista normale' : 'Adatta alla pagina' ;
		this.changeImage('bdv_estesa',this.extendedView ? 3 : 1) ;
		//alert(document.getElementById('bdv').offsetHeight) ;
		//document.getElementById('bdv_header').style.height = this.extendedView ? '0px' : '' ;
		document.modulo[this.path+'@esteso'].value = this.extendedView ? 'si' : 'no' ;

		var totalHeight = document.getElementById('bdv').offsetHeight ;
		var barHeight = document.getElementById('bdv_bar').offsetHeight ;
		var headerHeight = document.getElementById('bdv_header').offsetHeight ;
		//alert(totalHeight+"/"+document.body.offsetHeight) ;

		var w = 450 ;
		var h = 620 ;
		var wp = '' ;
		var hp = '' ;
		var ht = '' ;
		var wt = '' ;
		var wtable = '' ;
		if(this.extendedView) {
                    var w2 = document.body.offsetWidth - 190 ;
                    w = w2/2 ;
                    wtable = w2+'px' ;
                    h = totalHeight-barHeight-headerHeight ;
                    wp = w+'px' ;
                    hp = h+'px' ;
                    wt = (w-32)+'px' ;
                    ht = (h-32)+'px' ;
		}
		//document.getElementById('bdv_table').style.width = wtable ;
		document.getElementById('bdv_pages').style.height = hp ;
		document.getElementById('bdv_pag_sx').style.width = wp ;
		document.getElementById('bdv_pag_sx').style.height = hp ;
		document.getElementById('bdv_pag_dx').style.width = wp ;
		document.getElementById('bdv_pag_dx').style.height = hp ;
		document.getElementById('layer_bdv_pagina_sx').style.width = wp ;
		document.getElementById('layer_bdv_pagina_sx').style.height = hp ;
		document.getElementById('layer_bdv_illust_sx').style.width = wp ;
		document.getElementById('layer_bdv_illust_sx').style.height = hp ;
		document.getElementById('layer_bdv_indice_sx').style.width = wp ;
		document.getElementById('layer_bdv_indice_sx').style.height = hp ;
		document.getElementById('layer_bdv_trascr_sx').style.width = wt ;
		document.getElementById('layer_bdv_trascr_sx').style.height = ht ;
		document.getElementById('layer_bdv_pagina_dx').style.width = '100%' ;
		document.getElementById('layer_bdv_pagina_dx').style.height = hp ;
		document.getElementById('layer_bdv_trascr_dx').style.width = wt ;
		document.getElementById('layer_bdv_trascr_dx').style.height = ht ;
		
		document.images["bdv_sx"].height = h-20 ;
		document.images["bdv_dx"].height = h-20 ;

		this.loadPages() ;

	    }
	}
	//
	//----------------------------------------------------------------------


	// Gestione della lente di ingrandimento
	//----------------------------------------------------------------------
	//
	// TOGGLE LENS
	//----------------------------------------------------------------------
	// Attiva/disattiva la lente
	//----------------------------------------------------------------------
	Visualizzatore.prototype.toggleLens = function() {
            if(this.getImageState("bdv_lente")) {
                this.lensActive = !this.lensActive ;
                if(!this.lensActive) {
                    this.hideLens() ;
                    this.changeImage('bdv_lente',1) ;
                } else {
                    this.changeImage('bdv_lente',3) ;
                }
            } else
                alert("Lente non disponibile") ;
	}

	// HIDE LENS
	//--------------------------------------------------------------------------
	// Nasconde la lente (anche handler per l'onMouseMove sui layer non pagina)
	//--------------------------------------------------------------------------
	Visualizzatore.prototype.hideLens = function() {
            var lens = document.getElementById('bdv_lens') ;
            lens.style.visibility='hidden' ;
	}
	
	// MOVE LENS
	//--------------------------------------------------------------------------
	// Handler per l'onMouseMove sulla pagina su cui usare la lente
	//--------------------------------------------------------------------------
	Visualizzatore.prototype.moveLens = function(evt,side) {
	    if(this.lensActive) {
                if(!evt)
                    evt = window.event ;
                if(evt!=null) {
                    var bdv = document.getElementById('bdv') ;
                    var pag = document.getElementById('bdv_pages') ;
                    this.lens(evt.clientX,evt.clientY,pag.offsetWidth/2,pag.offsetTop + bdv.offsetTop) ;
                }
            } else {
                this.hidePopups() ;
	    }
	}

	// LENS
	//--------------------------------------------------------------------------
	// Spposta la lente nella posizione del cursore x,y tenendo conto degli 
	// offset dell'oggetto su cui zoomare ox,oy
	//--------------------------------------------------------------------------
	Visualizzatore.prototype.lens = function(x,y,ox,oy) {
            var lens = document.getElementById('bdv_lens') ;
            x+=document.documentElement.scrollLeft ;
            y+=document.documentElement.scrollTop
            var imglow = x<ox ? document.images["bdv_sx"] : document.images["bdv_dx"] ;
            var ih = imglow.height ;
            var iw = imglow.width ;
            if(x<ox-iw || y<oy || x>ox+iw || y>oy+ih) {
                lens.style.visibility = 'hidden' ;
            } else {
                var img = document.images["bdv_enlarge"] ;
                var p = x<ox ? this.pagSX : this.pagDX ;
                if(!lens.style.visibility || lens.style.visibility=='hidden' || this.lensPag!=p) {
                    lens.style.visibility='visible' ;
                    if(this.lensPag!=p) {
                        var pp = this.pages ? this.pages[p] : this.thumbs[this.thumb-1] ;
                        img.src = this.imagePrefix+"?sid="+this.sid+"&fid="+pp.zid ;//"&path="+this.imagePath+'/'+this.imagePath+'_'+this.arraylist[p].formatPage()+'z.jpg'
                        this.lensPag = this.pages ? p : this.thumb-1 ;
                    }
                }

                lens.scrollTop = img.offsetHeight*(y-oy)/ih-80 ;
                if(x<ox)
                    ox -= iw ;
                lens.scrollLeft = img.offsetWidth*(x-ox)/iw-160 ;

                window.status = document.documentElement.scrollLeft+"/"+document.documentElement.scrollTop ;
                lens.style.left = (x-160)+'px' ;
                lens.style.top = (y-80)+'px' ;
            }
	}

	// ADJUST LENS
	//--------------------------------------------------------------------------
	// Handler per l'onMouseMove all'interno della lente
	//--------------------------------------------------------------------------
	Visualizzatore.prototype.adjustLens = function(evt) {
		if(!evt)
			evt = window.event ;
		if(evt!=null) {
			var bdv = document.getElementById('bdv') ;
			var pag = document.getElementById('bdv_pages') ;
			this.lens(evt.clientX,evt.clientY,pag.offsetWidth/2,pag.offsetTop + bdv.offsetTop) ;
		}
	}

	// ZOOM BY LENS
	//--------------------------------------------------------------------------
	// Handler per l'onClick all'interno della lente
	//--------------------------------------------------------------------------
	Visualizzatore.prototype.zoomByLens = function(evt) {
		if(!evt)
			evt = window.event ;
		if(evt!=null) {
			var bdv = document.getElementById('bdv') ;
			var pag = document.getElementById('bdv_pages') ;
			this.zoom(evt.clientX < pag.offsetWidth/2 ? 'sx' : 'dx') ;
		}
	}
	//
	//------------------------------------------------------------------------------

	Visualizzatore.prototype.rotateSingle = function() {
		if(this.rotation>=0) {
			this.rotation = (this.rotation+1) % 4 ;
			document.getElementById("bdv_pag_dx").style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+this.rotation+')' ;
		} else {
		    alert("Rotazione disponibile solo su Internet Explorer") ;
		}
	}
        
        Visualizzatore.prototype.pageMoving = function(evt,side) {
            this.moveLens(evt, side) ;
            var selman = eval('this.imgSelMan'+side.toUpperCase()) ;
            if(selman)
                selman.mousemove(evt) ;
        }

        Visualizzatore.prototype.hidePopups = function() {
	    document.getElementById('bdv_lens').style.visibility='hidden' ;
	    document.getElementById('bdv_context_menu').style.visibility='hidden' ;
	}

	/* da eliminare: c'è getStruRoot!
	Visualizzatore.prototype.getMainStru = function(struNode) {
	    var ret = stru.id ;
	    var temp = stru ;
	    while(ret!=0) {
		temp = stru.getParent() ;
		
	    }
	    return ret ;
	}*/

	Visualizzatore.prototype.showIndexContextMenu = function(evt) {
	    var layer = document.getElementById('bdv_context_menu') ;
	    var instance = this ;
	    layer.innerHTML = "" ;
	    layer.appendChild(this.createMenuItem('Nuovo indice',function(evt) {instance.createNewIndex(evt)})) ;
	    
	    layer.style.left = (evt.clientX + document.body.scrollLeft - 5) + 'px' ;
	    layer.style.top = (evt.clientY + document.body.scrollTop - 5) + 'px' ;
	    layer.style.visibility = 'visible' ;
	}

	Visualizzatore.prototype.createNewIndex = function(evt) {
	    document.getElementById('bdv_context_menu').style.visibility='hidden' ;
	    var figli = this.index.root.figli ;
	    var n = figli.length+1 ;
	    var s = new Stru(-n,"Indice "+n,1,this.pages.length-1) ;
	    s.type = 2 ;
	    n = new Node(-n,s) ;
	    n.modified = true ;
	    this.index.addChild(0,n) ;
	    this.index.redraw() ;
	}

   	Visualizzatore.prototype.showStruContextMenu = function(evt) {

	    if(document.getElementsByName(this.name+"_saveindex").length) {

                var stru = this.index.selected.value ;
                var layer = document.getElementById('bdv_context_menu') ;
                layer.innerHTML = "" ;
                var instance = this ;

                var type = this.computeStruRoot(this.index.selected).value.type ;
                layer.innerHTML = "<div class='context_menu_item' style='text-align:center;font-variant:small-caps;font-weight:bold;font-style:italic;border:1px outset #D8CE89; background-color:#D8CE89'>[operazioni]</div>" ;
                if(type==2) {
                    if(stru.type==1)
                            layer.appendChild(this.createMenuItem('Aggiungi sopra',function(evt) {instance.showStruNewSibling(evt)})) ;
                    layer.appendChild(this.createMenuItem('Aggiungi figlio',function(evt) {instance.showStruNewChild(evt)})) ;
                    if(stru.type==1 && this.index.selected.figli.length)
                            layer.appendChild(this.createMenuItem('Rendi foglia',function(evt) {instance.makeStruLeaf(evt)})) ;
                    if(stru.type==1) {
                            layer.appendChild(this.createMenu('Sposta sotto...','struchoose')) ;
                            var node = this.index.selected ;
                            var i ;
                            var index = node.padre.figli.indexOf(node) ;
                            var divmenu = document.getElementById('bdv_context_menu_struchoose') ;
                            for(i=index-1;i>=0;i--) {
                                    var s = node.padre.figli[i].value ;
                                    divmenu.appendChild(this.createMenuItem(s.titolo, new Function(this.name+".moveStru("+node.id+","+s.id+")"))) ;
                            }
                    }
                    layer.appendChild(this.createMenuSeparator()) ;
                    layer.appendChild(this.createMenuItem('Modifica',function(evt) {instance.showStruEdit(evt)})) ;
                    layer.appendChild(this.createMenuItem('Elimina',function(evt) {instance.delStru(evt)})) ;

                    if(this.index.selected.info) {
                            layer.appendChild(this.createMenuSeparator()) ;
                            layer.appendChild(this.createMenuItem('Scollega spoglio',function(evt) {instance.unlinkAnalytic(evt)})) ;
                    } else {
                            //collegamento spogli non collegati
                            layer.appendChild(this.createMenuSeparator()) ;
                            layer.appendChild(this.createMenu('Collega spoglio','linkanalytic')) ;
                    }

                    if(!this.lostAnalytics) {
                            this.lostAnalytics = new Array() ;
                            this.magLoadClient.send("mag?sid="+this.savingID+"&op=getanalytics&rid="+this.rid, 
                                function(req) {
                                    if(req.getStatus()==200) {
                                        var xml = req.getResponseXML() ;
                                        var els = xml.getElementsByTagName("a") ;
                                        var i ;
                                        instance.lostAnalytics = new Array() ;
                                        for(i=0;i<els.length;i++) {
                                            instance.lostAnalytics[i*2] = els.item(i).getAttribute("id") ;
                                            instance.lostAnalytics[i*2+1] = els.item(i).text ? els.item(i).text : els.item(i).textContent ;
                                        }
                                        instance.doAnalyticsMenu(stru.id) ;
                                    }
                                }
                            ) ;
                    } else
                        this.doAnalyticsMenu(stru.id) ;

                } else
                    layer.innerHTML+="<div class='context_menu_item'><i>Nessuna operazione disponilibile</i></div>" ;

                layer.style.left = (evt.clientX + document.body.scrollLeft - 5) + 'px' ;
                layer.style.top = (evt.clientY + document.body.scrollTop - 5) + 'px' ;
                layer.style.visibility = 'visible' ;
                return false ;

	    } else
                return true ;

	}

	Visualizzatore.prototype.doAnalyticsMenu = function(nodeid) {
	    var divmenu = document.getElementById('bdv_context_menu_linkanalytic') ;
	    if(divmenu && this.lostAnalytics.length>1) {
                var i ;
                for(i=0;i<this.lostAnalytics.length;i+=2) {
                    var code = this.lostAnalytics[i] ;
                    divmenu.appendChild(this.createMenuItem(this.lostAnalytics[i+1], new Function(this.name+".linkAnalytic("+code+","+nodeid+")"))) ;
                }
	    }
	}

	Visualizzatore.prototype.linkAnalytic = function(refid,nodeid) {
	    var node = this.index.getNode(nodeid) ;
	    var i ;
	    var title ;
	    for(i=0;i<this.lostAnalytics.length;i++)
		if(this.lostAnalytics[i]==refid) {
		    title = this.lostAnalytics[i+1] ;
		    break ;
		}
	    this.lostAnalytics.splice(i,2) ;
	    node.info = refid ;
	    node.value.titolo = title ;
	    node.modified = true ;
	    this.index.redraw() ;
	    document.getElementById('bdv_context_menu_linkanalytic').style.visibility='hidden' ;
	    document.getElementById('bdv_context_menu').style.visibility='hidden' ;
	}

	Visualizzatore.prototype.unlinkAnalytic = function() {
	    if(confirm("Sei sicuro?")) {
                var node = this.index.selected ;
                this.lostAnalytics.push(node.info) ;
                this.lostAnalytics.push(node.value.titolo) ;
                node.info = null ;
                node.modified = true ;
                this.index.redraw() ;
	    }
	    document.getElementById('bdv_context_menu').style.visibility='hidden' ;
	}

    	Visualizzatore.prototype.createMenuItem = function(title,action,checked) {
	    var div = document.createElement("div") ;
	    div.innerHTML = "<a href='#'><img src='"+(checked ? 'check.gif' : 'tr.gif')+"' width='10' height='10'/>"+title+"</a>" ;
	    div.className = 'bdv_context_menu_item' ;
	    div.onclick = action ;
	    return div ;
	}
	
	Visualizzatore.prototype.createMenuSeparator = function() {
	    var ret = document.createElement("div") ;
	    //ret.setAttribute("style","width:100%") ;
	    ret.innerHTML = "<hr style='width:100; text-align: center'/>" ;
	    return ret ;
	}

	Visualizzatore.prototype.createMenu = function(title, menu) {
	    var div = document.createElement("div") ;
	    //div.setAttribute("style","width:100%") ;
	    var html = "<a href='#' style='display:inline'>"+title+"</a>" ;
	    html += "<div id='bdv_context_menu_"+menu+"' style='position:absolute;display:inline' class='bdv_popup'>" ;
	    html += "<div class='context_menu_item' style='width:100%;text-align:center;font-variant:small-caps;font-weight:bold;font-style:italic;border:1px outset #D8CE89; background-color:#D8CE89'>[scegli]</div>" ;
	    html += "</div>" ;
	    div.innerHTML = html ;

	    div.className = 'bdv_context_menu_item' ;
	    div.onmouseover = function() {
                document.getElementById('bdv_context_menu_'+menu).style.visibility = 'visible';
	    }
	    div.onmouseout = function() {
                document.getElementById('bdv_context_menu_'+menu).style.visibility = 'hidden';
	    }
	    return div ;
	}

	Visualizzatore.prototype.showStruMask = function(evt,title,start,stop) {
	    this.editingStru = this.index.selected.value ;
	    if(this.pages.length) {
                evt = evt ? evt : window.event ;
                var layer = document.getElementById("bdv_stru_edit") ;
                var stru = this.editingStru ;

                document.modulo['/bdviewer/popup/titolo'].value = title ;
                document.modulo['/bdviewer/popup/inizio'].selectedIndex = start - 1 ;
                document.modulo['/bdviewer/popup/fine'].selectedIndex = stop - 1 ;
                document.modulo['/bdviewer/popup/nr_inizio'].value = start ;
                document.modulo['/bdviewer/popup/nr_fine'].value = stop ;

                layer.style.left = (evt.clientX + document.body.scrollLeft) + 'px' ;
                layer.style.top = (evt.clientY + document.body.scrollTop) + 'px' ;
                layer.style.visibility = 'visible' ;
	    }
	    document.getElementById('bdv_context_menu').style.visibility='hidden' ;
	}

	Visualizzatore.prototype.hideStruMask = function() {
	    document.getElementById('bdv_stru_edit').style.visibility='hidden' ;
	    this.editingStruNew = null ;
	    this.editingStru = null ;
	}

	Visualizzatore.prototype.showStruEdit = function(evt) {
	    this.editingStruNew = null ;
	    document.getElementById('bdv_stru_edit_bar').innerHTML = 'Modifica Struttura Indice' ; 
	    var stru = this.index.selected.value ;
	    this.showStruMask(evt, stru.titolo, stru.start, stru.stop) ;
	}

	Visualizzatore.prototype.showStruNewChild = function(evt) {
	    this.editingStruNew = "child" ;
	    document.getElementById('bdv_stru_edit_bar').innerHTML = 'Nuova Struttura Indice' ;
	    var stru = this.index.selected.value ;
	    var start = stru.start ;
	    var n = this.index.getNode(stru.id) ;
	    if(n.figli.length)
                start = n.figli[n.figli.length-1].value.stop ;
	    this.showStruMask(evt,'',start,start) ;
	}

	Visualizzatore.prototype.showStruNewSibling = function(evt) {
	    this.editingStruNew = "sibling" ;
	    document.getElementById('bdv_stru_edit_bar').innerHTML = 'Nuova Struttura Indice' ;
	    var stru = this.index.selected.value ;
	    this.showStruMask(evt,'',stru.start,stru.start) ;
	}

	Visualizzatore.prototype.makeStruLeaf = function(evt) {
	    document.getElementById('bdv_context_menu').style.visibility='hidden' ;
	    if(confirm("Sei sicuro?")) {
                var node = this.index.selected ;
                var stopPag = node.figli[0].value.start-1 ;
                if(stopPag < node.value.start)
                    stopPag = stopPag+1 ;
                if(node.value.stop!=stopPag) {
                    node.modified = true 
                    node.value.stop = stopPag ;
                }

                var i ;
                var nodeIndex = node.padre.figli.indexOf(node) ;
                var padreLen = node.padre.figli.length ;
                for(i=padreLen-1;i>=nodeIndex+1;i--)
                    node.padre.figli[i+node.figli.length] = node.padre.figli[i] ;
                for(i=node.figli.length-1;i>=0;i--) {
                    if(!node.padre.id)
                    node.padre.id = -node.id
                    node.figli[i].padre = node.padre ;
                    node.figli[i].modified = true ;
                    node.padre.figli[nodeIndex+1+i] = node.figli[i] ;
                }
                node.figli = new Array() ;
                this.index.redraw() ;
	    }
	}

	Visualizzatore.prototype.delStru = function(evt) {
	    document.getElementById('bdv_context_menu').style.visibility='hidden' ;
	    if(confirm("Sei sicuro? Questa operazione rimuove l'intero ramo:\n\""+this.index.selected.value.titolo+"\"")) {
                this.index.removeChild(this.index.selected.id) ;
                this.index.redraw() ;
	    }
	}

	Visualizzatore.prototype.updateStru = function() {

	    var stru = null ;
	    var editingNode = this.index.getNode(this.editingStru.id) ;

	    if(!this.editingStruNew) {

                stru = this.editingStru ;

                //modificando uno stru riservato lo si rende ordinario!
                if(stru.id>0 && stru.id<1000) {
                    this.newStruCounter++ ;
                    stru.id = -this.newStruCounter ;
                    editingNode.id = stru.id ;
                    //propagazione modifica sui figli
                    var i ;
                    for(i=0;i<editingNode.figli.length;i++)
                        editingNode.figli[i].modified = true ;
                }

            } else {

                this.newStruCounter++ ;
                stru = new Stru(-this.newStruCounter,'',0,0) ;//i nodi negativi sono da inserire nel DB!

            }

            var tit = document.modulo['/bdviewer/popup/titolo'].value ;
            if(tit) {

                stru.titolo = tit ;
                stru.start = parseInt(document.modulo['/bdviewer/popup/inizio'].selectedIndex)+1 ;
                stru.stop = parseInt(document.modulo['/bdviewer/popup/fine'].selectedIndex)+1 ;

                var n = editingNode ;
                if(this.editingStruNew=="child") {
                        n = new Node(stru.id,stru) ;
                        this.index.addChild(this.editingStru.id,n) ;
                        editingNode.espanso=true ;
                } else if(this.editingStruNew=="sibling") {
                        n = new Node(stru.id,stru) ;
                        this.index.addSiblingBefore(this.editingStru.id,n) ;
                }
                n.modified = true ;
                this.index.redraw() ;
                this.showStru(this.editingStru.id) ;
                this.hideStruMask() ;

	    } else
                alert("Il titolo e' obbligatorio!") ;
	}

	Visualizzatore.prototype.moveStru = function(from, to) {
	    //from e to sono rovesciati come valori assoluti (si va dal basso verso l'alto nell'indice)
	    var startNode = this.index.getNode(from) ;
	    var startIndex = startNode.padre.figli.indexOf(startNode) ;
	    var endNode = this.index.getNode(to) ;
	    var endIndex = endNode.padre.figli.indexOf(endNode) ;
	    var i ;
	    var toMove = new Array() ;
	    for(i=endIndex+1;i<=startIndex;i++)
                toMove.push(endNode.padre.figli[i]) ;
	    for(i=0;i<toMove.length;i++) {
                var n = toMove[i] ;
                n.modified = true ;
                n.padre.figli.remove(n) ;
                endNode.figli.push(n) ;
                n.padre = endNode ;
	    }
	    if(!endNode.espanso)
                this.index.expandNode(endNode.id) ;
	    endNode.value.stop = startNode.value.stop ;
	    endNode.modified = true ;
	    this.index.redraw() ;
	    document.getElementById('bdv_context_menu_struchoose').style.visibility='hidden' ;
	    document.getElementById('bdv_context_menu').style.visibility='hidden' ;
	}

	Visualizzatore.prototype.presetStruStart = function(conf, section) {
	    if(!this.presetStru) {
                this.presetStru = true ;

                section = section ? section+"_" : "" ;
                //var startPag = parseInt(document.modulo['/bdviewer/popup/'+section+'nr_inizio'].value) ;
                //var stopPag = parseInt(document.modulo['/bdviewer/popup/'+section+'nr_fine'].value) ;
                var startPag = parseInt(document.modulo['/bdviewer/popup/'+section+'inizio'].selectedIndex)+1 ;
                var stopPag = parseInt(document.modulo['/bdviewer/popup/'+section+'fine'].selectedIndex)+1 ;
                var titPag = this.pages[this.pagSX].titolo ;

                if(this.pagSX > stopPag)
                    alert("Impossibile impostare la pagina di inizio ("+titPag+") successiva a quella di fine") ;

                else if(this.pagSX!=startPag && (!conf || confirm("Imposto la pagina iniziale a "+titPag+"?")))
                    //document.modulo['/bdviewer/popup/'+section+'inizio'].value = titPag ;
                    document.modulo['/bdviewer/popup/'+section+'inizio'].selectedIndex = this.pagSX-1;

	    }
	    this.presetStru = false ;
	}

	Visualizzatore.prototype.presetStruStop = function(conf, section) {
	    if(!this.presetStru) {
                this.presetStru = true ;

                section = section ? section+"_" : "" ;
                var startPag = parseInt(document.modulo['/bdviewer/popup/'+section+'inizio'].selectedIndex)+1 ;
                var stopPag = parseInt(document.modulo['/bdviewer/popup/'+section+'fine'].selectedIndex)+1 ;
                var titPag = this.pages[this.pagSX].titolo ;

                //controllo coerenza interna
                if(this.pagSX < startPag) {
                    alert("Impossibile impostare la pagina di fine ("+titPag+") precedente a quella di inizio") ;

                //controllo limiti struttura genitore
                } else if(!this.checkStruParentConstraints(startPag, this.pagSX)) {
                    alert("Impossibile impostare le pagine oltre i confini della struttura contenitore") ;

                //controllo limiti strutture adiacenti
                } else if(!this.checkStruBoundariesConstraints(startPag,this.pagSX)) {
                    alert("Impossibile impostare le pagine oltre i confini delle strutture adiacenti") ;

                //impostazione (confermata o meno)
                } else if(this.pagSX!=stopPag && (!conf || confirm("Imposto la pagina finale a "+titPag+"?"))) {
                    //document.modulo['/bdviewer/popup/'+section+'fine'].value = titPag ;
                    document.modulo['/bdviewer/popup/'+section+'fine'].selectedIndex = this.pagSX-1 ;
                }
	    }
	}

	Visualizzatore.prototype.changeStruStart = function() {
	    if(!this.presetStru) {
                this.presetStru = true ;
                var startPag = document.modulo['/bdviewer/popup/inizio'].selectedIndex+1 ;
                var stopPag = document.modulo['/bdviewer/popup/fine'].selectedIndex+1 ;
                var check = this.checkStruConstraints(startPag,stopPag) ;
                if(!check) {
                    this.showPages(startPag) ;
                    document.modulo['/bdviewer/popup/nr_inizio'].value = startPag ;
                } else {
                    document.modulo['/bdviewer/popup/inizio'].selectedIndex = parseInt(document.modulo['/bdviewer/popup/nr_inizio'].value) - 1 ;
                    alert(check) ;
                }
	    }
	    this.presetStru = false ;
	}

	Visualizzatore.prototype.changeStruStop = function() {
	    if(!this.presetStru) {
                this.presetStru = true ;
                var startPag = document.modulo['/bdviewer/popup/inizio'].selectedIndex+1 ;
                var stopPag = document.modulo['/bdviewer/popup/fine'].selectedIndex+1 ;
                var check = this.checkStruConstraints(startPag,stopPag) ;
                if(!check) {
                    this.showPages(stopPag) ;
                    document.modulo['/bdviewer/popup/nr_fine'].value = stopPag ;
                } else {
                    document.modulo['/bdviewer/popup/fine'].selectedIndex = parseInt(document.modulo['/bdviewer/popup/nr_fine'].value) - 1 ;
                    alert(check) ;
                }
	    }
	    this.presetStru = false ;
	}

	Visualizzatore.prototype.checkStruConstraints = function(pstart, pstop) {
	    var ret = null ;

	    //controllo coerenza interna
	    if(pstop < pstart) {
		//ret = "Impossibile impostare la pagina di fine precedente a quella di inizio" ;

	    //controllo limiti struttura genitore
	    } else if(!this.checkStruParentConstraints(pstart, pstop)) {
		ret = "Impossibile impostare le pagine oltre i confini della struttura contenitore" ;
		
	    //controllo limiti strutture adiacenti
	    } else if(!this.checkStruBoundariesConstraints(pstart,pstop)) {
		//ret = "Impossibile impostare le pagine oltre i confini delle strutture adiacenti" ;

	    }
	    return ret ;
	}

	Visualizzatore.prototype.checkStruParentConstraints = function(pstart, pstop) {
	    var sel = this.index.getNode(this.editingStru.id) ;
	    var struPadre = this.editingStruNew=="child" ? sel.value : sel.padre.value ;
	    return struPadre.start<=pstart && struPadre.stop>=pstop ;
	}

	Visualizzatore.prototype.checkStruBoundariesConstraints = function(pstart, pstop) {
	    var ret = true ;
	    var index1 = -1 ;
	    var index2 = -1 ;
	    var padre = null ;
	    if(!this.editingStruNew) {
	        var sel = this.index.getNode(this.editingStru.id) ;
                padre = sel.padre ;
                index1 = padre.figli.indexOf(sel)-1 ;
                index2 = index1+2 ;
	    } else if(this.editingStruNew=="child") {
                padre = this.index.getNode(this.editingStru.id) ;
                index1 = padre.figli.length-1 ;
                index2 = padre.figli.length ;
	    } else if(this.editingStruNew=="sibling") {
                var sel = this.index.getNode(this.editingStru.id) ;
                padre = sel.padre ;
                index2 = padre.figli.indexOf(sel) ;
                index1 = index2-1 ;
	    } else
                return false ;

	    if(index1>=0 && padre.figli[index1].value.stop>pstart)
		ret = false ;
	    if(index2<padre.figli.length && padre.figli[index2].value.start<pstop)
		ret = false ;

	    return ret ;
	}

	Visualizzatore.prototype.loadMAG = function(what) {
	    pagina.call(this.path,'reload',what.join('-')) ;
	}

	Visualizzatore.prototype.saveMAG = function() {
            var ajax = this.magSaveClient ;
	    if(!ajax.multisending) {
                //viene rigenerato a ogni salvataggio
                this.savingID = this.sid+"-"+Math.random() ;

                this.saveSections = new Array() ;
                this.saveMAGStack = new Array() ;
                if(this.index)
                    this.saveMAGStack.push(this.index.root) ;

                ajax.changeURL("mag?sid="+this.savingID+"&op=startsave") ;
                ajax.multisend() ;
            } else
                alert("Salvataggio dell'indice gia' in corso...") ;
	}

	Visualizzatore.prototype.showImgContextMenu = function(evt,side) {
	    var layer = document.getElementById('bdv_context_menu') ;
	    var instance = this ;

	    var pag ;
	    if(this.tipoSX=='illust') {
                pag = this.thumbs[this.thumb-1].pag ;
	    } else {
                pag = eval('this.pag'+side.toUpperCase()) ;
            }
        
            var selman = eval('this.imgSelMan'+side.toUpperCase()) ;
            var sels = selman.getSelectedZones() ;

            this.editingSide = side ;

            if(sels.length) {
                
                layer.innerHTML = "<div class='context_menu_item' style='text-align:center;font-variant:small-caps;font-weight:bold;font-style:italic;border:1px outset #D8CE89; background-color:#D8CE89'>zona</div>" ;
                
                var sel = sels[0] ;
                document.modulo[this.path+'@zoneid'].value = sel.id ;
                
                var linksel = document.getElementsByName('/piede/linksel/link') ;
                if(linksel.length)
                    linksel = linksel.item(0).value ;
                else
                    linksel = null ;
                if(linksel)
                    layer.appendChild(this.createMenuItem('Aggiungi link veloce',function(evt) {
                        pagina.call(instance.path,'makelink','zone-quick','','quicklink', linksel ? "resizable=yes" : '', '','','','salva') ;
                    })) ;
                    
                layer.appendChild(this.createMenuItem('Gestione links',function(evt) {
                    pagina.call(instance.path,'makelink','zone','','links') ;
                })) ;
                
                layer.appendChild(this.createMenuSeparator()) ;
                
                layer.appendChild(this.createMenuItem('Cambia titolo',function(evt) {instance.changeTitle(evt,'sel') ;})) ;
                layer.appendChild(this.createMenuItem('Elimina',function(evt) {
                    if(confirm("Sei sicuro?")) {
                        var man = eval('instance.imgSelMan'+side.toUpperCase()) ;
                        man.deleteSelected() ;
                    }
                })) ;
                
                if(this.choose) {
                    layer.appendChild(this.createMenuSeparator()) ;
                    layer.appendChild(this.createMenuItem('Scegli', function(evt) {
                        pagina.call(instance.path,'zonelink',sel.id,'','_parent','','','','','ripristina') ;
                    })) ;
                }
                
	    } else if(pag) {
                
                layer.innerHTML = "<div class='context_menu_item' style='text-align:center;font-variant:small-caps;font-weight:bold;font-style:italic;border:1px outset #D8CE89; background-color:#D8CE89'>pagina</div>" ;
                
                layer.appendChild(this.createMenuItem('Cambia nomenclatura',function(evt) {instance.changeTitle(evt,'img')})) ;
                layer.appendChild(this.createMenuItem('Illustrazione', function(evt) {instance.markIllust(evt)}, (this.pages[pag].pitflag&2)==2)) ;
                layer.appendChild(this.createMenuItem('Trascrizione', function(evt) {instance.transcript(evt,side)}, (this.pages[pag].pitflag&4)==4)) ;
                layer.appendChild(this.createMenuItem('Rinumera', function(evt) {instance.showRenumberMask(evt)})) ;
                
                if(this.choose) {
                    layer.appendChild(this.createMenuSeparator()) ;
                    layer.appendChild(this.createMenuItem('Scegli', function(evt) {
                        pagina.call(instance.path,'paglink',selman.imgrid,'','_parent','','','','','ripristina') ;
                    })) ;
                }
                
            //TODO: libro con illustrazioni solo!
	    } else
                
                layer.innerHTML += "<div class='context_menu_item'><i>Nessuna operazione disponibile</i></div>" ;
	    
	    layer.style.left = (evt.clientX + document.body.scrollLeft - 5) + 'px' ;
	    layer.style.top = (evt.clientY + document.body.scrollTop - 5) + 'px' ;
	    layer.style.visibility = 'visible' ;
            
	}

	Visualizzatore.prototype.changeTitle = function(evt,section) {
	    evt = evt ? evt : window.event ;
	    var popup = document.getElementById("bdv_img_edit") ;

	    popup.style.left = (evt.clientX + document.body.scrollLeft) + 'px' ;
	    popup.style.top = (evt.clientY + document.body.scrollTop) + 'px' ;
	    popup.style.visibility = 'visible' ;

	    document.getElementById('bdv_context_menu').style.visibility='hidden' ;
            var tit = "?" ;
            this.titleSection = section ;
            if(section=='img') {
                document.getElementById('bdv_img_edit_bar').innerHTML = "Modifica immagine" ;
                tit = eval('this.pages[this.pag'+this.editingSide.toUpperCase()+'].titolo') ;
            } else if(section=='sel') {
                document.getElementById('bdv_img_edit_bar').innerHTML = "Modifica selezione" ;
                var selman = eval('this.imgSelMan'+this.editingSide.toUpperCase()) ;
                tit = selman.getSelectedZones()[0].title ;
            }
	    document.modulo[this.path+"/popimg/titolo"].value = tit ;
	}

	Visualizzatore.prototype.updateTitleMask = function() {
	    var tit = document.modulo[this.path+"/popimg/titolo"].value ;
	    if(tit) {
                
                if(this.titleSection=='img') {
                    var p = eval('this.pages[this.pag'+this.editingSide.toUpperCase()+']') ;
                    p.titolo = tit ;
                    p.modified = true ;
                    this.reloadPages() ;
                } else if(this.titleSection=='sel') {
                    var selman = eval('this.imgSelMan'+this.editingSide.toUpperCase()) ;
                    var s = selman.getSelectedZones()[0] ;
                    s.setTitle(tit) ;
                    s.modified = true ;
                }
                
                this.hideTitleMask() ;
                
	    } else {
                
                alert("Il titolo e' obbligatorio!") ;
                
	    }
	}
    
	Visualizzatore.prototype.hideTitleMask = function() {
	    var popup = document.getElementById("bdv_img_edit") ;
	    popup.style.visibility = 'hidden' ;
	}

	Visualizzatore.prototype.markIllust = function(evt) {

	    document.getElementById('bdv_context_menu').style.visibility='hidden' ;
	    var pag = this.pages[this.pagDX] ;
	    var ill = (pag.pitflag & 2) == 2 ;

	    if(!ill) {

                var i ;
                for(i=0;i<this.thumbs.length;i++) {
                    var t = this.thumbs[i] ;
                    if(t.server==2 || t.pag > this.pagDX)
                        break ;
                }

                this.insertThumb(i,new Thumb(this.pagDX,pag.titolo,pag.id,pag.zid,null,pag.server)) ;
                this.rebuildSliderT() ;
                pag.pitflag |= 2 ;
                //this.setSections('illust','pagina') ;
                //this.thumbsPage = 0 ;
                //this.oldThumb = 0 ;
                //this.clearThumbSelection() ;
                //this.showThumb(i) ;

	    } else {

                var i ;
                for(i=0;i<this.thumbs.length;i++) {
                    var t = this.thumbs[i] ;
                    if(t.server!=2 && t.pag==this.pagDX) {
                        this.removeThumb(i) ;
                        break ;
                    }
                }

                //this.sliderT.removeValue(i) ;
                //this.rebuildSliderT() ;
                pag.pitflag &= 253 ;
                //var old = this.oldThumb ;
                //this.thumbsPage = 0 ;
                //this.oldThumb = 0 ;
                //this.clearThumbSelection() ;
                //this.showThumb(old) ;

	    }

	    pag.modified = true ;

	}
        
	Visualizzatore.prototype.transcript = function(evt, side) {

            var p = eval('this.pag'+side.toUpperCase()) ;
	    pagina.call(this.path,'/digle/consultazione/edittxt',this.pages[p].rid,'edittxt','edittxt','width=800,height=600') ;

	    /*document.getElementById('bdv_context_menu').style.visibility = 'hidden' ;

	    document.getElementById('bdv_pag_dx').style.visibility = 'hidden' ;
	    var layer = document.getElementById('bdv_trascr_edit') ;
	    layer.style.visibility = 'visible' ;

	    var ajax = this.txtClient ;
	    var pp = this.pages[this.pagDX] ;
	    ajax.open("GET", "textlo?sid="+this.sid+"&fid="+pp.id+"&rid="+pp.rid+"&para=no") ;
	    var path = this.path ;
	    ajax.onreadystatechange = function() {
			if(ajax.readyState==4 && ajax.status==200)
				document.modulo[path+'/txtedit/txt'].value = ajax.responseText ;
	    }
	    ajax.send() ;*/

	    //document.getElementById('bdv')
	}

	/*Visualizzatore.prototype.saveTranscrEdit = function(evt) {
	    var ajax = this.txtClient ;
	    var pp = this.pages[this.pagDX] ;
	    ajax.open("POST", "mag?sid="+this.sid+"&op=save-txt&pagid="+pp.id+"&txt="+document.modulo[this.path+'/txtedit/txt'].value) ;
	    ajax.onreadystatechange = function() {
		if(ajax.readyState==4 && ajax.status==200)
		    alert('OK') ;
	    }
	    ajax.send() ;
	    this.hideTranscrEdit() ;
	}

	Visualizzatore.prototype.hideTranscrEdit = function(evt) {
	    document.getElementById('bdv_pag_dx').style.visibility = 'visible' ;
	    document.getElementById('bdv_trascr_edit').style.visibility = 'hidden' ;
	}*/

	Visualizzatore.prototype.showRenumberMask = function(evt) {
	    evt = evt ? evt : window.event ;
	    document.getElementById('bdv_context_menu').style.visibility = 'hidden' ;
	    var layer = document.getElementById('bdv_imgnr_edit') ;
	    layer.style.left = (evt.clientX + document.body.scrollLeft - 5) + 'px' ;
	    layer.style.top = (evt.clientY + document.body.scrollTop - 5) + 'px' ;
	    layer.style.visibility = 'visible' ;
	    this.renumberStart = this.pagDX ;var ajax = this.magSaveClient ;
	    document.getElementById(this.name+'_imgnr_fine').innerHTML = "-" ;
	    this.changeRenumberType() ;
	}

	Visualizzatore.prototype.hideRenumberMask = function() {
	    document.getElementById('bdv_imgnr_edit').style.visibility = 'hidden' ;
	}

	Visualizzatore.prototype.changeRenumberType = function() {
	    var sel = document.modulo[this.path+'/imgnrpopup/tipo'] ;
	    document.getElementById(this.name+'_imgnr_tipo').innerHTML = sel.options[sel.selectedIndex].text ;
	}

	Visualizzatore.prototype.changeRenumberStart = function() {
	    var pag = document.modulo[this.path+'/imgnrpopup/inizio'] ;
	    var nr = parseInt(pag.value) ;
	    if(nr>0 && this.pagDX > this.renumberStart)
                document.getElementById(this.name+'_imgnr_fine').innerHTML = nr+this.pagDX-this.renumberStart ;
	}

	Visualizzatore.prototype.renumber = function() {
	    var i ;
	    var pag = parseInt(document.modulo[this.path+'/imgnrpopup/inizio'].value) ;
	    for(i=this.renumberStart;i<=this.pagDX;i++) {
                this.pages[i].titolo = document.getElementById(this.name+'_imgnr_tipo').innerHTML + " " + (pag + i - this.renumberStart) ;
                this.pages[i].modified = true ;
	    }
	    this.hideRenumberMask() ;
	    this.reloadPages() ;
	}

	Visualizzatore.prototype.reloadPages = function() {
	    for(i=1;i<this.pages.length;i++) {
                document.modulo['/bdviewer/popup/inizio'].options[i-1]=new Option(this.pages[i].titolo,i) ;
                document.modulo['/bdviewer/popup/fine'].options[i-1]=new Option(this.pages[i].titolo,i) ;
	    }
	    this.checkPages() ;
	}

	Visualizzatore.prototype.enboss = function(side,word) {
	    var lay = document.getElementById("layer_bdv_trascr_"+side) ;
	    var txt = lay.innerHTML ;
	    var newTXT = "" ;
	    var index = 0,newIndex ;
	    var re=new RegExp(word,"ig") ;
	    while(re.exec(txt)!=null) {
                newIndex = re.lastIndex ;
                var chars = RegExp.lastMatch ;
                newTXT += txt.substring(index,newIndex-chars.length) ;
                newTXT += "<span class='trasc_match'>"+chars+"</span>" ;
                index = newIndex ;
	    }
	    txt = newTXT+txt.substring(index) ;
	    lay.innerHTML = txt ;
	}
	
	Visualizzatore.prototype.showTxtContextMenu = function(evt,side) {
	    var layer = document.getElementById('bdv_context_menu') ;
	    var instance = this ;

	    layer.innerHTML = "<div class='context_menu_item' style='text-align:center;font-variant:small-caps;font-weight:bold;font-style:italic;border:1px outset #D8CE89; background-color:#D8CE89'>testo</div>" ;

	    layer.appendChild(this.createMenuItem('Modifica trascrizione', function(evt) {instance.transcript(evt,side)})) ;
            
            layer.appendChild(this.createMenuSeparator()) ;
            
            //TODO: marcature indice
	    //var sel = document.getSelection ? document.getSelection() : document.selection.createRange().text ;
	    //if(sel)
            //   layer.appendChild(this.createMenuItem('Marca selezione',function(evt) {instance.showTxtEdit(evt,side)})) ;
            
            var type = eval('this.tipo'+side.toUpperCase()) ;
            var oppside = side=='sx' ? 'dx' : 'sx' ;
            var opptype = eval('this.tipo'+oppside.toUpperCase()) ;
            
            var selman = eval('this.imgSelMan'+oppside.toUpperCase()) ;
            var zs = selman.getSelectedZones() ;
            var txtsel = eval('this.txtSelMan'+side.toUpperCase()) ;
            var ts = txtsel.getSelectedMarks() ;
            
            if(zs.length==1 && !ts.length) {
            //------------ menu' collega zona con selezione testo --------------
            //
                var z = zs[0] ;
                layer.appendChild(this.createMenuItem('Collega zona \''+z.title+'\'',function(evt) {
                    
                    var ar = new AjaxRequest() ;
                    var s = document.getElementById("layer_bdv_trascr_"+side) ;
                    var p = eval('instance.pages[instance.pag'+side.toUpperCase()+']') ;
                    
                    ar.addHandler(function(req) {
                        var ret = false ;

                        //aggiornamento da salvataggio precedente
                        var xml = req.getResponseXML() ;
                        var retid = xml.getElementsByTagName("zone") ;
                        if(retid.length) {
                            var retval = retid.item(0) ;
                            z.changeID(parseInt(retval.getAttribute("new-id")),selman.layer) ;
                        }
                        
                        if(!req.retrig && z.id<0) {
                            req.changeURL("mag?op=save-zone&zid="+z.id+"&title="+z.title+"&x="+z.x+"&y="+z.y+"&w="+z.w+"&h="+z.h) ;
                            ret = true ;
                        }
                        
                        return ret ;
                    }) ;
                    ar.addHandler(function(req) {
                        var ret = false ;
                        if(!req.retrig) {
                            req.changeURL("mag?op=link-zone2mark&sid="+instance.savingID+"&rid="+p.rid+"&zid="+z.id+"&start="+txtsel.start+"&end="+txtsel.end) ;
                            ret = true ;
                        }
                        return ret ;
                    }) ;
                    ar.addHandler(function(req) {
                        var ret = false ;
                        if(!req.retrig) {//prima passata
                            req.changeURL("mag?op=endsave&sid="+instance.savingID) ;
                            ret = true ;
                        } else if(type=='trascr')//seconda passata
                            instance.loadPage(side) ;
                        return ret ;
                    }) ;
                    instance.savingID = instance.sid+"-"+Math.random() ;
                    ar.changeURL("mag?op=startsave&sid="+instance.savingID) ;
                    ar.multisend() ;
                })) ;
            //
            //------------------------------------------------------------------
            
            } else if(ts.length) {
            //-------------- menu' editing marcature esistenti -----------------                
            //
                var i ;
                var sels = new Array() ;
                for(i=0;i<ts.length;i++)
                    if(!sels.contains(ts[i].id))
                        sels.push(ts[i].id) ;
                if(sels.length)
                    layer.appendChild(this.createMenuItem('Elimina marcature', function() {
                        if(confirm("Sei sicuro?")) {
                            var ar = new AjaxRequest() ;
                            ar.send("mag?op=delete-marks&ids="+sels.join(","), function(req) {
                                if(req.getStatus()==200) {
                                    instance.loadPage(side) ;
                                } else
                                    alert("Errore cancellazione") ;
                            }) ;
                        }
                    })) ;
            //
            //------------------------------------------------------------------
            }

	    layer.style.left = (evt.clientX + document.body.scrollLeft - 5) + 'px' ;
	    layer.style.top = (evt.clientY + document.body.scrollTop - 5) + 'px' ;
	    layer.style.visibility = 'visible' ;
	}

	Visualizzatore.prototype.showTxtEdit = function(evt,side) {
	    evt = evt ? evt : window.event ;
	    var layer = document.getElementById("bdv_txt_edit") ;

	    document.modulo['/bdviewer/poptxt/src'].value = document.getSelection() ;

	    layer.style.left = (evt.clientX + document.body.scrollLeft) + 'px' ;
	    layer.style.top = (evt.clientY + document.body.scrollTop) + 'px' ;
	    layer.style.visibility = 'visible' ;

	    document.getElementById('bdv_context_menu').style.visibility='hidden' ;
	}
        
        Visualizzatore.prototype.setZoneEdit = function() {
            var check = document.modulo[this.path+'@zonedit'] ;
            var ok = check ? check.checked : false ;
            if(this.imgSelManSX)
                this.imgSelManSX.setEditable(ok) ;
            if(this.imgSelManDX)
                this.imgSelManDX.setEditable(ok) ;
            if(this.txtSelManSX)
                this.txtSelManSX.setEditable(ok) ;
            if(this.txtSelManDX)
                this.txtSelManDX.setEditable(ok) ;
        }
        
        Visualizzatore.prototype.changeMarkType = function(evt) {
            var req = new AjaxRequest() ;
            var select = document.modulo[this.path+"/poptxt/auth"] ;
            //req.send("auth?type="+select.getSelectedIndex(), function(req) {
                //TODO: aggiungere le voci di authority
            //}) ;
            alert(select.options[select.selectedIndex].value) ;
        }
//
//------------------------------------------------------------------------------
