$(function() {
	// ajax form
    $('form').submit(function(){
        $.post($(this).attr('action'),
            $(this).serializeArray(),
            afterValidate,
            "json"
        );
        return false;
    });

    function afterValidate(data, status)  {
        //$(".message").remove();
        $("form div.required").removeClass('error');
		$('input, textarea').blur();
		
		if (data.errors) {
            onError(data.errors);
        } else {
			onSuccess(data.success);
		}
    }

    function onSuccess(data) {
		// $('#note').removeClass('error');
		
		window.location.href = '/participants/success';
    };

    function onError(data) {
        flashMessage(data.message, 'error');
        $.each(data.data, function(model, errors) {
            for (fieldName in this) {
                var element = $("#" + camelize(model + '_' + fieldName));
                element.parent().addClass('error');
            }
        });
    };

    function flashMessage(message, status) {
		// $('#note').addClass('message '+status);
    }

    function camelize(string) {
        var a = string.split('_'), i;
        s = [];
        for (i=0; i<a.length; i++){
            s.push(a[i].charAt(0).toUpperCase() + a[i].substring(1));
        }
        s = s.join('');
        return s;
    }
});
