/*--------------------------------------------------|
| dTree 2.05 | www.destroydrop.com/javascript/tree/ |
|---------------------------------------------------|
| Copyright (c) 2002-2003 Geir Landroe          |
|                                                  |
| This script can be used freely as long as all     |
| copyright messages are intact.                    |
|                                                   |
| Updated: 17.04.2003                               |
|--------------------------------------------------*/

var helpPath = '';
function setHelpPath(pathToImages){
    helpPath = pathToImages;
}

//--------------------------------------------------------
// Node object
//--------------------------------------------------------
function Node(id, pid, ident, name, visible, open, check, map, alternmap, adhoc, group, wms, legend, clickable, usemap, searchscale, mapscmin, mapscmax, usemapscmin, usemapscmax) {
    this.id = id;                  // own id
    this.pid = pid;                // parent id
    this.ident = ident;            // layer ID
    this.name = name;              // name of layer
    this.check = check || false;   // checked?
    this._io = open || false;      // open or closed
    this._ls = false;              // last sibling
    this._hc = false;              // has children?
    this._ai = 0;                  // own index
    this._pi;                      // parent index
    this.map = map;                // map string
    this.alternmap = alternmap;    // alternative map string (or true)
    this.adhoc = adhoc;            // adhoc-string
    this.group = group;            // Layer-Gruppe
    this.wms = wms;                // WMS name
    this.legend = legend;          // Legende
    this.usemap = usemap;          // Usemap?
    this.clickable = clickable;    // clickable?
    this.active = true;            // active?
    this.visible = visible;        // visible?
    this.searchscale = searchscale;// search result scale
    this.mapscmin = mapscmin;      // minimum mapscale
    this.mapscmax = mapscmax;      // maximum mapscale
    this.usemapscmin = usemapscmin;// minimum usemapscale
    this.usemapscmax = usemapscmax;// maximum usemapscale
};

//--------------------------------------------------------
// Tree object
//--------------------------------------------------------
function dTree(objName, style, lines, text) {
    this.config = {
        useLines: true,
        clickText: true
    }
    if (style=="classic") {
      this.icon = {
        node: helpPath+'img/page.gif',
        empty: helpPath+'img/pfeil-klein_empty.gif',
        join: helpPath+'img/join.gif', 
        joinBottom: helpPath+'img/joinbottom.gif', 
        plus: helpPath+'img/pfeil-klein_rechts.gif',    
        plusBottom: helpPath+'img/pfeil-klein_rechts.gif',
        minus: helpPath+'img/pfeil-klein_unten.gif',
        minusBottom: helpPath+'img/pfeil-klein_unten.gif',
        nlPlus: helpPath+'img/pfeil-klein_rechts.gif',
        nlMinus: helpPath+'img/pfeil-klein_unten.gif',
        checkon: helpPath+'images/haekchen_on.gif',
        checkoff: helpPath+'images/haekchen_off.gif',
        checkoninactive: helpPath+'images/haekchen_on_grau.gif',
        checkoffinactive: helpPath+'images/haekchen_off_grau.gif',
        checkempty: helpPath+'images/haekchen_empty.gif'      
      };
    }
    else { // original
      this.icon = {
        root: helpPath+'img2/base.gif',
        folder: helpPath+'img2/folder.gif',
        folderOpen: helpPath+'img2/folderopen.gif',
        node: helpPath+'img2/page.gif',
        empty: helpPath+'img2/empty.gif',
        line: helpPath+'img2/line.gif',
        join: helpPath+'img2/join.gif',
        joinBottom: helpPath+'img2/joinbottom.gif',
        plus: helpPath+'img2/plus.gif',
        plusBottom: helpPath+'img2/plusbottom.gif',
        minus: helpPath+'img2/minus.gif',
        minusBottom: helpPath+'img2/minusbottom.gif',
        nlPlus: helpPath+'img2/nolines_plus.gif',
        nlMinus: helpPath+'img2/nolines_minus.gif',
        checkon: helpPath+'images/haekchen_on.gif',
        checkoff: helpPath+'images/haekchen_off.gif',
        checkoninactive: helpPath+'images/haekchen_on_grau.gif',
        checkoffinactive: helpPath+'images/haekchen_off_grau.gif',
        checkempty: helpPath+'images/haekchen_empty.gif'   
      };
    }
    if (lines==true) this.config.useLines=true;
    else this.config.useLines=false;
    if (text==true) this.config.clickText=true;
    else this.config.clickText=false;
    this.obj = objName;
    this.aNodes = [];
    this.aIndent = [];
    this.root = new Node(-1);
    this.completed = false;
    this.alternmap = false;
    for (var n=1; n<this.aNodes.length; n++) if (this.aNodes[n].check==true && this.aNodes[n].alternmap=="true") this.alternmap = true;
};

