Ext.ns('Ext.training');

var courseStore = new Ext.data.SimpleStore({
    fields: ['title', 'courseid'],
    data : [['Ext JSオンラインセミナー', 'trial']]
});

var defaultCourse = 'trial';

Ext.training.Site = function() {

    Ext.QuickTips.init();
	Ext.training.Site.superclass.constructor.call(this, {
		layout: 'border',
		items: [{
			region: 'north',
			id: 'ext-training-header',
			height: 44,
			border: false,
			html: '<a href="http://www.extjs.co.jp/" id="ext-logo">Ext JS オンラインセミナー</a>'
		},{
			region: 'west',
			autoScroll: true,
			id: 'moduleTree',
			xtype: 'treepanel',
			plugins: [
                new Ext.ux.TreeOutliner({
				    outlineStyle: [
                        Ext.ux.TreeOutlineFormats.roman,
                        Ext.ux.TreeOutlineFormats.numeric
                    ],
				    delimiter: '. '
			    })
            ],
			split: true,
			width: 250,
			rootVisible: false,
			root: new Ext.tree.AsyncTreeNode(),
			loader: new Ext.tree.TreeLoader({url: 'slide-tree.'+defaultCourse+'.json'}),
			bbar: [{
                tooltip: 'すべて展開する',
                iconCls: 'tree-expand',
                handler: function() {
                    Ext.getCmp('moduleTree').expandAll()
                }
            }, '-', {
                tooltip: 'すべて折り畳む',
                iconCls: 'tree-collapse',
                handler: function() {
                    Ext.getCmp('moduleTree').collapseAll()
                }
            }, '-', {
                xtype: 'combo',
                id: 'course',
                store: courseStore,
                displayField: 'title',
                valueField: 'courseid',
                mode: 'local',
                triggerAction: 'all',
                selectOnFocus: true,
                value: defaultCourse,
                listeners: {
                    select: function(c,r,i){
                        var tree = Ext.getCmp('moduleTree');
                        tree.getLoader().url = 'slide-tree.'+r.data.courseid+'.json';
                        tree.getRootNode().reload();
                    }
                }
            }]
		},{
			region: 'center',
			id: 'content',
			autoScroll: true,
			autoLoad: 'SplashPage.html',
			bbar: [{
                tooltip: 'オプション表示',
                iconCls: 'options',
                menu: {
                    id: 'options-menu',
                    items: [{
                        text: '文字サイズ - 拡大',
                        iconCls: 'font-inc',
                        handler: this.changeSize.createDelegate(this, [2]),
                        hideOnClick: false
                    },{
                        text: '文字サイズ - 縮小',
                        iconCls: 'font-dec',
                        handler: this.changeSize.createDelegate(this, [-2]),
                        hideOnClick: false
                    },{
                        text: '文字サイズ - リセット',
                        iconCls: 'font-reset',
                        handler: this.resetSize.createDelegate(this)
                    }, '-', {
                        id: 'toggle',
                        text: 'スライド最大化',
                        iconCls: 'screen-maximize',
                        handler: this.toggleFullScreen
                    }]
                }
            },{
				id: 'launchExampleBtn',
				text: 'サンプル実行',
				icon: 'images/icons/eye.png',
				cls: 'x-btn-text-icon',
				disabled: true,
				handler: this.launchExample,
				scope: this
			}, '->', {
                iconCls: 'nav-prev',
                disabled: true,
                id: 'prevBtn',
                handler: this.navigate.createDelegate(this, [-1])
            },{
                iconCls: 'nav-next',
                disabled: true,
                id: 'nextBtn',
                handler: this.navigate.createDelegate(this, [1])
            }]
		}]
	});
	var moduleSm = Ext.getCmp('moduleTree').getSelectionModel();
	moduleSm.on('selectionchange', this.onSelectionChange, this, {buffer: 100});
};

