var tabmenu;//菜单页签对象
var tabpanel;//面板页签对象
//初始化home/menu/main区
$(document).ready(function () {
    $.ajaxSetup({ headers: { "Content-Type": "application/json" } });
    var body = $(document.body);
    //初始化home区=========
    var home = $("<div id='home'><img src='Kit/UserImg.ashx?size=64' onerror=this.src='../Content/images/web/icon64User.png' title='" + window.ip + "' height='90%' onclick=\"addTab('tab_Kit_UserDetail','用户信息','Kit/UserDetail.aspx', '../Content/images/web/icon16User.png');return false;\" ><div id='home1'><span></span> <a onclick=\"$.post('Default.aspx/Exit',function(rtn){window.location.href=rtn.d});\">注销</a></div></div>");
    body.append(home);
    $("#home1").find("span").first().text(window.userData.name);
    var home2 = $("<div id='home2'></div>");
    home2.append($("<img alt='我的桌面' title='我的桌面' src='../Content/images/web/icon16Organization.png' onclick=\"addTab('tab_Main','我的桌面','Main.aspx', '../Content/images/web/icon16Refrensh.png');return false;\" />"));
    home2.append($("<img alt='刷新面板' title='刷新桌面' src='../Content/images/web/icon16Refrensh.png' onclick=\"tabpanel.refresh('tab_Main');tabpanel.kills();return false;\" />"));
    home.append(home2);
    var home3 = $("<div id='home3'></div>");
    home3.append($("<img id='messenger' title='办公信使' src='../Content/images/web/icon16Messenger.png' onclick=\"addTab('tab_KitMessenger','办公信使','Kit/Messenger.aspx', '../Content/images/web/icon16Messenger.png');return false;\" />"));
    home3.append($("<img title='记事本' src='../Content/images/web/icon16Note.png' onclick=\"addTab('tab_KitNote','记事本','Kit/Note.aspx', '../Content/images/web/icon16Note.png');return false;\" />"));
    home3.append($("<img title='收支账本' src='../Content/images/web/icon16Money.png' onclick=\"addTab('tab_KitMoney','收支账本','Kit/Money.aspx','../Content/images/web/icon16Money.png');return false;\"/>"));
    home3.append($("<img title='通讯录' src='../Content/images/web/icon16Address.png' onclick=\"addTab('tab_KitAddress','通讯录','Kit/Address.aspx', '../Content/images/web/icon16Address.png');return false;\"/>"));
    home3.append($("<img  id='remind' title='任务提醒' src='../Content/images/web/icon16Remind.png' onclick=\"addTab('tab_KitRemind','任务提醒','Kit/Task.aspx', '../Content/images/web/icon16Remind.png');return false;\"/>"));
    home3.append($("<img title='帮助文档' src='../Content/images/web/icon16Help.png' onclick=\"addTab('tab_Help','帮助文档','../Help/Help.aspx', '../Content/images/web/icon16Help.png');return false;\"/>"));
    home.append(home3);
    //初始化menu区=========
    var menu = $("<div id='menu'></div>");
    body.append(menu);
    tabmenu = new TabMenu({
        renderTo: menu,
        autoResizable: true,
        border: '1',
        active: 0,
        items: [
            { id: 'tab_Menu', title: '开始菜单', html: '', closable: false, disabled: false, icon: '../Content/images/web/icon16Lamp.png' }
        ]
    });
    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: "Default.aspx/getMenu",
        data: "{code: '', pwa: false}",
        dataType: "json"
    })
    .done(function (result) {
        var json = eval('(' + result.d + ')').data;
        for (var i = 0; i < json.length; i++) {
            tabmenu.addTab({ id: json[i].Code, title: json[i].Name, html: "", closable: false, disabled: false, icon: json[i].IconType == null ? '../Content/images/web/icon16Lamp.png' : 'Icon.ashx?code=' + json[i].Code + "&size=16" });
        }
    })
    .fail(function () {
        //alert("菜单项加载失败！");
    });
    //初始化main区=========
    var main = $("<div id='main'></div>");
    body.append(main);
    tabpanel = new TabPanel({
        renderTo: main,
        autoResizable: true,
        border: '1',
        active: 0,
        items: [
            { id: 'tab_Main', title: '我的桌面', html: '<iframe id="tab_Main_ifm" name="tab_Main_ifm" src="Main.aspx" width="100%" height="100%" frameborder="0"></iframe>', closable: false, disabled: false, icon: "../Content/images/web/icon16Organization.png" }
        ]
    });
    //办公信使、任务提醒
    getNotify();
    window.setInterval(getNotify, 300000);
    function getNotify() {
        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: "Default.aspx/getNotify",
            dataType: "json",
            global: false
        })
        .done(function (rtn) {
            var json = eval('(' + rtn.d + ')');
            var messenger = home3.find("#messenger");
            if (json.messenger == 0) {
                messenger.attr("src", "../Content/images/web/icon16Messenger.png");
                messenger.attr("title", "办公信使");
            } else {
                messenger.attr("src", "../Content/images/web/icon16Messenger.gif");
                messenger.attr("title", "当前有" + json.messenger + "条未读消息");
            }
            var remind = home3.find("#remind");
            if (json.remind == 0) {
                remind.attr("src", "../Content/images/web/icon16Remind.png");
                remind.attr("title", "任务提醒");
            } else {
                remind.attr("src", "../Content/images/web/icon16Remind.gif");
                remind.attr("title", "当前有" + json.remind + "条待办任务");
            }
        });
    }
});
//获得菜单项=========
function getMenuItem(code, render) {
    popup(window);
    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: "Default.aspx/getMenu",
        data: "{code:'" + code + "', pwa: false}",
        dataType: "json"
    })
    .done(function (result) {
        var json = eval('(' + result.d + ')').data;
        var ul,li;
        for (var i = 0; i < json.length; i++) {
            if (!json[i].Url) {
                render.append($("<div class='expand' onclick=$(this).next().toggle();$(this).toggleClass('collapse').toggleClass('expand');><img src='" + (json[i].IconType == null ? '../Content/images/web/icon16Shortcut.png' : 'Icon.ashx?code=' + json[i].Code + '&size=16') + "'>" + json[i].Name + "</div>"));
                ul = $("<ul style='display:none'></ul>");
                render.append(ul);
            }
            else {
                if (json[i].ParentCode == code) {
                    li = $("<ul><li><img src='" + (json[i].IconType == null ? '../Content/images/web/icon16Shortcut.png' : 'Icon.ashx?code=' + json[i].Code + '&size=16') + "'>" + json[i].Name + "</li></ul>");
                    render.append(li);
                }
                else {
                    li = $("<li><img src='" + (json[i].IconType == null ? '../Content/images/web/icon16Shortcut.png' : 'Icon.ashx?code=' + json[i].Code + '&size=16') + "'>" + json[i].Name + "</li>");
                    ul.append(li);
                }
                switch (json[i].Target) {
                    case "new":
                        li.bind("click", json[i], function (e) { window.open(e.data.Url.replace("~/", "/")) });
                        break;
                    case "aide":
                        li.bind("click", json[i], function (e) { popup(null, e.data.Name, e.data.Url.replace("~/", "/"), '', 0,'100%', '100%'); });
                        break;
                    default:
                        li.bind("click", json[i], function (e) { addTab("tab_" + e.data.Code, e.data.Name, e.data.Url.replace("~/", "/"), e.data.IconType == null ? '../Content/images/web/icon16Shortcut.png' : 'Icon.ashx?code=' + e.data.Code + "&size=16") });
                        break;
                }
            }
        }
        popupClose(window);
    })
    .fail(function () {
        alert("菜单项加载失败，请重新点击或刷新浏览器！");
        popupClose(window);
    });
}
//获得快捷菜单项=========
function getShortcut(render) {
    popup(window);
    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: "Default.aspx/getMenus",
        data: "{code: '', pwa: false}",
        dataType: "json"
    })
    .done(function (result) {
        var json = eval('(' + result.d + ')').data;
        var parentCode = "";
        var ul,li;
        for (var i = 0; i < json.length; i++) {
            if (json[i].ParentCode != parentCode) {
                parentCode = json[i].ParentCode;
                render.append($("<div class='collapse' onclick=$(this).next().toggle();$(this).toggleClass('collapse').toggleClass('expand');><img src='" + (json[i].ParentIconType == null ? '../Content/images/web/icon16Shortcut.png' : 'Icon.ashx?code=' + json[i].ParentCode + '&size=16') + "'>" + json[i].ParentName + "</div>"));
                ul = $("<ul></ul>");
                li = $("<li><img src='" + (json[i].IconType == null ? '../Content/images/web/icon16Shortcut.png' : 'Icon.ashx?code=' + json[i].Code + '&size=16') + "'>" + json[i].Name + "</li>");
                ul.append(li);
                render.append(ul);
            }
            else {
                li = $("<li><img src='" + (json[i].IconType == null ? '../Content/images/web/icon16Shortcut.png' : 'Icon.ashx?code=' + json[i].Code + '&size=16') + "'>" + json[i].Name + "</li>");
                ul.append(li);
            }
            switch (json[i].Target) {
                case "new":
                    li.bind("click", json[i], function (e) { window.open(e.data.Url.replace("~/", "/")) });
                    break;
                case "aide":
                    li.bind("click", json[i], function (e) { popup(null, e.data.Name, e.data.Url.replace("~/", "/"), '', 0, '100%', '100%'); });
                    break;
                default:
                    li.bind("click", json[i], function (e) { addTab("tab_" + e.data.Code, e.data.Name, e.data.Url.replace("~/", "/"), e.data.IconType == null ? '../Content/images/web/icon16Shortcut.png' : 'Icon.ashx?code=' + e.data.Code + "&size=16") });
                    break;
            }
        }
        popupClose(window);
    })
    .fail(function () {
        popupClose(window);
    });
}
//面板页签增加方法=========
function addTab(id, title, url, icon) {
    tabpanel.addTab({ id: id, title: title, html: '<iframe id="' + id + '_ifm" name="' + id + '_ifm" src="' + url + '" width="100%" height="100%" frameborder="0"></iframe>', closable: true, disabled: false, icon: icon });
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
  * @description {Class} TabPanel
  * This is the main class of tab panel.
  */
TabMenu = function (config) {
    /**
     * @description {Config} renderTo   
     * {String or JQuery object} To specify where tab panel will be placed. It could be a DOM id or jquery object.
     */
    this.renderTo = config.renderTo || $(document.body);
    /**
     * @description {Config} border   
     * {Boolean} To show border or not.
     */
    this.border = config.border;
    this.render = typeof this.renderTo == 'string' ? $('#' + this.renderTo) : this.renderTo;
    /**
     * @description {Config} widthResizable   
     * {Boolean} Whether end user can change panel width by mouse dragging.
     */
    this.widthResizable = config.widthResizable;
    /**
     * @description {Config} heightResizable   
     * {Booean} Whether end user can change panel height by mouse dragging.
     */
    this.heightResizable = config.heightResizable;
    /**
     * @description {Config} autoResizable  
     * {Boolean} Whether panel resizes itself according to content.
     */
    this.autoResizable = config.autoResizable ? true : false;
    /**
     * @description {Config} width   
     * {String} Initialization width. 
     * @sample // width config, in px or percentage.
     * width : '200px'// or '100%'.
     */
    this.width = config.width || '100%';
    /**
     * @description {Config} height  
     * {String} Initialization height. 
     * @sample //heigh config 
     * height : '200px'// or '100%'.
     */
    this.height = config.height || '100%';
    /**
     * @description {Config} items   
     * {Array} Tab items array.
     */
    this.items = config.items;
    /**
     * @description {Config} active   
     * {Number} Active tab index. Base on 0.
     */
    this.active = config.active || 0;
    //this is tab array.
    this.tabs = [];
    this.scrolled = false;
    this.tabHeight = 100 + 4;
    this.fixNum = 2;
    this.scrollFinish = true;
    this.maxLength = config.maxLength || -1;
    this.maxzindex = 0;

    this.init();
};

TabMenu.prototype = {
    //initialization
    init: function () {

        var tabEntity = this;

        if (this.autoResizable) {
            this.widthResizable = this.heightResizable = true;
            this.render.css('overflow', 'hidden');
            $(window).resize(function () {
                window.setTimeout(function () {
                    tabEntity.resize();
                }, 200);
            });
        }
        //注释掉调整父对象
        //this.render.width(this.width);
        //this.render.height(this.height);

        var hwFix = this.border != 'none' ? 1 : 0;

        this.tabpanel = $('<DIV></DIV>');
        this.tabpanel.addClass('tabmenu');
        this.tabpanel.width(this.render.width());
        this.tabpanel.height(this.render.height() - hwFix);
        this.render.append(this.tabpanel);

        //construct container
        this.tabpanel_tab_content = $('<DIV></DIV>');
        this.tabpanel_tab_content.addClass('tabmenu_tab_content');
        this.tabpanel_tab_content.appendTo(this.tabpanel);

        //construct top scroll button
        this.tabpanel_top_scroll = $('<DIV></DIV>');
        this.tabpanel_top_scroll.bind('click', function () { tabEntity.moveTop(); });
        this.tabpanel_top_scroll.addClass('tabmenu_top_scroll');
        this.tabpanel_top_scroll.addClass('display_none');
        this.tabpanel_top_scroll.bind('mouseover', function () {
            var l = $(this);
            l.addClass('tabmenu_scroll_over');
            l.bind('mouseout', function () {
                l.unbind('mouseout');
                l.removeClass('tabpanel_scroll_over');
            });
        })
        this.tabpanel_top_scroll.appendTo(this.tabpanel_tab_content);

        //construct bottom scroll button
        this.tabpanel_bottom_scroll = $('<DIV></DIV>');
        this.tabpanel_bottom_scroll.bind('click', function () { tabEntity.moveBottom(); });
        this.tabpanel_bottom_scroll.addClass('tabmenu_bottom_scroll');
        this.tabpanel_bottom_scroll.addClass('display_none');
        this.tabpanel_bottom_scroll.bind('mouseover', function () {
            var r = $(this);
            r.addClass('tabmenu_scroll_over');
            r.bind('mouseout', function () {
                r.unbind('mouseout');
                r.removeClass('tabpanel_scroll_over');
            });
        })
        this.tabpanel_bottom_scroll.appendTo(this.tabpanel_tab_content);


        this.tabpanel_move_content = $('<DIV></DIV>');
        this.tabpanel_move_content.addClass('tabmenu_move_content');
        this.tabpanel_move_content.appendTo(this.tabpanel_tab_content);

        this.tabpanel_mover = $('<UL></UL>');
        this.tabpanel_mover.addClass('tabmenu_mover');
        this.tabpanel_mover.appendTo(this.tabpanel_move_content);

        this.tabpanel_tab_spacer = $('<DIV></DIV>');
        this.tabpanel_tab_spacer.addClass('tabmenu_tab_spacer');
        this.tabpanel_tab_spacer.appendTo(this.tabpanel_tab_content);

        //content div
        this.tabpanel_content = $('<DIV></DIV>');
        this.tabpanel_content.addClass('tabmenu_content');
        this.tabpanel_content.appendTo(this.tabpanel);

        var t_w = this.tabpanel.width();
        var t_h = this.tabpanel.height();

        if (this.border == 'none') {
            this.tabpanel.css('border', 'none');
        }

        this.tabpanel_tab_content.height(t_h);
        this.tabpanel_content.height(t_h);
        this.tabpanel_content.width(t_w - this.tabpanel_tab_content.get(0).offsetWidth - 1);

        this.update();

        for (var i = 0; i < this.items.length; i++) {
            this.items[i].notExecuteMoveSee = true;
            this.addTab(this.items[i]);
        }
        //activate tab
        if (this.active >= 0)
            this.show(this.active, false);
    },
    //scroll left
    moveTop: function () {
        if (this.scrollFinish) {
            this.disableScroll();
            this.scrollFinish = false;
            Fader.apply(this, new Array({
                element: this.tabpanel_mover,
                style: 'marginTop',
                num: this.tabHeight,
                maxMove: this.maxMove,
                onFinish: this.useableScroll
            }));
            this.run();
        }
    },
    //scroll bottom
    moveBottom: function () {
        if (this.scrollFinish) {
            this.disableScroll();
            this.scrollFinish = false;
            Fader.apply(this, new Array({
                element: this.tabpanel_mover,
                style: 'marginTop',
                num: this.tabHeight * -1,
                maxMove: this.maxMove,
                onFinish: this.useableScroll
            }));
            this.run();
        }
    },
    //scroll to end of left side
    moveToTop: function () {
        //no scroll button show
        if (this.scrolled && this.scrollFinish) {
            this.disableScroll();
            this.scrollFinish = false;
            var marginTop = parseInt(this.tabpanel_mover.css('marginTop')) * -1;
            Fader.apply(this, new Array({
                element: this.tabpanel_mover,
                style: 'marginTop',
                num: marginTop,
                maxMove: this.maxMove,
                interval: 20,
                step: (marginTop / 10) < 10 ? 10 : marginTop / 10,
                onFinish: this.useableScroll
            }));
            this.run();
        }
    },

    //scroll to end of left side
    moveToBottom: function () {
        if (this.scrolled && this.scrollFinish) {
            this.disableScroll();
            this.scrollFinish = false;
            var marginTop = parseInt(this.tabpanel_mover.css('marginTop')) * -1;
            var liHeight = this.tabpanel_mover.children().length * this.tabHeight;
            var cHeight = this.tabpanel_move_content.height();
            var num = (liHeight - cHeight - marginTop + this.fixNum) * -1;
            Fader.apply(this, new Array({
                element: this.tabpanel_mover,
                style: 'marginTop',
                num: num,
                maxMove: this.maxMove,
                step: (num * -1 / 10) < 10 ? 10 : num * -1 / 10,
                onFinish: this.useableScroll
            }));
            this.run();
        }
    },

    //move to visible position/////////////////////////////////////////////////////////
    moveToSee: function (position) {
        if (this.scrolled) {
            var liWhere = this.tabHeight * position;
            var ulWhere = parseInt(this.tabpanel_mover.css('marginTop'));
            var moveNum;
            if (ulWhere <= 0) {
                moveNum = (ulWhere + liWhere) * -1;
                if (((moveNum + ulWhere) * -1) >= this.maxMove)
                    this.moveToBottom();
                else {
                    this.disableScroll();
                    this.scrollFinish = false;
                    Fader.apply(this, new Array({
                        element: this.tabpanel_mover,
                        style: 'marginTop',
                        num: moveNum,
                        maxMove: this.maxMove,
                        step: (moveNum / 10) < 10 ? 10 : moveNum / 10,
                        onFinish: this.useableScroll
                    }));
                    this.run();
                }
            }
            else {
                moveNum = (liWhere - ulWhere) * -1;
                if ((moveNum * -1) >= this.maxMove)
                    this.moveToBottom();
                else {
                    this.disableScroll();
                    this.scrollFinish = false;
                    Fader.apply(this, new Array({
                        element: this.tabpanel_mover,
                        style: 'marginTop',
                        num: moveNum,
                        maxMove: this.maxMove,
                        onFinish: this.useableScroll
                    }));
                    this.run();
                }
            }
        }
    },
    //disable scroll buttons
    disableScroll: function () {
        this.tabpanel_top_scroll.addClass('tabmenu_top_scroll_disabled');
        this.tabpanel_top_scroll.attr('disabled', true);
        this.tabpanel_bottom_scroll.addClass('tabmenu_bottom_scroll_disabled');
        this.tabpanel_bottom_scroll.attr('disabled', true);
    },

    //to determin whether we can still scroll
    useableScroll: function () {
        var tabEntity = this;
        if (this.scrolled) {
            //we came to the end of top side
            if (parseInt(tabEntity.tabpanel_mover.css('marginTop')) == 0) {
                //disble top scroll button
                tabEntity.tabpanel_top_scroll.addClass('tabmenu_top_scroll_disabled');
                tabEntity.tabpanel_top_scroll.attr('disabled', true);
                //
                tabEntity.tabpanel_bottom_scroll.removeClass('tabpanel_bottom_scroll_disabled');
                tabEntity.tabpanel_bottom_scroll.removeAttr('disabled');
            }
                //we came to the end of bottom side
            else if (parseInt(tabEntity.tabpanel_mover.css('marginTop')) * -1 == tabEntity.maxMove) {
                tabEntity.tabpanel_top_scroll.removeClass('tabpanel_top_scroll_disabled');
                tabEntity.tabpanel_top_scroll.removeAttr('disabled', true);
                tabEntity.tabpanel_bottom_scroll.addClass('tabmenu_bottom_scroll_disabled');
                tabEntity.tabpanel_bottom_scroll.attr('disabled');
            }
            else {
                tabEntity.tabpanel_top_scroll.removeClass('tabpanel_top_scroll_disabled');
                tabEntity.tabpanel_top_scroll.removeAttr('disabled', true);
                tabEntity.tabpanel_bottom_scroll.removeClass('tabpanel_bottom_scroll_disabled');
                tabEntity.tabpanel_bottom_scroll.removeAttr('disabled');
            }
        }

        tabEntity.scrollFinish = true;
    },
    //update style
    update: function () {
        var cHeight = this.tabpanel_tab_content.height();
        if (this.scrolled)
            cHeight -= (this.tabpanel_top_scroll.height() + this.tabpanel_bottom_scroll.height());
        this.tabpanel_move_content.height(cHeight);
        this.maxMove = (this.tabpanel_mover.children().length * this.tabHeight) - cHeight + this.fixNum;
    },
    //to show scroll button if needed.
    showScroll: function () {
        var liHeight = this.tabpanel_mover.children().length * this.tabHeight;
        var tabContenHeight = this.tabpanel_tab_content.height();
        if (liHeight > tabContenHeight && !this.scrolled) {
            this.tabpanel_move_content.addClass('tabmenu_move_content_scroll');
            this.tabpanel_top_scroll.removeClass('display_none');
            this.tabpanel_bottom_scroll.removeClass('display_none');
            this.scrolled = true;
        }
        else if (liHeight < tabContenHeight && this.scrolled) {
            this.moveToTop();
            this.tabpanel_move_content.removeClass('tabpanel_move_content_scroll');
            this.tabpanel_top_scroll.addClass('display_none');
            this.tabpanel_bottom_scroll.addClass('display_none');
            this.scrolled = false;
            this.scrollFinish = true;
        }
    },

    /**
     * @description {Method} addTab To add a new tab.
     * @param {Object} item Object for item profile.
     * @sample  //to add a new tab 
     * addTab({id:"newtabid", 
     *    title:"I am new" ,
     *    html:"some new message goes here", 
     *    closable: true, 
     *    disabled:false, 
     *    icon:"image/new.gif"
     * });   
     */
    addTab: function (tabitem) {

        if (this.maxLength != -1 && this.maxLength <= this.tabs.length) {
            return false;
        }

        tabitem.id = tabitem.id || Math.uuid();

        //if id exist, switch to that one
        if ($('#' + tabitem.id).length > 0) {
            this.show(tabitem.id, false);
        }
        else if (this.scrollFinish) {
            var tabEntity = this;

            var tab = $('<LI></LI>');
            tab.attr('id', tabitem.id);

            tab.appendTo(this.tabpanel_mover);

            var title = $('<DIV></DIV>');
            title.html(tabitem.title.split('').join('<br/>'));
            title.appendTo(tab);

            var wFix = tabitem.closable == false ? 0 : 5;
            if (tabitem.icon) {
                title.addClass('icon_title');
                title.css('background-image', 'url("' + tabitem.icon + '")');
                if (title.width() > (this.tabWidth - 35 - wFix)) {
                    title.width((this.tabWidth - 50 - wFix));
                    title.attr('title', tabitem.title);
                    tab.append('<DIV>...</DIV>');
                }
            } else {
                title.addClass('title');
                if (title.width() > (this.tabWidth - 19 - wFix)) {
                    title.width((this.tabWidth - 30 - wFix));
                    title.attr('title', tabitem.title);
                    tab.append('<DIV>...</DIV>');
                }
            }

            var closer = $('<DIV></DIV>');
            closer.addClass('closer');
            closer.attr('title', '关闭页签');
            closer.appendTo(tab);

            var content = $('<DIV></DIV>');
            content.addClass('html_content');
            //为了兼容IE6将100%修改为固定值
            if (navigator.userAgent.indexOf("MSIE 6.0") > 0)
                content.height(this.tabpanel_content.height());
            content.appendTo(this.tabpanel_content);
            /*
            var child_frame = content.find('iframe');
            
            if(child_frame.length==1)
            {
              child_frame.attr('id', tabitem.id+'Frame');
              child_frame.attr('name', tabitem.id+'Frame');
            }
            */
            var activedTabIndex = this.tabpanel_mover.children().index(this.tabpanel_mover.find('.active')[0]);

            if (activedTabIndex < 0)
                activedTabIndex = 0;
            if (this.tabs.length > activedTabIndex)
                tabitem.preTabId = this.tabs[activedTabIndex].id
            else
                tabitem.preTabId = '';
            tabitem.tab = tab;
            tabitem.title = title;
            tabitem.closer = closer;
            tabitem.content = content;
            tabitem.disable = tabitem.disable == undefined ? false : tabitem.disable;
            tabitem.closable = tabitem.closable == undefined ? true : tabitem.closable;
            if (tabitem.closable == false)
                closer.addClass('display_none');

            if (tabitem.disabled == true) {
                tab.attr('disabled', true);
                title.addClass('.disabled');
            }

            this.tabs.push(tabitem);

            tab.bind('click', function (position) {
                return function () {
                    tabEntity.show(position, false);
                };
            }(this.tabs.length - 1));


            closer.bind('click', function (position) {
                return function () {
                    tabEntity.kill(position);
                };
            }(this.tabs.length - 1));

            //      if(tabitem.closable)
            //      {
            tab.bind('dblclick', function (position) {
                return function () {
                    tabEntity.refresh(position);
                };
            }(this.tabs.length - 1));
            //      }
            //不激活新添加的菜单
            //if (!tabitem.lazyload) {
            //    this.show(this.tabs.length - 1, tabitem.notExecuteMoveSee);
            //}

            this.showScroll();
            this.update();

            if (!tabitem.lazyload && !tabitem.notExecuteMoveSee) {
                this.moveToBottom();
            }
        }
    },
    /**
     * @description {Method} getTabPosision To get tab index.
     * @param {String} id item id.
     * @return {Number} index of tab.
     */
    getTabPosision: function (tabId) {
        if (typeof tabId == 'string') {
            for (var i = 0; i < this.tabs.length; i++) {
                if (tabId == this.tabs[i].id) {
                    tabId = i;
                    break;
                }
            }
        }
        return tabId;
    },
    /**
     * @description {Method} refresh To refresh tab content.
     * @param {String} id item id.
     */
    refresh: function (position) {
        position = this.getTabPosision(position);
        if (typeof position == 'string')
            return false;
        else {
            //if IFRAME exists, refresh the sub frames
            var iframes = this.tabs[position].content.find('iframe');
            if (iframes.length > 0) {
                var frameId = this.tabs[position].id + '_ifm';
                this.iterateFlush(window.frames[frameId]);
            }
        }
    },

    iterateFlush: function (iframeObj) {

        /*if(iframeObj.window.frames.length>0)
        {
          for(var i=0; i<iframeObj.window.frames.length; i++)
          {
            this.iterateFlush(iframeObj.window.frames[i]);
          }
        }
        else
        {*/
        if (iframeObj.document.forms.length > 0) {
            for (var i = 0; i < iframeObj.document.forms.length; i++) {
                try {
                    iframeObj.document.forms[i].submit();
                }
                catch (e) {
                    iframeObj.location.reload();
                }
            }
        }
        else {
            iframeObj.location.reload();
        }
        //}
    },
    show: function (position, notExecuteMoveSee) {
        if (this.tabs.length < 1)
            return false;
        position = this.getTabPosision(position);
        if (typeof position == 'string')
            position = 0;
        if (this.scrollFinish) {
            if (position >= this.tabs.length) {
                position = 0;
            }
            this.tabs[position].content.css('z-index', ++this.maxzindex);
            if (this.tabs[position].tab.hasClass('active')) {
                if (!notExecuteMoveSee) {
                    this.moveToSee(position);
                }
            }
            else {
                //load those never loaded
                if (this.tabs[position].content.html() == '') {
                    if (this.tabs[position].html != '') {
                        this.tabs[position].content.html(this.tabs[position].html);
                    }
                    else {
                        if (position == 0) {
                            getShortcut(this.tabs[position].content);
                        }
                        else {
                            getMenuItem(this.tabs[position].id, this.tabs[position].content);
                        }                         
                    }
                }
                this.tabpanel_mover.find('.active').removeClass('active');
                this.tabs[position].tab.addClass('active');
                if (!notExecuteMoveSee) {
                    this.moveToSee(position);
                }
            }
        }
    },
    /**
     * @description {Method} kill To close tab.
     * @param {String} id item id.
     */
    kill: function (position) {

        var tabEntity = this;
        //get tab index
        position = this.getTabPosision(position);

        var preTabId = this.tabs[position].preTabId;

        //detroy DOM
        this.tabs[position].closer.remove();
        this.tabs[position].title.remove();
        this.tabs[position].tab.remove();
        $("iframe:first", this.tabs[position].content).attr("src", "about:blank");
        this.tabs[position].content.remove();
        //remove from tabs 
        this.tabs.splice(position, 1);

        //rebind event handler because index changed.
        for (var i = 0 ; i < this.tabs.length; i++) {
            this.tabs[i].tab.unbind('click');
            this.tabs[i].tab.bind('click', function (i) {
                return function () {
                    tabEntity.show(i, false);
                };
            }(i));
            this.tabs[i].closer.unbind('click');
            this.tabs[i].closer.bind('click', function (i) {
                return function () {
                    tabEntity.kill(i);
                };
            }(i));
            //      if(this.tabs[i].closable)
            //      {
            this.tabs[i].tab.unbind('dblclick');
            this.tabs[i].tab.bind('dblclick', function (i) {
                return function () {
                    tabEntity.refresh(i);
                };
            }(i));
            //      }
        }
        //update width
        this.update();
        //to scroll bar 
        this.showScroll();
        //show last 
        this.show(preTabId, false);
    },
    /**
    * @description {Method} kill To close all tab.
    */
    kills: function () {
        var tabEntity = this;
        for (var i = this.tabs.length - 1; i >= 0; i--) {
            //var preTabId = this.tabs[i].preTabId;
            if (this.tabs[i].closable) {
                //detroy DOM
                this.tabs[i].closer.remove();
                this.tabs[i].title.remove();
                this.tabs[i].tab.remove();
                $("iframe:first", this.tabs[i].content).attr("src", "about:blank");
                this.tabs[i].content.remove();
                //remove from tabs 
                this.tabs.splice(i, 1);
            }
        }
        //update width
        this.update();
        //to scroll bar 
        this.showScroll();
    },
    /**
     * @description {Method} getTabsCount To get how many tabs are in the panel.
     * @return {Number} Number of tabs .
     */
    getTabsCount: function () {
        return this.tabs.length;
    },

    /**
     * @description {Method} setTitle To set tab title.
     * @param {String} id Item id.
     * @param {String} title Tab title.
     */
    setTitle: function (position, title) {
        position = this.getTabPosision(position);
        if (position < this.tabs.length)
            this.tabs[position].title.text(title);
    },

    /**
     * @description {Method} getTitle To get tab title.
     * @param {String} id item id.
     */
    getTitle: function (position) {
        position = this.getTabPosision(position);
        return this.tabs[position].title.text();
    },

    /**
     * @description {Method} setContent To set tab title.
     * @param {String} id Item id.
     * @param {String} title Tab inner html.
     */
    setContent: function (position, content) {
        position = this.getTabPosision(position);
        if (position < this.tabs.length)
            this.tabs[position].content.html(content);
    },

    /**
     * @description {Method} getContent To get tab inner html.
     * @param {String} id item id.
     */
    getContent: function (position) {
        position = this.getTabPosision(position);
        return this.tabs[position].content.html();
    },

    /**
     * @description {Method} setDisable To enable or disable tab.
     * @param {String} id Item id.
     * @param {Booleaan} True for disabled, false for enabled.
     */
    setDisable: function (position, disable) {
        position = this.getTabPosision(position);
        if (position < this.tabs.length) {
            this.tabs[position].disable = disable;
            if (disable) {
                this.tabs[position].tab.attr('disabled', true);
                this.tabs[position].title.addClass('.disabled');
            } else {
                this.tabs[position].tab.removeAttr('disabled');
                this.tabs[position].title.removeClass('.disabled');
            }
        }
    },

    /**
     * @description {Method} getDisable To determine whether tab is disabled or not.
     * @param {String} id item id.
     */
    getDisable: function (position) {
        position = this.getTabPosision(position);
        return this.tabs[position].disable;
    },

    /**
    * @description {Method} setClosable To enable or disable end user to close tab.
    * @param {String} id Item id.
    * @param {Booleaan} True for closable, false for not.
    */
    setClosable: function (position, closable) {
        position = this.getTabPosision(position);
        if (position < this.tabs.length) {
            this.tabs[position].closable = closable;
            if (closable) {
                this.tabs[position].closer.addClass('display_none');
            } else {
                this.tabs[position].closer.addClass('closer');
                this.tabs[position].closer.removeClass('display_none');
            }
        }
    },

    /**
     * @description {Method} getClosable To determine whether tab is closable or not.
     * @param {String} id item id.
     */
    getClosable: function (position) {
        position = this.getTabPosision(position);
        return this.tabs[position].closable;
    },

    /**
   * @description {Method} getActiveIndex To get index of active tab.
   * @return {Number} index of active tab.
   */
    getActiveIndex: function () {
        return this.tabpanel_mover.children().index(this.tabpanel_mover.find('.active')[0]);
    },

    /**
     * @description {Method} getActiveTab To get active tab.
     * @return {Object} Profile of active tab.
     */
    getActiveTab: function () {
        var activeTabIndex = this.tabpanel_mover.children().index(this.tabpanel_mover.find('.active')[0]);
        if (this.tabs.length > activeTabIndex)
            return this.tabs[activeTabIndex];
        else
            return null;
    },
    resize: function () {
        var hwFix = this.border == 'none' ? 0 : 2;

        if (this.widthResizable) {
            this.width = this.render.width();
            this.height = this.render.height();
            this.tabpanel.width(this.width);
            this.tabpanel_tab_content.height(this.height - hwFix);
            this.tabpanel_content.width(this.width - this.tabpanel_tab_content.get(0).offsetWidth - 1);
        }
        if (this.heightResizable) {
            this.height = this.render.height();
            this.tabpanel.height(this.height - hwFix);
            this.tabpanel_content.height(this.height - hwFix);
        }

        this.showScroll();
        this.useableScroll();
        this.update();

        var entity = this;
        setTimeout(function () { entity.moveToSee(entity.getActiveIndex()); }, 200);

    },

    /**
     * @description {Method} setRenderWH To set width and height of the panel.
     * @param {Object} wh width and height.
     * @sample //To set tab height and width  
     * setRenderWH({width:'200px', height:'400px'});   
     */
    setRenderWH: function (wh) {
        if (wh) {
            if (wh.width != undefined) {
                this.render.width(wh.width);
            }
            if (wh.height != undefined) {
                this.render.height(wh.height);
            }
            this.resize();
        }
    }
};

////////////////////////////////////////////////////////////////////////////////////////////////
/**
  * @description {Class} TabPanel
  * This is the main class of tab panel.
  */
TabPanel = function(config){
  /**
   * @description {Config} renderTo   
   * {String or JQuery object} To specify where tab panel will be placed. It could be a DOM id or jquery object.
   */
    this.renderTo = config.renderTo || $(document.body);
  /**
   * @description {Config} border   
   * {Boolean} To show border or not.
   */
  this.border = config.border;
  this.render = typeof this.renderTo == 'string' ? $('#'+this.renderTo) : this.renderTo;
  /**
   * @description {Config} widthResizable   
   * {Boolean} Whether end user can change panel width by mouse dragging.
   */
  this.widthResizable = config.widthResizable;
  /**
   * @description {Config} heightResizable   
   * {Booean} Whether end user can change panel height by mouse dragging.
   */
  this.heightResizable = config.heightResizable;
  /**
   * @description {Config} autoResizable  
   * {Boolean} Whether panel resizes itself according to content.
   */
  this.autoResizable = config.autoResizable ? true : false;
  /**
   * @description {Config} width   
   * {String} Initialization width. 
   * @sample // width config, in px or percentage.
   * width : '200px'// or '100%'.
   */
  this.width = config.width || '100%';
  /**
   * @description {Config} height  
   * {String} Initialization height. 
   * @sample //heigh config 
   * height : '200px'// or '100%'.
   */
  this.height = config.height || '100%';
  /**
   * @description {Config} items   
   * {Array} Tab items array.
   */
  this.items = config.items;
  /**
   * @description {Config} active   
   * {Number} Active tab index. Base on 0.
   */
  this.active = config.active || 0;
  //this is tab array.
  this.tabs = [];
  this.scrolled = false;
  this.tabWidth = 110 + 4;
  this.fixNum = 2;
  this.scrollFinish = true;
  this.maxLength = config.maxLength || -1;
  this.maxzindex = 0;
  
  this.init();
};

TabPanel.prototype = {
  //initialization
  init : function(){
    
    var tabEntity = this;
	
    if(this.autoResizable){
      this.widthResizable = this.heightResizable = true;
  	  this.render.css('overflow', 'hidden');
  	  $(window).resize(function(){
        window.setTimeout(function(){
          tabEntity.resize();
        }, 200);
  	  });
    }
      //注释掉调整父对象
    //this.render.width(this.width);
    //this.render.height(this.height);

	  var hwFix = this.border!='none'?2:0;

    this.tabpanel = $('<DIV></DIV>');
    this.tabpanel.addClass('tabpanel');
    this.tabpanel.width(this.render.width()-hwFix);
    this.tabpanel.height(this.render.height()-hwFix);
    this.render.append(this.tabpanel);
    
    //construct container
    this.tabpanel_tab_content = $('<DIV></DIV>');
    this.tabpanel_tab_content.addClass('tabpanel_tab_content');
    this.tabpanel_tab_content.appendTo(this.tabpanel);
    
    //construct left scroll button
    this.tabpanel_left_scroll = $('<DIV></DIV>');
    this.tabpanel_left_scroll.bind('click',function(){tabEntity.moveLeft();});
    this.tabpanel_left_scroll.addClass('tabpanel_left_scroll');
    this.tabpanel_left_scroll.addClass('display_none');
    this.tabpanel_left_scroll.bind('mouseover', function(){
      var l = $(this);
      l.addClass('tabpanel_scroll_over');
      l.bind('mouseout', function(){
        l.unbind('mouseout');
        l.removeClass('tabpanel_scroll_over');
      });
    })
    this.tabpanel_left_scroll.appendTo(this.tabpanel_tab_content);
    
    //construct right scroll button
    this.tabpanel_right_scroll = $('<DIV></DIV>');
    this.tabpanel_right_scroll.bind('click',function(){tabEntity.moveRight();});
    this.tabpanel_right_scroll.addClass('tabpanel_right_scroll');
    this.tabpanel_right_scroll.addClass('display_none');
    this.tabpanel_right_scroll.bind('mouseover', function(){
      var r = $(this);
      r.addClass('tabpanel_scroll_over');
      r.bind('mouseout', function(){
        r.unbind('mouseout');
        r.removeClass('tabpanel_scroll_over');
      });
    })
    this.tabpanel_right_scroll.appendTo(this.tabpanel_tab_content);
    
    
    this.tabpanel_move_content = $('<DIV></DIV>');
    this.tabpanel_move_content.addClass('tabpanel_move_content');
    this.tabpanel_move_content.appendTo(this.tabpanel_tab_content);
    
    this.tabpanel_mover = $('<UL></UL>');
    this.tabpanel_mover.addClass('tabpanel_mover');
    this.tabpanel_mover.appendTo(this.tabpanel_move_content);
    
    this.tabpanel_tab_spacer = $('<DIV></DIV>');
    this.tabpanel_tab_spacer.addClass('tabpanel_tab_spacer');
    this.tabpanel_tab_spacer.appendTo(this.tabpanel_tab_content);
    
    //content div
    this.tabpanel_content = $('<DIV></DIV>');
    this.tabpanel_content.addClass('tabpanel_content');
    this.tabpanel_content.appendTo(this.tabpanel);
    
    var t_w = this.tabpanel.width();
    var t_h = this.tabpanel.height();

    if(this.border=='none')
    {
	  this.tabpanel.css('border','none');
    }

	  this.tabpanel_tab_content.width(t_w);
    this.tabpanel_content.width(t_w);
	  this.tabpanel_content.height(t_h-this.tabpanel_tab_content.get(0).offsetHeight);
    
    this.update();

    for(var i=0; i<this.items.length; i++)
    {
	  this.items[i].notExecuteMoveSee = true;
      this.addTab(this.items[i]);
    }
    //activate tab
    if(this.active>=0)
      this.show(this.active, false);
  },
  //scroll left
  moveLeft : function(){
    if(this.scrollFinish)
    {
      this.disableScroll();
      this.scrollFinish = false;
      Fader.apply(this, new Array({
        element:this.tabpanel_mover,
        style:'marginLeft',
        num:this.tabWidth,
        maxMove:this.maxMove,
        onFinish : this.useableScroll
      }));
      this.run();
    }
  },
  //scroll right
  moveRight : function(){
    if(this.scrollFinish)
    {
      this.disableScroll();
      this.scrollFinish = false;
      Fader.apply(this, new Array({
        element:this.tabpanel_mover,
        style:'marginLeft',
        num:this.tabWidth*-1,
        maxMove:this.maxMove,
        onFinish : this.useableScroll
      }));
      this.run();
    }
  },
  //scroll to end of left side
  moveToLeft : function(){
    //no scroll button show
    if(this.scrolled && this.scrollFinish)
    {
      this.disableScroll();
      this.scrollFinish = false;
      var marginLeft = parseInt(this.tabpanel_mover.css('marginLeft'))*-1;
      Fader.apply(this, new Array({
        element : this.tabpanel_mover,
        style : 'marginLeft',
        num : marginLeft, 
        maxMove : this.maxMove,
        interval : 20,
		step : (marginLeft/10)<10?10:marginLeft/10,
        onFinish : this.useableScroll
      }));
      this.run();
    }
  },
  
  //scroll to end of left side
  moveToRight : function(){
    if(this.scrolled && this.scrollFinish)
    {
      this.disableScroll();
      this.scrollFinish = false;
      var marginLeft = parseInt(this.tabpanel_mover.css('marginLeft'))*-1;
      var liWidth = this.tabpanel_mover.children().length*this.tabWidth;
      var cWidth = this.tabpanel_move_content.width();
      var num = (liWidth - cWidth - marginLeft + this.fixNum)*-1;
      Fader.apply(this, new Array({
        element:this.tabpanel_mover,
        style:'marginLeft',
        num:num,
        maxMove:this.maxMove,
		step:(num*-1/10)<10?10:num*-1/10,
        onFinish : this.useableScroll
      }));
      this.run();
    }
  },
  
  //move to visible position/////////////////////////////////////////////////////////
  moveToSee : function(position){
    if(this.scrolled)
    {
      var liWhere = this.tabWidth * position;
      var ulWhere = parseInt(this.tabpanel_mover.css('marginLeft'));
      var moveNum;
      if(ulWhere<=0)
      {
        moveNum = (ulWhere + liWhere)*-1;
        if(((moveNum+ulWhere)*-1) >= this.maxMove)
          this.moveToRight();
        else
        {
          this.disableScroll();
          this.scrollFinish = false;
          Fader.apply(this, new Array({
            element:this.tabpanel_mover,
            style:'marginLeft',
            num:moveNum,
            maxMove:this.maxMove,
			step:(moveNum/10)<10?10:moveNum/10,
            onFinish : this.useableScroll
          }));
          this.run();
        }
      }
      else
      {
        moveNum = (liWhere - ulWhere) * -1;
        if((moveNum*-1) >= this.maxMove)
          this.moveToRight();
        else
        {
          this.disableScroll();
          this.scrollFinish = false;
          Fader.apply(this, new Array({
            element:this.tabpanel_mover,
            style:'marginLeft',
            num:moveNum,
            maxMove:this.maxMove,
            onFinish : this.useableScroll
          }));
          this.run();
        }
      }
    }
  },
  //disable scroll buttons
  disableScroll : function(){
    this.tabpanel_left_scroll.addClass('tabpanel_left_scroll_disabled');
    this.tabpanel_left_scroll.attr('disabled',true);
    this.tabpanel_right_scroll.addClass('tabpanel_right_scroll_disabled');
    this.tabpanel_right_scroll.attr('disabled', true);
  },
  
  //to determin whether we can still scroll
  useableScroll : function(){
    var tabEntity = this;
    if(this.scrolled)
    {
      //we came to the end of left side
      if(parseInt(tabEntity.tabpanel_mover.css('marginLeft')) == 0)
      {
        //disble left scroll button
        tabEntity.tabpanel_left_scroll.addClass('tabpanel_left_scroll_disabled');
        tabEntity.tabpanel_left_scroll.attr('disabled',true);
        //
        tabEntity.tabpanel_right_scroll.removeClass('tabpanel_right_scroll_disabled');
        tabEntity.tabpanel_right_scroll.removeAttr('disabled');
      }
      //we came to the end of right side
      else if(parseInt(tabEntity.tabpanel_mover.css('marginLeft'))*-1 == tabEntity.maxMove)
      {
        tabEntity.tabpanel_left_scroll.removeClass('tabpanel_left_scroll_disabled');
        tabEntity.tabpanel_left_scroll.removeAttr('disabled',true);
        tabEntity.tabpanel_right_scroll.addClass('tabpanel_right_scroll_disabled');
        tabEntity.tabpanel_right_scroll.attr('disabled');
      }
      else
      {
        tabEntity.tabpanel_left_scroll.removeClass('tabpanel_left_scroll_disabled');
        tabEntity.tabpanel_left_scroll.removeAttr('disabled',true);
        tabEntity.tabpanel_right_scroll.removeClass('tabpanel_right_scroll_disabled');
        tabEntity.tabpanel_right_scroll.removeAttr('disabled');
      }
    }
    
    tabEntity.scrollFinish = true;
  },
  //update style
  update : function(){
    var cWidth = this.tabpanel_tab_content.width();
    if(this.scrolled)
      cWidth -= (this.tabpanel_left_scroll.width()+this.tabpanel_right_scroll.width());
    this.tabpanel_move_content.width(cWidth);
    this.maxMove = (this.tabpanel_mover.children().length*this.tabWidth) - cWidth + this.fixNum;
  },
  //to show scroll button if needed.
  showScroll : function(){
    var liWidth = this.tabpanel_mover.children().length*this.tabWidth;
    var tabContentWidth = this.tabpanel_tab_content.width();
    if(liWidth > tabContentWidth && !this.scrolled){
      this.tabpanel_move_content.addClass('tabpanel_move_content_scroll');
      this.tabpanel_left_scroll.removeClass('display_none');
      this.tabpanel_right_scroll.removeClass('display_none');
      this.scrolled = true;
    }
    else if(liWidth < tabContentWidth && this.scrolled)
    {
	    this.moveToLeft();
      this.tabpanel_move_content.removeClass('tabpanel_move_content_scroll');
      this.tabpanel_left_scroll.addClass('display_none');
      this.tabpanel_right_scroll.addClass('display_none');
      this.scrolled = false;
	    this.scrollFinish = true;
    }
  },

  /**
   * @description {Method} addTab To add a new tab.
   * @param {Object} item Object for item profile.
   * @sample  //to add a new tab 
   * addTab({id:"newtabid", 
   *    title:"I am new" ,
   *    html:"some new message goes here", 
   *    closable: true, 
   *    disabled:false, 
   *    icon:"image/new.gif"
   * });   
   */
  addTab : function(tabitem){
	
    if(this.maxLength!=-1 && this.maxLength<=this.tabs.length){
	    return false;
    }
  
    tabitem.id = tabitem.id || Math.uuid();
    
    //if id exist, switch to that one
    if($('#'+tabitem.id).length>0)
    {
      this.show(tabitem.id, false);
    }
    else if(this.scrollFinish)
    {
      var tabEntity = this;
  
      var tab = $('<LI></LI>');
      tab.attr('id', tabitem.id);

      tab.appendTo(this.tabpanel_mover);
  
      var title = $('<DIV></DIV>');

      title.text(tabitem.title);
      title.appendTo(tab);

	    var wFix = tabitem.closable==false ? 0 : 5;
      if(tabitem.icon) {
        title.addClass('icon_title');
        title.css('background-image', 'url("'+tabitem.icon+'")');
        if(title.width()>(this.tabWidth-35-wFix)) {
          title.width((this.tabWidth-50-wFix));
          title.attr('title', tabitem.title);
          tab.append('<DIV>...</DIV>');
        }
      } else {
        title.addClass('title');
        if(title.width()>(this.tabWidth-19-wFix)) {
          title.width((this.tabWidth-30-wFix));
          title.attr('title', tabitem.title);
          tab.append('<DIV>...</DIV>');
        }
      }
      
      var closer = $('<DIV></DIV>');
      closer.addClass('closer');
      closer.attr('title', '关闭页签');
      closer.appendTo(tab);
      
      var content = $('<DIV></DIV>');
      content.addClass('html_content');
        //为了兼容IE6将高度100%修改为固定值
      if (navigator.userAgent.indexOf("MSIE 6.0") > 0)
          content.height(this.tabpanel_content.height());
      content.appendTo(this.tabpanel_content);
      /*
      var child_frame = content.find('iframe');
      
      if(child_frame.length==1)
      {
        child_frame.attr('id', tabitem.id+'Frame');
        child_frame.attr('name', tabitem.id+'Frame');
      }
      */
      var activedTabIndex = this.tabpanel_mover.children().index(this.tabpanel_mover.find('.active')[0]);
      
      if(activedTabIndex < 0)
        activedTabIndex = 0;
      if(this.tabs.length > activedTabIndex)
        tabitem.preTabId = this.tabs[activedTabIndex].id
      else
        tabitem.preTabId = '';
      tabitem.tab = tab;
      tabitem.title = title;
      tabitem.closer = closer;
      tabitem.content = content;
      tabitem.disable = tabitem.disable==undefined ? false : tabitem.disable;
      tabitem.closable = tabitem.closable==undefined ? true : tabitem.closable;      
      if(tabitem.closable==false)
        closer.addClass('display_none');
      
      if(tabitem.disabled==true) {
        tab.attr('disabled', true);
        title.addClass('.disabled');
      }
  
      this.tabs.push(tabitem);
      
      tab.bind('click', function(position){
        return function(){
          tabEntity.show(position, false);
        };
      }(this.tabs.length-1));
      

      closer.bind('click', function(position){
        return function(){
          tabEntity.kill(position);
        };
      }(this.tabs.length-1));
      
//      if(tabitem.closable)
//      {
        tab.bind('dblclick', function(position){
          return function(){
              tabEntity.refresh(position);
          };
        }(this.tabs.length-1));
//      }
      
      if(!tabitem.lazyload) {
        this.show(this.tabs.length-1, tabitem.notExecuteMoveSee);
      }
      
      this.showScroll();
      this.update();

      if(!tabitem.lazyload && !tabitem.notExecuteMoveSee) {
        this.moveToRight();
      }
    }
  },
  /**
   * @description {Method} getTabPosision To get tab index.
   * @param {String} id item id.
   * @return {Number} index of tab.
   */
  getTabPosision : function(tabId){
    if(typeof tabId == 'string')
    {
      for(var i=0; i<this.tabs.length; i++)
      {
        if(tabId == this.tabs[i].id)
        {
          tabId = i;
          break;
        }
      }
    }
    return tabId;
  },
  /**
   * @description {Method} refresh To refresh tab content.
   * @param {String} id item id.
   */
  refresh : function(position)
  {
    position = this.getTabPosision(position);
    if(typeof position == 'string')
      return false;
    else
    {
      //if IFRAME exists, refresh the sub frames
      var iframes = this.tabs[position].content.find('iframe');
      if(iframes.length>0)
      {
        var frameId = this.tabs[position].id+'_ifm';
        this.iterateFlush(window.frames[frameId]);
      }
    }
  },
  
  iterateFlush : function(iframeObj) {
    
    /*if(iframeObj.window.frames.length>0)
    {
      for(var i=0; i<iframeObj.window.frames.length; i++)
      {
        this.iterateFlush(iframeObj.window.frames[i]);
      }
    }
    else
    {*/
      if(iframeObj.document.forms.length>0)
      {
        for(var i=0; i<iframeObj.document.forms.length; i++)
        {
          try {
            iframeObj.document.forms[i].submit();
          }
          catch(e) {
            iframeObj.location.reload();
          }
        }
      }
      else
      {
        iframeObj.location.reload();
      }
    //}
  },
  show : function(position, notExecuteMoveSee){
    if(this.tabs.length<1)
      return false;
    position = this.getTabPosision(position);
    if(typeof position == 'string')
      position = 0;
    if(this.scrollFinish)
    {
      if(position >= this.tabs.length)
      {
        position = 0;
      }
      this.tabs[position].content.css('z-index', ++this.maxzindex);
      if(this.tabs[position].tab.hasClass('active'))
      {
        if(!notExecuteMoveSee)
        {
          this.moveToSee(position);
        }
      }
      else
      {
        //load those never loaded
        if(this.tabs[position].content.html()=='') {
            this.tabs[position].content.html(this.tabs[position].html);
        }
        this.tabpanel_mover.find('.active').removeClass('active');
        this.tabs[position].tab.addClass('active');
        if(!notExecuteMoveSee)
        {
          this.moveToSee(position);
        }
      }
    }
  },
  /**
   * @description {Method} kill To close tab.
   * @param {String} id item id.
   */
  kill : function(position){
  
    var tabEntity = this;
    //get tab index
    position = this.getTabPosision(position);
    
    var preTabId = this.tabs[position].preTabId;
    
    //detroy DOM
    this.tabs[position].closer.remove();
    this.tabs[position].title.remove();
    this.tabs[position].tab.remove();
    $("iframe:first", this.tabs[position].content).attr("src", "about:blank");
    this.tabs[position].content.remove();
    //remove from tabs 
    this.tabs.splice(position,1);
    
    //rebind event handler because index changed.
    for(var i=0 ; i<this.tabs.length; i++)
    {
      this.tabs[i].tab.unbind('click');
      this.tabs[i].tab.bind('click', function(i){
        return function(){
          tabEntity.show(i, false);
        };
      }(i));
      this.tabs[i].closer.unbind('click');
      this.tabs[i].closer.bind('click', function(i){
        return function(){
          tabEntity.kill(i);
        };
      }(i));
//      if(this.tabs[i].closable)
//      {
        this.tabs[i].tab.unbind('dblclick');
        this.tabs[i].tab.bind('dblclick', function(i){
          return function(){
              tabEntity.refresh(i);
          };
        }(i));
//      }
    }
    //update width
    this.update();
    //to scroll bar 
    this.showScroll();
    //show last 
    this.show(preTabId, false);
  },
/**
* @description {Method} kill To close all tab.
*/
kills: function () {
    var tabEntity = this;
    for (var i = this.tabs.length - 1; i >= 0; i--) {
        //var preTabId = this.tabs[i].preTabId;
        if (this.tabs[i].closable) {
            //detroy DOM
            this.tabs[i].closer.remove();
            this.tabs[i].title.remove();
            this.tabs[i].tab.remove();
            $("iframe:first", this.tabs[i].content).attr("src", "about:blank");
            this.tabs[i].content.remove();
            //remove from tabs 
            this.tabs.splice(i, 1);
        }
    }
    //update width
    this.update();
    //to scroll bar 
    this.showScroll();
},  
  /**
   * @description {Method} getTabsCount To get how many tabs are in the panel.
   * @return {Number} Number of tabs .
   */
  getTabsCount : function(){
    return this.tabs.length;
  },

  /**
   * @description {Method} setTitle To set tab title.
   * @param {String} id Item id.
   * @param {String} title Tab title.
   */
  setTitle : function(position,title){
    position = this.getTabPosision(position);
    if(position < this.tabs.length)
      this.tabs[position].title.text(title);
  },

  /**
   * @description {Method} getTitle To get tab title.
   * @param {String} id item id.
   */
  getTitle : function(position){
    position = this.getTabPosision(position);
    return this.tabs[position].title.text();
  },

  /**
   * @description {Method} setContent To set tab title.
   * @param {String} id Item id.
   * @param {String} title Tab inner html.
   */
  setContent : function(position,content){
    position = this.getTabPosision(position);
    if(position < this.tabs.length)
      this.tabs[position].content.html(content);
  },

  /**
   * @description {Method} getContent To get tab inner html.
   * @param {String} id item id.
   */
  getContent : function(position){
    position = this.getTabPosision(position);
    return this.tabs[position].content.html();
  },

  /**
   * @description {Method} setDisable To enable or disable tab.
   * @param {String} id Item id.
   * @param {Booleaan} True for disabled, false for enabled.
   */
  setDisable : function(position,disable){
    position = this.getTabPosision(position);
    if(position < this.tabs.length){
      this.tabs[position].disable = disable;
      if(disable){
        this.tabs[position].tab.attr('disabled',true);
        this.tabs[position].title.addClass('.disabled');
      }else{
        this.tabs[position].tab.removeAttr('disabled');
        this.tabs[position].title.removeClass('.disabled');
      }
    }
  },

  /**
   * @description {Method} getDisable To determine whether tab is disabled or not.
   * @param {String} id item id.
   */
  getDisable : function(position){
    position = this.getTabPosision(position);
    return this.tabs[position].disable;
  },

   /**
   * @description {Method} setClosable To enable or disable end user to close tab.
   * @param {String} id Item id.
   * @param {Booleaan} True for closable, false for not.
   */
  setClosable : function(position,closable){
    position = this.getTabPosision(position);
    if(position < this.tabs.length){
      this.tabs[position].closable = closable;
      if(closable){
        this.tabs[position].closer.addClass('display_none');
      }else{
        this.tabs[position].closer.addClass('closer');
        this.tabs[position].closer.removeClass('display_none');
      }
    }
  },

  /**
   * @description {Method} getClosable To determine whether tab is closable or not.
   * @param {String} id item id.
   */
  getClosable : function(position){
    position = this.getTabPosision(position);
    return this.tabs[position].closable;
  },
	
	/**
   * @description {Method} getActiveIndex To get index of active tab.
   * @return {Number} index of active tab.
   */
	getActiveIndex : function(){
		return this.tabpanel_mover.children().index(this.tabpanel_mover.find('.active')[0]);	
	},
  
  /**
   * @description {Method} getActiveTab To get active tab.
   * @return {Object} Profile of active tab.
   */
  getActiveTab : function(){
    var activeTabIndex = this.tabpanel_mover.children().index(this.tabpanel_mover.find('.active')[0]);
    if(this.tabs.length > activeTabIndex)
      return this.tabs[activeTabIndex];
    else
      return null;
  },
  resize : function(){
  	var hwFix = this.border == 'none' ? 0 : 2;

  	if(this.widthResizable) {
		
  	  this.width = this.render.width();
  	  this.tabpanel.width(this.width-hwFix);
  	  this.tabpanel_tab_content.width(this.width-hwFix);
  	  this.tabpanel_content.width(this.width-hwFix);
  	}
  	if(this.heightResizable) {
      this.height = this.render.height();
  	  this.tabpanel.height(this.height-hwFix);
  	  this.tabpanel_content.height(this.height - this.tabpanel_tab_content.get(0).offsetHeight);
  	}
  
  	this.showScroll();
  	this.useableScroll();
    this.update();
	
  	var entity = this;
  	setTimeout(function(){entity.moveToSee(entity.getActiveIndex());}, 200);
		
  },
  
  /**
   * @description {Method} setRenderWH To set width and height of the panel.
   * @param {Object} wh width and height.
   * @sample //To set tab height and width  
   * setRenderWH({width:'200px', height:'400px'});   
   */
  setRenderWH : function(wh) {
    if(wh) {
      if(wh.width!=undefined) {
        this.render.width(wh.width);
      }
      if(wh.height!=undefined) {
        this.render.height(wh.height);
      }
      this.resize();
    }
  }
};

/**附加对象
*@自动生成ID号
*/
Math.uuid = (function () {
    var $ = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
    return function (_, G) {
        var C = $, F = [], D = Math.random; G = G || C.length;
        if (_) {
            for (var B = 0; B < _; B++) F[B] = C[0 | D() * G]
        }
        else {
            var A = 0, E; F[8] = F[13] = F[18] = F[23] = "-"; F[14] = "4";
            for (B = 0; B < 36; B++)
                if (!F[B]) {
                    E = 0 | D() * 16; F[B] = C[(B == 19) ? (E & 3) | 8 : E & 15]
                }
            } 
            return F.join("")
        } 
    })();
    var randomUUID = Math.uuid

/**附加对象
*@自动调整页签
*/
Fader = function (config) {
  this.element = config.element;
  this.elementID = config.elementID;
  this.style = config.style;
  this.num = config.num;
  this.maxMove = config.maxMove;
  this.finishNum = "string";
  this.interval = config.interval || 10;
  this.step = config.step || 20;
  this.onFinish = config.onFinish;
  this.isFinish = false;
  this.timer = null;
  this.method = this.num >= 0;
  this.c = this.elementID ? $("#" + this.elementID) : this.element;
  this.run = function () {
    clearInterval(this.timer);
    this.fade();
    if (this.isFinish) {
      this.onFinish && this.onFinish();
    } else {
      var f = this;
      this.timer = setInterval(function () {
        f.run();
      }, this.interval);
    }
  };
  this.fade = function () {
    if (this.finishNum == "string") {
      this.finishNum = (parseInt(this.c.css(this.style)) || 0) + this.num;
    }
    var a = parseInt(this.c.css(this.style)) || 0;
    if (this.finishNum > a && this.method) {
      a += this.step;
      if (a >= 0) {
        this.finishNum = a = 0;
      }
    } else {
      if (this.finishNum < a && !this.method) {
        a -= this.step;
        if (a * -1 >= this.maxMove) {
          this.finishNum = a = this.maxMove * -1;
        }
      }
    }
    if (this.finishNum <= a && this.method || this.finishNum >= a && !this.method) {
      this.c.css(this.style, this.finishNum + "px");
      this.isFinish = true;
      this.finishNum = "string";
    } else {
      this.c.css(this.style, a + "px");
    }
  };
};

/* 遮罩层、操作项 */
var popupOption = new Object();
function popup(frame, title, content, target, position, width, height) {
    //有返回值给目标对像赋值并关闭窗口
    if (Object.prototype.toString.call(frame) === '[object Array]') {
        if (popupOption[frame[0]][1] != null && popupOption[frame[0]][2] != null) {
            popupOption[frame[0]][1].value = frame[1];
            popupOption[frame[0]][2].value = frame[2];
        }
        eval(eval(popupOption[frame[0]][3]));
        popupClose(popupOption[frame[0]][0]);
        return false;
    }
    var pop = frame.document.getElementById('popup');
    var opt = frame.document.getElementById('option');
    var msk = frame.document.getElementById('mask');

    var scrWidth = frame.self.scrollWidth || (frame.document.documentElement && frame.document.documentElement.scrollWidth) || frame.document.body.scrollWidth;
    var scrHeight = frame.self.scrollHeight || (frame.document.documentElement && frame.document.documentElement.scrollHeight) || frame.document.body.scrollHeight;
    var winWidth = frame.self.innerWidth || (frame.document.documentElement && frame.document.documentElement.clientWidth) || frame.document.body.clientWidth;
    var winHeight = frame.self.innerHeight || (frame.document.documentElement && frame.document.documentElement.clientHeight) || frame.document.body.clientHeight;
    var scrLeft = frame.self.scrollLeft || (frame.document.documentElement && frame.document.documentElement.scrollLeft) || frame.document.body.scrollLeft;
    var scrTop = frame.self.scrollTop || (frame.document.documentElement && frame.document.documentElement.scrollTop) || frame.document.body.scrollTop;
    var left = winWidth / 2;
    var top = winHeight / 2;
    //添加遮罩层
    if (!pop) {
        pop = frame.document.createElement("div");
        pop.id = "popup";
        pop.style.cssText = "position:absolute;top: 0px;left:0px;width: " + (scrWidth) + "px;height:" + (scrHeight) + "px;z-index: 1000005;background-color: gray;background: rgba(0,0,0,0.50);display: none;";
        frame.document.body.appendChild(pop);
        msk = frame.document.createElement("iframe");
        msk.id = "mask";
        msk.style.cssText = "position:absolute;width:64px;height:64px;left:" + (scrLeft + left) + "px;top:" + (scrTop + top) + "px;border:1px solid #7589A7;background-color:white";
        pop.appendChild(msk);
        opt = frame.document.createElement("div");
        opt.id = "option";
        pop.appendChild(opt);
    }
    //添加可操作项
    //设置窗口位置
    if (!title) {
        msk.style.cssText = "position:absolute;width:64px;height:64px;left:" + (scrLeft + left - 32) + "px;top:" + (scrTop + top - 32) + "px;border:1px solid #7589A7;background-color:white";
        opt.style.cssText = "position:absolute;width:64px;height:64px;left:" + (scrLeft + left - 32) + "px;top:" + (scrTop + top - 32) + "px;background-color:Transparent";
        opt.innerHTML = "<img src='" + parent.window.path + "/content/images/web/icon-loader.gif'>";
    }
    else {
        //设置窗口大小
        if (width == undefined) {
            width = 300;
        }
        else if (width == '100%') {
            width = winWidth;
        }
        if (height == undefined) {
            if (!target)
                height = 180;
            else
                height = 440;
        }
        else if (height == '100%') {
            height = winHeight;
        }
        //设置窗口位置
        var top = winHeight / 2 - height / 2;
        var left = winWidth / 2 - width / 2;
        switch (position) {
            case 1:
                top = 0;
                left = 0;
                break;
            case 2:
                top = 0;
                left = winWidth / 2 - width / 2;
                break;
            case 3:
                top = 0;
                left = winWidth - width - 2;
                break;
            case 4:
                top = winHeight / 2 - height / 2
                left = winWidth - width;
                break;
            case 5:
                top = winHeight - height;
                left = winWidth - width;
                break
            case 6:
                top = winHeight - height;
                left = winWidth / 2 - width / 2;
                break;
            case 7:
                top = winHeight - height;
                left = 0;
                break;
            case 8:
                top = winHeight / 2 - height / 2;
                left = 0;
                break;
        }
        msk.style.cssText = "position:absolute;width:" + width + "px;height:" + height + "px;left:" + (scrLeft + left) + "px;top:" + (scrTop + top) + "px;border:1px solid #7589A7;background-color:white";
        opt.style.cssText = "position:absolute;width:" + width + "px;height:" + height + "px;left:" + (scrLeft + left) + "px;top:" + (scrTop + top) + "px;border:1px solid #7589A7;background-color:white";
        var ttl = frame.document.createElement("div");
        ttl.style.cssText = "position:relative;height:24px;line-height:24px;padding-left:5px;background:url(" + parent.window.path + "/content/images/web/bgButton.png) bottom left repeat-x;border-bottom:1px solid #7589A7;font-size:12px;";
        ttl.innerHTML = title;
        opt.appendChild(ttl);
        var img = frame.document.createElement("img");
        img.src = parent.window.path + "/content/images/web/icon16close.png";
        img.style.cssText = "position:absolute;top:5px;right:3px;cursor:pointer;";
        img.onclick = function () { popupClose(frame) };
        ttl.appendChild(img);

        if (target == undefined || target == null) {
            var div = frame.document.createElement("div");
            div.style.cssText = "overflow:auto;height:" + (height - 28) + "px";
            div.innerHTML = content;
            opt.appendChild(div);
        }
        else {
            var ifm = frame.document.createElement("iframe");
            ifm.width = width;
            ifm.height = (height - 28);
            ifm.frameBorder = 0;
            ifm.src = content + "?frm=" + frame.name;
            if (target != '') {
                if (target[0] != null && target[1] != null) {
                    objVal = frame.document.getElementById(target[0]);
                    objTxt = frame.document.getElementById(target[1]);
                    ifm.src += "&val=" + objVal.value;
                    popupOption[frame.name] = [frame, objVal, objTxt, target[2] || ''];
                }
                else {
                    popupOption[frame.name] = [frame, null, null, target[2] || ''];
                }
            }
            opt.appendChild(ifm);
        }
    }
    //显示遮罩层
    pop.style.display = "";
}
function popupClose(frame) {
    if (frame.document.getElementById('popup')) {
        frame.document.getElementById('popup').style.display = "none";
        frame.document.getElementById('option').innerHTML = "";
    }
}
//WEB打印**frame为调用页面iframe窗口对象；val为打印内容容器ID或url
function printf(frame, val) {
    var ifm = frame.document.createElement("iframe");
    ifm.style.cssText = "position:absolute;width:0px;height:0px;left:-500px;top:-500px;";
    frame.document.body.appendChild(ifm);
    var obj = frame.document.getElementById(val);
    if (obj) {
        var doc = ifm.contentWindow.document;
        doc.write(obj.innerHTML);
        doc.close();
    }
    else {
        ifm.src = val;
    }
    setTimeout(function () {
        ifm.contentWindow.focus();
        ifm.contentWindow.print();
        ifm.src = "about:blank";
        frame.document.body.removeChild(ifm);
    }, 2000);
}
//表单验证(返回false或data）
function onForm(frame, id) {
    var fields = frame.document.getElementById(id).querySelectorAll('input,textarea,select');
    for (var i = 0; i < fields.length; i++) {
        if (fields[i].hasAttribute('required') && fields[i].value == '') {
            fields[i].focus();
            tip(frame, fields[i], '请填写此字段。');
            return false;
        }
        var type = fields[i].hasAttribute('number') ? 'number' : fields[i].hasAttribute('tel') ? 'tel' : fields[i].getAttribute('type');
        if (type && fields[i].value != '') {
            switch (type) {
                case 'number':
                    if (!/^(-?\d+)(\.\d+)?$/.test(fields[i].value)) {
                        fields[i].focus();
                        tip(frame, fields[i], '请填写有效的数字。');
                        return false;
                    }
                    break;
                case 'date':
                    if (!/^((?:19|20)\d\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])$/.test(fields[i].value)) {
                        fields[i].focus();
                        tip(frame, fields[i], '请填写有效的日期（如：2017-9-1）。');
                        return false;
                    }
                    break;
                case 'datetime':
                    if (!/^((?:19|20)\d\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])\s([0-1]?\d{1}|[2]{1}[0-3]{1}):([0-5]?\d{1}):([0-5]?\d{1})$/.test(fields[i].value)) {
                        fields[i].focus();
                        tip(frame, fields[i], '请填写有效的日期时间（如：2017-9-1 13:01:59）。');
                        return false;
                    }
                    break;
                case 'tel':
                    var tel = /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/;
                    var mobile = /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0-9]|170)\d{8}$/;
                    if (!(tel.test(fields[i].value) || (fields[i].value.length == 11 && mobile.test(fields[i].value)))) {
                        fields[i].focus();
                        tip(frame, fields[i], '请填写有效的电话号码。');
                        return false;
                    }
                    break;
            }
        }
    }
    return true;
}
function tip(frame, elem, msg) {
    var tip = frame.document.createElement("div");
    tip.style.cssText = 'position: absolute;top: ' + (pageY(elem) + elem.offsetHeight + 7) + 'px;left:' + pageX(elem) + 'px;max-width:280px;box-sizing:content-box;border:1px solid #A9B7C7;border-radius: 5px;padding: 10px;background-color: #FBFBFB;font-size: 14px;line-height:150%;';
    tip.innerHTML = '<span style="position: absolute;top:-10px;color: #A9B7C7;font-family:SimSun;font-size: 14px;"><b style="position: absolute;color:#A9B7C7;z-index: 1;">◆</b><b style="position: absolute;color:#FBFBFB;z-index: 2;top:1px;">◆</b></span>';
    tip.innerHTML += '<div style="display: inline-block;background-color: #FAAB20;color: white;font-family:SimHei;font-size: 15px;font-weight: bold;width: 18px;height: 18px;border-radius: 2px;text-align: center;margin-right: 5px;">!</div>';
    tip.innerHTML += msg;
    frame.document.body.appendChild(tip);
    setTimeout(function () {
        if (tip)
            frame.document.body.removeChild(tip);
    }, 5000);
}
function pageX(elem) {
    return elem.offsetParent ? (elem.offsetLeft + pageX(elem.offsetParent)) : elem.offsetLeft;
}
function pageY(elem) {
    return elem.offsetParent ? (elem.offsetTop + pageY(elem.offsetParent)) : elem.offsetTop;
}