// Change Language
var tabs;
var open_tabs = {};

function changeLanguage(v){
    ajaxCall('index_action.php?task=changeLanguage', 'form1');
}

// change labor union
function changeUnion(v){
    ajaxCall('index_action.php?task=changeUnion', 'form1');
}

function changeUnionSubmit(url,name,pw,change_url){
  	document.form1.method = "post";   
	document.form1.action = url;     
	document.form1.user_name.value = name;     
	document.form1.user_pass.value = pw;     
	document.form1.change_url.value = change_url;     
//	document.forms[0].language_id = language;     
//  	document.forms[0].submit();    
//	ajaxCall('login_action.php?task=login', 'form1');
	ajaxCall(url, 'form1');
}
// refresh center panel
function refreshPage(){
    //Ext.get('center-iframe').dom.src = Ext.get('center-iframe').dom.src;
    /*bg_module = getCookie('bg_module');
     url = Ext.get(bg_module).dom.name;
     iframe = Ext.get('iframe-'+url).dom;
     iframe.src=iframe.src;*/
    top.location = top.location.href.split('#')[0];
}

function loadPage(){
    loadCenterPage('H02'); // Load home
    var bg_module = getCookie('bg_module') || 'H02';
    if (bg_module != 'H02') 
        loadCenterPage(bg_module);
}

// load center page
function loadCenterPage(id,params){
    current = Ext.get(id);
    if (!current || !current.dom) {
        id = 'H02';
        current = Ext.get(id);
    }
    
    url = current.dom.name;
    if( params ){
    	// create a timestamp to avoid cache
    	var now = new Date();
		var temp = now.getTime();
		var temp = temp.toString().substr(0,10);
		
    	sep=window.location.href.indexOf("?")>-1?"&":"?";    	
    	url=url+sep+params+'&tmp='+temp;
    }
    title = current.dom.title;
    
    top.Ext.get('loading').show();
    
    var n = centerPanel.getComponent('tab' + id);
    if (!n) {
        iconImage = '<img class="x-menu-item-icon" src="' + web_path + '/images/module/' + moduleIcon[id] + '"/>';//icon ? '<img class="x-menu-item-icon" src="'+icon+'"/>' : '';
        n = centerPanel.add({
            'id': 'tab' + id,
            'title': iconImage + title || id,
            closable: (id != 'H02'),
            html: '<iframe scrolling="auto" frameborder="0" width="100%" height="100%" src="' + url + '" id="iframe-' + id + '"></iframe>'
        });
    }
    else {
        iframe = Ext.get('iframe-' + id).dom;
        if (iframe) 
            iframe.src = url;//iframe.src;
    }
    //alert('<iframe scrolling="auto" frameborder="0" width="100%" height="100%" src="'+url+'" id="iframe-'+id+'"></iframe>');
    centerPanel.setActiveTab(n);
    //if (id!='H02') setCookie('bg_module', id);
    var tmp = Ext.get('tab' + id).child('.x-panel-bwrap');
    if (tmp) 
        tmp.dom.style.display = 'block';
    //if(Ext.isIE7) document.getElementById('iframe-'+id).height = centerPanel.getInnerHeight();
    centerPanel.on('resize', function(){
        if (document.getElementById('iframe-' + id)) 
            document.getElementById('iframe-' + id).height = centerPanel.getInnerHeight();
    });
    centerPanel.fireEvent('resize');
    viewport.doLayout(true);
}

function expandMenu(id){
    var obj = viewPanel[id];
    for (var i = 1; i < viewPanel.length; i++) {
        if (i != id) 
            viewPanel[i].collapse();
    }
    setCookie('viewPanel', id);
}

function collapseMenu(id){
    if (getCookie('viewPanel') == id) {
        setCookie('viewPanel', 0);
    }
}

