﻿/*!
 *
 * HAP - hivesoft Historical Archives Platform
 * 
 * 2003-2009, (c) hivesoft di Christian Assante
 * 
 * Nome: hap.js
 * Funzione: Libreria javascript con funzioni di integrazione
 *           della piattaforma HAP.
 *
 */
function postData(id_elemento,extension,parametri,data){
	var elemento;
	
	$(id_elemento).innerHTML = '<img alt="loading" src="images/loading.gif" /> Caricamento in corso... attendere prego.';
	
	new Ajax.Request(extension+"?"+parametri, {
        method: "post",
        postBody: data,
        onSuccess: function(transport) {
            $(id_elemento).innerHTML = transport.responseText;
        },
        onFailure: function(transport) {
            $(id_elemento).innerHTML = transport.responseText;
        }
    }); 
}

function initResults(id_elemento,extension,parametri,data,cluster){
	var elemento;
	
	$(id_elemento).innerHTML = '<img alt="loading" src="images/loading.gif" /> Caricamento in corso... attendere prego.';
	
	new Ajax.Request(extension+"?"+parametri, {
        method: "post",
        postBody: data,
        onSuccess: function(transport) {
            $(id_elemento).innerHTML = transport.responseText;
        
            if (cluster) {
                new Ajax.Request('AJAXClustering.ashx', {
                    method: 'get',   
                    onSuccess: function(transport) {
                        if (transport.responseText.length>0) {
                            expand('acluster');
                            cluster=$('cluster');
                            cluster.update(transport.responseText);

                            /*
                            //Aggiornamento caption
                            var archivi=$("archivi");
                            var testo, size, i, j;
                            if (archivi.options.length==1) {
                                cluster.select("div a").each(function(obj, index) {
                                    testo=obj.innerHTML;
                                    i=testo.lastIndexOf('[');
                                    j=testo.lastIndexOf(']');
                                    size=testo.substring(i+1,j);
                                    testo=testo.substr(0,i-1);
                                    this.appendChild(new Element('option', { title: testo + ' [' + size + ']', 'hap:cluster': obj.onclick }).update('[' + size + '] ' + testo));
                                }, archivi);
                            }
                            */
                        }
                    }
                });

            }
            
            var holders=$(id_elemento).getElementsByClassName('holder');
            for (var i=0; i<holders.length; i++) {
                addRemoveHolder(holders[i],true);
                Event.observe(holders[i], 'click', function (e) {
                    addRemoveHolder(Event.element(e),false);
                });
            }
        },
        onFailure: function(transport) {
            $(id_elemento).innerHTML = transport.responseText;
        }
    }); 

}
function addRemoveHolder(obj,init,action) {
    var uri;

    if (init) {
        obj.checked=!(document.getElementById(normalizeURI(obj.value))==null);
    } else {
        var data = "<holder ";
        if (obj.tagName=="INPUT") {
            action=(obj.checked ? "add" : "remove");
            uri=obj.value;
        } else {
            if (action==null) action="remove";
            uri=obj.getAttribute("hap:uri");
        }
        uri=normalizeURI(uri);
        data += "action=\"" + action + "\" ";
        data += "uri=\"" + uri + "\" ";
        data += "/>";
        
        new Ajax.Request('AJAXHolder.ashx', {
            method: 'post',   
            postBody: data,
            onSuccess: function(transport) {
                var x = $(uri);
                if(transport.responseText.length>0) {
                    if (transport.responseText.substr(0,6)!='alert(') {
                        $('emptyHolder').hide();
                        x = $('piedeHolder');
                        x.show();
                        new Insertion.Before(x, transport.responseText);
                        alert("Documento aggiunto al raccoglitore");
                    } else {
                        eval(transport.responseText);
                        if (obj.tagName=="INPUT") obj.checked = false;
                    }
                } else {
                    x.remove();
                    if ($('raccoglitore').childElements().length<=3) {
                        $('emptyHolder').show();
                        $('piedeHolder').hide();
                    }
                    alert("Documento rimosso dal raccoglitore");
                }
            }
        }); 
    }
}

