﻿/// <reference name="MicrosoftAjax.js"/>
/// <reference name="Pacem.Web.Extensions.Tween.Tween.js" assembly="Pacem.Web.Extensions"/>
/// <reference name="AjaxControlToolkit.Common.CommonScripts.js" assembly="AjaxControlToolkit"/>
/// <reference name="AjaxControlToolkit.Compat.Timer.Timer.js" assembly="AjaxControlToolkit"/>
Type.registerNamespace('Pacem.UI');

Pacem.UI.ImageRotatorBehavior = function(element) {

    Pacem.UI.ImageRotatorBehavior.initializeBase(this, [element]);

    this._imageReferences = [];
    this._currentIndex = -1;
    this._interval = 5.0;
    this._transitionDuration = 0.5;
    this._imageControl = null;
    this._images = null;
    this._tween = null;
    this._timer = null;
    this._tickHandler = null;
    this._loadedHandler = null;
    this._loadedProperty = "pacem_readyForRotator";
    this._arrayIndex = "pacem_arraySourceIndex";
    this._callbackProperty = "pacem_rotatorCallback";
    this._trailingOnTicker = false;
    this._started = false;
}

Pacem.UI.ImageRotatorBehavior.prototype = {

    initialize: function() {
        Pacem.UI.ImageRotatorBehavior.callBaseMethod(this, 'initialize');

        var el = this.get_element();

        if (el.tagName.toLowerCase() == "a") {
            var maybeAnchorChildren = el.getElementsByTagName("IMG");
            if (maybeAnchorChildren.length == 0)
                throw "Target control is not a valid image Object";
            else
                this._imageControl = maybeAnchorChildren[0];
        } else
            this._imageControl = el;

        this._loadedHandler = Function.createDelegate(this, this._notifyLoaded);
        /* preloading */
        this._images = [];
        for (var j = 0; j < this._imageReferences.length; j++) {
            if (this._imageReferences[j] != "") {
                var img = new Image();
                var callback = Function.createCallback(this._loadedHandler, img);
                img[this._arrayIndex] = j;
                img[this._callbackProperty] = callback;
                $addHandler(img, "load", callback);
                img.src = this._imageReferences[j].Url.trim();
                this._images.push(img);
            }
        }
        if (this._images.length == 0) return;
        this._timer = new Sys.Timer();
        this._tickHandler = Function.createDelegate(this, this._onTick);
        this._timer.add_tick(this._tickHandler);
        this._onTick();
    },

    dispose: function() {
        if (this._tween)
            this._tween.dispose();
        //
        for (var j = 0; j < this._images.length; j++)
            $removeHandler(this._images[j], "load", this._images[j][this._callbackProperty]);
        //
        this._timer.remove_tick(this._tickHandler);
        this._timer.dispose();
        Pacem.UI.ImageRotatorBehavior.callBaseMethod(this, 'dispose');
    },

    add_indexChanged: function(handler) {
        /// <summary>
        /// Add an event handler for the indexChanged event
        /// </summary>
        /// <param name="handler" type="Function" mayBeNull="false">
        /// RoutedEvent handler
        /// </param>
        /// <returns />
        this.get_events().addHandler('indexChanged', handler);
    },
    remove_indexChanged: function(handler) {
        /// <summary>
        /// Remove an event handler from the indexChanged event
        /// </summary>
        /// <param name="handler" type="Function" mayBeNull="false">
        /// RoutedEvent handler
        /// </param>
        /// <returns />
        this.get_events().removeHandler('indexChanged', handler);
    },
    raiseIndexChanged: function(eventArgs) {
        /// <summary>
        /// Raise the indexChanged event
        /// </summary>
        /// <param name="eventArgs" type="Sys.EventArgs" mayBeNull="false">
        /// Event arguments for the indexChanged event
        /// </param>
        /// <returns />
        var handler = this.get_events().getHandler('indexChanged');
        if (handler) {
            handler(this, eventArgs);
        }
    },
    _notifyLoaded: function(evt, obj) {
        obj[this._loadedProperty] = true;
        if (this._trailingOnTicker == true && obj[this._arrayIndex] == this._currentIndex) {
            this._gattai();
        }
    },
    _refreshTicker: function() {
        var interval = parseInt(this._interval * 1000);
        this._timer.set_interval(interval);
        this._timer.set_enabled(true);
    },
    _notifyIndexChanged: function() {
        this.raiseIndexChanged(Sys.EventArgs.Empty);
        this._refreshTicker();
    },
    _onTick: function() {
        var me = this;
        me._currentIndex++;
        if (me._currentIndex >= me._images.length)
            me._currentIndex = 0;
        if (me._images[me._currentIndex][me._loadedProperty] != true)
            me._trailingOnTicker = true;
        else {
            me._trailingOnTicker = false;
            me._gattai();
        }
    },
    _gattai: function() {
        if (this._started == true)
            this._startFadeOut();
        else {
            $common.setElementOpacity(this._imageControl, 0);
            this._started = true;
            this._startFadeIn();
        }
    },
    _startFadeOut: function() {
        var start = $common.getElementOpacity(this._imageControl);
        if (this._tween)
            this._tween.dispose();
        this._tween = $create(Pacem.UI.Tween, { 'property': 'opacity', 'easingFunc': Pacem.UI.Easing.Sine.easeInOut, 'start': start, 'finish': 0.0, 'duration': this._transitionDuration / 2.0 },
        { 'motionChanged': this._tweenChanged, 'motionFinished': Function.createDelegate(this, this._tweenFinished1) }, null, this._imageControl);
    },
    _startFadeIn: function() {
        this._imageControl.src = this._images[this._currentIndex].src;
        //
        if (this._tween)
            this._tween.dispose();
        this._tween = $create(Pacem.UI.Tween, { 'property': 'opacity', 'easingFunc': Pacem.UI.Easing.Sine.easeInOut, 'start': 0.0, 'finish': 1.0, 'duration': this._transitionDuration / 2.0 },
        { 'motionChanged': this._tweenChanged, 'motionFinished': Function.createDelegate(this, this._tweenFinished2) }, null, this._imageControl);
    },
    _tweenChanged: function(sender, args) {
        // opacity
        $common.setElementOpacity(sender.get_object(), args.get_currentPosition());
    },
    _tweenFinished1: function(sender, args) {
        // fade-out finished -> launch fade-in
        this._startFadeIn();
    },
    _tweenFinished2: function(sender, args) {
        // fixing undesired IE behavior on PNG's
        if (sender.get_object().style.filter && sender.get_object().style.removeAttribute)
            sender.get_object().style.removeAttribute('filter');
        // fade-in finished -> fire events
        this._notifyIndexChanged();
    },


    get_currentIndex: function() {
        return this._currentIndex;
    },

    get_imageReferences: function() {
        return this._imageReferences;
    },
    set_imageReferences: function(value) {
        this._imageReferences = value;
    },

    get_interval: function() {
        return this._interval;
    },
    set_interval: function(value) {
        this._interval = value;
    },

    get_transitionDuration: function() {
        return this._transitionDuration;
    },
    set_transitionDuration: function(value) {
        this._transitionDuration = value;
    }
}

Pacem.UI.ImageRotatorBehavior.registerClass('Pacem.UI.ImageRotatorBehavior', AjaxControlToolkit.BehaviorBase);

if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();