Ext.BLANK_IMAGE_URL = 'lib/resources/s.gif';



Ext.onReady(function(){
    Ext.QuickTips.init();
	 
	 Ext.state.Manager.setProvider(new Ext.state.CookieProvider());



    var url = 'getFuncList.cgi';
    var currentdb = 'g';

	 
	 var Record = Ext.data.Record.create([
           {name: 'function',      mapping:'function',     type: 'string'},
           {name: 'class',    mapping:'class',   type: 'string'},
           {name: 'description', mapping:'description',type: 'string'},
	  ]);

    // create the data store
    var store = new Ext.data.Store({
			proxy: new Ext.data.HttpProxy({url: url}),
			baseParams:{'lib':currentdb},
			reader:new Ext.data.JsonReader(
				{id:'function', root:'rows'}, Record)
	});
			
	 var cm = new Ext.grid.ColumnModel([
					   {id: 'function',      header: "Function",         width:100,  sortable:true, dataIndex:"function"},
						{id: 'class',    header: "Class", width:100, sortable:true, dataIndex:"class"},
						{id: 'description', header: "Description",    width:300,  sortable:true, dataIndex:"description"}
	 ]);
 
	
	var menutree = new Ext.tree.TreePanel({
			region:'center',
			id:'menuList',
			baseCls:'x-panel-menulist',
			header:false,
         loader: new Ext.tree.TreeLoader(),
         rootVisible:false,
         lines:false,
			autoScroll:true,
			root: new Ext.tree.AsyncTreeNode({
				 text:'Document Center',
				 expanded:true,
				 iconCls:'foldericon',
				 children:[{
					   text:'Library',
						iconCls:'foldericon',
					   expanded:true,
					   children:[{
								id:'g',
								text:'G-language GAE',
								lib:'g',
//								iconCls:'ecellicon',
								leaf:true
					   },{
								id:'bp',	
								text:'BioPerl',
								lib:'bp',
//								iconCls:'ecellicon',
								leaf:true
					   }]
				 },{
					  text:'Online Documents',
					  iconCls:'foldericon',
					  expanded:true,
					  children:[{
								id:'home',
								text:'HomePage',
								leaf:true,
								jumpUrl:'http://www.g-language.org/wiki/'
					  },{
								id:'soft',
								text:'Software/Download',
								leaf:true,
								jumpUrl:'http://www.g-language.org/wiki/software'
					  },{
								id:'changelog',
								text:'Changelog',
								leaf:true,
								jumpUrl:'http://www.g-language.org/wiki/changelog'
					  },{
								id:'documents',
								text:'Manual/Tutorial',
								leaf:true,
								jumpUrl:'http://www.g-language.org/wiki/documents'
					  },{
								id:'publications',
								text:'Publications',
								leaf:true,
								jumpUrl:'http://www.g-language.org/wiki/publications'
					  }]
				 },{
					  text:'Related Applications',
					  iconCls:'foldericon',
					  expanded:true,
					  children:[{
								id:'gbt',
								text:'GenomeProjector',
								leaf:true,
								openUrl:'http://g-language.org/g3/'
					  },{
								id:'mana',
								text:'PathwayProjector',
								leaf:true,
								openUrl:'http://ws.g-language.org/g4/'
					  },{
								id:'keggviz',
								text:'Pathway Vizualization',
								leaf:true,
								openUrl:'http://g-language.org/data/marray/software/map2swf.cgi'
					  },{
								id:'megu',
								text:'MEGU',
								leaf:true,
								openUrl:'http://megu.iab.keio.ac.jp/map2svg.cgi'
					  }]
				 }]
			})
  });

	  

	
       var viewport = new Ext.Viewport({
            layout:'border',
				monitorResize:true,
				autoHeight:true,
            items:[
                new Ext.BoxComponent({ // raw
                    region:'north',
                    el: 'north',
                    height:51
                }),{
                    region:'south',
                    contentEl: 'south',
                    split:true,
                    height: 100,
                    minSize: 100,
                    maxSize: 200,
                    collapsible: true,
						  collapsed: true,
						  border: false,
                    title:'Console',
                    margins:'0 0 0 0'
			    },
/**				 
				   {
                    region:'east',
                    title: 'East Side',
                    collapsible: true,
                    split:true,
                    width: 250,
                    minSize: 175,
                    maxSize: 800,
                    layout:'fit',
                    margins:'0 5 0 0',
                    items:
                        new Ext.TabPanel({
                            border:false,
                            activeTab:1,
                            tabPosition:'bottom',
                            items:[{
                                html:'<p>A TabPanel component can be a region.</p>',
                                title: 'A Tab',
                                autoScroll:true
                            },
                            new Ext.grid.PropertyGrid({
                                title: 'Property Grid',
                                closable: true,
                                source: {
                                    "(name)": "Properties Grid",
                                    "grouping": false,
                                    "autoFitColumns": true,
                                    "productionQuality": false,
                                    "created": new Date(Date.parse('10/15/2006')),
                                    "tested": false,
                                    "version": .01,
                                    "borderWidth": 1
                                }
                            })]
                        })
                 },
 */					  
					  {
                    region:'west',
							title: 'West Panel',
							header:false,
						  split:true,
                    width: 200,
							minSize: 150,
							maxSize: 400,
                    collapsible: false,
                    margins:'0 0 0 0',
                    layout:'border',
                    items: [
							menutree,{
							region:'south',
							contentEl: 'albumartdiv',
							id:'model image',
							title:'Analysis Image',
							height:250,
							collapsible:true
					}]
                },
					 //!!!CENTER PANEL!!!
                new Ext.TabPanel({
                    region:'center',
                    activeTab:0,
						  resizeTabs:true,
						  enableTabScroll:true,
							minSize: 500,
							monitorResize:true,
                    items:[{
									title: 'List of Functions',
									closable:false
							  }
						   ]
                })
             ]
        });

	   viewport.doLayout();


			
			
   	var maingrid = new Ext.grid.GridPanel({
								el:viewport.layout.center.panel.getComponent(0).getEl(),
								store:store,
								cm: cm,
								sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
								stripeRows: true,
								autoScroll:true,
								viewConfig: {
									forceFit:true,
									autoFill:true
									},
								loadMask:true,
								enableDragDrop:true,
								enableColumnMove: true,
								enableColumnResize: true,
								autoExpandColumn: 'name'
                   });
      store.load();
		maingrid.render();
				
		function rowClicked(grid, rowClicked, e) {
				var selectionModel = grid.getSelectionModel();
				var record = selectionModel.getSelected(); 
//			alert('<iframe src="' + url + '?lib=' + currentdb + '&func=' + record.data['function'] + 
//												'&cls=' + record.data['class'] + '" height=100% width=100% scrolling=yes frameborder="no">></iframe>');

//				document.getElementById("albumart").src="models/" + currentdb + "/gif/"+record.data['id']+".gif";
		}
		
	   function confirmRemove(p, c){
				Ext.MessageBox.confirm('Really close?', 'Are you sure that you want to close this tab?', function(btn){
					if(btn == 'yes'){
						viewport.layout.center.panel.un("beforeremove", confirmRemove);
						p.remove(c);
						viewport.layout.center.panel.on("beforeremove", confirmRemove);
					}
				});
				return false;
		}

//		viewport.layout.center.panel.on("beforeremove", confirmRemove);
								
      maingrid.on('rowclick', rowClicked);
		maingrid.on('rowdblclick', function(grid, rowClicked, e){
								var selectionModel = grid.getSelectionModel();
								var record = selectionModel.getSelected(); 
								var escapedFunc = escape(record.data['function']);
								var escapedCls  = escape(record.data['class']);	
								var uri = url + '?lib=' + currentdb + '&func=' + escapedFunc + '&cls=' + escapedCls;
								var html = '<iframe src="' + uri + '" id="' + escapedFunc + 
													  '-iframe" height=100% width=100% scrolling=yes frameborder="no"></iframe>';	
								var tab = viewport.layout.center.panel.add({
												title: record.id,
												html: html,
												closable:true
								});
								tab.show();
						});

				  
		viewport.layout.west.panel.on("resize", function(){
			var width = viewport.layout.west.panel.getInnerWidth();
			viewport.layout.west.panel.getComponent(1).setHeight(width);
			document.getElementById("albumart").height = width - 20;
			document.getElementById("albumart").width = width;
			viewport.doLayout();
		});
		viewport.layout.west.panel.setWidth("200");

		menutree.on('click', function(n){
			if(n.attributes['lib'] == 'bp'){
				document.getElementById("albumart").src="pict/BioPerlLogo.png";
			}else{
				document.getElementById("albumart").src="http://www.g-language.org/data/logo/glang-10.gif";
			}
//				maingrid.getTopToolbar().hide();
				
             if(n.isLeaf()){
							n.select();
							var jumpUrl = n.attributes['jumpUrl'];
							var openWin = n.attributes['openWin'];
							var openUrl = n.attributes['openUrl'];
							if(jumpUrl){
								var tab = viewport.layout.center.panel.add({
												title: n.attributes['text'],
												html:'<iframe src="' + jumpUrl + '" id="' + n.attributes['id'] + 
													  '-iframe" height=100% width=100% scrolling=yes frameborder="no"></iframe>',
												closable:true
								});
								tab.show();
							}else if(openUrl){
								window.open(openUrl, "", 'menubar=no, toolbar=no, location=no, directories=no, status=no, scrollbars=yes'); 
							}else if(openWin){
							    window.open(openWin);	
							}else{
								currentdb = n.attributes['lib'];
								store.baseParams = {"lib":currentdb};
								store.load();
								viewport.layout.center.panel.activate(0);
							}
             }else{
				}
      });
		
     menutree.getNodeById(currentdb).select();


    var onFilteringBeforeQuery = function(e) {
		//grid.getSelectionModel().clearSelections();

		  var value = Ext.get('query').dom.value;
        if (value.length==0) {
            store.clearFilter();
        } else {
            value = value.replace(/^\s+|\s+$/g, "");
            if (value=="")
                return;
					store.filterBy(function(r) {
					// filter operator AND on all keywords for defined columns
						valueArr = value.split(/\ +/);
						for (var j=0; j<valueArr.length; j++) {
							re = new RegExp(Ext.escapeRe(valueArr[j]), "i");
							keep = false;

							for (var i=0,len=cm.getColumnCount(); i<len; i++){
									if (re.test(r.get(cm.getColumnId(i)))==true){
											keep = true;
									}
							}
							if (!keep){
								return false;
							}
						}
						return true;
					});
		}
	};
	
	
      Ext.get('searchform').on('keyup', onFilteringBeforeQuery);


		setTimeout(function(){
			Ext.get('loading').remove();
			Ext.get('loading-mask').fadeOut({remove:true});
		}, 150);
	
});



window.onbeforeunload = function(e){
//	return e.returnValue = 'Really close E-Cell Online?';
};


function viewImage(url) { 
	var image = new Image();
	image.src=(url);
	window.open(url, 'open_window', 'menubar=yes, toolbar=no, location=no, directories=no, status=no, scrollbars=no, resizable=no, width=' + image.height + ',height=' + image.width + ', left=50, top=50'); 
} 

