﻿(function ($) {

    $.fn.checkBoxList = function (options) {

        var settings = {
            'addSelectAll': false
        };

        function updateCheckedList(div) {
            var vals = new Array();
            $(div).find("input:checkbox:checked").each(function (i) {
                if ($(this).val() != '-1')
                    vals.push($(this).val());
            });

            if ($(div).find("#selectall") != null) {
                if ($(div).find("input:checkbox:checked").length == $(div).find("input:checkbox").length - 1)
                    $(div).find("#selectall").attr("checked", true);
            }

            $(div).children("input:hidden:first").val(vals.join(','));
            
        }

        return this.each(function () {
            // If options exist, lets merge them
            // with our default settings
            if (options) {
                $.extend(settings, options);
            }

            // checkBoxList plugin code here
            if (options.addSelectAll.toLowerCase() == 'true') {
                $(this).find('table').prepend('<tr><td><input id="selectall" type="checkbox" value="-1" /></td><td>Select/Unselect All</td></tr>');
                $(this).find("#selectall").click(function () {
                    var status = $(this).attr('checked');
                    $(this).parents().filter('div:first').find("input:checkbox").each(function () {
                        $(this).attr("checked", status);
                    })
                });
            }

            //Update the current list
            updateCheckedList($(this));
           
            //Add update for all click events
            var div = $(this);
            $(this).find("input:checkbox").click(function () {
               updateCheckedList(div);
            });
        });
    };
})(jQuery);
