/**
 * @author Tyler
 */

PagePanel = function(config){
	Ext.apply(this, config);
	var tbar = this.constructTbar();
	PagePanel.superclass.constructor.call(this, {
        id:'page-panel',
        title:'Pages',
		iconCls: 'page-panel-icon',
		border: false,
		autoScroll:true,
        rootVisible:false,
		lines:false,
        animCollapse:false,
        animate: false,
        loader: new Ext.tree.TreeLoader({dataUrl: this.url}),
        root: new Ext.tree.AsyncTreeNode({
	        text: 'Price Book', 
	        draggable:false,
	        id:'source'
	    }),
        collapseFirst:false,
        tbar: tbar  
    });

	this.root.expand(false, false, this.rootCallback);
	
	this.getSelectionModel().on({
		'selectionchange' : function(sm, node){
			if(node){
				if(node.isLeaf()){
					this.fireEvent('pageselect', node.attributes, this.pageType);
					this.selectedNode = node;
				}
			}
		},
		scope:this
	});
	
	this.addEvents({pageselect: true});
	
	this.on('contextmenu', this.onContextMenu, this);
}

Ext.extend(PagePanel, Ext.tree.TreePanel, {
	pageType: 'PricePage',
	contextNode: null,
	rootCallback: null,
	constructTbar: function(){
		return [{
	        id:'bt-previous', 
	        iconCls: 'icon-previous',
	        tooltip:{title: 'Previous Page', text: 'Go to the previous page.'}, 
	        cls: 'x-btn-icon', 
	        handler: this.prevPage,
	        scope: this
	    },'-',{
	        id:'bt-next', 
	        iconCls: 'icon-next',
	        tooltip:{title: 'Next Page', text: 'Go to the next page.'},
	        cls: 'x-btn-icon', 
	        handler: this.nextPage,
	        scope: this
	    }];
	},
	nextPage : function(){
		var sm = this.selModel;
		if(this.selectedNode){
			if(this.selectedNode.nextSibling){
				sm.select(this.selectedNode.nextSibling);
			} else {
				var p = this.selectedNode.parentNode;
				if(p.nextSibling){
					p.nextSibling.expand(false, false, function(){
						sm.select(p.nextSibling.firstChild);
					});
				}
			}
		} else {
			this.root.firstChild.expand(false, false, function(node){
				sm.select(node.firstChild);
			});
			
		}
	},
	prevPage : function(){
		var sm = this.selModel;
		if(this.selectedNode){
			if(this.selectedNode.previousSibling){
				sm.select(this.selectedNode.previousSibling);
			} else {
				var p = this.selectedNode.parentNode;
				if(p.previousSibling){
					p.previousSibling.expand(false, false, function(node){
						sm.select(node.lastChild);
					});
				}
			}
		}
	},
	onContextMenu : function(node, e){
		this.contextNode = node;
		this.pageMenu = new Ext.menu.Menu({
			id: 'tree-page-menu',
			items: [{
				iconCls: 'icon-pdf',
				text: 'Export to PDF',
				handler: this.pdf,
				scope: this
			},{
				iconCls: 'icon-print',
				text: 'Print Page',
				tooltip: {title: 'Print Page', text: 'Comming soon!  You can print any of the price pages by downloading it as PDF and printing it.'},
				disabled: true
			}]
		});
		
		this.sectionMenu = new Ext.menu.Menu({
			id: 'tree-section-menu',
			items: [{
            	text:'Expand',
            	iconCls:'icon-node-expand',
            	handler: function(){
            		node.expand(false, false);
            	}
            },
            {
            	text:'Collapse',
            	iconCls:'icon-node-collapse',
            	handler: function(){
            		node.collapse();
            	}				
	       	}]
		});
		if(node.isLeaf()){
			this.pageMenu.showAt(e.getXY());
		} else {
			this.sectionMenu.showAt(e.getXY());
		}
	},
	selectNode : function(id){
		var node = this.getNodeById(id);
		this.getSelectionModel().select(node);
	},
	pdf: function(){
		window.open('/printing/pdf?by=page&id=' + this.contextNode.id);
	}
});	/*
 * Ext JS Library 2.0 Dev 5
 * Copyright(c) 2006-2007, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * This code has not yet been licensed for use.
 */