function normalizeURI(uri) {
    var i=uri.lastIndexOf("/");
    if (uri.substr(i-4, 4)!="hier") {
        j=uri.lastIndexOf("/", i - 1);
        if (j>=0) {
            uri=uri.substr(0, j + 1)+"hier"+uri.substr(i, uri.length - i);
        } else {
            uri="hier"+uri.substr(i, uri.length - i);
        }
    }
    return uri;
}

function initSearch()   {

    $('risultato').innerHTML = '<h3>Risultati della ricerca</h3>Nessuna ricerca attualmente disponibile.';
    $('ricercaAvanzata').innerHTML = '<img src="images/loading.gif" /> Caricamento in corso... attendere prego.';
    
    new Ajax.Request('AJAXQuery.ashx', {
        method: "get",
        onSuccess: function(transport) { 
            var elm=$('ricercaAvanzata');
            elm.innerHTML = transport.responseText;
            initFinderWizard(elm);
        }
    }); 
    
    return false;
}

function addOptions(objSelect, key, label, dictionary, type) {
    var myOption=document.createElement("OPTION");
    myOption.setAttribute("value",key);
    myOption.setAttribute("hap:dictionary",dictionary);
    myOption.innerHTML=label;
    objSelect.appendChild(myOption);
}

function getCluster(obj) {
    var key, uri;
    
    key=obj.getAttribute('hap:key');
    uri=obj.getAttribute('hap:uri');
    expand('acluster');    

    if (obj.className=='chiuso') {
        obj.className='aperto';
        collapse('cls' + key);
    } else {
        obj.className='chiuso';
        
        var elm=$('cls' + key);
        if (elm.innerHTML.length<=1) {
            var data = "<clustering ";
            data += "uri=\"" + uri + "\" ";
            data += "key=\"" + key + "\" ";
            data += "/>";

            postData('cls' + key, 'AJAXClustering.ashx', '', data);
        }
        expand('cls' + key);
    }
    
    return false;
}

function getClusterSelection(obj, key) {
	var xml, value, uri;
    
    //collapse('cluster');
    pannelli(divcollapsecontenuti,'risultato', aspegnicontenuti,this,'tasto_chiuso','tasto_aperto');
    
    obj=$(obj);
    uri = obj.up(1).previous('a').getAttribute('hap:uri');
    value = obj.up().getAttribute('hap:cls');
    
    xml = '<freeQuery ';
    xml += 'refine="' + uri + '"';
    xml += '>' + key + '="' + value + '"' + '</freeQuery>';

    initResults('risultato','AJAXQuery.ashx','',xml);
  
    accendi_cavalieri(aspegnicontenuti,'arisultato','chiuso','aperto'); 
}

function getSelection(obj, page){
	var data = "<selection ";
	if (typeof obj=='object') {
	    if (obj.getAttribute("hap:uri")!=null)  data += "uri=\"" + obj.getAttribute("hap:uri") + "\" ";
	    if (obj.getAttribute("hap:page")!=null) data += "page=\"" + obj.getAttribute("hap:page") + "\" ";
	} else {
	    data += "uri=\"" + obj + "\" ";
	    if (page!=null) data += "page=\"" + page + "\" ";
	}
	data += "/>";

	initResults('risultato','AJAXSelection.ashx','',data);
}

function refineQuery(obj){
    var sel = $('currentSelectionId');
    if (sel!=null) sel = sel.innerHTML;
    sendQuery(obj,sel)
}

function sendQuery(obj,refine){
	var data, xml, searchType;

    try {
        searchType=obj.parentNode.id;
        data = browseElement(obj.parentNode);
    } catch(exception) {
        return false;
    }
    
    pannelli(divcollapsecontenuti,'risultato', aspegnicontenuti,this,'tasto_chiuso','tasto_aperto');
    
	if (data.length>0) {
	    xml = '<hapQuery';
	    if ((typeof refine!="undefined") && (refine!=null)) xml += ' refine="' + refine + '"';

        if (searchType=='ricercaAvanzata') {
	        var value;
	        [ 'tipo', 'desinenza', 'somiglianza', 'ramo'].each(function(s, index) {
	            value=$(s).getValue();
	            if (value!=null) if (value.length>0) {
	                if (s=='ramo') value=myTree.lastRootFolder.id;
	                xml += ' ' + s + '="' + value + '"';
	            }
            });
	    } else {
            if (myTree.limitTree!=null) xml += ' ramo="' + myTree.limitTree + '"';
	    }
	    
	    xml += '>' + data + '</hapQuery>';
    
        initResults('risultato','AJAXQuery.ashx','',xml, true);

        accendi_cavalieri(aspegnicontenuti,'arisultato','chiuso','aperto'); 

    } else {
        alert('Nessun criterio di ricerca inserito');
    }
}

