/*
========================================================================================
    renderMenuClientScript -
========================================================================================

    2006-12-21 AM    In TP we process the nodes when the page is loaded 
                    there for the code in onTunaMenuClick should not be executed.
                    The code is not removed because if somebodey wants categories 
                    to only be exposed in the tree this will come in handy.
    2006-12-21 AM    Added possibility to set class for selected node

TunaMenu - Documentation
    
The menu consists of a UL/LI list that is process by a javascript that appends click events to each LI depending on its child nodes.
    
#### CLASS ####
    
    TunaMenu(id, isStatic)
        * id        = the root element of the tree
        * isStatic  = if the tree should be static or not
    
#### Public METHODS ####
    
    TunaMenu.AddNodeClass(id, ref)
        * id = the internal css mapping vars
            - tm_tree           : the main tree
            - tm_nodeParent     : a node with childs
            - tm_nodeChild      : a node whitout childs
            - tm_nodeClosed     : when a tm_nodeParent is closed
            - tm_nodeOpened     : when a tm_nodeParent is open
            - tm_nodeSelected     : node is selected additional to the others
        * ref = your css class
    This method maps your css classes the internal vars used by the object when processing the items
    
    TunaMenu.Process(initdeep)
        * initdeep = (boolean) determins if the whole tree (true) or just the top nodes (false) shold be proceess initialy
    Iterates the nodes and applies events to the tree 
    
    TunaMenu.ExpandNode(nodeid, showchildren)
        * nodeid        = what node id to expand to
        * showchildren  = if children for the node should be show
    Opens up a node in the tree, and set the correct css class for the node. Will save the node as open, next time the page reloads
    
    TunaMenu.FindNode = function(nodeid, showchildren)
        * nodeid        = what node id to expand to
        * showchildren  = if children for the node should be show
    Same as TunaMenu.ExpandNode but dont save the node as opened
    
    TunaMenu.ExpandAll()
        * null
    Expands all nodes
    
#### Private METHODS ####    
    
    TunaMenu.prototype.processItems(elm, nodeclass, nodeid)
        * elm       = starting element in the tree
        * nodeclass = what internal class should be used (see AddNodeClass * id paramater)
        * nodeid    = target node
    Processes nodes from starting node (* elm) to ending node (* nodeid) and sets internal class (* nodeclass);
    
    TunaMenu.prototype.processTree = function(elm, initdeep)
        * elm       = starting element in the tree
        * initdeep  = (boolean) if childnodes should be processed
    Processes nodes and automatic asign the correct internal class (see AddNodeClass * id paramater)
    
    TunaMenu.setnodeState(node)
        * node  = the node to set
    Saves/Removes node state from js-cookie, cookies are used to remeber where in the tree the user has clicked.
    
#### Example #####    
    
    //Create the tuna tree
    var tt;
    tm = new TunaMenu('tree');
    tm.StaticTree = false | true
    tm.AddNodeClass("tm_tree", "tm_tree");
    tm.AddNodeClass("tm_nodeParent", "bullet");    
    tm.AddNodeClass("tm_nodeChild",  "tm_bullet");
    tm.AddNodeClass("tm_nodeClosed", "tm_closed");
    tm.AddNodeClass("tm_nodeOpened", "tm_opened");
    tm.AddNodeClass("tm_nodeSelected", "tm_selected");
    tm.Process(false);
    
    tm.ExpandNode(nodeid);
    tm.ExpandAll();
    tm.FindNode(nodeid);

*/

// description="Prototypes"

    Date.prototype.dateAdd = function(datepart, interval) 
    {
        //if (isNaN(this)) this = new Date();
        switch (datepart.substring(0,1).toLowerCase()) 
        {
            case "s": return new Date(Date.parse(this) + (1000 * interval));
            case "n": return new Date(Date.parse(this) + (60000 * interval));
            case "h": return new Date(Date.parse(this) + (3600000 * interval));
            case "d": return new Date(Date.parse(this) + (86400000 * interval));
            case "w": return new Date(Date.parse(this) + ((86400000 * 7) * interval));
            case "m": return new Date(this.getFullYear(), (this.getMonth()) + interval, this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds());
            case "y": return new Date((this.getFullYear() + interval), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds());
        }
    }
    
