﻿function FixCheckBoxList(Control) {
    Control = document.getElementById(Control);
    var i = 0;
    var s = "document.forms[0]." + Control.id;
    var FirstClick = false;
    var changed;

    if (Control.Boxes == undefined) {
        Control.Box = new Array();
        Control.CheckedBoxes = new Array();
        while (eval(s + "_" + i) != undefined) {
            Control.Box[i] = eval(s + "_" + i);
            Control.CheckedBoxes[i] = Control.Box[i].checked;
            i = i + 1;
        }
        Control.Boxes = i;
        FirstClick = true;
    }

    changed = WhatHasChanged(Control, FirstClick);
    FirstClick = false;

    if (changed != undefined) {
        //Om "Alla" kryssrutan blev ikryssad eller urkryssad
        if (changed == 0) {
            if (Control.CheckedBoxes[0] == true) {
                CheckAll(Control, true)
            }
            else if (Control.CheckedBoxes[0] == false) {
                CheckAll(Control, false)
            }
        }

        //"Alla" rutan kan inte vara kryssad om inte alla andra är kryssade.
        if (changed != 0) {
            var allChecked = true;
            for (i = 1; i < Control.Boxes; i++) {
                if (Control.CheckedBoxes[i] == false) {
                    allChecked = false
                }
            }
            Control.Box[0].checked = allChecked;
            Control.CheckedBoxes[0] = allChecked;
        }
    }
}

function WhatHasChanged(Control, FirstClick) {
    if (FirstClick) {
        for (i = 0; i < Control.Boxes; i++) {
            if (Control.CheckedBoxes[i]) {
                return i;
            }
        }
    }
    else {
        for (i = 0; i < Control.Boxes; i++) {
            if (Control.CheckedBoxes[i] != Control.Box[i].checked) {
                Control.CheckedBoxes[i] = Control.Box[i].checked;
                return i;
            }
        }
    }
    return undefined;
}

function CheckAll(Control, Value) {
    var i = 0;

    for (i = 1; i < Control.Boxes; i++) {
        Control.Box[i].checked = Value;
        Control.CheckedBoxes[i] = Value;
    }
}

