///////////////////////////////////////////////////////////////////////////////////
//  Tree Management Section
///////////////////////////////////////////////////////////////////////////////////


function CollectionTreeManager(formName)
{
    this.defaultCollections = [];
    this.categories         = [];
    this.collectionIds      = [];
    this.formName           = formName;

    // The cache of images that are used in the collection tree
    this.imageCache = [];
}

CollectionTreeManager.prototype.setDefaultCollections = function(defaultCollections)
{
    this.defaultCollections = defaultCollections;
}

CollectionTreeManager.prototype.setCategories = function(cats)
{
    this.categories = cats;
}

CollectionTreeManager.prototype.setCollectionIds = function(collIds)
{
    this.collectionIds = collIds;
}

//-----------------------------------------------------------------------------
// Gets all occurances of a checkbox which corresponds to the collectionId
//-----------------------------------------------------------------------------
CollectionTreeManager.prototype._getCheckBoxesFromCollectionId = function(collectionId)
{
    var ret = [];

    // Find the checkbox with the default collecion id
    var inputs = document.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++)
    {
        if (inputs[i].type == "checkbox")
        {
            var checkBoxValue = inputs[i].value;
            if (collectionId == checkBoxValue       ||
                collectionId == this._extractId(checkBoxValue) )
            {
                ret.push(inputs[i]);
            }
        }
    }

    return ret;
}

//-----------------------------------------------------------------------------
// Expand or Collapse Single Tree Node
//-----------------------------------------------------------------------------
CollectionTreeManager.prototype.toggle = function(item)
{
    var obj = document.getElementById(item);

    if (obj.style.display != "none")
    {
        this.collapseNode(item);
    } 
    else 
    {
	    this.expandNode(item);
    }

    document.getElementById("all").checked = this._areAllChecked();

    // if all nodes are expanded, then change the main node to minus
    if (this._areAllNodesExpanded(this.categories))
    {
        this.setImage("allCategoryImage", "minus");
    }

    // if all nodes are collapsed, then change the main node to plus
    if (this._areAllNodesCollapsed(this.categories))
    {
        this.setImage("allCategoryImage", "plus");
    }

    return false;
}

//-----------------------------------------------------------------------------
// collapse a tree node
//-----------------------------------------------------------------------------
CollectionTreeManager.prototype.collapseNode = function(item)
{
    var obj = document.getElementById(item);
    obj.style.display = "none";
    this.setImage("ximg"+item, "plus");
}

//-----------------------------------------------------------------------------
// expand a tree node
//-----------------------------------------------------------------------------
CollectionTreeManager.prototype.expandNode = function(item)
{
    var obj = document.getElementById(item);
    obj.style.display = "block";
    this.setImage("ximg"+item, "minus");
}

//-----------------------------------------------------------------------------
// find out whether or not all of the nodes in the array are expanded
//-----------------------------------------------------------------------------
CollectionTreeManager.prototype._areAllNodesExpanded = function(categoryArray)
{
    for(var i = 0; i < categoryArray.length; i++)
    {
        if (document.getElementById(categoryArray[i]).style.display == "none")
        {
            return false;
        }
    }
    return true;
}

//-----------------------------------------------------------------------------
// find out whether or not all of the nodes in the array are collapsed
//-----------------------------------------------------------------------------
CollectionTreeManager.prototype._areAllNodesCollapsed = function(categoryArray)
{
    for(var i = 0; i < categoryArray.length; i++)
    {
        if (document.getElementById(categoryArray[i]).style.display == "block")
        {
            return false;
        }
    }

    return true;
}

//-----------------------------------------------------------------------------
// toggles all of the categories in the array
//-----------------------------------------------------------------------------
CollectionTreeManager.prototype.toggleAll = function()
{
    var img = document.images["allCategoryImage"];

    if (String(img.src).indexOf("plus.gif") > 0)
    {
        this._expandAll(this.categories);
    } 
    else 
    {
        this._collapseAll(this.categories);
    }

    return false;
}

//-----------------------------------------------------------------------------
// Expands all nodes in the category Array
//-----------------------------------------------------------------------------
CollectionTreeManager.prototype._expandAll = function(categoryArray)
{
    this.setImage("allCategoryImage", "minus");
    for (var i = 0; i < categoryArray.length; i++) 
    {
        this.expandNode(categoryArray[i]);
    }    
}

