/// <reference path="../../Scripts/jquery.enableTouch.js"/>

(function ($) {
    function ResponsiveVolumeControl() { }

    ResponsiveVolumeControl.prototype._create = function () {
        this._super();

        this._populateElements();
        this._addHandlers();

        this.element.find('.toucharea').enableTouch();

        this.initialized = true;
        this.refresh();
    };

    ResponsiveVolumeControl.prototype._setOption = function (key, value) {
        this._super(key, value)

        if (this.initialized) this.refresh();
    };

    ResponsiveVolumeControl.prototype.refresh = function () {
        this._displayValue();
        this._updateLayout();
    };

    ResponsiveVolumeControl.prototype.options = {
        'change': function (value, muted) { },
        'button': '', 				// URL
        'mutedButton': '',         // URL
        'buttonWidth': 30, 		// CSS px
        'layout': 'expanded', 	// or 'collapsed' or 'popout'
        'muted': false,
        'mutedText': 'X',
        'value': 70, 			// 0-100, volume level (value for slider)
        'popoutOffset': 100, 	// CSS px between collapsed and popout
        'thumbClass': 'thumb',
        'progressClass': 'progress',
        'popoutHideDelay': 5000 // ms
    };

    // #region States

    ResponsiveVolumeControl.prototype.layout = function (layout) {
        this.options.layout = layout;
        this._updateLayout();
    };

    ResponsiveVolumeControl.prototype.value = function (value, muted) {
        this._value(false, value, muted);
    };

    ResponsiveVolumeControl.prototype._value = function (fireHandler, value, muted, source) {
        value = (typeof value == "number") ? value : this.options.value;
        muted = (typeof muted !== "undefined") ? muted : this.options.muted;

        this.options.value = value;
        this.options.muted = muted;

        this._displayValue(source);

        if (fireHandler && this.options.change) {
            this.options.change(this.options.value, this.options.muted);
        }
    };

    ResponsiveVolumeControl.prototype._displayValue = function (source) {
        var displayPosition = this.options.muted ? 0 : this.options.value;
        var displayText;
        if (this.options.muted) {
            displayText = this.options.mutedText;
        } else if (this.options.value < 100) {
            displayText = Math.floor(this.options.value) + '%';
        } else {
            displayText = Math.floor(this.options.value);
        }

        this.element.find(this.selectors.slider).not(source).slider({ value: displayPosition });
        var collapsedSib = this.element.find(this.selectors.collapsed).data("sib");
        if (this._collapsedSibInstance) {
            this._collapsedSibInstance.label = displayText;
            this._collapsedSibInstance.title = displayText;
        }

        this._updateTextSize();

        this.element.find(this.selectors.muteButton).toggle(!this.options.muted);
        this.element.find(this.selectors.unmuteButton).toggle(this.options.muted);
    };


    ResponsiveVolumeControl.prototype._toggleMuted = function (muted) {
        if ((typeof muted) === "undefined") muted = !this.options.muted;

        this.options.muted = muted;
        this._value(true);
    };

    ResponsiveVolumeControl.prototype._togglePopout = function (show) {
        this._cancelHideDelay();
        if (show === true || (show !== false && this.options.layout != "popout")) {
            this._updateLayout("popout");
            this._hideAfterDelay();
        } else if (this.options.layout != "expanded") {
            this._updateLayout("collapsed");
        }
    };

    ResponsiveVolumeControl.prototype._hideAfterDelay = function () {
        var self = this;
        this._cancelHideDelay();
        this._popoutTimer = setTimeout(
            function () { self._togglePopout(false); },
            this.options.popoutHideDelay);
    },
    ResponsiveVolumeControl.prototype._cancelHideDelay = function () {
        clearTimeout(this._popoutTimer);
    };
    // #region Setup

    ResponsiveVolumeControl.prototype._populateElements = function () {
        this.element.empty();
        this.element.html(this._html);
        this.element.find(this.selectors.slider).slider({
            range: "min",
            orientation: "horizontal"
        });
        this._applyBaseStyle();
    };

    ResponsiveVolumeControl.prototype._html = '	\
		<div class="expanded">	\
			<button class="volume"></button>	\
            <button class="volume-muted"></button>	\
			<div class="ui-slider-container slider">	\
				<div class="track"></div>	\
                <div class="thumb ui-slider-handle"></div>  \
				<!-- progress -->	\
                <div class="toucharea"></div>   \
			</div>	\
		</div>	\
		\
		<button class="collapsed">  \
            <!-- text: .ui-button-text -->  \
        </button> \
		<div class="popout">	\
			<button class="volume"></button>	\
            <button class="volume-muted"></button>	\
			<div class="ui-slider-container slider">	\
					<div class="track"></div>	\
					<div class="thumb ui-slider-handle"></div>  \
                    <!-- progress  -->	\
                    <div class="toucharea"></div>   \
			</div>	\
		</div>	\
	';


    ResponsiveVolumeControl.prototype.selectors = {
        slider: '.ui-slider-container',
        thumb: '.ui-slider-handle',
        progress: '.ui-slider-range',
        text: '.text',
        popout: '.popout',
        collapsed: '.collapsed',
        expanded: '.expanded',
        muteButton: '.expanded button.volume, .popout button.volume',
        unmuteButton: '.expanded button.volume-muted, .popout button.volume-muted'
    };

    // #endregion

    // #region Style

    ResponsiveVolumeControl.prototype._applyBaseStyle = function () {
        var self = this;

        this.element.css('position', 'relative');
        this.element.addClass('ui-responsive-container');
        this.element.find(this.selectors.popout).css('position', 'absolute');

        this.element.find(this.selectors.thumb).addClass(this.options.thumbClass);
        this.element.find(this.selectors.progress).addClass(this.options.progressClass);


        this.element.find(this.selectors.slider).css({
            'position': 'absolute',
            'left': 0 + 'px',
            'right': 0
        });
        if (!this.options.button) {
            this.element.find(this.selectors.muteButton).hide();
        } else {
            var buttonSrc = this.options.button;
            var mutedButtonSource = this.options.mutedButton;

            var muteButtons = this.element.find(this.selectors.muteButton);
            muteButtons.each(function (index, element) {
                new Mediasite.Player.SingleImageButton(element, {
                    'src': buttonSrc,
                    'title': Mediasite.Player.Localization.Buttons.Mute
                });
            });
            
            var unmuteButtons = this.element.find(this.selectors.unmuteButton);
            unmuteButtons.each(function (index, element) {
                new Mediasite.Player.SingleImageButton(element, {
                    'src': mutedButtonSource,
                    'title': Mediasite.Player.Localization.Buttons.UnMute
                });
            });

            var width = this.element.find(this.selectors.muteButton).width();
            this.element.find(this.selectors.slider).css({
                'left': width + 'px'
            });
        }


        this._collapsedSibInstance = new Mediasite.Player.SingleImageButton(this.element.find(this.selectors.collapsed).get(0), {
            ratio: 1
        });
    };

    ResponsiveVolumeControl.prototype._collapsedSibInstance = {};

    ResponsiveVolumeControl.prototype._updateLayout = function (layout) {
        this._cancelHideDelay();

        switch (layout) {
            case 'popout':
            case 'collapsed':
            case 'expanded':
                break;
            default:
                layout = this.options.layout || 'expanded';
                break;
        }

        this.element.removeClass('layout-popout layout-collapsed layout-expanded').addClass('layout-' + layout);
        switch (layout) {
            case "popout":
                this._showPopout();
                break;
            case "collapsed":
                this._hidePopout();
                break;
            case "expanded":
                this._hidePopout(true);
                break;
        }


        this.options.layout = layout;
    };

    ResponsiveVolumeControl.prototype._updateTextSize = function () {
        if (this.options.layout == "expanded") return;

        // todo: resize text to fit
    };



    ResponsiveVolumeControl.prototype._showPopout = function () {
        var popout = this.element.find(this.selectors.popout);
        popout.stop().fadeIn(50);

        popout.position({
            "my": "center",
            "at": "center",
            "of": this.element.find(this.selectors.collapsed),
            using: function (offset) {
                popout.css('left', offset.left);
            }

        });
    };

    ResponsiveVolumeControl.prototype._hidePopout = function (fast) {
        var popout = this.element.find(this.selectors.popout);
        if (fast) { popout.stop().hide(); }
        else { popout.stop().fadeOut(200); }
    };

    // #endregion

    // #region User interaction handlers
    ResponsiveVolumeControl.prototype._addHandlers = function () {
        var self = this;

        this.element.find(this.selectors.muteButton).bind("click", function (e) {
            self._onClickToggleMuted();
        });
        this.element.find(this.selectors.unmuteButton).bind("click", function (e) {
            self._onClickToggleMuted();
        });

        this.element.find(this.selectors.collapsed).bind("click", function (e) {
            self._onClickTogglePopout();
        });

        this.element.find(this.selectors.popout).bind('click mouseover mousemove', function (e) {
            self._onInteractPopout();
        });

        this.element.find(this.selectors.slider).bind('slide', function (e, ui) {
            self._onChangePosition(e.target, ui.value);
        });
    };

    ResponsiveVolumeControl.prototype._onClickToggleMuted = function () {
        this._toggleMuted();

        (this.options.muted
            ? this.element.find(this.selectors.unmuteButton)
            : this.element.find(this.selectors.muteButton)
        ).trigger('mouseover').focus()
    };
    ResponsiveVolumeControl.prototype._onClickTogglePopout = function () {
        this._togglePopout();
    };

    ResponsiveVolumeControl.prototype._onInteractPopout = function () {
        this._hideAfterDelay();
    };

    ResponsiveVolumeControl.prototype._onChangePosition = function (target, position) {
        this._value(true, position, false, target);
    };


    // #endregion


    $.widget('ui.responsiveVolumeControl', /* 'ui.responsiveButtonPopout',*/ResponsiveVolumeControl.prototype);
} (jQuery, window));