//--------------------------------------------------------
// Adds a new node to the node array
//--------------------------------------------------------
dTree.prototype.add = function(id, pid, ident, name, visible, open, checked, map, alternmap, adhoc, group, wms, legend, clickable, usemap, searchscale, mapscmin, mapscmax, usemapscmin, usemapscmax) {
    this.aNodes[this.aNodes.length] = new Node(id, pid, ident, name, visible, open, checked, map, alternmap, adhoc, group, wms, legend, clickable, usemap, searchscale, mapscmin, mapscmax, usemapscmin, usemapscmax);
};

//--------------------------------------------------------
// Creates the tree structure
//--------------------------------------------------------
dTree.prototype.buildTree = function(pNode) {
    var n=0;
    if (!pNode) pNode=this.root;
    for (n; n<this.aNodes.length; n++) {
        if (this.aNodes[n].pid == pNode.id) { // find all sons
            var cn = this.aNodes[n];
            cn._pi = pNode;
            cn._ai = n;
            this.setCS(cn);
            this.buildTree(cn);
            if (cn._ls) break;
        }
    }
};

//--------------------------------------------------------
// Checks if a node has any children and if it is the last sibling
//--------------------------------------------------------
dTree.prototype.setCS = function(node) {
    var lastId;
    for (var n=0; n<this.aNodes.length; n++) {
        if (this.aNodes[n].pid == node.id) node._hc = true;
        if (this.aNodes[n].pid == node.pid) lastId = this.aNodes[n].id;
    }
    if (lastId==node.id) node._ls = true;
};

//--------------------------------------------------------
// Outputs the tree to the page
//--------------------------------------------------------
dTree.prototype.toString = function() {
    var str = '<div class="dtree">\n';
    if (document.getElementById) {
      str += this.addNode(this.root);
    }
    else str += 'Browser not supported.';
    str += '</div>';
    this.completed = true;
    return str;
};

//--------------------------------------------------------
// Runs through the tree
//--------------------------------------------------------
dTree.prototype.addNode = function(pNode) {
    var str = '';
    var n=0;
    n = pNode._ai;
    for (n; n<this.aNodes.length; n++) {
        if (this.aNodes[n].pid == pNode.id) {
            var cn = this.aNodes[n];
            cn._p = pNode;
            cn._ai = n;
            this.setCS(cn);
            str += this.node(cn, n);
            if (cn._ls) break;
        }
    }
    return str;
};

//--------------------------------------------------------
// Creates the node icon and text
//--------------------------------------------------------
dTree.prototype.node = function(node, nodeId) {
    var str = '', onclick='';
    if (node.visible==true) {
      var str = '<div class="dTreeNode">';
      //if (node.clickable==true) 
      str += this.indent(node, nodeId);
      if (node.pid != this.root.id) {
          if (node.active==true) { 
              if (node.check==true) icon=this.icon.checkon; else icon=this.icon.checkoff;
              onclick='onclick=\"javascript: ' + this.obj + '.setLayercheck('+nodeId+',false);\" style=\"cursor:pointer\"';
          }
          else {
              if (node.check==true) icon=this.icon.checkoninactive; else icon=this.icon.checkoffinactive;
              onclick='style=\"cursor:default\"';
          }
          if (node.clickable==true) str += '<img name=\"check\" style="padding-bottom:3px; padding-top:3px;" value=\"\" id=\"node'+nodeId+'\" src='+icon+' '+onclick+'>';
          if (this.config.clickText && node.clickable==true) {
              str += '<span id=\"text'+nodeId+'\" '+onclick+' class=\"'+(node.active==true?'active':'inactive')+'\"> '+node.name+'</span>';
          }
          else str += ' '+node.name;
      }
      str += '</div>';
    }
      if (node._hc) {
        str += '<div id="d' + this.obj + nodeId + '" class="clip" style="display:' + ((this.root.id == node.pid || node._io) ? 'block' : 'none') + ';">';
        str += this.addNode(node);
        str += '</div>';
      }
    this.aIndent.pop();
    return str;
};