var MyTab = Ext.extend(Ext.TabPanel, {
    autoScrollTabs: function(){
        this.pos = this.tabPosition == 'bottom' ? this.footer : this.header;
        var count = this.items.length;
        var ow = this.pos.dom.offsetWidth;
        var tw = this.pos.dom.clientWidth;
        
        var wrap = this.stripWrap;
        var wd = wrap.dom;
        var cw = wd.offsetWidth;
        var pos = this.getScrollPos();
        var l = this.edge.getOffsetsTo(this.stripWrap)[0] + pos;
        
        if (!this.enableTabScroll || count < 1 || cw < 20) { // 20 to prevent display:none issues
            return;
        }
        if (l <= tw) {
            wd.scrollLeft = 0;
            wrap.setWidth(tw);
            if (this.scrolling) {
                this.scrolling = false;
                this.pos.removeClass('x-tab-scrolling');
                this.scrollLeft.hide();
                this.scrollRight.hide();
                if (Ext.isAir) {
                    wd.style.marginLeft = '';
                    wd.style.marginRight = '';
                }
            }
        }
        else {
            if (!this.scrolling) {
                this.pos.addClass('x-tab-scrolling');
                if (Ext.isAir) {
                    wd.style.marginLeft = '18px';
                    wd.style.marginRight = '18px';
                }
            }
            tw -= wrap.getMargins('lr');
            wrap.setWidth(tw > 20 ? tw : 20);
            if (!this.scrolling) {
                if (!this.scrollLeft) {
                    this.createScrollers();
                }
                else {
                    this.scrollLeft.show();
                    this.scrollRight.show();
                }
            }
            this.scrolling = true;
            if (pos > (l - tw)) { // ensure it stays within bounds
                wd.scrollLeft = l - tw;
            }
            else { // otherwise, make sure the active tab is still visible
                this.scrollToTab(this.activeTab, false);
            }
            this.updateScrollButtons();
        }
    },
    
    createScrollers: function(){
        this.pos = this.tabPosition == 'bottom' ? this.footer : this.header;
        var h = this.stripWrap.dom.offsetHeight;
        
        // left
        var sl = this.pos.insertFirst({
            cls: 'x-tab-scroller-left'
        });
        sl.setHeight(h);
        sl.addClassOnOver('x-tab-scroller-left-over');
        this.leftRepeater = new Ext.util.ClickRepeater(sl, {
            interval: this.scrollRepeatInterval,
            handler: this.onScrollLeft,
            scope: this
        });
        this.scrollLeft = sl;
        
        // right
        var sr = this.pos.insertFirst({
            cls: 'x-tab-scroller-right'
        });
        sr.setHeight(h);
        sr.addClassOnOver('x-tab-scroller-right-over');
        this.rightRepeater = new Ext.util.ClickRepeater(sr, {
            interval: this.scrollRepeatInterval,
            handler: this.onScrollRight,
            scope: this
        });
        this.scrollRight = sr;
    }
});

Ext.example = function(){
    var msgCt;
    
    function createBox(t, s){
        return ['<div class="msg">', '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>', '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><div class="ext-mb-icon box_msg"/><!--<h3>', t, '</h3>-->', s, '</div></div></div></div>', '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>', '</div>'].join('');
    }
    return {
        msg: function(title, format,second){
            if (!msgCt) {
                msgCt = Ext.DomHelper.insertFirst(document.body, {
                    id: 'msg-div'
                }, true);
            }
            msgCt.alignTo(document, 'c-c',[0,-50]);
            var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
            var m = Ext.DomHelper.append(msgCt, {
                html: createBox(title, s)
            }, true);
            m.slideIn('c').pause(second?second:2).fadeOut({duration:0.5,remove:true});
        },
        
        init: function(){
        }
    };
}();

function popupMsg(t, s,second){
    Ext.example.msg(t, s,second);
}

Ext.ux.TabCloseMenu = function(){
    var menu, ctxItem;
    this.init = function(tp){
        tp.on('contextmenu', onContextMenu);
    }
    
    function onContextMenu(ts, item, e){
        if (!menu) { // create context menu on first right click
            menu = new Ext.menu.Menu([{
                id: centerPanel.id + '-close',
                text: 'Close Tab',
                handler: function(){
                    centerPanel.remove(ctxItem);
                }
            }, {
                id: centerPanel.id + '-close-others',
                text: 'Close Other Tabs',
                handler: function(){
                    centerPanel.items.each(function(item){
                        if (item.closable && item != ctxItem) {
                            centerPanel.remove(item);
                        }
                    });
                }
            }, {
                id: centerPanel.id + '-refresh-current',
                text: 'Refresh Current Tab',
                handler: function(){
                    module = ctxItem.id.replace('tab', 'iframe-');
                    iframe = document.getElementById(module);
                    if (iframe) 
                        iframe.src = iframe.src;
                }
            }]);
        }
        ctxItem = item;
        var items = menu.items;
        items.get(centerPanel.id + '-close').setDisabled(!item.closable);
        var disableOthers = true;
        centerPanel.items.each(function(){
            if (this != item && this.closable) {
                disableOthers = false;
                return false;
            }
        });
        items.get(centerPanel.id + '-close-others').setDisabled(disableOthers);
        menu.showAt(e.getPoint());
    }
};

