var cc_Tree_Image_Src              = '../../';
var cc_Tree_SessionActionOpenNode  = '';
var cc_Tree_SessionParamsOpenNode  = '';
var cc_Tree_SessionActionCloseNode = '';
var cc_Tree_SessionParamsCloseNode = '';
var cc_Tree_Icons			       = new Array(6);

// Loads all icons that are used in the tree
function cc_Tree_preloadIcons()
{
	cc_Tree_Icons[0] = new Image();
	cc_Tree_Icons[0].src = cc_Tree_Image_Src + 'plus.gif';
	cc_Tree_Icons[1] = new Image();
	cc_Tree_Icons[1].src = cc_Tree_Image_Src + 'plusbottom.gif';
	cc_Tree_Icons[2] = new Image();
	cc_Tree_Icons[2].src = cc_Tree_Image_Src + 'minus.gif';
	cc_Tree_Icons[3] = new Image();
	cc_Tree_Icons[3].src = cc_Tree_Image_Src + 'minusbottom.gif';
	cc_Tree_Icons[4] = new Image();
	cc_Tree_Icons[4].src = cc_Tree_Image_Src + 'folder.gif';
	cc_Tree_Icons[5] = new Image();
	cc_Tree_Icons[5].src = cc_Tree_Image_Src + 'folderopen.gif';
}

function cc_Tree_Lnk()
{
    this.nom       = cc_Tree_Lnk.arguments[0];
    this.lien      = cc_Tree_Lnk.arguments[1];
    this._class     = cc_Tree_Lnk.arguments[2];
    this._style     = cc_Tree_Lnk.arguments[3];
    this.functions = new Array();
    this.linkposition = 'after';

    if( this.lien == '' || typeof this.lien == 'undefined') this.lien = 'javascript:void(0);';

    this.setClass = function(c) { this._class=c; };
    this.setStyle = function(s) { this._style=s; };

    // Defines if additional links will be displayed before or after main link
    this.setLinkPosition = function(position)
    {
        if( position != 'before' )
            position = 'after';
        this.linkposition = position;
    }

    this.setAction    = cc_Tree_setAction;
    this.getActionKey = cc_Tree_getActionKey;
}

function cc_Tree_Node()
{
    this.id        = cc_Tree_Node.arguments[0];
    this.parent    = cc_Tree_Node.arguments[1];
    this.nom       = cc_Tree_Node.arguments[2];
    this.lien      = cc_Tree_Node.arguments[3];
    this.isOpen    = cc_Tree_Node.arguments[4];
    this._class     = cc_Tree_Node.arguments[5];
    this._style     = cc_Tree_Node.arguments[6];
    this.functions = new Array();
    this.links     = new Array();

    //if( this.lien == '' || typeof this.lien == 'undefined') this.lien = 'javascript:void(0);';
    if( this.lien == '' || typeof this.lien == 'undefined') this.lien = '';
    if( this.useAnchor )
        this.lien += '#cc_Tree_'+this.id;
        
    this.setClass = function(c) { this._class=c; };
    this.setStyle = function(s) { this._style=s; };

    this.addLnk       = cc_Tree_addLnk;    
    this.setAction    = cc_Tree_setAction;
    this.getActionKey = cc_Tree_getActionKey;
}

function cc_Tree_addLnk(n,l,c,s)
{
    var l = new cc_Tree_Lnk(n,l,c,s);
    this.links[ this.links.length ] = l;
    return l;
}
    
function cc_Tree_setAction(a,v)
{
    var k = this.getActionKey(a);
    if( k )
        this.functions[k] = new Array(a,v);
    else
        this.functions[this.functions.length] = new Array(a,v);
}

function cc_Tree_getActionKey(a)
{
    for(var i=0; i < this.functions.length; i++)
    {
        var f = this.functions[i];
        if( f[0] == a ) return i;
    }
    return 0;
}

function cc_Tree_buildLinks(links, linkposition)
{
    var buf = '';
	for(var i=0; i < links.length; i++)
	{
	    var l = links[i];

        if( l.linkposition == linkposition )
        {
    	    if(linkposition == 'after' )
    	        buf += '&nbsp;';

    	    buf += '<a href="'+l.lien+'"';
    	    if( l._class ) buf += ' class="'+l._class+'"';
    	    if( l._style ) buf += ' style="'+l._style+'"';
    	    buf += cc_Tree_buildFunctions(l.functions);
    	    buf += '>'+l.nom+'</a>';

    	    if(linkposition == 'before' )
    	        buf += '&nbsp;';

        }
	}
	return buf;
}

