var Spinner = new Class({
    initialize: function(size) {
        this.spokes = 9;
        if(size)
            this.size = size
        else
            this.size = 30
        this.interval_id = null;

        this.canvas = new Element('canvas', {
            'width': this.size,
            'height': this.size,
            'style': 'display: inline; opacity: 0;'
        });

        this.container = new Element('div', {
            
        })
        this.container.grab(this.canvas, 'top');

        this.ctx = this.canvas.getContext('2d');
        this.ctx.translate(this.size/2, this.size/2);	// Center the origin
        this.ctx.lineWidth = this.size/10;
        this.ctx.lineCap = "round";
    },
    start: function() {
        this.interval_id = this.draw.periodical(100, this);
        this.canvas.fade(1);
    },
    stop: function() {
        clearTimeout(this.interval_id);
        this.canvas.fade(0);
    },
    draw: function() {
        this.ctx.clearRect(-this.size/2, -this.size/2, this.size, this.size);		// Clear the image
        this.ctx.rotate(Math.PI*2/this.spokes);	// Rotate the origin
        for (var i=0; i<this.spokes; i++) {
            this.ctx.rotate(Math.PI*2/this.spokes);	// Rotate the origin
            this.ctx.strokeStyle = "rgba(0,0,0,"+ i/this.spokes +")";	// Set transparency
            this.ctx.beginPath();
            this.ctx.moveTo(0, this.size/5);
            this.ctx.lineTo(0, this.size/2.5);
            this.ctx.stroke();
        }
    },
    toElement: function() {
        return this.container;
    }
});

var SpinnerOverlay = new Class({
    initialize: function(element) {
        this.element = element;
        this.overlay = new Element('div');
        this.overlay.fade('hide');
        this.spinner = new Spinner();
        this.overlay.grab(this.spinner);
        element.getParent().grab(this.overlay);
        this.overlay.position({
            'relativeTo': this.element,
            'position': 'center',
        });
    },
    show: function() {
        this.overlay.position({
            'relativeTo': this.element,
            'position': 'center',
        });
        this.spinner.start();
        this.overlay.fade(1);
        this.element.fade(.2);
    },
    hide: function() {
        this.spinner.stop();
        this.overlay.fade(0);
        this.element.fade(1);
    },
    toElement: function() {
        return this.overlay;
    }
});