function getNextElement(obj)
{
	//workaround a ff.
	if (obj)
	{
		var tmpObj=obj.nextSibling;
		if (tmpObj)
		{
			if (tmpObj.nodeType==1) return tmpObj;
			
			tmpObj=getNextElement(tmpObj);
			
			return tmpObj;
		}
	}
	return null;
}

function getPrevElement(obj)
{
	//workaround a ff.
	if (obj)
	{
		var tmpObj=obj.previousSibling;
		if (tmpObj)
		{
			if (tmpObj.nodeType==1) return tmpObj;
			
			tmpObj=getPrevElement(tmpObj);
			
			return tmpObj;
		}
	}
	return null;
}

function resort(obj) {
	var data = "<selection ";
	data += "uri=\"" + $("archivi").getValue() + "\" ";
	data += "sort=\"" + obj.options[obj.selectedIndex].value + "\" ";
	data += "/>";

	initResults('risultato','AJAXSelection.ashx','',data);
}

function initFinderWizard(objContainer) {
	var ff=true;
    var obj;

    switch (objContainer.getAttribute('hap:type')) {
        case "match":
            objContainer.selectedIndex=0;
            break;
                    
        case "channel":
            objContainer.selectedIndex=0;
            objContainer.onchange = function() {
                obj=this;
                while (obj!=null) {
                    var type=this.options[this.selectedIndex].getAttribute('hap:type');
                
                    switch (obj.getAttribute('hap:type')) {
                        case "dictionary":
                            var dict=this.options[this.selectedIndex].getAttribute('hap:dictionary');
                            
                            if (type!="label") dict='';
                            else if (dict!='') dict=this.options[this.selectedIndex].value;
                            
                            obj.style.display = (((dict=='') || (dict==null)) ? 'none' : '');
                            
                            //break;

                        case "query":
                        case "queryB":
                            switch (type) {
                                case "date":
                                    obj.className="queryDate";
                                    obj.style.width="110px";
                                    break;
                                case "separator":
                                case "label":
                                default:
                                    obj.className=( (obj.getAttribute('hap:type')=='queryB') ? "hide" : "query");
                                    obj.style.width="220px";
                                    obj.setAttribute('hap:dictionary', this.options[this.selectedIndex].value);
                            }
                            
                            break;
                    }
                    obj=getNextElement(obj);
                }
            };
            
            objContainer.onchange();
            break;
        
        case "query":
            objContainer.value='';
        /*
            objContainer.onclick= function() {
                window.status=this.className;
            }
            */
            break;
            
        case "dictionary":
             /*
             objContainer.rel="gb_page_center[1000, 600]";
             objContainer.onmouseover= function() {
                //currentDictionary=getPrevElement(this);
                currentDictionary="ziocan";
             };
             */

             objContainer.onclick= function() {
                currentDictionary=getPrevElement(this);
                currentDictionary=getPrevElement(currentDictionary);
                //NewWindow(this.href,'name','1000','600','yes');
                NewWindow(this.href,'',960,589);
                return false;
             };
             break;

        default:
            //if (objContainer.getAttribute('hap:type')!=null) alert(objContainer.getAttribute('hap:type'));
    }

    
	//scorre gli elementi contenuti nell'oggetto passato e ne estrae l' Xml
    if(objContainer.childNodes.length>0)
    {
        var chld;
        for (var x=0;x<objContainer.childNodes.length;x++)
        {			
	        chld=objContainer.childNodes[x];
	        if(chld.nodeType==1)
	        {
		        var rtnStr=initFinderWizard(chld);
		        /*
		        if(rtnStr.length>1) 
		        {
			        xmlString+=rtnStr;
			        voidValue=false;
		        }
		        */
	        }
        }
    }

	//if (voidValue) xmlString="";

	//return xmlString;
	return true;
}

