/**
 * フローティング機能をコンポーネントに追加するミックスインです。
 */
Ext.define('Ext.util.Floating', {
    mixinId: 'floating',

    uses: ['Ext.Layer', 'Ext.ZIndexManager'],

    /**
     * @cfg {Boolean} focusOnToFront
     * {@link #toFront 前面に移動した}ときに、フローティングコンポーネントに自動的に{@link Ext.Component#method-focus フォーカス}を当てるかどうかを指定します。
     */
    focusOnToFront: true,

    /**
     * @cfg {String/Boolean} shadow
     * フローティングコンポーネントに影を付けるかどうかを指定します。trueに設定して、{@link Ext.Shadow}、またはシャドウの画面である{@link Ext.Shadow#mode}を示す文字列を自動的に作成します。影を無効にする場合はfalseを指定します。
     */
    shadow: 'sides',

    /**
     * @cfg {Boolean} constrain
     * 含んでいる要素内のコンポーネントを制限する場合はtrue、含んでいる要素の外側へ置く場合はfalse。デフォルトでは、このコンポーネントは`document.body`に描画されます。別の要素内でこのコンポーネントの描画や制限を行うには、{@link Ext.Component#renderTo renderTo}を指定します。
     */
    constrain: false,

    /**
     * @cfg {Boolean} [fixed=false]
     * `true`に設定すると、このコンポーネントはブラウザのビューポートの`X, Y`の各座標に固定され、ドキュメントのスクロールに影響されなくなります。
     */

    /**
     * @cfg {Number} shadowOffset
     * 影のオフセットをピクセル単位で指定します。
     */

    /**
     * @property {Ext.ZIndexManager} zIndexManager
     * 描画後の{@link Ext.Component#floating floating}コンポーネントにのみ存在します。
     *
     * このコンポーネントのz-indexを管理しているZIndexマネージャを参照します。
     *
     * {@link Ext.ZIndexManager ZIndexマネージャ}はフローティングコンポーネントのz-indexのスタックを管理し、最上位の可視モーダルなフローティングコンポーネント下に挿入される単一モーダルなマスクも備えています。
     *
     * フローティングコンポーネントは、z-indexスタックの{@link Ext.Component#toFront 前に運ばれる}場合と{@link Ext.Component#toBack 後ろに送られる}場合があります。
     *
     * これは、プログラムで{@link Ext.Component#method-render 描画}されるフローティングコンポーネント用のデフォルトのグローバルな{@link Ext.WindowManager ZIndexマネージャ}となります。
     *
     * コンテナに追加される{@link #floating}コンポーネントの場合、ZIndexマネージャは最初に見つかるフローティング祖先コンテナから取得されます。見つからなかった場合、グローバルな{@link Ext.WindowManager ZIndexマネージャ}が使用されます。
     *
     * {@link Ext.Component#floating}および{@link #zIndexParent}を参照してください。
     * @readonly
     */

    /**
     * @property {Ext.Container} zIndexParent
     * これは、コンテナの子アイテムとして挿入されており、祖先にフローティングコンテナを含んでいる{@link Ext.Component#floating}コンポーネントにのみ存在します。
     *
     * コンテナの子アイテムである{@link Ext.Component#floating}コンポーネントの場合、zIndexParentは祖先フローティングコンテナとなり、フロートするすべての子孫の起点となるz-index値の元となります。これには、すべての子孫フローティングコンポーネントにz-index化サービスを提供する{@link Ext.ZIndexManager ZIndexマネージャ}が備わっています。
     *
     * プログラムで{@link Ext.Component#method-render 描画}されるフローティングコンポーネントには、`zIndexParent`プロパティが備わっていません。
     *
     * 例えば、ウインドウ内にあるComboBoxのドロップダウン{@link Ext.view.BoundList 境界リスト}は、ウインドウをその`zIndexParent`として用意しており、ウインドウがz-indexスタック内に配置されている場合には常にそのウインドウ上に表示されます。
     *
     * {@link Ext.Component#floating}および{@link #zIndexManager}を参照してください。
     * @readonly
     */

     config: {
         /**
          * @private
          * @cfg {Number} activeCounter {@link #zIndexManager}がスタックをソートする際に使うアクティブ化インデックスを示す、インクリメントする数値カウンタ。
          */
         activeCounter: 0,
         
         /**
          * @cfg {Boolean/Number} [alwaysOnTop=false] このコンポーネントがz-インデックススタックの最上位にある必要があることを示すフラグ。{@link #zIndexManager}がスタックをソートする際に使われます。
          *
          * これを正の数値にすると、常に一番上のコンポーネントになるように、表示された複数のコンポーネントの順序に優先順位をつけることができます。
          *
          * これを*負*の数値に設定すると、Z-インデックススタックの*一番下*にコンポーネントが来るように、優先順位をつけることができます。
          */
         alwaysOnTop: false
     },

    constructor: function (dom) {
        var me = this;

        me.el = new Ext.dom.Layer(Ext.apply({
            preventSync  : true,
            hideMode     : me.hideMode,
            shadow       : (typeof me.shadow != 'undefined') ? me.shadow : 'sides',
            shadowOffset : me.shadowOffset,
            constrain    : false,
            fixed        : me.fixed,
            shim         : (me.shim === false) ? false : undefined
        }, me.floating), dom);

        // If modal, and focus navigation not being handled by the FocusManager,
        // catch tab navigation, and loop back in on tab off first or last item.
        if (me.modal && !(Ext.enableFocusManager)) {
            me.mon(me.el, {
                keydown: me.onKeyDown,
                scope: me
            });
        }

        // mousedown brings to front
        // Use capture to see the event first before any contained DD instance stop the event.
        me.mon(me.el, {
            mousedown: me.onMouseDown,
            scope: me,
            capture: true
        });

        // release config object (if it was one)
        me.floating = true;

        // Register with the configured ownerCt.
        // With this we acquire a floatParent for relative positioning, and a zIndexParent which is an
        // ancestor floater which provides zIndex management.
        me.registerWithOwnerCt();

        me.initHierarchyEvents();
    },

    initFloatConstrain: function () {
        var me = this,
            floatParent = me.floatParent;

        // If a floating Component is configured to be constrained, but has no configured
        // constrainTo setting, set its constrainTo to be it's ownerCt before rendering.
        if ((me.constrain || me.constrainHeader) && !me.constrainTo) {
            me.constrainTo = floatParent ? floatParent.getTargetEl() : me.container;
        }
    },

    initHierarchyEvents: function() {
        var me = this,
            syncHidden = this.syncHidden;

        if (!me.hasHierarchyEventListeners) {
            me.mon(Ext.GlobalEvents, {
                hide: syncHidden,
                collapse: syncHidden,
                show: syncHidden,
                expand: syncHidden,
                added: syncHidden,
                scope: me
            });
            me.hasHierarchyEventListeners = true;
        }
    },

    registerWithOwnerCt: function() {
        var me = this,
            ownerCt = me.ownerCt,
            zip = me.zIndexParent;

        if (zip) {
            zip.unregisterFloatingItem(me);
        }

        // Acquire a zIndexParent by traversing the ownerCt axis for the nearest floating ancestor.
        // This is to find a base which can allocate relative z-index values
        zip = me.zIndexParent = me.up('[floating]');

        // Set the floatParent to the ownertCt if one has been provided.
        // Otherwise use the zIndexParent.
        // Developers must only use ownerCt if there is really a containing relationship.
        me.floatParent = ownerCt || zip;
        me.initFloatConstrain();
        delete me.ownerCt;

        if (zip) {
            zip.registerFloatingItem(me);
        } else {
            Ext.WindowManager.register(me);
        }
    },

    // Listen for TAB events and wrap round if tabbing of either end of the Floater
    onKeyDown: function(e) {
        var me = this,
            shift,
            focusables,
            first,
            last;

        // If tabbing off either end, wrap round.
        // See Ext.dom.Element.isFocusable
        // Certain browsers always report tabIndex zero in the absence of the tabIndex attribute.
        // Testing the specified property (Standards: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-862529273)
        // Should filter out these cases.
        // The exception is IE8. In this browser, all elements will yield a tabIndex
        // and therefore all elements will appear to be focusable.
        // This adversely affects modal Floating components.
        // These listen for the TAB key, and then test whether the event target === last focusable
        // or first focusable element, and forcibly to a circular navigation.
        // We cannot know the true first or last focusable element, so this problem still exists for IE8
        if (e.getKey() === e.TAB) {
            shift = e.shiftKey;
            focusables = me.query(':focusable');
            if (focusables.length) {
                first = focusables[0];
                last = focusables[focusables.length - 1];
                if (!shift && last.hasFocus) {
                    e.stopEvent();
                    first.focus();
                } else if (shift && first.hasFocus) {
                    e.stopEvent();
                    last.focus();
                }
            }
        }
    },

    // @private
    // Mousedown brings to front, and programatically grabs focus
    // *unless the mousedown was on a focusable element*
    onMouseDown: function (e) {
        var me = this,
            focusTask = me.focusTask,
            
            // Do not autofocus the Component (which delegates onto the getFocusEl() descendant)
            // for touch events.
            parentEvent = e.parentEvent,
            preventFocus = parentEvent && parentEvent.type === 'touchstart',
            target, dom;

        if (me.floating &&
            // get out of here if there is already a pending focus.  This usually means
            // that the handler for a mousedown on a child element set the focus on some
            // other component, and we so not want to steal it back. See EXTJSIV-9458
            (!focusTask || !focusTask.id)) {

            target = e.target;
            dom = me.el.dom;
            // loop the target's ancestors to see if we clicked on a focusable element
            // or a descendant of a focusable element,  If so we don't want to focus
            // this floating component. If we end up with no target, it probably means
            // it's been removed from the DOM, so we should attempt to bring ourselves
            // to front anyway
            while (!preventFocus && target && target !== dom) {
                if (Ext.fly(target).isFocusable()) {
                    preventFocus = true;
                }
                target = target.parentNode;
            }

            // If what was mousedowned upon is going to claim focus anyway, pass
            // preventFocus as true.
            me.toFront(preventFocus);
        }
    },

    // @private
    syncShadow : function() {
        if (this.floating) {
            this.el.sync(true);
        }
    },

    onBeforeFloatLayout: function(){
        this.el.preventSync = true;
    },

    onAfterFloatLayout: function(){
        delete this.el.preventSync;
        this.syncShadow();
    },

    /**
     * このコンポーネントの非表示状態をその階層の状態に同期させます。
     * @private
     */
    syncHidden: function() {
        var me = this,
            hidden = me.hidden || !me.rendered,
            hierarchicallyHidden = me.hierarchicallyHidden = me.isHierarchicallyHidden(),
            pendingShow = me.pendingShow;

        if (hidden !== hierarchicallyHidden) {
            if (hierarchicallyHidden) {
                me.hide();
                me.pendingShow = true;
            } else if (pendingShow) {
                delete me.pendingShow;
                if (pendingShow.length) {
                    me.show.apply(me, pendingShow);
                } else {
                    me.show();
                }
            }
        }
    },

    // @private
    // z-index is managed by the zIndexManager and may be overwritten at any time.
    // Returns the next z-index to be used.
    // If this is a Container, then it will have rebased any managed floating Components,
    // and so the next available z-index will be approximately 10000 above that.
    setZIndex: function(index) {
        var me = this;

        me.el.setZIndex(index);

        // Next item goes 10 above;
        index += 10;

        // When a Container with floating descendants has its z-index set, it rebases any floating descendants it is managing.
        // The returned value is a round number approximately 10000 above the last z-index used.
        if (me.floatingDescendants) {
            index = Math.floor(me.floatingDescendants.setBase(index) / 100) * 100 + 10000;
        }
        return index;
    },

    /**
     * フローティングコンポーネントを制約された領域に移動します。
     *
     * デフォルトでは、このコンポーネントはそのコンポーネントが追加されたコンテナ、またはそれがレンダリングされた要素内に制限されます。
     *
     * 別の制約が渡される場合があります。
     * @param {String/HTMLElement/Ext.dom.Element/Ext.util.Region} [constrainTo] このコンポーネントが制約される要素、または{@link Ext.util.Region 領域}。デフォルトは、このフローティングコンポーネントが描画された要素です。
     */
    doConstrain: function(constrainTo) {
        var me = this,
            // Calculate the constrained poition.
            // calculateConstrainedPosition will provide a default constraint
            // region if there is no explicit constrainTo, *and* there is no floatParent owner Component.
            xy = me.calculateConstrainedPosition(constrainTo, null, true);

        // false is returned if no movement is needed
        if (xy) {
            me.setPosition(xy);
        }
    },

    updateActiveCounter: function(activeCounter) {
        var z = this.zIndexParent;

        // If we have a zIndexParent, it has to rebase its own zIndices
        if (z && this.bringParentToFront !== false) {
            z.setActiveCounter(++Ext.ZIndexManager.activeCounter);
        }

        // Rebase the local zIndices
        if (z = this.zIndexManager) {
            z.onComponentUpdate(this);
        }
    },

    updateAlwaysOnTop: function(alwaysOnTop) {
        var z = this.zIndexManager;

        // Rebase the local zIndices
        if (z) {
            z.onComponentUpdate(this);
        }
    },

    /**
     * 同じ{@link Ext.ZIndexManager ZIndexManager}で管理されている他の表示されているフローティングコンポーネントの前に、このフローティングコンポーネントを移動させます。
     *
     * このコンポーネントがモーダルの場合、z-index上でのこのモーダルマスクのちょうど下に挿入されます。
     *
     * @param {Boolean} [preventFocus=false] `true`を指定すると、コンポーネントがフォーカスされなくなります。
     * @return {Ext.Component} this
     */
    toFront: function(preventFocus) {
        var me = this;

        // ZIndexManager#onCollectionSort will call setActive if this component ends up on the top.
        // That will focus it if we have been requested to do so.
        if (me.zIndexManager.bringToFront(me, preventFocus || !me.focusOnToFront)) {
            if (me.hasListeners.tofront) {
                me.fireEvent('tofront', me, me.el.getZIndex());
            }
        }
        return me;
    },

    /**
     * @private
     * このメソッドは{@link Ext.ZIndexManager}によって内部で呼び出され、フローティングコンポーネントがzIndexのスタックの上位へ移動されたか、そのzIndexのスタックの上位から出されたかを伝えます。
     *
     * _ウィンドウ_が別のウィンドウに取り換えられる場合、そのウィンドウを非アクティブ化すれば、そのシャドウを非表示にできます。
     *
     * また、このメソッドは{@link Ext.Component#activate アクティブ化}イベントまたは{@link Ext.Component#deactivate 非アクティブ化}イベントを、どちらのアクションが起きたかに応じて発火させます。
     *
     * @param {Boolean} [active=false] コンポーネントをアクティブ化する場合はtrue、非アクティブ化する場合はfalse。
     * @param {Ext.Component} [newActive] 非アクティブ化された場合、最上位のzIndexを引き継ぐ、新たにアクティブになったコンポーネント。
     */
    setActive: function(active, newActive, doFocus) {
        var me = this;
        
        if (active) {
            if (me.el.shadow && !me.maximized) {
                me.el.enableShadow(true);
            }
            if (doFocus) {
                me.previousFocus = Ext.Element.getActiveElement();
                me.focus(false, true);
            } else {
                me.previousFocus = null;
            }
            me.fireEvent('activate', me);
        } else {
            // Only the *Windows* in a zIndex stack share a shadow. All other types of floaters
            // can keep their shadows all the time
            if (me.isWindow && (newActive && newActive.isWindow) && me.hideShadowOnDeactivate) {
                me.el.disableShadow();
            }
            me.fireEvent('deactivate', me);
            
            // IE8 will throw an exception is the target is not focusable
            if (me.previousFocus && (!Ext.isIE8 || Ext.fly(me.previousFocus).isFocusable())) {
                me.previousFocus.focus();
                me.previousFocus = null;
            }
        }
    },

    /**
     * このコンポーネントより背面にある(z-indexがこれより小さい)、他の見えている状態のウィンドウに送ります。
     * @return {Ext.Component} this
     */
    toBack: function() {
        this.zIndexManager.sendToBack(this);
        return this;
    },

    /**
     * コンポーネントを、そのコンテナの中央に設置します。
     * @return {Ext.Component} this
     */
    center: function() {
        var me = this,
            xy;

        if (me.isVisible()) {
            xy = me.getAlignToXY(me.container, 'c-c');
            me.setPagePosition(xy);
        } else {
            me.needsCenter = true;
        }
        return me;
    },
    
    onFloatShow: function() {
        if (this.needsCenter) {
            this.center();    
        }
        delete this.needsCenter;

        if (this.toFrontOnShow) {
            this.toFront();
        }
    },

    // @private
    fitContainer: function(animate) {
        var me = this,
            parent = me.floatParent,
            container = parent ? parent.getTargetEl() : me.container,
            newBox = container.getViewSize(),
            newPosition = parent || (container.dom !== document.body) ?
                // If we are a contained floater, or rendered to a div, maximized position is (0,0)
                [0, 0] :
                // If no parent and rendered to body, align with origin of container el.
                container.getXY();

        newBox.x = newPosition[0];
        newBox.y = newPosition[1];
        me.setBox(newBox, animate);
    }
});