﻿$(document).ready(function() {

    // top level
    $("input.parent").click(function() {
        var chk = this;
        $("ul#" + this.name + " li input").each(function() {
            this.checked = chk.checked;
        })
        //alert(this.name);

    });

    // second level
    $("input.chapter").click(function() {
        var parId = $(this).parent().parent().get(0).id

        //alert('changed');

        if (!this.checked) {
            $("input[name='" + parId + "']").attr('checked', false);
        }
        
    })

    // third level
    $("ul.gr ul input").click(function() {
        var parId = $(this).parent().parent().get(0).id

        //alert('changed');
        updateParent(parId);

    })

    $(".sectionSwitch").click(function() {
        var mainSwitch = this;
        var parentDiv = $(this).parents("div.report_section").attr("id");

        $("#" + parentDiv + " input").each(function() {
            this.checked = mainSwitch.checked;
        })
    })

    // on deselect of any deselect parent
    $("#customize input:checkbox").click(function() {

        if ($(this).attr("class") != "sectionSwitch") {
            var parentDiv = $(this).parents("div.report_section").attr("id");

            //alert(parentDiv);
            if (!this.checked) {
                $("#" + parentDiv + " .sectionSwitch").attr("checked", false);
            }

            checkSections();
        }
    })

    checkSections();


});

function updateParent(parId) {
    var par = $("#" + parId);

    var parId = par.parent().parent().get(0).id

    //alert('changed');

    if (!par.checked) {
        $("input[name='" + parId + "']").attr('checked', false);
    }
}

function checkSections() {

    $(".report_section").each(function() {

        var thisId = $(this).attr("id");
        var sectionSwitch = $("#" + thisId + " .sectionSwitch");

        var allChecked = true;

        $("#" + thisId + " input").each(function() {
            if (!this.checked) {
                if ($(this).attr("class") != "sectionSwitch") {
                    // not checked	
                    allChecked = false;
                }
            }
        })

        if (allChecked) {
            //alert("all checked");
            sectionSwitch.attr("checked", "checked");
        }
    })

}
