/// <reference path="../ScriptReference/jquery-1.7.1-vsdoc.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);

    
    // Sanitize background position values
    (function () {
        var left = options.backgroundPosition.getLeft();
        if (left.getQuantity() == 0 && left.getUnit() !== 'px') {
            left = new Mediasite.Css.Length(0, 'px');
        }

        var top = options.backgroundPosition.getTop();
        if (top.getQuantity() == 0 && top.getUnit() !== 'px') {
            top = new Mediasite.Css.Length(0, 'px');
        }

        options.backgroundPosition = new Mediasite.Css.BackgroundPosition(left, top);
    })();

    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);
    }
}
// -===========================================================================