Ext.onReady(Ext.example.init, Ext.example);

//show backend help
var help_win;
Ext.EventManager.on(window, "load", function(){
    //when help dialog show or first loaded module menu treeLoad.loaded callback function
    var fnHelpNodeExpand = function(){
        /****/
        var helpTabId = centerPanel.getActiveTab().id;
        var helpModuleId = "module_" + helpTabId.substr(3, 1) + "00";
        var helpId = "help_" + helpTabId.substr(3, 3);
        if (Ext.getCmp("trHelp") && Ext.getCmp("trHelp").getNodeById(helpModuleId)) {
            Ext.getCmp("trHelp").getNodeById(helpModuleId).select();
            Ext.getCmp("trHelp").getNodeById(helpModuleId).expand();
            
        }
        if (Ext.getCmp("trHelp") && Ext.getCmp("trHelp").getNodeById(helpId)) {
            Ext.getCmp("trHelp").getNodeById(helpId).select();
            Ext.getCmp("trHelp").getNodeById(helpId).expand();
            storeHelpContent.baseParams = {
                pno: helpId
            };
            storeHelpContent.load();
        }
    };

	 //show video
    fnWatchVideo = function(url,title){
        if (url) {
            var help_video_url = help_url + url;
            
            tabPanelHelp.add({
                id: "video_" + url.replace(".", "_"),
                title: title,
                closable: true,
				autoDestroy:true,
                border: true,
				iconCls:'video-icon',
                html: "<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.Macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0'  width='100%' height='99%'>												            <param name='movie' value='" + help_url + url + "' /><param name='quality' value='high' /><param name='bgcolor' value='#FFFFFF' />												            <!--[if !IE]><-->												                <object data='" + help_url + url + "' width='100%' height='99%' type='application/x-shockwave-flash'>												                    <param name='quality' value='high' /><param name='bgcolor' value='#FFFFFF' /><param name='pluginurl' value='http://www.Macromedia.com/go/getflashplayer' />FAIL (the brower should render some flash content, not this)												                </object>												            <!--><![endif]>												        </object>"
            })
            tabPanelHelp.setActiveTab("video_" + url.replace(".", "_"));
            var tmp = Ext.get("video_" + url.replace(".", "_")).child('.x-panel-bwrap');
            if (tmp) 
                tmp.dom.style.display = 'block';
        }
        else {
            alert('no video');
        }
    };
    var trHelp = new Ext.tree.TreePanel({
        id: "trHelp",
        region: 'west',
        header: false,
        titleCollapse: true,
        width: 200,
        minSize: 175,
        maxSize: 600,
        
        collapsible: true,
        
        rootVisible: false,
        autoScroll: true,
        animate: true,
        split: true,
        
        root: new Ext.tree.AsyncTreeNode({
            text: 'Root',
            draggable: false,
            id: 'trHelpRoot'
        }),
        loader: new Ext.tree.TreeLoader({
            dataUrl: "menu/help_menu.php",
            listeners: {
                "load": function(cur, node, res){ //when loaded and current activie module panel,continue expand to leaf
                    var helpTabId = centerPanel.getActiveTab().id;
                    var helpModuleId = "module_" + helpTabId.substr(3, 1) + "00";
                    var helpId = "help_" + helpTabId.substr(3, 3);
                    if (node.id == Ext.getCmp("trHelp").getRootNode().id || node.id == helpModuleId || node.id == helpId) {
                        fnHelpNodeExpand();
                    }
                }
            }
        }),
        tbar: [{
            text: '',
            iconCls: 'expand-all-icon',
            listeners: {
                'click': function(){
                    if (this.iconCls == 'expand-all-icon') {
                        trHelp.expandAll(true);
                        this.setIconClass("collapse-all-icon");
                    }
                    else {
                        trHelp.collapseAll(true);
                        this.setIconClass("expand-all-icon");
                    }
                }
            }
        }, {
            text: '',
            iconCls: 'x-tool x-tool-toggle x-tool-collapse-west toggle-icon',
            listeners: {
                'click': function(){
                    trHelp.toggleCollapse(true);
                }
            }
        }],
        listeners: {
            "click": function(node, e){
                if (!node) 
                    return;
                
                if (node.id.indexOf("module_") == 0) { //parent module ,then expand
                    node.expand();
                }
                else 
                    if (node.id.indexOf("help_") == 0) {
                        //node.select();
                        node.expand();
                        storeHelpContent.baseParams = {
                            pno: node.id
                        };
                        storeHelpContent.load();
                        tabPanelHelp.setActiveTab("helpwelcome");
                        var tmp = Ext.get('helpwelcome').child('.x-panel-bwrap');
                        if (tmp) 
                            tmp.dom.style.display = 'block'
                        
                    }
                    else {
                        if (storeHelpContent.baseParams['pno'] != node.parentNode.id) { //if click from another parent node to this,then load content first
                            storeHelpContent.baseParams = {
                                pno: node.parentNode.id
                            };
                            storeHelpContent.load({
								callback:function(r,opt,isSuccess){
									if(isSuccess){
										return false;
									}
									var iScrollTop=Ext.get("help_" + node.id).getY()-Ext.get("helpwelcome").getY()- 5;  //get offset top
									if(iScrollTop>0){
										Ext.getCmp('helpwelcome').body.scroll('bottom',iScrollTop,true)  //scrol to the help item
									}else{
										Ext.getCmp('helpwelcome').body.scroll('top',-iScrollTop,true)
									}
								}
							});
                        }else{
							var iScrollTop=Ext.get("help_" + node.id).getY()-Ext.get("helpwelcome").getY()- 5;  //get offset top
							if(iScrollTop>0){
								Ext.getCmp('helpwelcome').body.scroll('bottom',iScrollTop,true)  //scrol to the help item
							}else{
								Ext.getCmp('helpwelcome').body.scroll('top',-iScrollTop,true)
							}
						}
                       
					   
                        return false;                        
                    }
            }
        }
    });
    var storeHelpContent = new Ext.data.Store({
        overClass: 'x-view-over',
        autoLoad: false,
        proxy: new Ext.data.ScriptTagProxy({
            url: 'menu/help_menu.php?node=contents'
        }),
        reader: new Ext.data.JsonReader({
            root: 'results',
            fields: ['video', 'permission_no', 'language_id', 'helps_id', 'subject', 'content']
        })
    });
    
    var pnlHelpWelcome = new Ext.Panel({
        id: "helpwelcome",
        title: help,
        autoScroll: true,
		iconCls:'help-icon',
        items: new Ext.DataView({
            tpl: new Ext.XTemplate('<tpl for=".">', '<div class="search-item" id="help_content_{helps_id}">', '<div class="help_title"><h3><span>{subject}</span>&nbsp;&nbsp;    {video}</div>', '<div class="help_content">{content}</div>', '</div></tpl>'),
            store: storeHelpContent,
            itemSelector: 'div.search-item'
        })
    });
    var tabPanelHelp = new MyTab({
        region: 'center',
        id: 'east-tabPanel-help',
        width: 'auto',
        height: 'auto',
        tabPosition: 'bottom',
        activeTab: "helpwelcome",
        baseCls: "x-panel-body",
        items: [pnlHelpWelcome]
    });
    
    
    help_win = new Ext.Window({
        layout: 'border',
		modal:true,
        width: 900,
        height: 500,
        closeAction: 'hide',
        collapsible: true,
        maximizable: true,
        items: [trHelp, tabPanelHelp]
    });
    help_win.on('show', fnHelpNodeExpand);
    Ext.get('top_help').on('click', function(){
        help_win.show(this);
    });
});
Ext.EventManager.on(window, 'unload', function(){
    var id = centerPanel.getActiveTab().id.replace('tab', '');
    setCookie('bg_module', id);
});
