﻿var valtech = valtech || {};

// Creates a new spinner inside the given DOM element. The spinner
// animation is accomplished by moving a sprite with setTimeout
// so make sure to clean up with 'hide' after use.
valtech.spinnerOverlay = function () {

    // Factory, draws an animated spinner inside
    // the given element
    var create = function (element) {
        var $overlay,
		    $container,
            $fill,
		    visible = false,
		    initialised = false,
            spinnerAnimation = 0,
            spinnerTimeout = 0;

        // Updates the spinner sprite every 100ms
        var animateSpinner = function () {
            spinnerAnimation -= 30;
            if (spinnerAnimation > 0) {
                spinnerAnimation = 240;
            }
            $overlay.css("background-position", "0px " + spinnerAnimation + "px");
            spinnerTimeout = setTimeout(animateSpinner, 100);
        };

        this.show = function () {
            if (visible) { return; }
            $overlay.show();
            animateSpinner();
            visible = true;
        };

        // Hides the spinner and cancels the running animation
        this.hide = function () {
            if (!visible) { return; }
            if ($fill) { $fill.remove(); }
            clearTimeout(spinnerTimeout);
            $overlay.hide();
            visible = false;
        };

        $container = $(element);
        $overlay = $("<div class='vt-spinner-overlay'></div>");

        // If the given element is smaller than 40x40px we inject
        // an empty element to allow some room for the spinner
        var fillHeight = $container.height() < 40 ? 40 : $container.height(),
            fillWidth = $container.width() < 40 ? 40 : $container.width();

        if (fillHeight === 40 || fillWidth === 40) {
            $fill = $("<div style='position: relative; margin-left: -20px; margin-top: -20px; top: 50%; left: 50%; height: " + fillHeight + "px; width: " + fillHeight + "px;'>&nbsp;</div>");
            $container.append($fill);
        }

        $container.prepend($overlay);
        animateSpinner();
        visible = true;
    };

    return create;
} ();
