$(document).ready(function() {
    //Valideert de formuliervelden.
    $('#contentcontainer form :input').bind('paste blur', function () {
        var ajaxReturn = 'true';
        var text;

        if ($(this).hasClass('NotEmpty')) {
            ajaxReturn = $(this).ajaxValidation('notempty');
            text       = 'Field is required';
        }
        if ($(this).hasClass('MX') && ajaxReturn == "true") {
            ajaxReturn = $(this).ajaxValidation('mx');
            text       = 'Enter a valid e-mail address';
        }
        if ($(this).hasClass('CustomUniqueUser') && ajaxReturn == "true") {
            ajaxReturn = $(this).ajaxValidation('customuniqueuser', $("input[name=usr_id]").val());
            text       = 'Username already exists';
        }
        if ($(this).hasClass('StringLength') && ajaxReturn == "true") {
            ajaxReturn = $(this).ajaxValidation('stringlength', $(this).attr('minLength'));
            text       = 'Uw wachtwoord moet minimaal ' + $(this).attr('minLength') + ' tekens bevatten';
        }
        if ($(this).hasClass('Identical') && ajaxReturn == "true") {
            ajaxReturn = $(this).ajaxValidation('identical',$('input.same').val());
            text       = 'The passwords do not match';
        }
        if ($(this).hasClass('Checkbox') && ajaxReturn == "true") {
            if ($(this).attr('checked')) {
                ajaxReturn = "true";
            } else {
                ajaxReturn = "false";
            }
            text = 'Please accept the Terms and Conditions';
        }

        //Verwijdert de error.
        $(this).siblings('.errors').remove();

        $('label[for=' + $(this).attr('id') + '] span').remove();
        $('label[for=' + $(this).attr('id') + ']').css('color','black');

        if (ajaxReturn == 'false') {
            //Voegt een error toe aan het label van het veld.
            var label = $('label[for=' + $(this).attr('id') + ']');
            label.animate({
                color: "red"
            }, "slow");
            label.append('<span class="error"> ('+text+') </span>');
            var error = $('label[for=' + $(this).attr('id') + '] span.error').css('color', 'black');
            error.animate({
                color: "red"
            }, "slow");
        }
    });

    $.fn.ajaxValidation = function(classname, match) {
        var ajaxReturn = $.ajax({
            url:      '/validation/ajax' + classname,
            type:     'POST',
            data:     ({value: $(this).val(), match: match}),
            dataType: 'html',
            async:    false
         }).responseText;
        return ajaxReturn;
    }

    $("div#contentcontainer form").bind('submit', function () {
        $('div#contentcontainer form :input').each(function() {
            $(this).blur();
        });
        if($('span.error').length > 0) {
              return false;
        }
    });
});
