// create a namespace using a hashmap
cstree = {
    collapsedClass: 'collapsed',
    expandedClass: 'expanded',
    selectedClass: 'selected',
    parentSelectAll: false,
    selectedIds: [],
    selectionMode: 'and',
    xmlHttp: null,
    pagesize: 5,
    pagenumber: 1,
    
    initialize: function() {
        // cs tree parent
        var cs_ul = document.getElementById('cs-tree');
        
        // iterate through all <li> tags and add links
        var li_nodes = cs_ul.getElementsByTagName('li');        
        
        for (var i=0;i<li_nodes.length;i++) {
            li = li_nodes[i];
            innerUls = li.getElementsByTagName('ul');
            // if list item has children
            if (innerUls.length>0) {
                wrapNode(li.getElementsByTagName('a')[0], 'span', 'expandButton');
                addClassName(innerUls[0], cstree.collapsedClass);
                // register event handler
                li.getElementsByTagName('span')[0].onclick = cstree.showHide;
            }
            if (!cstree.parentSelectAll && innerUls.length>0) {
                //li.getElementsByTagName('a')[0].onclick = cstree.showHide;
            } else {
                li.getElementsByTagName('a')[0].onclick = cstree.toggleSelection;
            }
        }
        
        cstree.preselectItems();
        cstree.unfoldSelectedItems();
        cstree.submitSelection();
    },
    
    preselectItems: function() {
        uids = [];        
        
        // get uids from query string
        var query = location.search.substring(1);
        var pairs = query.split("&");
        for(var i=0; i<pairs.length; i++) { 
            pair = pairs[i].split("=");
            if (pair.length>1) {
                // get uids
                if (pair[0]=='cs_uids:list') {
                    uids.push(pair[1]);
                }
                // get selection mode
                if (pair[0]=='cs_mode') {
                    cstree.selectionMode = pair[1];
                }
            }
        }
        
        // get uids from session if we got nothing from query string
        // (keep selection if user navigates back)
        if (uids.length<1) {
            var cookie_uids = document.cookie.match ('(^|;)cs_uids=([^;]*)');
            if (cookie_uids) {
                uids = cookie_uids[2].split(',');
                cstree.selectionMode = uids.pop(); // the last element is the selection mode
            }
        }
        
        cstree.selectedIds = uids;
        // assign selected class to selected items
        var cs_ul = document.getElementById('cs-tree');
        var li_nodes = cs_ul.getElementsByTagName('li');
        for (var i=0;i<li_nodes.length;i++) {
            var aNode = li_nodes[i].getElementsByTagName('a')[0];
            var id = aNode.getAttribute('id');
            if ((uids.indexOf(id) > -1) && !hasClassName(aNode, 'selected')) {
                addClassName(aNode, 'selected');
            }            
        }
        
        // assign selected class to current selection mode
        andNode = document.getElementById('cs-config-and');
        orNode = document.getElementById('cs-config-or');
        if (cstree.selectionMode == 'and') {
            removeClassName(orNode, cstree.selectedClass);
            addClassName(andNode, cstree.selectedClass);
        } else {
            removeClassName(andNode, cstree.selectedClass);
            addClassName(orNode, cstree.selectedClass);
        }        
    },
    
    unfoldSelectedItems: function() {
        var cs_ul = document.getElementById('cs-tree');
        var ul_nodes = cs_ul.getElementsByTagName('ul');
        for (var i=0; i<ul_nodes.length; i++) {
            selectedNodes = cssQuery('a.selected', ul_nodes[i]);
            if (selectedNodes.length>0) {
                replaceClassName(ul_nodes[i], cstree.collapsedClass, cstree.expandedClass, true);
                replaceClassName(ul_nodes[i].previousSibling, 'expandButton', 'collapseButton');
            }
        }        
    },
    
    showHide: function(e) {
        var targetNode = this;
        var node = targetNode.parentNode.getElementsByTagName('ul')[0];
        var toggleNode = this;
        if (hasClassName(node, cstree.collapsedClass)) {
            replaceClassName(node, cstree.collapsedClass, cstree.expandedClass);
            replaceClassName(toggleNode, 'expandButton', 'collapseButton');
        } 
        else {
            if (hasClassName(node, cstree.expandedClass)) {
                replaceClassName(node, cstree.expandedClass, cstree.collapsedClass);
                replaceClassName(toggleNode, 'collapseButton', 'expandButton');
            }
        }      
        cstree.cancelClick(e);       
    },

    toggleSelection: function(event) {
        //if (!event) var event = window.event; // IE compatibility
        var targetNode = this;
        var parentLI = targetNode.parentNode;
        if (parentLI.nodeName.toLowerCase() != 'li') {parentLI = parentLI.parentNode;}
        if (hasClassName(targetNode, 'selected')) {
            removeClassName(targetNode, 'selected');
            idx = cstree.selectedIds.indexOf(targetNode.getAttribute('id'));
            cstree.selectedIds.splice(idx, 1);
            
            // if node has children, also unselect them
            children = parentLI.getElementsByTagName('li');
            for (var i=0; i<children.length; i++) {
                aNode = children[i].getElementsByTagName('a')[0];
                removeClassName(aNode, 'selected');
                idx = cstree.selectedIds.indexOf(aNode.getAttribute('id'));
                cstree.selectedIds.splice(idx, 1);
            }
        } else {
            addClassName(targetNode, 'selected');
            cstree.selectedIds.push(targetNode.getAttribute('id'))
            
            // if node has children, also select them
            children = parentLI.getElementsByTagName('li');
            for (var i=0; i<children.length; i++) {
                aNode = children[i].getElementsByTagName('a')[0];
                if (!hasClassName(aNode, 'selected')) {
                    addClassName(aNode, 'selected');
                    cstree.selectedIds.push(aNode.getAttribute('id'));
                }
            }
            
        }
        //alert(cstree.selectedIds);
        cstree.pagenumber = 1;
        cstree.submitSelection();        
        cstree.cancelClick(event);
        
    },
    
/* helper methods */
	cancelClick:function(e){
		if (window.event){
			window.event.cancelBubble = true;
			window.event.returnValue = false;
			return;
		}
		if (e){
			e.stopPropagation();
			e.preventDefault();
		}
	},

/* ajax stuff */
    getXmlHttpObject:function() { 
        var objXMLHttp = null;
        if (window.XMLHttpRequest) {
            objXMLHttp=new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        return objXMLHttp;
    },
    submitSelection:function() {
        cstree.xmlHttp = cstree.getXmlHttpObject();
        var url = window.location.pathname +  "/xmlGetCsBrowserResults";
        parameters = 'pagenumber=' + cstree.pagenumber;
        parameters += '&cs_mode=' + cstree.selectionMode;
        for (var i=0; i<cstree.selectedIds.length; i++) {
            parameters += "&cs_uids:list=" + cstree.selectedIds[i];
        }
        cstree.xmlHttp.onreadystatechange = cstree.updateResults;
        cstree.xmlHttp.open('POST', url, true);
        cstree.xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        cstree.xmlHttp.setRequestHeader("Content-length", parameters.length);
        cstree.xmlHttp.setRequestHeader("Connection", "close");
        cstree.xmlHttp.send(parameters);
        cstree.saveSelection();
    },
    updateResults:function() {
        if (cstree.xmlHttp.readyState==4 || cstree.xmlHttp.readyState=="complete") {
            document.getElementById("cs-results").innerHTML=cstree.xmlHttp.responseText;
        }        
    },
    showPage:function(event) {
        cstree.submitSelection();
        cstree.cancelClick(event);
    },
    
    saveSelection: function() {
        // delete cookie if nothing is selected
        if (cstree.selectedIds.length<1) {
            expires = new Date(new Date().getTime()-1);
            document.cookie = 'cs_uids=;expires=' + expires.toGMTString();
            return;
        }
        // store current selection in cookie for 5 minutes
        expires = new Date(new Date().getTime() + 300000);
        document.cookie = 'cs_uids=' + cstree.selectedIds.join(',') + ',' 
            + cstree.selectionMode + ';expires=' + expires.toGMTString();
    },
    
    toggleSelectionMode: function(event) {
        andNode = document.getElementById('cs-config-and');
        orNode = document.getElementById('cs-config-or');
        
        if (cstree.selectionMode == 'or') {
            cstree.selectionMode = 'and';
            removeClassName(orNode, cstree.selectedClass);
            addClassName(andNode, cstree.selectedClass);
        } else {
            cstree.selectionMode = 'or';
            removeClassName(andNode, cstree.selectedClass);
            addClassName(orNode, cstree.selectedClass);
        }
        
        cstree.pagenumber = 1;
        cstree.showPage(event);
    },
    clearSelection: function(event) {
        for (var i=0; i<cstree.selectedIds.length; i++) {
            removeClassName(document.getElementById(cstree.selectedIds[i]), cstree.selectedClass);
        }
        cstree.selectedIds = [];
        cstree.saveSelection();
        cstree.showPage(event);
    } 
}

// if indexOf is not implemented by the browser
// note: this is not an js 1.6 conform implementation!
if (!Array.prototype.indexOf) {
	Array.prototype.indexOf = function array_indexOf() {
		if (arguments.length>0) {
		    for (var i=0; i<this.length; i++) {
		        if (this[i] == arguments[0]) {
		            return i;
		        }
		    }
		}
		return -1;
	}
};

registerPloneFunction(cstree.initialize);