//description="MenuItemsClientScript";
    function TunaMenu(id, isStatic)
    {    
        if (!document.createElement) return;

        this.id = id;
        this.nodestate = Get_Cookie("TunaMenu_"+ this.id);                
        
        this.StaticTree = isStatic || false;
                        
        this.AddNodeClass("tm_tree", "tm_tree");
        this.AddNodeClass("tm_nodeParent", "bullet");    
        this.AddNodeClass("tm_nodeChild",  "tm_bullet");
        this.AddNodeClass("tm_nodeClosed", "tm_closed");
        this.AddNodeClass("tm_nodeOpened", "tm_opened");
        this.AddNodeClass("tm_nodeSelected", "tm_selected");
    }
    
    
    TunaMenu.prototype.AddNodeClass = function( id, ref )
    {
        this[id] = ref;
    }
    
    TunaMenu.prototype.Render = function(initdeep)
    {
        var elm = document.getElementById(this.id);
        if( !elm )
            return false;
        this.processTree(elm, (initdeep == true));
        
        if(this.StaticTree) 
        {
            this.ExpandAll();
            return;
        }
        
        //Open saved nodes    
        if( this.nodestate != '' )
        {
            var nodes = this.nodestate.split( '\t' );
            for( var i=0; i<nodes.length; i++ )
            {
                this.FindNode(unescape(nodes[i]), true);
            }
        }
        
    }
    
    TunaMenu.prototype.FilterNodes = function(criteriafunc, initdeep, elm)
    {
        elm = (elm) ? elm : document.getElementById(this.id);
        
        this.filter = criteriafunc;
        
        for(var i=0; i<elm.childNodes.length; i++)
        {
            var item = elm.childNodes[i];
                
            if(item.nodeName == "LI") 
            {
                //catch errors in user custom function
                try
                {
                    //Check if this node should be filtered out
                    item.style.display = (this.filter(item)) ? 'block' : 'none';
                }
                catch( err )
                {
                    /*
                    var debugwin = window.open('','debugwin', 'height=400,width=400,scrollbars=1');
                    debugwin.document.write('<h2>Debug win</h2>\n\n');
                    
                    var debug = elm.nodeName +' - '+ elm.id  +' - '+  this.filter 
                    debugwin.document.write('<h2>'+ debug +'</h2>\n\n');
                    */
                }     
                  
                for(var u=0; u<item.childNodes.length; u++)
                {
                    var child = item.childNodes[u];
                    if(child.nodeName == "UL" && initdeep) 
                    {               
                        this.FilterNodes(this.filter, initdeep, child);
                    }
                }
            }
        }
    }
    
    // Expands enough nodes to expose an LI with a given ID
    TunaMenu.prototype.ExpandNode = function( nodeid, showchildren ) 
    {
        var elm = this.FindNode( nodeid, showchildren );
        this.setnodeState( elm );
        return elm;
    }
    
    TunaMenu.prototype.SetNodeSelected = function( nodeEl ) 
    {
        var selectedCls = String( this.tm_nodeSelected );
        if( this.SelectedNode )
        {
            var oldSelected = document.getElementById( oldSelected );
            
            if( oldSelected )
            {
                var cls = String( oldSelected.className );
                cls = cls.Replace( ' '+selectedCls, '' );
                oldSelected.className = cls;
            }
        }
        
        if( nodeEl )
        {
            nodeEl.className = nodeEl.className + ' '+selectedCls;
            this.SelectedNode = nodeEl.id;
        }
        
        return nodeEl;
    }
    
    // Expands enough nodes to expose an LI with a given ID
    TunaMenu.prototype.FindNode = function( nodeid, showchildren ) 
    {
        var elm = document.getElementById( this.id );
        if ( !elm )
            return false;
        
        if( this.processItems( elm, this.tm_nodeOpened, nodeid ) )
        {
            elm = document.getElementById(nodeid);
            if( showchildren )
            {
                for(var i=0; i<elm.childNodes.length; i++)
                {
                    var child = elm.childNodes[i];
                    if( child.nodeName == "UL" )
                    {
                        this.FindNode( child.firstChild.id );
                        break;
                    }
                }
            }
            // TODO: remmed in debug purpose, IE hungs its self if(elm && elm.scrollIntoView) elm.scrollIntoView(false);
        }
        return elm;
    }
            
    // Full expands a tree with a given ID
    TunaMenu.prototype.ExpandAll = function() 
    {
        var elm = document.getElementById(this.id);
        if( !elm )
            return false;
        this.processItems(elm, this.tm_nodeOpened);
    }

    TunaMenu.prototype.processItems = function(elm, nodeclass, nodeid) 
    {
        if(!elm.childNodes || elm.childNodes.length == 0) return false;
        
        for( var i=0; i<elm.childNodes.length; i++ ) 
        {
            var item = elm.childNodes[i];
            if (nodeid && nodeid == item.id) return true;
            
            if(item.nodeName == "LI") 
            {
                var hasChilds = false;
                for (var c=0; c<item.childNodes.length; c++) 
                {
                    var child = item.childNodes[c];
                    if(child.nodeName == "UL") 
                    {
                        if(!item.isProcessed) 
                        {
                            this.processTree(child, true);
                            item.isProcessed = true;
                        }
                        hasChilds = true;
                        var ret = this.processItems(child, nodeclass, nodeid);
                        if(nodeid && ret) 
                        {
                            item.className = nodeclass;
                            return true;
                        }
                    }
                }
                if(hasChilds && nodeid == null) 
                {
                    item.className = nodeclass;
                }
            }
        }
    }
            
    TunaMenu.prototype.processTree = function(elm, initdeep)
    {
        if(!elm.childNodes || elm.childNodes.length == 0) return;

        for(var i=0; i<elm.childNodes.length; i++) 
        {
            var item = elm.childNodes[i];
            if(item.nodeName == "LI") 
            {
                item.isProcessed = initdeep;
                
                var hasChilds = false;
                for(var c=0; c<item.childNodes.length; c++) 
                {
                    var child = item.childNodes[c];
                    if (child.nodeName == "UL") 
                    {
                        hasChilds = true;
                        if(initdeep) this.processTree(child, initdeep);
                    }
                }

                var t = '\u00A0'; // &nbsp;
                var s = document.createElement("SPAN");
                s.base        = this;
                s.className   = this.tm_nodeParent;

                if( hasChilds ) 
                {
                    if(this.isEmpty(item.className)) 
                    {
                        item.className = this.tm_nodeClosed;
                    }

                    if(item.firstChild.nodeName == "#text") 
                    {
                        t += item.firstChild.nodeValue;
                        item.removeChild(item.firstChild);
                    }

                    if(!this.StaticTree)
                    {
                        s.onclick = onTunaMenuClick
                    }
                }
                else 
                {
                    // No sublists, so it's just a bullet node
                    item.className = this.tm_nodeChild;
                    s.onclick = function () { return false; }
                }

                s.appendChild(document.createTextNode(t));
                item.insertBefore(s, item.firstChild);
            }
        }
    }

    TunaMenu.prototype.setnodeState = function( node )
    {
        //Get the main container
        while(node.nodeName != 'LI')
        {
            node = node.parentNode;
        }
        
        var isOpen = false;
        if( node.className == this.tm_nodeOpened || node.className == ( this.tm_nodeOpened + ' ' + this.tm_nodeSelected ) )
        {
            isOpen = true;
        }
        else if( node.className == this.tm_nodeChild || node.className == ( this.tm_nodeChild + ' ' + this.tm_nodeSelected ) )
        {
            isOpen = true;
        }
        
        var id = node.id +"\t"
        
        //Temp fix, todo make sure parent hides childs, this works for url id
        if( !isOpen )
        {
            var temp = this.nodestate.split('\t');
            var arr = new Array()
            for(var i=0; i<temp.length; i++)
            {
                if(temp[i].indexOf(node.id) == -1)
                    arr[arr.length] = temp[i];
            }
            this.nodestate = arr.join('\t');
        }
        
        this.nodestate = this.nodestate.replace(new RegExp(id, 'gi'),'');
        if( isOpen )
            this.nodestate += id;
        
        Set_Cookie("TunaMenu_"+ this.id, this.nodestate, "", "/", "", false);
    }
    
    TunaMenu.prototype.isEmpty = function(obj)
    {
        return (obj || obj == "");
    }
    
    function onTunaMenuClick()
    {
        /*
        2006-12-21 AM    In TP we process the nodes when the page is loaded 
                        there for this code shoul not be executed.
                        The code is not removed because if somebodey wants categories 
                        to only be exposed in the tree this will come in handy.
        
        */
        /*
        if(!this.parentNode.isProcessed) 
        {    
             var childs = this.parentNode.childNodes
             for(var i=0; i<childs.length; i++)
             {  
                  if(childs[i].nodeName == 'UL') this.base.processTree(childs[i], false);
             }
             this.parentNode.isProcessed = true;
        }
        this.parentNode.className = (this.parentNode.className == this.base.tm_nodeOpened) ? this.base.tm_nodeClosed : this.base.tm_nodeOpened;
        this.base.setnodeState(this);
        return false;
        */
    }
            
