var OU = OU || {};

OU.spinner = (function(utils) {
    "use strict";

    function Spinner(parent) {
        console.log(parent);
        this.container = utils.createElement('div', 'loader-container');
        this.parent = parent || document.body;
        this.el = utils.createElement('div', 'loader');
        this.spinner = utils.createElement('div', 'loader-spinner');
        this.text = utils.createElement('div', 'loader-text');
        this.diameter = 40;
        this.animation = null;
    }

    Spinner.prototype = {
        init: function() {
            this.spinner.style.display = 'inline-block';
            this.spinner.style.border = Math.round(this.diameter / 7) + 'px solid #f3f3f3';
            this.spinner.style.borderTopColor = '#3498db';
            this.spinner.style.borderRadius = '50%';
            this.spinner.style.width = this.diameter + 'px';
            this.spinner.style.height = this.diameter + 'px';

            this.text.innerHTML = 'Loading...';
            this.text.style.marginTop = '8px';

            this.el.style.textAlign = 'center';
            this.el.style.position = 'absolute';
            this.el.style.top = '50%';
            this.el.style.left = '50%';
            this.el.style.transform = 'translate(-50%, -50%)';
            this.el.appendChild(this.spinner);
            this.el.appendChild(this.text);

            // this.container.style.height = window.innerHeight + 'px';
            // this.container.style.height = this.container.parentNode.clientHeight + 'px';
            this.container.style.minHeight = '200px';
            this.container.style.position = 'relative';
            this.container.style.visibility = 'visible';
            this.container.appendChild(this.el);

            this.parent.appendChild(this.container);
            this.parent.addEventListener('activity-loaded', this);

            this.start();
        },

        start: function() {
            var deg = 0,
                unit = 8;

            (function spin() {
                this.spinner.style.transform = 'rotate(' + (deg += unit) + 'deg)';
                this.animation = requestAnimationFrame(spin.bind(this));
            }.bind(this))();
        },

        stop: function() {
            cancelAnimationFrame(this.animation);
            this.container.style.display = 'none';
        },

        handleEvent: function(e) {
            switch (e.type) {
                case 'activity-loaded':
                    this.stop();
            }
        }
    };

    return {
        construct: function(parent) {
            return new Spinner(parent);
        }
    };
})(OU.utils);