/// <reference path="../ScriptReference/jquery-1.5.2.js"/>
/// <reference path="Scripts/jquery-1.5.2.js"/>
/// <reference path="Scripts/Mediasite.Geometry.js"/>
/// <reference path="Scripts/Mediasite.Css.js"/>
if (!Mediasite) {
    var Mediasite = {};
}

// SpriteAnimation
// +===========================================================================
Mediasite.SpriteAnimation = function (element, options) {
    element = $(element);
    options = $.extend({
        backgroundImage: element.css('backgroundImage'),
        backgroundPosition: Mediasite.Css.BackgroundPosition.ofElement(element),
        spriteWidth: element.width(),
        initialFrameIndex: 0,
        totalFrames: 2,
        frameDuration: 500 // milliseconds
    }, options);

    if (options.backgroundPosition.getLeft().getUnit() !== 'px' && options.backgroundPosition.getLeft().getUnit() !== '') {
        throw 'Only px values are supported for backgroundPosition.';
    }

    var interval = null;
    var currentFrameIndex = 0;
    gotoFrame(options.initialFrameIndex);


    this.Start = function () {
        if (interval !== null) {
            return; // already started.
        }

        interval = setInterval(nextFrame, options.frameDuration);
    }

    this.Stop = function () {
        clearInterval(interval);
        interval = null;
    }

    this.Reset = function () {
        gotoFrame(options.initialFrameIndex);
    }


    function nextFrame() {
        gotoFrame((currentFrameIndex + 1) % options.totalFrames);
    }

    function gotoFrame(index) {
        currentFrameIndex = index;
        var newLeftQuantity = options.backgroundPosition.getLeft().getQuantity() - (options.spriteWidth * currentFrameIndex);
        var newLeftLength = new Mediasite.Css.Length(newLeftQuantity, options.backgroundPosition.getLeft().getUnit());
        var newPosition = new Mediasite.Css.BackgroundPosition(newLeftLength, options.backgroundPosition.getTop());

        element.css('backgroundPosition', newPosition);
    }
}
// -===========================================================================