//-----------------------------------------------------------------------------
// Collapses all nodes in the category Array
//-----------------------------------------------------------------------------
CollectionTreeManager.prototype._collapseAll = function(categoryArray)
{
    this.setImage("allCategoryImage", "plus");
    for(var i = 0; i < categoryArray.length; i++)
    {
        this.collapseNode(categoryArray[i]);
    }
}

//-----------------------------------------------------------------------------
// Sets the checked state of the all source check box
//-----------------------------------------------------------------------------
CollectionTreeManager.prototype.checkAllSources = function()
{
    if (typeof(document.getElementById("all")) != "undefined")
    {
        document.getElementById("all").checked = this._areAllChecked();
    }
}

//-----------------------------------------------------------------------------
// Check All Nodes Under a Group
//-----------------------------------------------------------------------------
CollectionTreeManager.prototype.check_group = function(item)
{
    var category = document.getElementById("z"+item);
    var collections = document.getElementById(item).getElementsByTagName("input");
    for (var i = 0; i < collections.length; i++)
    {
        collections[i].checked = category.checked;
    }

    this.checkAllSources();
}

//-----------------------------------------------------------------------------
// Checks Status of a Group
//-----------------------------------------------------------------------------
CollectionTreeManager.prototype.check_status = function(item)
{
    // get the category element identified by "item"
    var category = document.getElementById("z"+item);

    // get all of this category element's children
    var collections = document.getElementById(item).getElementsByTagName("input");

    // If there are no child nodes, then return
    if (collections.length === 0)
    {
        return;
    }

    // Count the children that are "checked"
    var check_count = 0;

    for (var i = 0; i < collections.length; i++)
    {
        if (collections[i].type == 'checkbox' && collections[i].checked)
        {
            check_count++;
        }
    }

    // if all the children are checked, then the parent is checked
    if (check_count > 0 && check_count == collections.length)
    {
        category.checked = true;
    }
    else
    {
        category.checked = false;
        // if some, but not all of the categories are checked, then expand this category node
        if (check_count !== 0)
        {
            this.expandNode(item);
        }
    }

    this.checkAllSources();
}

//-----------------------------------------------------------------------------
// Sets the checked state of the checkboxes
//-----------------------------------------------------------------------------
CollectionTreeManager.prototype._setAllCheckBoxes = function(checked)
{
    var root  = document.getElementById("categoryBlock");
    var nodes = root.getElementsByTagName("input");
    if (nodes)
    {
        // set the check value for all check boxes
        for (var i = 0; i < nodes.length; i++)
        {
            var element = nodes[i];
            if (element.type == "checkbox")
            {
                element.checked = checked;
            }
        }
    }
}

//-----------------------------------------------------------------------------
// unchecks all checkboxes in the search form
//-----------------------------------------------------------------------------
CollectionTreeManager.prototype._uncheckAll = function()
{
    this._setAllCheckBoxes(false);
}

//-----------------------------------------------------------------------------
// checks all checkboxes in the search form
//-----------------------------------------------------------------------------
CollectionTreeManager.prototype._checkAll = function()
{
    this._setAllCheckBoxes(true);
}

//-----------------------------------------------------------------------------
// Finds out if all of the checkboxes in the search form are checked
//-----------------------------------------------------------------------------
CollectionTreeManager.prototype._areAllChecked = function()
{
    var root = document.getElementById("categoryBlock");
    var nodes = root.getElementsByTagName("input");
    if (!nodes)
    {
        return false;
    }

    for (var i = 0; i < nodes.length; i++) {
        if (nodes[i].type == "checkbox" && nodes[i].id != "all") {
            if (!nodes[i].checked) {
                return false;
            }
        }
    }

    return true;
}

//-----------------------------------------------------------------------------
// Extracts the collection id from a string that is the combination of category
// id and collection id.
//-----------------------------------------------------------------------------
CollectionTreeManager.prototype._extractId = function(value)
{
    var underIndex = value.indexOf("_");
    var ret = "";
    if (underIndex > 0)
    {
        ret = value.substr(underIndex + 1, value.length - 1);
    }

    return ret;
}

