/*
 * jQuery Plugin to make forms "ajaxable".
 *
 * How to use
 ============
 * 1. Include both the `ajaxForm.jquery.min.js` and this file into the document.
 * 2. Add the `auto-ajax-form` class to the form you want to submit with ajax.
 * 3. ????
 * 4. Profit!
 *
 *
 * Notes
 =======
 * The submit button of the form will be disabled when the user submit it, and re-enabled when
 * the ajax response kick in. This is meant to avoid multiple requests to be send.
 *
 */
$.fn.autoAjaxForm = function(){
	return $(this).each(function(){
		$form = $(this);

		// If the form is already "ajaxable", abort.
		if($form.data('auto-ajax-form')) return;

		// Mark the form as "ajaxable", so we don't apply multiple times.
		$form.data('auto-ajax-form', true);

		$form.ajaxForm({
			url: $form.attr('action'),
			type: 'post',
			beforeSubmit:function() {
			    // Remove all the errors stuff from the form
                $form.find('.has-errors').removeClass('has_error');
                $form.find('.errors').remove();

			    // Deactivate the submit button to avoid multiple submit
				$('input[type="submit"], button', $form).attr('disabled', 'disabled');
		    },
			success: function(data){
                if (data.valid) {
                    // If the form is valid, just redirect to the "redirect_url"
                    window.location = data.success_url
                } else {
                    // If the form is invalid, we must handle the errors from the response.
                    jQuery.each(data.errors, function(field_id, field_errors){
                        // Create an element by field, to add the errors into.
                        var $errors_elem_list =  $("<ul class='help-block list-unstyled errors'></ul>");

                        jQuery.each(field_errors, function(index, error_message){
                            // For each error of this field, create a new element,
                            // and add the error message inside.
                            var $errors_elem_item =  $("<li></li>");
                            $errors_elem_item.text(error_message);
                            // Append the message into the list of errors
                            $errors_elem_list.append($errors_elem_item);
                        });
                        // Finally, append the error list into the form field wrapper,
                        // and mark the field state with the class "has-error"
                        var $field = $('#id_'+field_id).closest('div');
                        $field.append($errors_elem_list).addClass('has-error');
                    })
                    // And don't forget to reactive the submit button
		            $('input[type="submit"], button', $form).removeAttr('disabled');
                }
		    },
		    error: function(data){
                $('input[type="submit"], button', $form).attr('disabled', 'disabled');
        	}
        });
	})
};

$('.auto-ajax-form').autoAjaxForm();
