/// <reference path="3rdParty/jquery.js" />
/// <reference path="3rdParty/jquery-ui.js" />
/// <reference path="Mediasite.Geometry.js" />

(function($, window, undefined) {
    $.widget("ui.fittedImage", {
        options: {
            container: null,
            aspectRatio: '16:9' // or '4:3'
        },
        _create: function() {
            var self = this;
            this._super();
            this.element.css('position', 'relative');
            this.element.on('load', function() { self.refresh(); });
        },

        _init: function() {
            if (!this.options.container) {
                this.options.container = this.element.parent();
            }
        },

        src: function(src) {
            var self = this;
            this.element.attr('src', src);
            setTimeout(function() { self.refresh(); }, 1);
        },


        refresh: function() {
            var src = this.element.attr('src');
            if (!src) return;
            
            var image = new Image();
            image.src = src;
            if (!image.width) return;

            var nativeSize = new Mediasite.Geometry.Rect(0, 0, image.width, image.height);
            var containerSize = new Mediasite.Geometry.Rect(0, 0, this.options.container.width(), this.options.container.height());

            var scaledSize = Mediasite.Geometry.ScaleToFit(nativeSize, containerSize);
        
            this.element.css({
                position: 'absolute',
                left: scaledSize.left() + 'px',
                top: scaledSize.top() + 'px',
                width: scaledSize.width() + 'px',
                height: scaledSize.height() + 'px'
            });
        }
    });
})(jQuery, window);

