﻿/// <reference path="jquery-1.3.2-vsdoc.js" />
$(document).ready(function(e) {
    // Add watermarks and the datepicker.
    $('.phoneNumber').watermark('999-999-9999');
    $('.datePicker').watermark('mm/dd/yyyy')
    $('.datePicker').datepicker({
        onSelect: function(input, inst) {
            // Hide the watermark when a value is selected.
            $.watermark.hide(this);

            // Prevents exception in IE when used in conjunction with ASP.Net validators.
            $(this).trigger('change', null);
        }
    });

    // Get the charity checkboxes, if available.
    var charities = $('input:checkbox[id^="uxCharities"]');

    if (charities.length) {
        var percentages = $('input:text[id^="uxPercentages"]');
        var totalPercentage = $('#uxTotalPercentage');

        // Constrain the input for percentages.
        percentages.numeric({ allow: '.' });

        // Hide unused charity percentage textboxes as default.
        $('input:text[id^="uxPercentages"]').each(function(i) {
            if (this.value.trim().length == 0)
                $(this).hide();
        });

        // Update the total on change.
        percentages.bind('change', function(e) {
            var total = 0;

            percentages.each(function(i) {
                if (this.value.trim().length > 0) {
                    total += parseFloat(this.value);
                }
            });

            totalPercentage.val(total);
        });

        // Toggle visibility based on charity selection.
        charities.bind('click', function(e) {
            var row = this.parentNode.parentNode;

            if (this.checked) {
                $(row.cells[1]).find('input:text').show();
            }
            else {
                var textbox = $(row.cells[1]).find('input:text');
                textbox.val('').hide();

                // Trigger validation and change to update the total and clear validation messages.
                ValidatorValidate($('#' + textbox.attr('id') + '_RangeValidator')[0]);
                textbox.trigger('change');
            }
        });
    }
});

/*
 * Custom validator for the total.
*/
function validateTotal(source, arguments) 
{
    var total = 0;

    // Add the percentage from all of the checked charities.
    $('input:checkbox:checked[id^="uxCharities"]').each(function(i) {
        var percentage = $(this.parentNode.parentNode).find('input:text').val();

        if (percentage.trim().length > 0) {
            total += parseFloat(percentage);
        }
    });

    if (total > 100) {
        arguments.IsValid = false;
    }
}