var strChannel, strMatch, strValue;
function browseElement(objContainer) {
    var xmlString="";
	var obj;
	
	switch (objContainer.getAttribute('hap:type')) {
	    case "search":
            strChannel="";
            strMatch="";
            strValue="";
	        break;

	    case "match":
	        strMatch = objContainer.options[objContainer.selectedIndex].value;
	        break;

	    case "channel":
	        strChannel = objContainer.options[objContainer.selectedIndex].value;
	        break;

	    case "query":
	        strValue=objContainer.value.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/>/g,"&gt;").replace(/</g,"&lt;");
            if (strValue.length>0) {
                xmlString='<' + strChannel + ' ';
                if (strMatch.length>0) xmlString+='match="' + strMatch + '" ';
                if (objContainer.className!='queryDate') {
                    xmlString+='value="' + strValue + '" />\n';
                } else {
                    xmlString+='rangeA="' + strValue + '" ';
                    obj=getNextElement(objContainer);
                    if (obj!=null) strValue=obj.value.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/>/g,"&gt;").replace(/</g,"&lt;");
                    xmlString+='rangeB="' + strValue + '" />\n';
                }
            } else {
                if (objContainer.className=='queryDate') {
                    obj=getNextElement(objContainer);
                    if (obj!=null) {
                        strValue=obj.value.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/>/g,"&gt;").replace(/</g,"&lt;");
                        if (strValue.length>0) {
                            xmlString='<' + strChannel + ' ';
                            if (strMatch.length>0) xmlString+='match="' + strMatch + '" ';
                            xmlString+='rangeB="' + strValue + '" />\n';
                        }
                    }
                }
            }
            break;
            
        case "simple":
	        strValue=objContainer.value.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/>/g,"&gt;").replace(/</g,"&lt;");
            if (strValue.length>0) {
                xmlString='<simple value="' + strValue + '" />\n';
            }
            break;
	}

	//scorre gli elementi contenuti nell'oggetto passato e ne estrae l' Xml
    for (var x=0;x<objContainer.childNodes.length;x++)
    {			
        var chld=objContainer.childNodes[x];
        if(chld.nodeType==1)
        {
	        var rtnStr=browseElement(chld);
	        if(rtnStr.length>0) 
	        {
		        xmlString+=rtnStr;
		        voidValue=false;
	        }
        }
    }

	return xmlString;
}

function showDocument(obj) {
	var data;
	
	if (typeof obj=='object') {
        pannelli(divcollapsecontenuti,'documento', aspegnicontenuti,obj,'chiuso','aperto');
	    data = "<document ";
	    if (obj.getAttribute("hap:uri")!=null) {
	        data += "uri=\"" + obj.getAttribute("hap:uri") + "\" ";
	        if (hapTracker!=null) hapTracker._trackPageview(obj.getAttribute("hap:uri"));
	    }
	    if (obj.getAttribute("hap:mode")!=null) data += "mode=\"" + obj.getAttribute("hap:mode") + "\" ";
	    data += "/>";
	} else {
        pannelli(divcollapsecontenuti,'documento', aspegnicontenuti,this,'chiuso','aperto');
	    data = "<document uri=\"" + obj + "\" mode=\"hierarchy\" />";
        if (hapTracker!=null) hapTracker._trackPageview(obj);
	}
	
	loadDocument(data);	
    accendi_cavalieri(aspegnicontenuti,'adocumento','chiuso','aperto');
}