function cc_Tree_buildFunctions(functions)
{
    var buf = '';
	for(var i=0; i < functions.length; i++)
	{
	    var f = functions[i];
	    buf += ' '+f[0]+'="'+f[1]+'"';
	}
	return buf;
}

var cc_Trees = new Array();

function cc_Tree()
{
    this.tid                = cc_Trees.length;
    cc_Trees[this.tid]      = this;
    this.nodes              = new Array();
    this.openNodes          = new Array();
    this.loadedNodes        = new Array();
    this.treeFirstNodeTitle = cc_Tree.arguments[0];
    this.lien               = cc_Tree.arguments[1];
    this._class             = cc_Tree.arguments[2];
    this._style             = cc_Tree.arguments[3];
    if( cc_Isset(cc_Tree.arguments[4]) ) cc_Tree_Image_Src = cc_Tree.arguments[4];
    this.functions          = new Array();
    this.links              = new Array();
    this.useAnchor          = 0;
    this.useIcons           = 0;
    
    cc_Tree_preloadIcons();
    
    if( this.treeFirstNodeTitle == '' || typeof this.treeFirstNodeTitle == 'undefined') this.treeFirstNodeTitle = 'Racine';
    if( this.lien == '' || typeof this.lien == 'undefined') this.lien = 'javascript:void(0);';

    this.setClass = function(c) { this._class=c; };
    this.setStyle = function(s) { this._style=s; };
    
    this.addLnk       = cc_Tree_addLnk;    
    this.setAction    = cc_Tree_setAction;
    this.getActionKey = cc_Tree_getActionKey;

    this.setAjaxActionOpenNode = function(a,p)
    {
        cc_Tree_SessionActionOpenNode = a;
        cc_Tree_SessionParamsOpenNode = p;
    }

    this.setAjaxActionCloseNode = function(a,p)
    {
        cc_Tree_SessionActionCloseNode = a;
        cc_Tree_SessionParamsCloseNode = p;
    }

    this.addLine = function(i,p,n,l,o,c,s)
    {        
        var n = new cc_Tree_Node(i,p,n,l,o,c,s);
        this.nodes[ this.nodes.length ] = n;
        return n;
    }
    
    this.setAnchorUse = function(v)
    {
        this.useAnchor = 1;
    }
    
    this.setIconUse = function(v)
    {
        this.useIcons = 1;
    }
    
    this.display = function()
    {
        document.write('<div id="cc_Tree_Conteneur"></div>');
        
        var div = new Object;
        div = document.createElement("DIV");
        div.id = 'cc_Tree_Conteneur_0';
        div.style.lineHeight = '18px';
        var contenu = '<img src="'+ cc_Tree_Image_Src + 'base.gif" align="absbottom" alt="" /></a>';
        div.innerHTML = contenu;
        
        // les liens
        var liensBefore = new Array;
        var liensAfter  = new Array;
        
        for(var j=0; j < this.links.length; j++)
        {
    	    var l = this.links[j];
    
            a = new Object;
            a = document.createElement("A");
            a.innerHTML = l.nom;
            a.href = l.lien;
            if( l._class ) a.className     = l._class;
            if( l._style ) a.style.cssText = l._style;
            for(var k=0; k < l.functions.length; k++)
                a.setAttribute( l.functions[k][0] , l.functions[k][1] );
            if( l.linkposition == 'before' )
                liensBefore.push(a);
            else
                liensAfter.push(a);
        }
        
        a = new Object;
        a = document.createElement("A");
        a.innerHTML = this.treeFirstNodeTitle;
        a.href = this.lien;
        if( this._class ) a.className     = this._class;
        if( this._style ) a.style.cssText = this._style;
        for(var j=0; j < this.functions.length; j++)
            a.setAttribute( this.functions[j][0] , this.functions[j][1] );

        var spaceSpan = document.createElement("SPAN");
        spaceSpan.innerHTML = '&nbsp;';

        for(var j=0; j<liensBefore.length; j++)
        {
            div.appendChild(liensBefore[j]);
            if( j < liensBefore.length )
                div.appendChild(spaceSpan);
        }
        div.appendChild(a);
        $('cc_Tree_Conteneur').appendChild(div);
        
        this.affNodes(0,0);
        for( var i=0; i < this.openNodes.length; i++ )
        {
            this.affNodes(this.openNodes[i],this.getMaxParentDernier(this.openNodes[i]));
        }   
    }

    this.getMaxParentDernier = function(n)
    {
        n = this.getNodeById(n);
        while(n.parent)
            n = this.getNodeById(n.parent);
        return this.lastSibling(n.id, n.parent);
    }
    
    // Checks if a node has any children
    this.hasChildNode = function(parentNode)
    {
    	for(i=0; i < this.nodes.length; i++)
    	{
    		var n = this.nodes[i];
    		if(n.parent == parentNode) return true;
    	}
    	return false;
    }

    // get a node by id
    this.getNodeById = function(nid)
    {
        for(var i=0; i < this.nodes.length; i++)
            if( this.nodes[i].id == nid ) return this.nodes[i];
        return;
    }
    
    // level ?
    this.getNodeLevel = function(node)
    {
        var lvl = 0;
        while( node.parent )
        {
            node = this.getNodeById(node.parent);
            lvl++;
        }
        return lvl;
    }
    
    // Checks if a node is the last sibling
    this.lastSibling = function(node, parentNode)
    {
    	var lastChild = 0;
    	for(i=0; i < this.nodes.length; i++)
    	{
    		var n = this.nodes[i];
    		if (n.parent == parentNode)
    			lastChild = n.id;
    	}
    	if (lastChild==node) return true;
    	return false;
    }

    // Checks if a node is open
    this.isNodeOpen = function(node)
    {
    	for(i=0; i < this.openNodes.length; i++)
    		if (this.openNodes[i]==node) return true;
    	return false;
    }

    // Checks if a node is loaded
    this.isNodeLoaded = function(node)
    {
    	for(i=0; i < this.loadedNodes.length; i++)
    		if (this.loadedNodes[i]==node) return true;
    	return false;
    }    
    
    // Puts in array nodes that will be open
    this.setOpenNodes = function(openNode)
    {
        var n = this.getNodeById(openNode);
        if( !n ) return;
        if( this.isNodeOpen(n.id) ) return;
        this.openNodes.push(n.id);
    	this.setOpenNodes(n.parent);
        return;
    	for (i=0; i < this.nodes.length; i++)
    	{
    		var n = this.nodes[i];
    		if (n.id==openNode && !this.isNodeOpen(n.id) )
    		{
    		    alert(openNode);
    			this.openNodes.push(n.id);
    			//this.setOpenNodes(n.parent);
    		}
    	}
    }
    
    this.getAffNodeInfo = function(n)
    {
        return {
            'level'   : this.getNodeLevel(n),
            'dernier' : this.lastSibling(n.id, n.parent),
            'enfants' : this.hasChildNode(n.id),
            'ouvert'  : this.isNodeOpen(n.id)
        };
    }

    this.affNodes = function(p,derniers)
    {
        var div , a , conteneur;
        
        if( this.isNodeLoaded(p) )
        {
            div = $('cc_Tree_MainConteneur_'+p);
            if( div.style.display == 'none' )
            {
                div.style.display = 'block';
                $('cc_Tree_Join_' + p ).src = cc_Tree_Image_Src+'minusbottom.gif';
                $('cc_Tree_Icon_' + p ).src = cc_Tree_Image_Src+'folderopen.gif';
            }
            else
            {
                div.style.display = 'none';
                $('cc_Tree_Join_' + p ).src = cc_Tree_Image_Src+'plusbottom.gif';
                $('cc_Tree_Icon_' + p ).src = cc_Tree_Image_Src+'folder.gif';
            }
            return;
        }
        
        this.loadedNodes.push(p);
        conteneur = document.createElement("DIV");
        conteneur.id = 'cc_Tree_MainConteneur_' + p;
                
        for (var i=0; i < this.nodes.length; i++)
        {
            var n = this.nodes[i];
            if( n.parent != p ) continue;
        
            //Ouverture du noeud initialise en ouvert
            if( n.isOpen )
                this.setOpenNodes(n.id);

            // informations sur le noeud
            var nodeInfos = this.getAffNodeInfo(n);
        
            if( p == 0 && nodeInfos['dernier'] ) var _derniers = 1;
            else                                 var _derniers = derniers;
                
            var contenu = '';
                   
			while(nodeInfos['level']-- > 0 )
			{
                if( _derniers )
                    contenu += '<img src="'+cc_Tree_Image_Src+'empty.gif" align="absbottom" alt="" />';
                else
                    contenu += '<img src="'+cc_Tree_Image_Src+'line.gif" align="absbottom" alt="" />';
			}
                
            if( nodeInfos['enfants'] )
            {
                contenu += '<a href="javascript: cc_Tree_OpenClose( '+this.tid+' , ' + n.id + ', '+_derniers+');"><img id="cc_Tree_Join_' + n.id + '" src="'+cc_Tree_Image_Src + (nodeInfos['ouvert'] ? 'minus' : 'plus' ) + 'bottom.gif" align="absbottom" alt="Open/Close node" /></a>';
                contenu += '<a href="javascript: cc_Tree_OpenClose( '+this.tid+' , ' + n.id + ', '+_derniers+');"><img id="cc_Tree_Icon_' + n.id + '" src="'+cc_Tree_Image_Src+'folder' + (nodeInfos['ouvert'] ? 'open' : '' ) + '.gif" align="absbottom" alt="Open/Close node" /></a>';
            }
            else
            {
                contenu += '<img src="'+cc_Tree_Image_Src+'join' + (nodeInfos['dernier'] ? 'bottom' : '') + '.gif" align="absbottom" alt="" />';
                contenu += '<img src="'+cc_Tree_Image_Src+'page.gif" align="absbottom" alt="" />';
            }
                                   
            var ls	= this.lastSibling(n.id, n.parent);
            
            var tid = this.tid;
            
            div = new Object;
            div = document.createElement("DIV");
            div.id = 'cc_Tree_Conteneur_' + n.id
            div.style.lineHeight = '18px';
            div.innerHTML = contenu;
            
            // les liens
            var liensBefore = new Array;
            var liensAfter  = new Array;
            
            for(var j=0; j < n.links.length; j++)
            {
        	    var l = n.links[j];
        
                a = new Object;
                a = document.createElement("A");
                a.innerHTML = l.nom;
                a.href = l.lien;
                if( l._class ) a.className     = l._class;
                if( l._style ) a.style.cssText = l._style;
                for(var k=0; k < l.functions.length; k++)
                    a.setAttribute( l.functions[k][0] , l.functions[k][1] );
                if( l.linkposition == 'before' )
                    liensBefore.push(a);
                else
                    liensAfter.push(a);
            }
            
            a = new Object;
            a = document.createElement("A");
            a.innerHTML = n.nom;
            a.href = n.lien;
            if( n._class ) a.className     = n._class;
            if( n._style ) a.style.cssText = n._style;
            for(var j=0; j < n.functions.length; j++)
                a.setAttribute( n.functions[j][0] , n.functions[j][1] );

            var spaceSpan = document.createElement("SPAN");
            spaceSpan.innerHTML = '&nbsp;';

            for(var j=0; j<liensBefore.length; j++)
            {
                div.appendChild(liensBefore[j]);
                if( j < liensBefore.length )
                    div.appendChild(spaceSpan);
            }
            div.appendChild(a);
            
            for(var j=0; j<liensAfter.length; j++)
            {
                if( j < liensAfter.length )
                    div.appendChild(spaceSpan);
                div.appendChild(liensAfter[j]);
            }
                            
            
            
            conteneur.appendChild(div);
        }
        cc_Tree_Inject(conteneur,$('cc_Tree_Conteneur_' + p),'inside');
    }
}

