var appurl = "/";
var _loadingDiv = $("#loadingDiv");

function addFormValidator(formName, postUrl)
{
	$(formName).submit(function() { 
		_loadingDiv.show();
		$.post(postUrl, $(this).serializeArray(), afterValidate, "json");
		return false;
	});
}

function afterValidate(data, status) 
{
	$(".message").remove();
	$(".error-message").remove();

	if (data.errors) {
		onError(data.errors);
	} else if (data.success) {
		onSuccess(data.success);
	}
}

function onSuccess(data) {
	flashMessageSuccess(data.message);
	_loadingDiv.hide();
	window.setTimeout( function() {window.location.href = appurl + data.redirect;}, 2000);
};

function onError(data) {
	flashMessageError(data.message);
	if(data.data != null) {
		$.each(data.data, function(model, errors) {
			for (fieldName in this) {
				var element = $("#" + camelize(model + '_' + fieldName));
				//var _insert = $(document.createElement('div')).insertAfter(element);
				var _insert = $(document.createElement('div')).appendTo(element.parent());
				_insert.addClass('error-message').text(this[fieldName])
			}
			_loadingDiv.hide();
		});
	}
};

function flashMessage(msg) {
	$('#ajaxMessage').text(msg);
	$('#ajaxMessage').css('display', 'none');
	$('#ajaxMessage').fadeIn('fast');
	$('#ajaxMessage').fadeOut(5000);
}

function flashMessageSuccess(msg) {
	$('#ajaxMessage').css('backgroundImage', 'url(' + appurl + 'img/success.gif)');
	flashMessage(msg);
}

function flashMessageError(msg) {
	$('#ajaxMessage').css('backgroundImage', 'url(' + appurl + 'img/error.gif)');
	flashMessage(msg);
}

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;
}

//Auto load & bind AjaxForm
$(function() {
	$('.ajaxForm').each(function(i) {		
		addFormValidator('#'+$(this).attr('id'), $(this).attr('action'));
	});
});
