﻿(function($) {

    //#region $.fn.checkAll

    $.fn.checkAll = function(options) {
        var o = $.extend({}, $.fn.checkAll.defaults, options);
        var parentContainer = this;

        return this.find('input:checkbox[id$=' + o.headerCheckBoxID + ']').each(function() {
            var instance = $(this);
            var headerCheckBox = parentContainer.find('input:checkbox[id$=' + o.headerCheckBoxID + ']');
            if (parentContainer.length != 0) {
                instance.bind(o.checkBoxEvent, function(e) {
                    if (this.checked) {
                        parentContainer.find('input:checkbox[id$=' + o.childCheckBoxID + ']').attr('checked', true);
                    }
                    else {
                        parentContainer.find('input:checkbox[id$=' + o.childCheckBoxID + ']').removeAttr('checked');
                    }
                });
                parentContainer.find('input:checkbox[id$=' + o.childCheckBoxID + ']').bind(o.checkBoxEvent, function(e) {
                    //To uncheck the header checkbox when there are no selected checkboxes in itemtemplate
                    if (parentContainer.find('input:checkbox[id$=' + o.childCheckBoxID + ']:checked').length == 0) {
                        headerCheckBox.removeAttr('checked');
                    }
                    //To check the header checkbox when there are all selected checkboxes in itemtemplate
                    else if (parentContainer.find('input:checkbox[id$=' + o.childCheckBoxID + ']:checked').length == parentContainer.find('input:checkbox[id$=' + o.childCheckBoxID + ']').length) {
                        headerCheckBox.attr('checked', true);
                    }
                    else {
                        headerCheckBox.removeAttr('checked');
                    }
                });
            }
        });
    };

    //#endregion $.fn.checkAll

    //#region $.fn.checkAll.defaults

    $.fn.checkAll.defaults = {
        checkBoxEvent: 'click',
        childCheckBoxID: 'chkID',
        headerCheckBoxID: 'chkAll'
    };

    //#endregion $.fn.checkAll.defaults

})(jQuery);
