﻿
/*
    An object to for groups of checkboxes to be toggled by a single checkbox.
    (De)Select All
*/

function CheckboxList() {
    this.selectAll = null;      // The (De)Select All checkbox
    this.list = new Array();    // The group of checkboxes to be toggled

    this.setSelectAll = _setSelectAll;
    this.addCheckbox = _addCheckbox;

    function _setSelectAll(elementID) {
        // get the element, and if successful, attach a handler on the click
        selectAll = $get(elementID);
        if (selectAll) {
            selectAll.onclick = _selectAllToggled;
        }
    }

    function _addCheckbox(elementID) {
        // get the element, and if successful, add a handler for the click and add it only once to the group of checkboxes
        var newCheckbox = $get(elementID);
        if (newCheckbox) {
            if (!_checkCheckboxExistsInList(newCheckbox)) {
                newCheckbox.onclick = _checkboxInListToggled;
                list.push(newCheckbox);
            }
        }
    }

    function _selectAllToggled(e) {
        // Set the group of checkboxes to the same state and the (De)Select all checkbox
        var targ;
        if (!e) var e = window.event;
        if (e.target) targ = e.target;
        else if (e.srcElement) targ = e.srcElement;

        for (var i in list) {
            if (list[i]) {
                list[i].checked = targ.checked; ;
            }
        }


    }

    function _checkboxInListToggled(e) {
        // Check to see if all of the checkboxes have the same state, and if so, set the (De)Select state to the same.
        var targ;
        if (!e) var e = window.event;
        if (e.target) targ = e.target;
        else if (e.srcElement) targ = e.srcElement;

        var allCheckboxesHaveSameState = true;
        for (var i in list) {
            if (list[i]) {
                if (list[i].checked != targ.checked)
                    allCheckboxesHaveSameState = false
            }
        }

        if (allCheckboxesHaveSameState) {
            selectAll.checked = targ.checked;
        }
    }

    function _checkCheckboxExistsInList(cb) {
        for (var i = 0; i < list.length; i++) {
            if (list[i] == cb) { return true; }
        }
        return false;
    }

    return this;
}

