﻿
    function ValidateMaxSelectedValue(source) {

        if (source.CheckBoxList != null) {
            var count = CountSelectedBox(source);
            var error = 0;

            if (count < source.MinSelectedValue) {
                error = 2;
            }
            else if (source.MaxSelectedValue > 0 && count > source.MaxSelectedValue) {
                error = 1;
            }
            
            DisplayCssError(source, error);


            if (error == 1 || error == 2) {
                return false;
            }
            else {
                return true;
            }
        }

    }
    
    function CountBox(source) {

        var i = 0, x = 0;
        var inputs = $('#' + source.CheckBoxList + ' > input');
        if (inputs.length == 0)
            inputs = $('#' + source.CheckBoxList + ' > span > input');

        return inputs.length;

    }
    
    function CountSelectedBox(source) {
    
        var i = 0, x = 0;
        var inputs = $('#' + source.CheckBoxList + ' > input');
        if (inputs.length == 0)
            inputs = $('#' + source.CheckBoxList + ' > span > input');
            
        if (inputs != null && inputs.length > 0) {
            
            for (i = 0; i < inputs.length; i++) {
                if ($('#' + inputs[i].id).attr('checked')) {
                    x++;
                }
            }
        }
        return x;

    }

    function DisplayCssError(source, error) {

        var c = 'title';
        var msg = '';
        var html = $('#' + source.Label).html();
        
        html = html.replace('<p>' + source.MaxErrorMessage + '</p>', '');
        html = html.replace('<p>' + source.MinErrorMessage + '</p>', '');
        html = html.replace('<P>' + source.MaxErrorMessage + '</P>', '');
        html = html.replace('<P>' + source.MinErrorMessage + '</P>', '');

       
        if (error == 1) {
            c = 'title_error';
            html = html + '<p>' + source.MaxErrorMessage + '</p>';
            
        }
        else if (error == 2) {
            c = 'title_error';
            html = html + '<p>' + source.MinErrorMessage + '</p>';
        }

        $('#' + source.Label).attr('class', c);
        
        if (CountBox(source) > 1) {
            $('#' + source.Label).html(html);           
        }
    }
    