function cc_Tree_Inject(el,par,where)
{
	switch(where){
		case 'before': par.parentNode.insertBefore(el, par); break;
		case 'after':
			var next = par.nextSibling;
			if (!next) par.parentNode.appendChild(el);
			else par.parentNode.insertBefore(el, next);
			break;
		case 'top':
			var first = par.firstChild;
			if (first){
				par.insertBefore(el, first);
				break;
			}
		default: par.appendChild(el);
	}
}


// Opens or closes a node
function cc_Tree_OpenClose(treeId,node, derniers)
{
    cc_Trees[treeId].affNodes(node,derniers);
    
    var theDiv  = $('cc_Tree_MainConteneur_'  + node);
    var _data   = '';

    // comme le div a été déjà ouvert/fermé par affNodes, on inverse le test

	if( theDiv.style.display == 'none' )
    {
        if( cc_Tree_SessionActionCloseNode )
        {
            _data = 'do='+cc_Tree_SessionActionCloseNode+'&node_id=' + node;
            if( cc_Tree_SessionParamsCloseNode ) _data += '&'+cc_Tree_SessionParamsCloseNode;
            sendData('null',_data, ajaxTree, 'GET');
        }
	}
	else
    {
        if( cc_Tree_SessionActionOpenNode )
        {
            _data = 'do='+cc_Tree_SessionActionOpenNode+'&node_id=' + node;
            if( cc_Tree_SessionParamsOpenNode ) _data += '&'+cc_Tree_SessionParamsOpenNode;
            sendData('null',_data, ajaxTree, 'GET');
        }
	}
}

// Push and pop not implemented in IE
if(!Array.prototype.push) {
	function array_push() {
		for(var i=0;i<arguments.length;i++)
			this[this.length]=arguments[i];
		return this.length;
	}
	Array.prototype.push = array_push;
}
if(!Array.prototype.pop) {
	function array_pop(){
		lastElement = this[this.length-1];
		this.length = Math.max(this.length-1,0);
		return lastElement;
	}
	Array.prototype.pop = array_pop;
}