var Forms = {

	dynamicValidate: function(key){
		jQuery('[id="'+key+'"]').change(function(event){
			event.preventDefault();

			var element = jQuery(this);

			var value 	=	jQuery(this).val();

			jQuery(this).removeClass('wise-form-correct');
			jQuery(this).removeClass('wise-form-errors');

			$.ajax(
			{
				type: "POST",
				url: window.location.href,
				dataType: "json",
				data: "validate=1&value="+value+'&key='+key,
				success: function(json)
				{
					if(json.state == 'invalid'){
						Forms.attachError(key, json.message);
					}
					else{
						Forms.cleanState(key);
					}
				}
			});

			return false;
		});

	},

	cleanState: function(key){
		jQuery('#' + key).removeClass('wise-form-error');
		jQuery('#' + key).parents('.wise-form-item').find('.wise-form-errors').html('');
		jQuery('#' + key).parents('.wise-form-item').find('.wise-form-errors').hide();
	},

	attachError: function(key, message){
		jQuery('#' + key).addClass('wise-form-error');
		jQuery('#' + key).parents('.wise-form-item').find('.wise-form-errors').html(message);
		jQuery('#' + key).parents('.wise-form-item').find('.wise-form-errors').show(200);


	},

	processForm: function(form_key, callback) {
		
		jQuery(form_key + ' input[type="submit"]').click(function(event){
			event.preventDefault();

			var data = jQuery(this).parents('form').serialize();

			jQuery(this).parents('form').find('.wise-form-notice').hide();

			jQuery(this).parents('form').find('.wise-form-errors').hide();
			jQuery(this).parents('form').find('.wise-form-input').removeClass('wise-form-error');
			jQuery(this).parents('form').find('.wise-form-errors').hide();

			$.ajax(
			{
				type: "POST",
				url: window.location.href,
				dataType: "json",
				data: "ajax=1&"+data,
				success: function(json)
				{
					if(json.type == 'errors'){

						for (var field in json.errors) {
							var error = json.errors[field];
							Forms.attachError(field, error);
						}
					}
					else if(callback){
						callback(json);
					}
				}
			});
		});
	}
}


