/**
 * Prevent form double validation
 * by adding an overlay on submit button
 *
 * @author amoussard
 * @author rmouillard
 */
jQuery(document).ready(function ()
{
    jQuery('.validation li button').live('click', function(e) {
        var $form = jQuery(this).closest('form');
        if ($form.length > 0) {
            $form.activateValidationProtection();
        }
    });
});

/**
 * Activate the protection overlay
 * Usage : jQuery('#my_form').activateValidationProtection();
 */
jQuery.fn.activateValidationProtection = function()
{
    var $button = jQuery(this).find('.validation li button');

    // Does no triggers if the form is marked as invalid (javascript prevalidation)
    if ($button.length > 0 && !$button.hasClass('noLoader') && jQuery(this).valid()) {
        $button.next().hide();
        $button.before('<div class="loader_wrapper"></div>');
        $button.append('<div class="loader small"></div>');
    }
};

/**
 * Deactivate the activated protection overlay.
 * Usage : jQuery('#my_form').deactivateValidationProtection();
 */
jQuery.fn.deactivateValidationProtection = function()
{
    var $button = jQuery(this).find('.validation li button');

    // Only remove if the protection element is found
    if ($button.length > 0 && jQuery(this).find('.validation li .loader_wrapper').length > 0) {
      $button.next().next().show();
      $button.find('.loader').remove();
      $button.prev().remove();
    }
};
