$(function() {

    /**
     * Javascript to do the actual validation for Adding/Editing users in the modal window.
     */


    //var _loadingDiv = $("#ajaxLoading");




    $('#submitUserButton').button();




    $('#UserAddUserForm').submit(function(){

	 $('#submitUserButton').button('disable');

	$.post("/users/add_user",

	    $('#UserAddUserForm').serializeArray(),
	    function(data) {
		var dataArray = $.parseJSON(data);
		if (dataArray.errors) {
		    onError(dataArray.errors);
		} else if (dataArray.success) {
		    onSuccess(dataArray.success);
		}


	    });
	return false;
    });
 


    function onSuccess(data) {

	$(".message").remove();
	flashMessage(data.message);
	//_loadingDiv.hide();
	window.setTimeout(function() {
            window.location.reload(true);
        }, 2000);

    };

    function onError(data) {
	 $('#submitUserButton').button('enable');
	flashMessage(data.message);
	$.each(data.data, function(model, errors) {
	    for (fieldName in this) {
		var element = $("#" + camelize(model + '_' + fieldName));
		var _insert = $(document.createElement('div')).insertAfter(element);
		_insert.addClass('error-message').text(this[fieldName])
	    }
	    _loadingDiv.hide();
	});
    };

    function flashMessage(message) {
	var _insert = $(document.createElement('div')).css('display', 'none');
	_insert.attr('id', 'flashMessage').addClass('message').text(message);
	_insert.insertAfter($('#UserAddUserForm')).fadeIn();
    }

    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;


    }






});