//--------------------------------------------------------
// Adds the empty and line icons
//--------------------------------------------------------
dTree.prototype.indent = function(node, nodeId) {
    var str = '';
    if (this.root.id != node.pid) {
//      for (var n=1; n<this.aIndent.length; n++)
        for (var n=(node._hc?0:1); n<this.aIndent.length; n++)
           str += '<img src="' + ( (this.aIndent[n] >= 1 && this.config.useLines) ? this.icon.line : this.icon.empty ) + '" alt="" />';
            (node._ls) ? this.aIndent.push(0) : this.aIndent.push(1);
        if (node._hc) {
            str += '<img id="j' + this.obj + nodeId + '" src="';
            if (!this.config.useLines) str += (node._io) ? this.icon.nlMinus : this.icon.nlPlus;
            else str += ( (node._io) ? ((node._ls && this.config.useLines) ? this.icon.minusBottom : this.icon.minus) : ((node._ls && this.config.useLines) ? this.icon.plusBottom : this.icon.plus ) );
            str += '" alt="" onClick=\"javascript: ' + this.obj + '.o('+nodeId+');\" style=\"cursor:pointer\"/>';
        } else str += '<img src="' + ( (this.config.useLines) ? ((node._ls) ? this.icon.joinBottom : this.icon.join ) : this.icon.empty) + '" alt="" />';
    }
    return str;
};

//--------------------------------------------------------
// Adds the empty and line icons
//--------------------------------------------------------
dTree.prototype.setCS = function(node) {
    var lastId;
    for (var n=0; n<this.aNodes.length; n++) {
        if (this.aNodes[n].pid == node.id) node._hc = true;
        if (this.aNodes[n].pid == node.pid) lastId = this.aNodes[n].id;
    }
    if (lastId==node.id) node._ls = true;
};

//--------------------------------------------------------
// Toggle Open or close
//--------------------------------------------------------
dTree.prototype.o = function(id) {
    var cn = this.aNodes[id];
    if (cn._io==true) {
      if (this.checkAllChildren(id,true)) return;
    }
    this.nodeStatus(!cn._io, id, cn._ls);
    cn._io = !cn._io;
//    my_statistik("title="+encodeURI(cn.name)+"&open="+cn._io+"&action=layer_open");
    eventID=2;
};

//--------------------------------------------------------
// Checks if all children of a node are selected or unselected
//--------------------------------------------------------
dTree.prototype.checkAllChildren = function(node, check) {
    for (var n=0; n<this.aNodes.length; n++) {
        if (this.aNodes[n].pid == node) {
            if (this.aNodes[n].check==check || this.checkAllChildren(n,check)) return true;
        }
    }
    return false;
}

//--------------------------------------------------------
// Open or close all nodes
//--------------------------------------------------------
dTree.prototype.oAll = function(status) {
    for (var n=0; n<this.aNodes.length; n++) {
        if (this.aNodes[n]._hc && this.aNodes[n].clickable && this.aNodes[n].pid != this.root.id) {
            this.nodeStatus(status, n, this.aNodes[n]._ls);
            this.aNodes[n]._io = status;
        }
    }
};

//--------------------------------------------------------
// Opens the tree to a specific node
//--------------------------------------------------------
dTree.prototype.openTo = function(nId, bFirst) {
    if (!bFirst) {
        for (var n=0; n<this.aNodes.length; n++) {
            if (this.aNodes[n].id == nId) {
                nId=n;
                break;
            }
        }
    }
    var cn=this.aNodes[nId];
    if (cn.pid==this.root.id || !cn._pi) return;
    cn._io = true;
    if (this.completed && cn._hc && cn.clickable) this.nodeStatus(true, cn._ai, cn._ls);
    this.openTo(cn._pi._ai, true);
};

//--------------------------------------------------------
// Change the status of a node(open or closed)
//--------------------------------------------------------
dTree.prototype.nodeStatus = function(status, id, bottom) {
    eDiv= document.getElementById('d' + this.obj + id);
    eJoin= document.getElementById('j' + this.obj + id);
    eJoin.src = (this.config.useLines)?
        ((status)?((bottom)?this.icon.minusBottom:this.icon.minus):((bottom)?this.icon.plusBottom:this.icon.plus)):
        ((status)?this.icon.nlMinus:this.icon.nlPlus);
    eDiv.style.display = (status) ? 'block': 'none';
};

//--------------------------------------------------------
// If Push and pop is not implemented by the browser
//--------------------------------------------------------
if (!Array.prototype.push) {
    Array.prototype.push = function array_push() {
        for(var i=0;i<arguments.length;i++)
            this[this.length]=arguments[i];
        return this.length;
    }
};
if (!Array.prototype.pop) {
    Array.prototype.pop = function array_pop() {
        lastElement = this[this.length-1];
        this.length = Math.max(this.length-1,0);
        return lastElement;
    }
};

