//= require vendor/spin.js

(function()
{
    'use strict';

    var spinner_options =
    {
        lines: 11, // The number of lines to draw
        length: 0, // The length of each line
        width: 4, // The line thickness
        radius: 6, // The radius of the inner circle
        corners: 1, // Corner roundness (0..1)
        rotate: 0, // The rotation offset
        direction: 1, // 1: clockwise, -1: counterclockwise
        color: '#000', // #rgb or #rrggbb or array of colors
        speed: 1.2, // Rounds per second
        trail: 60, // Afterglow percentage
        shadow: false, // Whether to render a shadow
        hwaccel: false, // Whether to use hardware acceleration
        className: 'spinner', // The CSS class to assign to the spinner
        zIndex: 2e9, // The z-index (defaults to 2000000000)
        top: '50%', // Top position relative to parent
        left: '50%' // Left position relative to parent
    };

    var page = jQuery(document);

    page.on('loadingstart', function(e)
    {
        var target = jQuery(e.target);

        if (target.hasClass('loading'))
        {
            return;
        }

        var target_is_button = target.is('.button');

        if (target_is_button)
        {
            // disable button immediately to prevent double posts
            target.data('disabled-before-loading', !!target.prop('disabled') );
            target.trigger('disable');
        }

        // but start animation only after a small delay
        target.data('loadingtimeout', setTimeout( function()
        {
            target.addClass('loading');

            if (!target.data('spinner'))
            {
                var text_color = target.css('color');
                if (text_color)
                {
                    spinner_options.color = text_color;
                }

                target.data('spinner', new Spinner( spinner_options ) );
            }

            target.data('spinner').spin(target[0]);
        }, 100));
    });

    page.on('loadingend', function(e)
    {
        var target = jQuery(e.target);

        clearTimeout( target.data('loadingtimeout') );

        var target_is_button = target.is('.button');

        if (target_is_button)
        {
            var disabled_before_loading = target.data('disabled-before-loading') ;

            if (typeof disabled_before_loading != 'undefined')
            {
                if (!disabled_before_loading)
                {
                    target.trigger('enable');
                }
                target.removeData('disabled-before-loading');
            }
        }

        if (!target.hasClass('loading'))
        {
            return;
        }

        if (target.data('spinner'))
        {
            target.data('spinner').stop(target);
        }

        target.removeClass('loading');

    });

}());