function loadDocument(data, title) {
	$('documento').innerHTML = '<img src="images/loading.gif" /> Caricamento in corso' + (typeof(title)=='undefined'?'':' ' + title) + '... attendere prego.';
	
	new Ajax.Request("AJAXDocument.ashx", {
        method: "post",
        postBody: data,
        onSuccess: function(transport) {
            var doc=$('documento');
            doc.innerHTML = transport.responseText;

            var tog;
            var myContent = doc.select('.content');
            myContent.each(function(ele,i) {
                tog=ele.previous();
                Event.observe(tog, "click" , function(e){
                    var obj=Event.element(e);
                    ele.toggle();
                    if (obj.hasClassName('toggle')) {
                        obj.removeClassName('toggle');
                        obj.addClassName('untoggle');
                    } else {
                        obj.removeClassName('untoggle');
                        obj.addClassName('toggle');
                    }
                    //obj.className = (obj.className=='toggle' ? "untoggle" : "toggle");
                });
                if (tog.hasClassName('untoggle')) fireEvent(tog, "click");
            });
            
            data=getRequest();
            if (data!=null) {
	            new Ajax.Request("AJAXFindRelations.ashx", {
                    method: "post",
                    postBody: data,
                    onSuccess: function(transport) {
                        setRelation(createXmlObj(transport.responseText));
                    },
                    onFailure: function(transport) {
                        alert(transport.responseText);
                    }
                }); 
            }
        },
        onFailure: function(transport) {
            $('documento').innerHTML = transport.responseText;
        }
    }); 
}

function setRelation(obj) {

	if (obj==null) return false;
	
	var i,j;
	var rels;
	var divs;
	var relId;
	var strTemp;
		
	divs=$('documento').getElementsBySelector('div[type="RelationSearch"]');
	rels=obj.getElementsByTagName("a");
	
	for (i=0; i<rels.length; i++) {
	    relId=rels[i].attributes.item(0).nodeValue;

        if (relId!=null) {
		    relId = relId.replace('  ',' ').replace('\n','').replace('\t','');
		    //Vado a trovare il relId da sostituire
		    for (j=0; j<divs.length; j++) {
			    if (divs[j].id==relId) {
	                //divs[j].replace(typeof rels[i].xml!='undefined' ? rels[i].xml : rels[i].childNodes[0].nodeValue);
	                rels[i].childNodes[0].nodeValue = divs[j].innerHTML;
	                //alert(rels[i].childNodes[0].nodeValue + '\n' + divs[j].innerHTML);
	                if (typeof rels[i].xml!='undefined') {
	                    strTemp = rels[i].xml;
	                } else {
	                    strTemp = rels[i].childNodes[0].nodeValue;
	                }
	                divs[j].replace(strTemp);
			        j=divs.length;
			    }
		    }
	    }
        
	}
}

function getRequest() {
    var relDivs;
    var divId='';
    var data;
    var bFound=false;

	relDivs=$('documento').getElementsBySelector('div[type="RelationSearch"]');
    
    data="<findRelations>\n";
    for (var i=0; i<relDivs.length; i++) {
        if (relDivs[i].id!='') {
            data += '   <relation id=\"' + relDivs[i].id + '\" />\n';
		    bFound=true;
	    }
	}
    data+="</findRelations>\n";
    
	return (bFound ? data : null);
}

function editDocument(obj) {
	var data = "dataentry/HAPEdit.aspx?uri=" + (typeof obj=="object" ? obj.getAttribute("hap:uri") : obj);
	var win = window.open(data,"dataentry");
	if (win!=null) win.window.focus();
}

function selectDocumentType(level, parentID, brotherID) {
	if (level!=null) {
	    var data = "dataentry/selectTemplate.aspx?level="+level;
	    if (parentID!=null) data+="&parentId="+parentID;
	    if (brotherID!=null) data+="&brotherId="+brotherID;
    	
	    var win = window.open(data,"dataentry");
	    if (win!=null) win.window.focus();
    } else alert("Informazioni relative al dataentry non disponibili");
}

function newDocument(scheda, parentID, brotherID) {
	var data = "HAPEdit.aspx?encodinganalog=" + scheda ;
	if (parentID!=null) data+="&puri="+parentID;
	if (brotherID!=null) data+="&buri="+brotherID;

    location.href=data;
	//var win = window.open(data,"dataentry");
	//if (win!=null) win.window.focus();
}

function newAuthority(scheda, parentID, brotherID) {
	var data = "HAPEdit.aspx?encodinganalog=" + scheda ;
	data+="&dec=authority";
	if (parentID!=null) data+="&puri="+parentID;
	if (brotherID!=null) data+="&buri="+brotherID;

    location.href=data;
	//var win = window.open(data,"Authority");
	//if (win!=null) win.window.focus();
}