//--------------------------------------------------------
// Called when a checkbox is checked or unchecked
//--------------------------------------------------------
dTree.prototype.setLayercheck = function(id,single) {

    //if (!my_checkWMSComplete()) return;
    if (this.aNodes[id].active==false) return;
    var check=this.aNodes[id].check;
    if (check==true) check=false; else check=true;   
    this.aNodes[id].check=check;
    if (check) document.getElementById('node'+id).src=this.icon.checkon;
    else document.getElementById('node'+id).src=this.icon.checkoff;
    if (this.aNodes[id].legend!="") this.showLegend(id);
    if (single==true) return;
    this.set_alternmap(id,check);
    this.groupcheck(id,check);
    this.specialcheck(id,check);
    this.toggleAllChildren(id, check);
    
    var newRequestLayers = "";
    //alert(d.aNodes[4].mrequestLayers = 0;ap+check);
    var comma = "";
    for (var n = 0; n < this.aNodes.length; n++) {
        if(this.aNodes[n].check == true){
            newRequestLayers += comma+d.aNodes[n].map;
            comma = ",";
        }
    }
    
    if(newRequestLayers != requestLayers){
        requestLayers = newRequestLayers;
        updateLayers();
    }
    
};

//--------------------------------------------------------
// Toggle Check/Uncheck of all children of a node
//--------------------------------------------------------
dTree.prototype.toggleAllChildren = function(node, check) {
    for (var n=0; n<this.aNodes.length; n++) {
        if (this.aNodes[n].pid == node) {
            //document.getElementById('node'+this.aNodes[n].id).check=check; 
            if (check==true) { document.getElementById('node'+this.aNodes[n].id).src=this.icon.checkon; this.aNodes[n].check=true; }
            else { document.getElementById('node'+this.aNodes[n].id).src=this.icon.checkoff; this.aNodes[n].check=false; }
            if (this.aNodes[n].legend!="") this.showLegend(n);
            this.specialcheck(n, check);
            if (this.aNodes[n]._hc) { this.toggleAllChildren(n,check); }
        }
    }
};

dTree.prototype.showLegend = function(id) {
    var show=true;
    for (var n=0; n<this.aNodes.length; n++) {
        if ((n!=id) && (this.aNodes[n].legend==this.aNodes[id].legend) && (this.aNodes[n].check==true) && (this.aNodes[n].active==true)) show=false;
    }
    if (show==true) my_subShow(this.aNodes[id].legend, this.aNodes[id].check);
}

dTree.prototype.getMaps = function(wms,sep,indent,usemap) {
    var str=""; var str2=""; var has_adhoc=false;
    for (var n=0; n<this.aNodes.length; n++) {
       if (this.alternmap==false || this.aNodes[n].alternmap=="true" || this.aNodes[n].alternmap=="") map=this.aNodes[n].map; else map=this.aNodes[n].alternmap;
       if (this.aNodes[n].check==true && this.aNodes[n].active==true && map.length>1 && this.aNodes[n].wms==wms) {
          if (usemap==false || (this.aNodes[n].usemap==true && this.aNodes[n].usemapscmin<=myScale && this.aNodes[n].usemapscmax>=myScale)) {
             adhoc=this.aNodes[n].adhoc;
             if (adhoc.length>1) has_adhoc=true;
             if (str.length==0) { 
                str=indent+map+indent; 
                if (adhoc.length>1) str2=adhoc; else str2="logicallayer";
             }
             else { 
                str+=sep+indent+map+indent;
                if (adhoc.length>1) str2+=","+adhoc; else str2+=",logicallayer";
             }
          }
       }
    }
    return new Array(str,str2,has_adhoc);
};

dTree.prototype.getMaps2 = function() {
    var str=""; var str2="";
    for (var n=0; n<this.aNodes.length; n++) {
       if (this.alternmap==false || this.aNodes[n].alternmap=="true" || this.aNodes[n].alternmap=="") map=this.aNodes[n].map; else map=this.aNodes[n].alternmap;
       if (this.aNodes[n].check==true && map.length>1) {

// ------------------------------
// Version mit mehreren Layern
// ------------------------------
          if (str.length==0) { str=map; str2="logicallayer"; }
          else { str+=","+map; str2+=",logicallayer"; }

//------------------------------
// Version mit einem Layer
//------------------------------
//          if (str.length==0) { str="\""+map+"\""; str2="logicallayer"; }
//          else { str+="!k!\""+map+"\""; str2+=",logicallayer"; }

       }
    }
    return new Array(str,str2);
};