//-----------------------------------------------------------------------------
// Checks no Collections by Default
//-----------------------------------------------------------------------------
CollectionTreeManager.prototype._setupTree = function(collectionIds)
{
    if (collectionIds.length === 0) 
    {        
        this._uncheckAll();
    }
    else if (collectionIds[0] == "all")
    {
        this._checkAll();
    }
    else
    {
        var collectionCheckBoxes = document.forms[this.formName].selectedCollections;
        if (typeof(collectionCheckBoxes) == "undefined")
        {
            collectionCheckBoxes = document.forms[this.formName].collections;
        }

        if (typeof(collectionCheckBoxes) == "undefined")
        {
            alert("Error:  Why are there no collections?");
            return;
        }
        
        for (var i = 0; i < collectionCheckBoxes.length; i++)
        {
            var collectionCheckbox = collectionCheckBoxes[i];
            collectionCheckbox.checked = false;
            for (var j = 0; j < collectionIds.length; j++) {
                if (collectionCheckbox.value == collectionIds[j] ||
                    this._extractId(collectionCheckbox.value) == collectionIds[j] )
                {
                    collectionCheckbox.checked = true;
                }
            }
        }

        // go through each category and decided if we need to show it
        for (var i = 0; i < this.categories.length; i++)
        {
            var categoryName = "cat" + (i + 1);
            if (document.getElementById("z" + categoryName)) 
            {
                this.check_status(categoryName);
            }
        }
    }

    this.checkAllSources();
}

//-----------------------------------------------------------------------------
// check all of the coll checkboxes
//-----------------------------------------------------------------------------
CollectionTreeManager.prototype._selectAll = function(collections)
{
    if (!collections)
    {
        return;
    }

    // set the check value for all check boxes
    for (var i = 0; i < collections.length; i++) 
    {
        collections[i].checked = true;
    }
}

//-----------------------------------------------------------------------------
// uncheck all of the collections checkboxes
//-----------------------------------------------------------------------------
CollectionTreeManager.prototype._deselectAll = function(collections)
{
    if (!collections)
    {
        return;
    }

    // set the check value for all check boxes
    for (var i = 0; i < collections.length; i++) 
    {
        collections[i].checked = false;
    }
}

//-----------------------------------------------------------------------------
// adds an image to the image cache
//-----------------------------------------------------------------------------
CollectionTreeManager.prototype.addToImageCache = function(imageName, src, alt, title)
{
    this.imageCache[imageName]       = new Image(11, 11);
    this.imageCache[imageName].src   = src;
    this.imageCache[imageName].alt   = alt;
    this.imageCache[imageName].title = title;
}

//-----------------------------------------------------------------------------
// set the image identified by imgId to the image with name: imgName
// this assumes that there is an array of images named "imageCache"
// that contains the image to set.
//-----------------------------------------------------------------------------
CollectionTreeManager.prototype.setImage = function(imgId, imgName)
{
    document.images[imgId].src   = this.imageCache[imgName].src;
    document.images[imgId].alt   = this.imageCache[imgName].alt;
    document.images[imgId].title = this.imageCache[imgName].title;
}

//-----------------------------------------------------------------------------
// Handler for the onclick event from the "check all" checkbox
//-----------------------------------------------------------------------------
CollectionTreeManager.prototype.toggleSelect = function()
{
    var chkAllElement = document.getElementById("all");
    
    if (chkAllElement.checked)
    {
        this._selectAll(document.forms[this.formName].selectedCollections);
        this._checkAll();
    }
    else
    {
        this._deselectAll(document.forms[this.formName].selectedCollections);
        this._uncheckAll();
    }
}

//-----------------------------------------------------------------------------
// Initializes the array of checkboxes
//-----------------------------------------------------------------------------
CollectionTreeManager.prototype.setupCategoryTree = function()
{
    var cb;
    var i;
    var j;
    if (typeof(C) == "undefined")
    {
        if (this.defaultCollections[0] != "NONE")
        {
            C = [];

            if (this.defaultCollections[0] == "ALL")
            {
                C[0] = "all";
            }
            else
            {
                for (i = 0; i < this.defaultCollections.length; ++i)
                {
                    cb = this._getCheckBoxesFromCollectionId(this.defaultCollections[i]);
                    for (j = 0; j < cb.length; ++j)
                    {
                        C.push(cb[j].value);
                    }
                }
            }
        }
    }
    else if (C.length === 0)
    {
        for (i = 0; i < g_collectionIds.length; ++i)
        {
            cb = this._getCheckBoxesFromCollectionId(g_collectionIds[i]);
            for (j = 0; j < cb.length; ++j)
            {
                C.push(cb[j].value);
            }
        }
    }

    if (typeof(C) != "undefined")
    {
        this._setupTree(C);
    }

    if (this.categories.length === 1)
    {
        this._expandAll(this.categories);
    }
}
 