// Very simple plugin for adding a close context menu to tabs

Ext.ux.TabCloseMenu = function(){
    var tabs, menu, ctxItem;
    this.init = function(tp){
        tabs = tp;
        tabs.on('contextmenu', onContextMenu);
    }

    function onContextMenu(ts, item, e){
        if(!menu){ // create context menu on first right click
            menu = new Ext.menu.Menu([{
                id: tabs.id + '-close',
                text: 'Close Tab',
                handler : function(){
                    tabs.remove(ctxItem);
                }
            },{
                id: tabs.id + '-close-others',
                text: 'Close Other Tabs',
                handler : function(){
                    tabs.items.each(function(item){
                        if(item.closable && item != ctxItem){
                            tabs.remove(item);
                        }
                    });
                }
            }]);
        }
        ctxItem = item;
        var items = menu.items;
        items.get(tabs.id + '-close').setDisabled(!item.closable);
        var disableOthers = true;
        tabs.items.each(function(){
            if(this != item && this.closable){
                disableOthers = false;
                return false;
            }
        });
        items.get(tabs.id + '-close-others').setDisabled(disableOthers);
        menu.showAt(e.getPoint());
    }
};/**
 * @author Tyler
 */

PageManager = function(config){
	Ext.apply(this, config);
	PageManager.superclass.constructor.call(this, {
        id: 'page-manager',
		region:'center',
        margins:'0 5 5 0',
        resizeTabs:true,
        minTabWidth: 120,
        enableTabScroll: true,
        plugins: new Ext.ux.TabCloseMenu(),
		activeTab: 0
	});	
}

Ext.extend(PageManager, Ext.TabPanel, {
	openPage : function(pageType, data){
		var tab;
		var manager = this;
		if(!(tab = this.getItem(data.id))){
			var page;
			switch(pageType){
				case 'CostPage':
					Ext.Ajax.request({
						url: '/printing/editorbook/costpage',
						params: {'id': data.id},
						callback: function(options, bSuccess, response){
							r = Ext.decode(response.responseText);
							if(1 === r.success){
								tab = new CostPage(r.data);
								manager.add(tab);
								manager.setActiveTab(tab);
							} else {
								Ext.MessageBox.alert('Error', r.error);
							}
						}
					});
					break;
					
				case 'PrintingPage': 
					Ext.Ajax.request({
						url: '/printing/book/page/',
						params: {'id': data.id},
						callback: function(options, bSuccess, response){
							var r = Ext.decode(response.responseText);
							if(1 === r.success){
								tab = new PrintingPage(r.result);
								manager.add(tab);
								manager.setActiveTab(tab);
							}
						}
					})
					break;
					
				case 'IndustrialPage':
					page = new IndustrialPage(data);
					manager.add(page);
					manager.setActiveTab(page);
					break;	
					
				case 'InformationPage':
					page = new InformationPage(data);
					tab = page;
					manager.add(page);
					manager.setActiveTab(tab);
					break;	
					
				case 'Page':
					page = new Page(data);
					manager.add(page);
					manager.setActiveTab(page);
					break;		
			}
		} else {
			this.setActiveTab(tab);
		}
	}
});/**
 * @author Tyler
 */

Page = Ext.extend(Ext.Panel, {
	closable: true,
	autoScroll: true,
	bodyStyle: {padding: '5px'},
	initComponent: function(){
		Page.superclass.initComponent.call(this);
	}
});/**
 * @author Tyler
 */
InformationPage = function(config){
	Ext.apply(this, config);
	
	InformationPage.superclass.constructor.call(this, {
		title: this.text,
		tabTip: this.text,
		bodyStyle: {padding: '5px'},
		autoLoad:{
			url: '/default/information/page',
			params: {'id': this.id}
		}
	});
}

