﻿/*
* Validate Grid
* version: 1.0 (01/16/2010)
* @requires jQuery v1.2 or later
*
* Usage:
$('#MyButtonClientID').validateGrid({
noItemsMessage: 'There are no items in the list.',
selectAtLeastOneItemMessage: 'Please select at least one item.',
confirmToProceedMessage: 'Are you sure you want to proceed ?',
childCheckBoxID: 'chkID',
eventToValidate: 'click'
}, $('#MyGridClientID'));
*/

(function($) {

    //#region $.fn.validateGrid

    $.fn.validateGrid = function(options, grid, customProceed) {
        ///	<summary>
        ///	Validates the grid on specified event of control. This plug-in assumes you have checkboxes
        /// in the grid and on click of button say, you want to check whether there are any selected items 
        /// in the grid or not if yes, then return true for the action else return false
        ///	</summary>
        ///	<param name="options" type="Options">A set of key/value</param>
        ///	<param name="grid" type="jQuery">An element, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements.</param>
        ///	<param name="customProceed" type="Function" optional="true">A function to execute when any of the element is checked</param>
        /// <returns type="jQuery" />

        var o = $.extend({}, $.fn.validateGrid.defaults, options);

        return this.each(function() {
            var instance = $(this);
            instance.bind(o.eventToValidate, function() {
                var childCheckBoxSelector = 'input:checkbox[id$=' + o.childCheckBoxID + ']';
                var childCheckBoxCheckedSelector = childCheckBoxSelector + ':checked';
                if ($(childCheckBoxSelector, grid).length == 0) {
                    alert(o.noItemsMessage);
                    return false;
                }
                else {
                    if ($(childCheckBoxCheckedSelector, grid).length == 0) {
                        alert(o.selectAtLeastOneItemMessage);
                        return false;
                    }
                    else {
                        if ($.isFunction(customProceed)) {
                            return customProceed();
                        }
                        else {
                        	if (!confirm(o.confirmToProceedMessage)) {
                        		return false;
                        	}
                        }
                    }
                }

            });

        });
    };

    //#endregion $.fn.validateGrid

    //#region $.fn.validateGrid.defaults

    $.fn.validateGrid.defaults = {
        noItemsMessage: 'There are no items in the list.',
        selectAtLeastOneItemMessage: 'Please select at least one item.',
        confirmToProceedMessage: 'Are you sure you want to proceed ?',
        childCheckBoxID: 'chkID',
        eventToValidate: 'click'
    };

    //#endregion $.fn.validateGrid.defaults

})(jQuery);