dTree.prototype.setLayers = function(layer,only) {
    var i, n;
    if (only==null || only==false) {
       for (n=0; n<this.aNodes.length; n++) { 
          if (this.aNodes[n].pid!=this.root.id && this.aNodes[n].check==true) {
             this.aNodes[n].check=false; 
             if (this.aNodes[n].visible==true) document.getElementById('node'+this.aNodes[n].id).src=this.icon.checkoff;
          }
       }
       this.oAll(false);
    }
    layers=layer.split(',');
    for (i=0; i<layers.length; i++) {
       for (n=0; n<this.aNodes.length; n++) {
          if (this.aNodes[n].pid!=this.root.id && this.aNodes[n].ident==layers[i]) { 
             this.aNodes[n].check=true;
             if (this.aNodes[n].legend!="") this.showLegend(n);
             if (this.aNodes[n].visible==true && this.aNodes[n].clickable==true) document.getElementById('node'+this.aNodes[n].id).src=this.icon.checkon;
          }
       }
    }
};

dTree.prototype.mapcheck = function(layername) {
    if (layername==null || layername.length<=1) return true;
    for (var n=0; n<this.aNodes.length; n++) {
       if (this.alternmap==false || this.aNodes[n].alternmap=="true" || this.aNodes[n].alternmap=="") map=this.aNodes[n].map; else map=this.aNodes[n].alternmap;
       if (map==layername && this.aNodes[n].check==true && this.aNodes[n].active==true) return true;
    }
    return false;
};

dTree.prototype.scalecheck = function(scale) {
    for (n=1; n<this.aNodes.length; n++) {
        if (this.aNodes[n].visible==true) {
            if (this.aNodes[n].mapscmin<=scale && this.aNodes[n].mapscmax>=scale) {
                if (this.aNodes[n].active==false) this.activate(n, true);
            }
            else {
                if (this.aNodes[n].active==true) this.activate(n, false);
           }
        }
    }
}

dTree.prototype.activate = function(id, active) {
    if (active==true) {
        if (this.aNodes[id].clickable==true) {
            if (this.aNodes[id].check==true) document.getElementById('node'+id).src=this.icon.checkon;
            else document.getElementById('node'+id).src=this.icon.checkoff;
            document.getElementById('text'+id).className='active';
            document.getElementById('node'+id).style.cursor="pointer";
            document.getElementById('text'+id).style.cursor="pointer";
        }
        this.aNodes[id].active=true;
    }
    else {
        if (this.aNodes[id].clickable==true) {
            if (this.aNodes[id].check==true) document.getElementById('node'+id).src=this.icon.checkoninactive;
            else document.getElementById('node'+id).src=this.icon.checkoffinactive;
            document.getElementById('text'+id).className='inactive';
            document.getElementById('node'+id).style.cursor="default";
            document.getElementById('text'+id).style.cursor="default";
        }
        this.aNodes[id].active=false;
    }
}


dTree.prototype.set_alternmap = function(id, check) {
    if (this.aNodes[id].alternmap=="true") {
        if (check==true) this.alternmap=true;
        else {
            var last=true;
            for (var n=1; n<this.aNodes.length; n++) if (this.aNodes[n].check==true && this.aNodes[n].alternmap=="true") last=false;
            if (last==true) this.alternmap=false;
        }
    }
}

dTree.prototype.check = function(id, check) {
    if (check==true) {
        this.aNodes[id].check=true;
        if (this.aNodes[id].legend!="") this.showLegend(id);
        if (this.aNodes[id].visible==true && this.aNodes[id].clickable==true) document.getElementById('node'+this.aNodes[id].id).src=this.icon.checkon;
    }
    else {
        this.aNodes[id].check=false;
        if (this.aNodes[id].legend!="") this.showLegend(id);
        if (this.aNodes[id].visible==true && this.aNodes[id].clickable==true) document.getElementById('node'+this.aNodes[id].id).src=this.icon.checkoff;
    }
}

dTree.prototype.groupcheck = function(id, check) {
    group=this.aNodes[id].group;
    if (group.length<=1) return;
    if (group.indexOf('-')==0) {
       for (var n=1; n<this.aNodes.length; n++) {
           if (n!=id && this.aNodes[n].group==group && check==true && this.aNodes[n].active==true) this.check(n, false);
       }
    }
    else {
       for (var n=1; n<this.aNodes.length; n++) {
           if (n!=id && this.aNodes[n].group==group && this.aNodes[n].check!=check) this.check(n, check);
       }
    }
}

dTree.prototype.get_scale = function(layer) {
    for (n=1; n<this.aNodes.length; n++) if (this.aNodes[n].map==layer) return this.aNodes[n].searchscale;
    return null;
}

/* Spezial-Button-Funktionen */
dTree.prototype.specialcheck = function(id, check) {
};

