(function(factory) {
    if(typeof define === 'function' && define.amd) {
        var scripts = ['jquery','bootstrap','gritter'];
        define(scripts, factory);
    }else {
        factory(jQuery);
    }
}(function($) {
    return horizon.engine.iframe =  {
        active: false,
            openModalNum: 0,
        /**
         * 打开modal层
         * @params: option { url: 页面路径, root: window对象, closeCallback: 回调函数 }
         * */
        open: function (option) {
        var modalId = 'modal_' + (this.openModalNum++),
            $widget = $('.horizon-task-modal .horizon-task-widget'),
            $asideTrigger = $('.aside-trigger[data-target=".horizon-task-modal"]'),
            $dropdownMenu = $widget.find('.dropdown-menu'),
            $tabContent = $widget.find('.tab-content'),
            $menu = $dropdownMenu.children('.menu-tls').clone()
                .removeClass('hidden menu-tls').addClass('active').data(option)
                .find('a[data-toggle="tab"]').data('target', '#' + modalId).end(),
            $pane = $('<div class="tab-pane pane-tls"> <iframe width="100%" height="100%" frameborder="0" src="" style="display: block;"></iframe> </div>')
            //$tabContent.children('.pane-tls').clone()
            $pane.removeClass('pane-tls').addClass('active')
                .attr({
                    id: modalId,
                    'widget-id': modalId
                });
        $dropdownMenu.children(':not(.menu-tls)').removeClass('active').end().append($menu);
        $tabContent.children(':not(.pane-tls)').removeClass('active').end().append($pane);
        $widget.find('.widget-title').html($menu.find('a[data-toggle="tab"]').html());
        this.setTaskNum();
        setTimeout(function () {
            var $iframe = $pane.find('iframe');
            $iframe[0].name = modalId;
            $iframe[0].src = option.url;
            //弹出层关闭的回调函数
            if(option.callback) {
                $menu.data('closeCallback',option.callback);
            }
            if (typeof option.title == 'string') {
                $menu.find('a[data-toggle="tab"]').html(option.title);
                $widget.find('.widget-title').html(option.title);
            } else {
                if ($iframe[0].attachEvent) {
                    $iframe[0].attachEvent('onload', function () {
                        try {
                            var _title = window.frames[modalId].document.getElementsByTagName('title')[0].innerHTML;
                            if (_title != null && _title != '') {
                                $menu.find('a[data-toggle="tab"]').html(_title);
                                $widget.find('.widget-title').html(_title);
                            }
                        } catch (e) {
                        }
                    });
                } else {
                    $iframe[0].onload = function () {
                        horizon.engine.iframe.setModalTitle($menu, $widget, $iframe, modalId);
                    }
                }
            }
        }, 1);
        $asideTrigger.removeClass('hidden');
        if (!$asideTrigger.parent().hasClass('in')) {
            $asideTrigger.trigger(horizon.tools.clickEvent());
        }
    },
        /**
         * 关闭modal层
         * */
        close: function ($target) {
            var $widget = $('.horizon-task-modal .horizon-task-widget'),
                $asideTrigger = $('.aside-trigger[data-target=".horizon-task-modal"]'),
                $dropdownMenu = $widget.find('.dropdown-menu'),
                $tabContent = $widget.find('.tab-content'),
                $menu = $target ? $target : $dropdownMenu.children('.active'),
                $pane = $tabContent.find($menu.children('a[data-toggle="tab"]').data('target')),
                $iframeWin = $pane.find('iframe')[0].contentWindow;
            try {
                if ($iframeWin && $iframeWin.horizon && typeof $iframeWin.horizon.closeCallback == 'function') {
                    try {
                        $iframeWin.horizon.closeCallback($menu);
                    } catch (e) {
                        alert(e.message);
                    }
                    return;
                }
            } catch (e) {
            }

            if ($menu.hasClass('active')) {
                var $nextActive;
                if (!$menu.prev().is('.hidden')) {
                    $nextActive = $menu.prev();
                } else if ($menu.next().length) {
                    $nextActive = $menu.next();
                }
                if ($nextActive) {
                    var $tabA = $nextActive.children('a[data-toggle="tab"]');
                    $nextActive.addClass('active');
                    $widget.find('.widget-title').html($tabA.html());
                    $tabContent.find($tabA.data('target')).addClass('active');
                } else {
                    $asideTrigger.trigger(horizon.tools.clickEvent());
                    $asideTrigger.addClass('hidden');
                }
            }
            try {
                var pRoot = $menu.data('root'),
                    pCloseCallback = $menu.data('closeCallback');
                setTimeout(function () {
                    horizon.vars.ie ? $(':focusable').focus() : '';
                    document.getElementsByTagName('body')[0].focus();
                }, 1);
                if (pCloseCallback) {
                    pRoot.eval(pCloseCallback);
                }
            } catch (e) {
                // IE: 原页面已被释放
                horizon.vars.ie ? setTimeout(function () {
                    $(':focusable').focus()
                }, 1) : '';
            }
            $menu.remove();
            $pane.remove();
            this.setTaskNum();

        },
        setTaskNum: function () {
            var $widget = $('.horizon-task-modal .horizon-task-widget'),
                $asideTrigger = $('.aside-trigger[data-target=".horizon-task-modal"]'),
                $num = $asideTrigger.find('.task-num');
            $num.html($widget.find('.tab-pane:not(.pane-tls)').length);
        },
        init: function () {
            var $widget = $('.horizon-task-modal .horizon-task-widget'),
                $asideTrigger = $('.aside-trigger[data-target=".horizon-task-modal"]'),
                event = horizon.tools.clickEvent();
            $widget.find('[data-action="remove"]').on(event, function () {
                horizon.engine.iframe.close();
            });
            $widget.find('[data-action="hide"]').on(event, function () {
                $asideTrigger.trigger(event);
            });
            $widget.on('reload.ace.widget', function () {
                var $box = $(this),
                    $iframe = $box.find('.tab-pane.active iframe');
                $iframe[0].contentWindow.location.reload();
                setTimeout(function () {
                    $box.trigger('reloaded.ace.widget');
                }, 1);
            });
            $widget.on('show.bs.tab', '.widget-menu [data-toggle="tab"]', function () {
                var $this = $(this);
                $this.closest('.widget-menu').find('.active').removeClass('active');
            }).on('shown.bs.tab', '.widget-menu [data-toggle="tab"]', function () {
                var $this = $(this),
                    $widgetTitle = $this.closest('.widget-header').find('.widget-title'),
                    $tabA = $this.closest('.widget-menu').find('.active').find('a[data-toggle="tab"]');
                $widgetTitle.html($tabA.html());
            });
            this.active = true;
        },
        setModalTitle: function ($menu, $widget, $iframe, modalId) {
            setTimeout(function () {
                try {
                    var _title = '';
                    if (window.frames[modalId].document) {
                        _title = window.frames[modalId].document.getElementsByTagName('title')[0].innerHTML;
                    } else {
                        if($iframe[0].contentWindow.document.getElementsByTagName('title').length > 0){
                            _title = $iframe[0].contentWindow.document.getElementsByTagName('title')[0].innerHTML;
                        }
                    }
                    if (_title == '') {
                        horizon.engine.iframe.setModalTitle($menu, $widget, $iframe, modalId);
                    } else {
                        $menu.find('a[data-toggle="tab"]').html(_title);
                        $widget.find('.widget-title').html(_title);
                    }

                } catch (e) {
                }
            }, 100);
        }
    }
}));