function deleteDocument(uri, nodeObj)
{
	if (window.confirm('Sei sicuro di voler cancellare veramente il documento corrente?'))
	{
		var data = "<document uri=\"" + uri + "\" mode=\"delete\" />";
        new Ajax.Request("AJAXDocument.ashx", {
            method: "post",
            postBody: data,
            onSuccess: function(transport) {
                alert('Documento cancellato correttamente!');
                if (typeof nodeObj!='undefined') $(nodeObj.treeView.varName + "_" + nodeObj.internalId).hide();
            },
            onFailure: function(transport) {
        		JustPressed = false;
                alert(transport.responseText);
            }
        }); 
	}
}

function pasteNode(data) {
    new Ajax.Request('AJAXHierarchy.ashx', {
        method: "post",
        postBody: data,
        onSuccess: function(transport) { 
        	//rimuovo tutte le selezioni
	        for(x=0;x<myTree.cuttedItems.length;x++){
		        myTree.cuttedItems[x].cutted=false;
	        }
	        myTree.cuttedItems=new Array()
            hierarchyUri(myTree.lastRootFolder.id,myTree);
        }
    }); 
}

function dataNeeded(emptyFolder) {
    new Ajax.Request('AJAXHierarchy.ashx?id=' + emptyFolder.id, {
        method: "get",
        onSuccess: function(transport) { 
            emptyFolder.feed(createXmlObj(transport.responseText));
        }
    }); 

    return false;
}

function dataNeededEx(emptyFolder,nextSibling) {
    new Ajax.Request('AJAXHierarchy.ashx?id=' + emptyFolder.id + (nextSibling!=null ? '&newid=' + nextSibling.id : ''), {
        method: "get",
        onSuccess: function(transport) { 
            if (transport.responseText.length>0) {
                emptyFolder.feed(createXmlObj(transport.responseText));
                dataNeeded(emptyFolder,lastFolder.childArray[lastFolder.childArray.length-1]);
            }
        }
    }); 

    return false;
}

function tooltip(nodeObj,treeViewObj) {
    /*proprietà di nodeObj:
    '    ID()
    '    livelloArchivistico()
    '    subscribed()
    '		type	-> 0=folder / 1=document
    '	parent	-> nodeObj
    '   tooltip()
    */
    if (nodeObj!=null) {    
        if (nodeObj.tooltip.length>0) {
            var myTT='<div id="popup1"><div id="popup2"><p>' + nodeObj.tooltip + '</p></div></div>';
            window.ddrivetip(myTT);
        }
    } else {
        window.hideddrivetip();
    }
}

function textClick(nodeObj,treeViewObj) {
    /*proprietà di nodeObj:
    '    ID()
    '    livelloArchivistico()
    '    subscribed()
    '		type	-> 0=folder / 1=document
    '	parent	-> nodeObj
    '   tooltip()
    */
    showDocument(nodeObj.id);
}

function iconClick(nodeObj,treeViewObj) {
    treeViewObj.clear();

    new Ajax.Request('AJAXHierarchy.ashx?newid=' + nodeObj.id, {
        method: "get",
        onSuccess: function(transport) { 
            treeViewObj.feed(createXmlObj(transport.responseText));
        }
    }); 
    return false;        
}

function rootClick(nodeObj,treeViewObj) {
    if (nodeObj.type!=1) {
        treeViewObj.clear();
        
        new Ajax.Request('AJAXHierarchy.ashx?newid=' + nodeObj.id, {
            method: "get",
            onSuccess: function(transport) { 
                treeViewObj.feed(createXmlObj(transport.responseText));
            }
        }); 
        
        return false;        
    } else {
        alert("click su rootFolder: "  + nodeObj.id);
    }
}

function hierarchyUri(uri,treeViewObj) {
    treeViewObj.clear();

    if (uri!=null) pannelli(divcollapsecontenuti,'struttura', aspegnicontenuti,treeViewObj,'chiuso','aperto');

    new Ajax.Request('AJAXHierarchy.ashx' + (uri!=null ? '?newid=' + uri : ''), {
        method: "get",
        onSuccess: function(transport) { 
            treeViewObj.feed(createXmlObj(transport.responseText));
            if (treeViewObj.limitTree=='true') treeViewObj.limitTree=myTree.lastRootFolder.id;
            if (uri!=null) accendi_cavalieri(aspegnicontenuti,'astruttura','chiuso','aperto');
        },
        onFailure: function(transport) { 
            alert(transport.responseText);
        }
    }); 
    return false;        
}

