
// Create a zebra tables object to handle table colouring
var zebraTables = new ZebraTable();

// foldArray is a relational array of folder names to open/closed
// status. A folder is open if its value in foldArray is true, and
// closed if it is false. 'b' is the base folder, and should always 
// be open!
var foldArray = new Array;
foldArray['b'] = true;

// Function to do actual table folding. 
function fold(tableid, id)
{
    var table = document.getElementById(tableid);

    // toggle the fold for the id if one is specified
    if(id != null && id != -1) {
        foldArray[id] = !foldArray[id];
    }

    if(id != -1) {
        // Now go through all the rows in the table working out the fold state
        table.getElements('tr').each(function(tr,i) {
                // skip rows without _ entirely...
                var pos = tr.id.indexOf('_');
                if(pos > 0) {
                    // The id of each element encodes the controllers and itemid using the
                    // syntax: controller(.controller...)_itemid so we want to pull out the
                    // controllers to work out if the item is visible.
                    var controls = tr.id.substring(0, tr.id.indexOf('_'));
                    
                    // Now make an array out of the period separated list of controllers
                    var depends = controls.split('.');
                    
                    // Now go through the list of controllers, anding them to see if we're visible
                    var visible = foldArray['b'];
                    for(var i = 0; i < depends.length; ++i) {
                        visible &= foldArray[depends[i]];
                    }
                    
                    // Now hide or show the row
                    tr.style.display = visible ? '' : 'none';
                    
                    // Is this a folder?
                    if(tr.id.charAt(tr.id.length - 1) == 'f') {
                        // Yes, toggle the fold icon. Work out the folder id
                        var foldid = tr.id.substring(tr.id.indexOf('_') + 1, tr.id.length - 1);
                        
                        // Use the id to work out the fold icon
                        var icon = foldArray[foldid] ? 'fold_opened.png' : 'fold_closed.png';
                        
                        // update the image
                        document.getElementById(tr.id + '.fold').src = 'templates/default/images/' + icon;
                    }
                }
        });
    }

    zebraTables.zebraize(table);
}