Ext.extend(Ext.training.Site, Ext.Viewport, {

    afterRender : function() {

        Ext.training.Site.superclass.afterRender.call( this );



/*
        var moduleSm = Ext.getCmp('moduleTree').getSelectionModel();
        Ext.getCmp('moduleTree').selModel.onKeyDown = function() {
            console.debug(this.nav);
        }
*/
    	this.nav = new Ext.KeyMap( Ext.getDoc(), {
    		key: [ Ext.EventObject.RIGHT, Ext.EventObject.LEFT ],
    		handler: function( k, e ) {
                if( k === Ext.EventObject.RIGHT ) {
                    this.navigate( 1 );
                } else if( k == Ext.EventObject.LEFT ) {
                    this.navigate( -1 );
                }
    		},
            scope: this,
    		stopEvent: true
    	});
    },

	onSelectionChange : function(sm, node) {

        // プレゼンテーションボイス（解説）初期化
//        var t = Ext.getCmp('pvoice');
//        t.setIconClass('pvoice-show');
//        t.setText('解説表示');
//        t.pvoice = undefined;

		var content = Ext.getCmp('content');
		var depth = node.getDepth();
		if (depth === 1) {
			if (!node.expanded) {
				node.expand(null, null, function(){
					sm.selectNext();
				});
			}else{
				sm.selectNext();
			}
		} else if (depth === 2) {
			var idx = node.parentNode.indexOf(node);
			var pageNum = idx + 1;
			var folderName = node.parentNode.attributes.folder;
			var page = String.format('{0}/{1}{2}', folderName, node.attributes.filename, '?'+(new Date()).format('u'));
			content.load({
                url: page,
								scripts: true,
                callback: function() {

/*                    if( Ext.getCmp('pvoice').pvoice ) {
                        this.togglePVoice( false );
                    }
*/
                },
                scope: this
            });

			var mth = node.attributes.exampleUrl ? 'enable' : 'disable';
			Ext.getCmp('launchExampleBtn')[mth]();
			var prevStatus = idx ? 'enable' : 'disable';
			Ext.getCmp('prevBtn')[prevStatus]();
			Ext.getCmp('nextBtn').enable();
		}
	},

	navigate : function(delta) {
		var moduleSm = Ext.getCmp('moduleTree').getSelectionModel();
		if (delta > 0) {
			moduleSm.selectNext();
		}else{
			moduleSm.selectPrevious();
		}
	},

    toggleFullScreen: function() {
        var method = this.fullScreen ? 'show' : 'hide';
        Ext.getCmp('moduleTree')[method]();
        Ext.getCmp('ext-training-header')[method]();
        Ext.getCmp('moduleTree').ownerCt.doLayout();
        var t = Ext.getCmp('toggle');
        t.setIconClass(this.fullScreen ? 'screen-maximize' : 'screen-restore');
        t.setText(this.fullScreen ? 'スライド最大化' : 'スライドを元に戻す');
        this.fullScreen = !this.fullScreen;
    },

    togglePVoice : function( reverse ) {

        var method = this.pvoice ? 'show' : 'hide';

        var divs = document.getElementsByTagName( "div" );

        for(divnum in divs) {

            if( !divs[ divnum ] )
                continue;

            var classNames = divs[ divnum ].className;
            var bExists = false;
            if( typeof( classNames ) == 'string' ) {

                var arrCls = classNames.split( ' ' );

                for( var i=0; i<arrCls.length; i++ ) {
                    if(
                        arrCls[ i ] == 'pvoice-area-show' ||
                        arrCls[ i ] == 'pvoice-area-hide'
                    ) {
                        bExists = true;
                        break;
                    }
                }

                if( divs[ divnum ] ) {
                    var el = new Ext.Element( divs[ divnum ] );
                }

                if( bExists ) {
                    el.addClass( 'pvoice-area-' + ( ( method == 'hide' ) ? 'show' : 'hide' ) );
                    el.removeClass( 'pvoice-area-' + method );
                }
            }
        }

        if( reverse !== false ) {
/*
            var t = Ext.getCmp('pvoice');
            t.setIconClass(this.pvoice ? 'pvoice-show' : 'pvoice-hide');
            t.setText(this.pvoice ? '解説表示':'解説非表示');
*/
            this.pvoice = !this.pvoice;
        }

    },

    changeSize : function(val) {
        var rule = Ext.util.CSS.getRule('#content', true);
        var size = parseInt(rule.style.getPropertyValue('font-size'));
        if(!this.fontSize){
            this.fontSize = size;
        }
        Ext.util.CSS.updateRule('#content', 'fontSize', size + val + 'px');
    },

    resetSize : function(){
        Ext.util.CSS.updateRule('#content', 'fontSize', (this.fontSize || 14) + 'px');
    },
	launchExample: function() {
		var sm = Ext.getCmp('moduleTree').getSelectionModel();
		var n = sm.getSelectedNode();
		window.open(n.attributes.exampleUrl);
	}
});