function getSubscribed() {
    //'per ora ho limitato la sottoscrizione a massimo 1 elemento, se serve la cambiamo in un attimo
    if(myTree.subscribedItems[0]){
        alert('Id: ' + myTree.subscribedItems[0].id);
    }
}

function getSelected(){
	if (myTree.currentItem){
        alert(myTree.currentItem.id);
    }
}

function getCutted(){
	if (myTree.cuttedItems){
        var idArray = new Array();
		for(x=0;x<myTree.cuttedItems.length;x++){
			idArray.push(myTree.cuttedItems[x].id);
		}
		alert(idArray.join("\n"));
	}
}

/* FUNZIONI AJS USATE DA LIBRERIA.JS 
function cloner(element) {
    return element.cloneNode(true);
}

function insertBefore(elm, reference_elm) {
    reference_elm.parentNode.insertBefore(elm, reference_elm);
    return elm;
}
*/
function isIn(elm, list) {
    var i = getIndex(elm, list);
    if(i != -1)
        return true;
    else
        return false;
}

function getIndex(elm, list/*optional*/, eval_fn) {
    for(var i=0; i < list.length; i++)
        if(eval_fn && eval_fn(list[i]) || elm == list[i])
            return i;
    return -1;
}

function viewImage(url) {
    window.open('AJAXAttachment.ashx?resource=' + url, '_blank');
    if (hapTracker!=null) hapEvent._trackEvent("View Image", url);
    return false;
}

function viewOutput(obj, uri, option) {
    window.open('AJAXContent.ashx?uri=' + uri + '&option=' + option + '&type=' + obj.options[obj.selectedIndex].value, '_blank');
    if (hapTracker!=null) hapEvent._trackEvent("View " + obj.options[obj.selectedIndex].value, uri);
    return false;
}


/* Dizionario.js */
function aggiungi_dizionario(obj,elenco_dizionario,div){
	var valore=obj.value;
	if(obj.checked){
		elenco_dizionario.push(valore);
	}else{
		if(isIn(valore,elenco_dizionario)){
			for(var x=0; x<=(elenco_dizionario.length-1) ; x++){
				if(elenco_dizionario[x] == valore ){
					elenco_dizionario.splice(x,1);
					break;
				}
			}
		}
	}
	elenco_dizionario.sort();
	scrivi_dizionario(elenco_dizionario,div);
	return elenco_dizionario;
}
function scrivi_dizionario(elenco_dizionario,div){
	var subobj=document.getElementById(div);
	var s='';
	for(var x=0; x<=(elenco_dizionario.length-1) ; x++){
		s+='<li>'+elenco_dizionario[x]+'</li>';
	}
	var testo=(s != '')?'<ul>'+s+'</ul>':'<p>Nessun elemento selezionato</p>';	
	subobj.innerHTML=testo;
}

function getDictionary(obj) {
    var sv;
    var data;
    //var cd = (typeof window.opener=="undefined" ? parent.currentDictionary : window.opener.currentDictionary);
    var cd = parent.currentDictionary;
    
    sv = $("startValue")
    sv.value = ((obj==null) ? ((sv.value.length>0) ? sv.value : "A")  : obj.innerHTML);
    
	data = "<dictionary ";
    data += " key=\"" + cd.getAttribute('hap:dictionary') + "\"";
    data += " startValue=\"" + sv.value + "\"";
    data += " min=\"" + $('frequency').value + "\"";
    data += " spectral=\"" + $('spectral').checked + "\" />";
	data += "/>";
	
	$('elenco_dizionario').innerHTML = '<img src="images/loading.gif" /> Caricamento in corso... attendere prego.';	
	new Ajax.Request('AJAXDictionary.ashx', {
        method: "post",
        postBody: data,
        onSuccess: function(transport) {
            var ele=$('elenco_dizionario');
            ele.innerHTML = transport.responseText;
            $('sx').down().innerHTML = ele.down().innerHTML;
        },
        onFailure: function(transport) {
            $('elenco_dizionario').innerHTML = transport.responseText;
        }
    });
}

