﻿function CheckBoxSelectMulti_CheckChanged(controlPrefix, indexClicked)
{
    var cbl = $get(controlPrefix + 'cblS').rows[0].cells;

    // Check if all are selected?
    var areAllSelected = true;
    var countOfSelectable = 0;
    
    for (i = 1;i < cbl.length; ++i)
    {
        // Any that are not selected?
        if (GetCheckBox(cbl[i]).checked == false) areAllSelected = false;
        
        // Count the number that are selectable.
        if (GetCheckBox(cbl[i]).disabled == false) countOfSelectable++;
    }
    
    // Are they all selected or is there only just one selectable?
    if (areAllSelected || countOfSelectable == 1) 
    {
        indexClicked = 0;
        GetCheckBox(cbl[0]).checked = true;
    }
    else
        GetCheckBox(cbl[0]).checked = false;

    // Check if nothing is selected?
    var isNothingSelected = true;
    
    for (i = 1;i < cbl.length; ++i)
        if (GetCheckBox(cbl[i]).checked) isNothingSelected = false;
    
    if (isNothingSelected) indexClicked = 0;
    
    // If All is selected then de-select anything else.
    if (indexClicked == 0)
    {
        for (i = 1;i < cbl.length; ++i) GetCheckBox(cbl[i]).checked = false;
        
        GetCheckBox(cbl[0]).checked = true;
    }
}

// Finds the checkbox control regardless of the depth of spans .NET puts around it.
function GetCheckBox(cb)
{
    if (cb.childNodes[0].childNodes.length > 0)
        return cb.childNodes[0].childNodes[0];
    else 
        return cb.childNodes[0]
}