// description - TunaMenu extended functions
            
    function favouritesClick()
    {
        parent.main.document.location="/TradePoint/Item Favourites - List";
    }
    
    function nodeClick( id, url, extra )
    {
        if(elm.parentNode.firstChild.nodeName == 'SPAN')
        {            
            try
            {
                elm.parentNode.firstChild.onclick();
            }
            catch(e){}
        }
       
        //if(elm.parentNode.childNodes.length < 3) 
        {
            /* Bread Crums not used here..
            var qs = getBreadCrums(elm);
            setTimeout('document.location="' + url + '&' + 'bc='+ escape(qs) +'"', 1000);*/
            if(extra)
                extra = '&' + extra;
            else
                extra = "";
            
            setTimeout('document.location="' + url + extra + '"', 1000);
        }
        elm.blur();
    }
    
    function getBreadCrums(elm)
    {
        var qs = new Array();
        
        while(elm)
        {
            var cnt = elm.childNodes.length;
            for(var i=0; i < cnt; i++)
            {
                var child = elm.childNodes[i];
                    
                if(child.nodeName == "A")
                {
                    var val = child.innerHTML;
                    qs[qs.length] = elm.getAttribute("id") +'\t'+ val;
                    break;
                }
            }
            elm = elm.parentNode;                
        }
        
        qs.reverse();
        return qs.join('');
    }
    
    var celm = document.getElementById('treeIndex');
    var telm = document.getElementById('tree');
    
    function filterNodes( chr )
    {
        celm.innerHTML = '';
        telm.style.display = 'none';
    
        function checkFirstChar(elm)
        {
            if( elm.nodeName == 'LI' && ( elm.className == "tm_bullet" || elm.className == "" ) )
            {
                var child = elm.firstChild;
                
                while( child.nodeName != 'A' ) 
                {
                    child = child.nextSibling;
                }
                
                var val = child.innerHTML.substring(0,1).toUpperCase();
                if(this.filterChar == val)
                {
                    this.filterCache[this.filterCache.length] = { node : child.cloneNode(true), value : child.innerHTML };
                }
            }
            return true;
        }
        
        function filterSorter(n1, n2)
        {
            n1 = n1.value;
            n2 = n2.value;
            
            // Compare the two values.
            if (n1 < n2) return -1;
            if (n1 > n2) return 1
            return 0;            
        }
        
        tm.filterChar = chr;
        tm.filterCache = new Array();
        tm.FilterNodes(checkFirstChar, true);
        
        tm.filterCache.sort(filterSorter);
        var cnt = tm.filterCache.length;
        for(var i=0; i < cnt; i++)
        {
            var li = document.createElement("LI");
            li.appendChild(tm.filterCache[i].node);
            celm.appendChild(li);
        }
    }
        
// description - Cookies
            
    function Get_Cookie(name) 
    {
        var start = document.cookie.indexOf(name+"=");
        var len = start+name.length+1;
        if ((!start) && (name != document.cookie.substring(0,name.length))) return "";
        if (start == -1) return "";
        var end = document.cookie.indexOf(";",len);
        if (end == -1) end = document.cookie.length;
        return unescape(document.cookie.substring(len,end));
    }  

    function Set_Cookie(name,value,expires,path,domain,secure) 
    {
        document.cookie = name + "="     + escape(value) +
            ( (expires) ? ";expires="     + expires.toGMTString() : "") +
            ( (path)     ? ";path="         + path : "") +
            ( (domain)     ? ";domain="     + domain : "") +
            ( (secure)     ? ";secure"     : "");
    }

    function Delete_Cookie(name,path,domain) 
    {
        if (Get_Cookie(name)) document.cookie = name + "=" +
            ( (path)     ? ";path=" + path : "") +
            ( (domain)     ? ";domain=" + domain : "") +
            ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
    }