function updateDictionary() {
	var s="";
	for(var x=0; x<=(elenco_dizionario.length-1) ; x++){
	    if (s.length>0) s+=" OR ";
	    if (location.href.indexOf("ti=radio")>0)
		    s+=elenco_dizionario[x].replace(/^\s+|\s+$/g,"");
	    else
		    s+="\"" + elenco_dizionario[x] + "\"";
	}

    //parent.currentDictionary.setAttribute('value', s);
    parent.currentDictionary.value = s;
    parent.Lightview.hide();

/*
    //if (window.opener!=null) {
        window.opener.currentDictionary.setAttribute('value', s);
        window.opener.focus();
        window.close();
        */
    /*} else {
        parent.currentDictionary.setAttribute('value', s);
        parent.myLightWindow.deactivate();
    }*/
}

function toggleArea(obj) {
    //$(obj.nextSibling).toggle();
    obj=$(obj);
    obj.next().toggle();
    //obj.className = (obj.className=='toggle' ? "untoggle" : "toggle");
    if (obj.hasClassName('toggle')) {
        obj.removeClassName('toggle');
        obj.addClassName('untoggle');
    } else {
        obj.removeClassName('untoggle');
        obj.addClassName('toggle');
    }
}

function help(obj) {
    var win=window.open(obj.href,'help');
    win.focus();
    return false;
}

function duplica(obj) {
    var container=$(obj).up('.bloccoRicercaRip');
    var beforeof=$('tappo');
    var newHTML;
    
    newHTML='<div class="bloccoRicercaRip" hap:type="search">\n';
    newHTML+=container.innerHTML;
    newHTML+='</div>\n';
    
    new Insertion.Before(beforeof, newHTML);
    
    var elm=beforeof.previous();
    initFinderWizard(elm);
}

function rimuovi(obj) {
    $(obj).up('.bloccoRicercaRip').remove();
}

function tooltipResults(nodeObj) {
    if (nodeObj!=null) {    
        var obj=$(nodeObj).next();
        if (obj!=null) {    
            var myTT='<div id="popup1"><div id="popup2">' + obj.innerHTML + '</div></div>';
            window.ddrivetip(myTT);
        }
    } else {
        window.hideddrivetip();
    }
}

function loadjscssfile(filename, filetype){
    var fileref;
    if (filetype=="js"){ //if filename is a external JavaScript file
        fileref=document.createElement('script');
        fileref.setAttribute("type","text/javascript");
        fileref.setAttribute("src", filename);
    }
    else if (filetype=="css"){ //if filename is an external CSS file
        fileref=document.createElement("link");
        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css");
        fileref.setAttribute("href", filename);
    }
    if (typeof fileref!="undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref);
}

function fireEvent(element,event){
    var evt;
    if (document.createEventObject){
        // dispatch for IE
        evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}

var hapWindow=Class.create();
hapWindow.prototype = {
	initialize: function(lightbox) {
	    this.mode=lightbox;
	},
	
	open: function(url, title, target){ 
	    if (typeof(url)=='object') {
	        url=$(url);
	        if (typeof title=='undefined') title=(url.getAttribute("title")!=''?url.getAttribute("title"):url.innerHTML);
	        target = url.getAttribute("target");	        
	        url = url.getAttribute("href");
	        //alert(title + '\n' + target + '\n' + url);
	    }
	    
	    switch (this.mode) {
            case 'lightbox':
	    	    //NewWindow(url, title);
                Lightview.show({ href: url, title: title, rel: 'iframe', options: { autosize: true }});
	            break;
	        case 'window':
        	    var win = window.open(url,this.mode);
        	    if(win.window.focus) win.window.focus();
	            break;
	        default:
            	location.href=url;
	            break;
	    }
        
        return false;
	},

    hierarchyUri: function(uri) {
	    switch (this.mode) {
            case 'lightbox':
            case 'self':
                parent.hierarchyUri(uri,parent.myTree);
                parent.Lightview.hide();
	            break;
	        case 'window':
	        default:
                hierarchyUri(uri,myTree);
	            break;
	    }
	    
        return false;        
    }

}