Ext.extend(InformationPage, Ext.Panel,{
	closable: true,
	autoScroll: true
});/**
 * @author Tyler
 */

Book = function(config){
	Ext.QuickTips.init();
	Ext.apply(config, this);
	Ext.Ajax.on('beforerequest', this.showSpinner, this);
	Ext.onReady(this.initBook, this);
};

Ext.extend(Book, Ext.util.Observable, {
	pageType: 'page',
	fadeLoad : function(){
		setTimeout(function(){
	        Ext.get('loading').remove();
	        Ext.get('loading-mask').fadeOut({remove:true});
	    }, 400);
	},
	showSpinner: function(){
		
	}
});/**
 * @author Tyler
 */

InformationBook = function(config){
	InformationBook.superclass.constructor.call(this);
};

Ext.extend(InformationBook, Book, {
	initBook: function(){
		var pagePanel = new PagePanel({url: '/default/information/tree', rootCallBack: function(root){
			pagePanel.selectNode(root.firstChild);
		}});
		var pageManager = new PageManager({items: new InformationPage({
			id: '1',
			text: 'Delivery Schedule',
			closable: false,
			iconCls: 'icon-page-text'
		})});
		pagePanel.on('pageselect', this.onPageSelect, this);
		pageManager.on('tabchange', this.onTabChange, this);
		this.pageManager = pageManager;
		this.pagePanel = pagePanel;
		
		this.viewport = new Ext.Viewport({
	        layout:'border',
	        items:[{
	                region:'north',
	                height:75,
					layout: 'anchor',
					cls: 'book-header',
					border: false,
					items: [{
						xtype: 'box',
						el: 'header',
						border: false,
						anchor: 'none -25'
					},new Ext.Toolbar({
						cls: 'pricebook-menu',
						items: [{
							text: 'Home',
							handler: function(){
								window.location = '/default/index/';
							}	
						},'-',{
							text: 'Printing',
							handler: function(){
								window.location = 'http://64.129.12.203/E3Catalog/topframe.htm';
							}
						},'-',{
							text: 'Industrial',
							handler: function(){
								window.location = 'http://64.129.12.203/E3Catalog/topframe.htm';
							}
						},'-',{
							text: 'Information',
							disabled: true
						},'-',{
							text: 'Shop',
							handler: function(){
								window.location = 'http://64.129.12.203/e3commerce/topframe.htm';
							}
						},'-',{
							text: 'Contact',
							handler: function(){
								window.location = '/default/contact/index';
							}
						},'-',{
							text: 'Employment',
							handler: function(){
								window.location = '/default/employment/index';
							}
						},'->',{
							iconCls: 'icon-pdf',
							tooltip: {title: 'Export to PDF', text: 'Export current page to PDF.'},
							handler: this.pdf,
							scope: this
						},'-',{
							iconCls: 'icon-print',
							tooltip: {title: 'Print Page', text: 'Print this page.'},
							hanlder: function(){
								window.print();
							}	
						},'-',{
							iconCls:'icon-help',
							tooltip:{title: 'Help',text: 'Need help with the pricebook?  Click here!'},
							handler: function(){
								window.location = '/default/index/help/';
							}
						}]
					})]
	            },
				new Ext.BoxComponent({ // raw element
	                region:'south',
	                el: 'status',
	                height:25
	            }),
	            pageManager,
	            {
	                    region:'west',
	                    id:'west-panel',
	                    split:true,
	                    width: 350,
	                    minSize: 350,
	                    maxSize: 400,
	                    collapsible: true,
						title: 'Navigation',
	                    margins:'0 0 0 5',
	                    layout:'accordion',
	                    layoutConfig:{
	                        animate:true
	                    },
	                    items: pagePanel
	                }
	         ]
	    });
		this.fadeLoad();
	},
	onPageSelect: function(data){
		this.pageManager.openPage('InformationPage', data);
	},
	onTabChange: function(pm, newTab){
		this.pagePanel.selectNode(newTab.id);
	}
});
