var ATT;
var tabnames;
var tabid;


//////////////////
// diaBtab get database
// from db select ver.
var blastDataType;
var blastDBType = 'prot';

function set_db(type){

    blastDBType = type;


    if(blastDataType == "nucl"){
	if(blastDBType == "nucl"){
	    program = "blastn";
	}else if(blastDBType == "prot"){
	    program = "blastx";
	}
    }else if(blastDataType == "prot"){
	if(blastDBType == "nucl"){
	    program = "tblastx";
	}else if(blastDBType == "prot"){
	    program = "blastp";
	}
    }
    
    if(program){
	document.getElementById('pgm').innerHTML = program;
	document.diaBtabformname.diaBonname.disabled = false;
    }
}
// diaBtab get database
//////////////////


//////////////////
// Focus
var focus_line_flag = 0; // circle is or not yet?
var focus_circle_flag = 0; // line is or not yet?
var linenum = 0;
var circlenum = 0;

var focusrect = [];
var focusline = [];
var circle_img = [];
function focus(orgid, datafolder, keyword, click_or_over){

  if(click_or_over == 1){
  }else if(click_or_over == 2){
  }else{
    if(focus_circle_flag){ // circle is or not yet?
	if(circlenum == 0){
	    map.removeOverlay(circle_img[0]);
	}else{
	    for(i = 0; i <= circlenum; i ++){
		map.removeOverlay(circle_img[i]);
	    }
	}
    }
    if(focus_line_flag){ // line is or not yet?
	if(linenum == 0){
	    map.removeOverlay(focusline[0]);
	}else{
	    for(i = 0; i <= linenum; i ++){
		map.removeOverlay(focusline[i]);
	    }
	}
    }


    Ext.Ajax.request({
	    url : 'main.cgi' ,
		params : { query : keyword,
			       datafolder : datafolder,
	                       focus : 1,
			       organism : maparea},
		    method: 'POST',
			    success: function ( result, request ) {
		    hoge = result.responseText;
		    var piyo = eval("("+hoge+")");

		    var circles = piyo.person.circle;
		    var circle_xy = [];
	            var circle_id = [];
		    if(circles.match(/MNUM:(\d+?):CXY::(.+?):ID::(.+)/)){
			circlenum = RegExp.$1; // circle is or not yet?

			var circle_xy_b = RegExp.$2;
			circle_xy = circle_xy_b.split(":");

			var circle_id_b = RegExp.$3;
			circle_id = circle_id_b.split(":");
		    }
		    if(circles.match(/circle/)){
			focus_circle_flag = 1;
		    }
		    for(var i = 0; i <= circlenum; i ++){
		        var num = i * 2;
			circle_img[i] = new GMarker(new GLatLng(circle_xy[num], circle_xy[num+1]), icon[3]);
			circle_img[i].point = new GLatLng(circle_xy[num], circle_xy[num+1]);
			circle_img[i].comp = circle_id[i];
			circle_img[i].num = i;
			circle_img[i].type = 'img';
			map.addOverlay(circle_img[i]);
		    }

		    var line = piyo.person.line;
		    if(line.match(/LNUM:(\d+)/)){
			linenum = RegExp.$1;
		    }
		    if(line.match(/focusline/)){
			focus_line_flag = 1;
		    }
		    eval(line);

		}
/*
		    failure: function ( result, request) {
			Ext.MessageBox.alert('Failed1', result.responseText);
		    }
*/
 	   });
	}
}



function pseudoGCircle(point, radius, color, weight, opacity) {
    var vertex = 360;
    var EquatorialRadius = 6378137;
    var F = 298.257223563;
    var E = ((2 * F) -1) / Math.pow(F, 2);
    var PI_ER = Math.PI * EquatorialRadius;
    var TMP = 1 - E * Math.pow(Math.sin(point.latRadians()), 2);
    var arc_lat = (PI_ER * (1 - E)) / (180 * Math.pow(TMP, 3/2)); 
    var arc_lng = (PI_ER * Math.cos(point.latRadians())) / (180 * Math.pow(TMP, 1/2)); 
    var R = radius * 1000;
    var points = new Array(vertex);
    for (i = 0; i <= vertex; i++) {
        var rad = (i / (vertex / 2)) * Math.PI;
        var lat = (R / arc_lat) * Math.sin(rad) + point.lat();
        var lng = (R / arc_lng) * Math.cos(rad) + point.lng();
        points[i] = new google.maps.LatLng(lat, lng);
    }
//    return new google.maps.Polyline(points, color, weight, 1);
    return new google.maps.Polygon(points, '#0000FF', weight, 1, '#0000FF', 1);
}


// Focus
//////////////////




//////////////////
// meta search
var keyword;
function searchSubmit(orgid, slidenum, datafolder){
    keyword = Ext.get('query').dom.value;

    if(!keyword){
	keyword = "clear";
    }
    Ext.Ajax.request({
	    url : 'main.cgi' ,
		params : { query : keyword,
		    range : slidenum,
		    datafolder : datafolder,
		    organism : maparea},
		method: 'POST',
		success: function ( result, request ) {
		hoge = result.responseText;		    
		var piyo = eval("("+hoge+")");
		var htmls = piyo.person.nobu;
		
		document.getElementById('msg').innerHTML = htmls;
		map.clearOverlays();
		
		var maku = piyo.person.baku;
		eval(maku);
		
		var bou = piyo.person.lark;
		eval(bou);

		var num = piyo.person.num;
		if(num.length){
		    if(maparea == 'map'){
			Ext.getCmp('center-tab1id').setTitle("Reference Pathway (" + num  +")");
		    }else{
			Ext.getCmp(tabid).setTitle(tabnames + "(" + num  +")");
		    }
		}
		
		
		var opt = piyo.person.opt;
		if(opt == "1"){
		    msgmode = "masssearch";
		    document.getElementById('slider').style.display = 'inline';
		}else{
		    msgmode = "normal";
		    document.getElementById('slider').style.display = 'none';
		}
		
	    }
/*,
		failure: function ( result, request) {
		Ext.MessageBox.alert('Failed', result.responseText);
	    }
*/
	});
}
// meta search
//////////////////

//var centertabs;

Ext.onReady(function(){

        // NOTE: This is an example showing simple state management. During development,
        // it is generally best to disable state management as dynamically-generated ids
        // can change across page loads, leading to unpredictable results.  The developer
        // should ensure that stable state ids are set for stateful components in real apps.

	//	Ext.state.Manager.setProvider(new Ext.state.CookieProvider());


    /////////////////
    //// diaBtab program checker from textarea ver.
    Ext.get('diaBonid').on('click', function(){
			       var Bdata = Ext.get("diaBtabareaid").dom.value;
			       var data = Ext.get("diaBtabareaid").dom.value;
			       var pgm = document.getElementById('pgm').innerHTML;
			       var diaBel = document.diaBtabformname.database;
			       var diaBcount = diaBel.length;
			       var db;
			       for(var p = 0; p < diaBcount; p ++){
				   if(diaBel[p].checked){
				       db = Ext.get(diaBel[p]).dom.value;
				   }else{
				       
				   }
			       }
			       if(!pgm && data){
				   diaBcheck(data);
				   pgm = document.getElementById('pgm').innerHTML;
			       }
			       if(db && data){
				   //////////////////////////
				   ////////// Progress Msg
				   
				   Ext.MessageBox.show({
					   title: 'Please wait',
					       msg: 'Loading items...',
					       progressText: 'Initializing...',
					       width:300,
					       progress:true,
					       closable:false,
					       });
				   var f = function(v){
				       return function(){
					   if(v == 30){
					   }else{
					       var i = v/25;
					       Ext.MessageBox.updateProgress(i, Math.round(100*i)+'% completed');
					   }
				       };
				   };
				   
				   for(var iTime = 1; iTime < 50; iTime ++){
				       setTimeout(f(iTime), iTime*4000);
				   };
				   

				   ////////// Progress Msg
				   //////////////////////////

			       }else{
				   Ext.MessageBox.alert('Error', 'Please input or select sequence or database.');
			       }
			   });
    
    
    Ext.get('diaBtabformid').on('keyup', function(){
				    var data = Ext.get("diaBtabareaid").dom.value;
				    diaBcheck(data);
				});
    Ext.get('diaBtabformid').on('mouseover', function(){
				    var data = Ext.get("diaBtabareaid").dom.value;
				    diaBcheck(data);
				});
    function diaBcheck(data){
	Ext.Ajax.request({
		url : 'kblast_checker.cgi' ,
		    params : { data : data},
		    method: 'POST',
       		    success: function ( result, request ) {
		    list = result.responseText;
		    var program;
		    blastDataType = list;
		    
		    if(blastDataType == "nucl"){
			if(blastDBType == "nucl"){
			    program = "blastn";
			}else if(blastDBType == "prot"){
			    program = "blastx";
			}
		    }else if(blastDataType == "prot"){
			if(blastDBType == "nucl"){
			    program = "tblastx";
			}else if(blastDBType == "prot"){
			    program = "blastp";
			}
		    }
		    if(program){
			document.getElementById('pgm').innerHTML = program;
			document.diaBtabformname.diaBonname.disabled = false;
		    }
		}
	});
    }
    //// diaBtab program checker from textarea ver.
    /////////////////

    /////////////////
    ////  diaCtab input
    Ext.get('diaConid').on('click', function(){

/*
	Ext.MessageBox.show({
	   title: 'Please wait',
		      msg: 'Loading items...',
		      progressText: 'Initializing...',
		      width:300,
		      progress:true,
		      closable:false,
		      });
	var f = function(v){
	    return function(){
		if(v == 30){
		}else{
		    var i = v/10;
		    Ext.MessageBox.updateProgress(i, Math.round(100*i)+'% completed');
		}
	    };
	};
	
	for(var iTime = 1; iTime < 11; iTime ++){
	    setTimeout(f(iTime), iTime*400);
	};
*/
    });
    ////  diaCtab input
    /////////////////


    /////////////////
    ////  file upload
    var upfile;
    Ext.form.FileUploadField = Ext.extend(Ext.form.TextField, {
	buttonText: 'Browse...',
	buttonOnly: false,
	buttonOffset: 3,

	// private
	readOnly: true,
	autoSize: Ext.emptyFn,
    
	// private
	initComponent: function(){
	    Ext.form.FileUploadField.superclass.initComponent.call(this);
	    this.addEvents('fileselected');
	},
	readOnly: true,    
	autoSize: Ext.emptyFn,
    
	// private
	initComponent: function(){
	    Ext.form.FileUploadField.superclass.initComponent.call(this);
	    this.addEvents('fileselected');
	},
    
	// private
	onRender : function(ct, position){
	    Ext.form.FileUploadField.superclass.onRender.call(this, ct, position);
        
	    this.wrap = this.el.wrap({cls:'x-form-field-wrap x-form-file-wrap'});
	    this.el.addClass('x-form-file-text');
	    this.el.dom.removeAttribute('name');
        
	    this.fileInput = this.wrap.createChild({
		id: this.getFileInputId(),
		name: this.name||this.getId(),
		cls: 'x-form-file',
                        tag: 'input', 
                        type: 'file',
                        size: 1
			});
        
	    var btnCfg = Ext.applyIf(this.buttonCfg || {}, {
		text: this.buttonText
	    });
	    this.button = new Ext.Button(Ext.apply(btnCfg, {
		renderTo: this.wrap,
		cls: 'x-form-file-btn' + (btnCfg.iconCls ? ' x-btn-icon' : '')
	    }));
        
	    if(this.buttonOnly){
		this.el.hide();
		this.wrap.setWidth(this.button.getEl().getWidth());
	    }
        
	    this.fileInput.on('change', function(){
		upfile = this.fileInput.dom.value;
		var v = this.fileInput.dom.value;
		this.setValue(v);
		this.fireEvent('fileselected', this, v);
	    }, this);
	},
    
	// private
	getFileInputId: function(){
	    return this.id+'-file';
	},
    
	// private
	onResize : function(w, h){
	    Ext.form.FileUploadField.superclass.onResize.call(this, w, h);
        
	    this.wrap.setWidth(w);
        
	    if(!this.buttonOnly){
		var w = this.wrap.getWidth() - this.button.getEl().getWidth() - this.buttonOffset;
		this.el.setWidth(w);
	    }
	},
    
	// private
	preFocus : Ext.emptyFn,
    
	// private
	getResizeEl : function(){
	    return this.wrap;
	},
	// private
	getPositionEl : function(){
	    return this.wrap;
	},

	// private
	alignErrorIcon : function(){
	    this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
	}
    
    });
    Ext.reg('fileuploadfield', Ext.form.FileUploadField);

    ////  file upload
    /////////////////



    function showResult(){
	Ext.example.msg('OK', 'Done');
    };

    if(topflag == 12){
	Ext.example.msg('OK', 'Done');
    }

    
/*
    Ext.get('diaAsampleon').on('click', function(){
	var htmls = "sample data";
	document.getElementById('diaAtabareaid').innerHTML = htmls;
    });
*/





    /////////
    //dialog
        var win;
	var tabs;
	var nav;
	var button = Ext.get('show-btn');
	button.on('click', function(){
		if(!win){
		    tabs = new Ext.TabPanel({
			    region    : 'center',
			    margins   : '3 3 3 0', 
			    activeTab : 0,
			    defaults  : {
			    },
			    items     : [{
				    contentEl:'diaAtab',
				    autoScroll : true,
				    html:'<p>Input Experimental Data</p>',
				    title    : "Data Mapping",
       				    closable : false,
				    listeners : {
					activate : function(){
					    document.getElementById('diaNav').innerHTML = "<p style=\"line-height:150%\">Users can reflect experimental data, metabolome or microarray. Specify the color or scale of the lines or circles freely, a customized map overlays on the pathway map. Users can put original pictures on map. Furthermore, users can upload a tab-delimited data file, the first rows are component identifier, and the columns are experimental data.</p><br/>";
					}
				    }
				},{
				    contentEl:'diaBtab',
				    html:'<p>Input any sequences for BLAST</p>',
				    title    : 'KEGG BLAST',
				    closable : false,
				    listeners : {
					activate : function(){
					    document.getElementById('diaNav').innerHTML = "<p style=\"line-height:150%\">This tool is supported by KEGG BLAST. Users input fasta format and chose database. A BLAST program, blastn, blastp, blastx, tblastn and tblastx, is determined automatically by whether inputed sequence is base or amino acid and chosen database type.<br/>This function based on KEGG BLAST.</p>";
					}
				    }
				},{ 
				    contentEl:'diaCtab',
				    html:'<p style=\"line-height:150%\">Input FASTA file.</p>',
				    title    : 'Pathway Prediction',
			      	    closable : false,
				    listeners : {
					activate : function(){
					    document.getElementById('diaNav').innerHTML = "<p style=\"line-height:150%\">It asks for the FASTA format file. From submitted file, this system predict pathway using BLAT.</p>";
					}
				    }
				}],
			});
		    
		    // Panel for the west
		    nav = new Ext.Panel({
			    contentEl   : 'diaNav',
			    title       : 'Navigater',
			    region      : 'west',
			    split       : true,
			    width       : 150,
			    collapsible : false,
       			    style       :"background:black;opacity:1;",
			    margins     : '3 0 3 3',
			    cmargins    : '3 3 3 3'
		    });
		    
		    win = new Ext.Window({
			    title    : 'Tools',
			    width    : 730,
			    height   : 500,
				closable : false,
			    //border : false,
			    plain    : true,
                            modal    : true,
			    layout   : 'border',
				//			    autoScroll : true,
			    items    : [nav, tabs],
			    buttons  :  [
			    {
				    text     : 'Close',
					contentEl : 'diaButClose',
					id   : 'diaButCloseId',
				    handler  : function(){
					win.hide();
				    }
				}]
			});
		}
		
		win.show(button);
	    });

	// DiaJob & Dialog window
	//////////////////


    
	//////////////////
	// Organism Grid by XML
	var store = new Ext.data.Store({
		url: 'org.xml',
		reader: new Ext.data.XmlReader(
	{record: 'Item', id: 'KEGGID', totalRecords: '@total'},
	[
	{name:'Name'},
	'KEGGName',
	'FullName',
	'Domain', 
	'Kingdom',
	'Sub'])
	    });
	
	
	var cm = new Ext.grid.ColumnModel([
	{id: 'FullName', header: "Name", width : 200, dataIndex: 'FullName', sortable: true},
	{id: 'KEGGName', header: "Domain", width: 100, dataIndex: 'Domain', sortable: true},
	{id: 'Kingdom', header: "Kingdom", width: 100, dataIndex: 'Kingdom', sortable: true},
	{id: 'Sub', header: "Subphylum", width: 100, dataIndex: 'Sub', sortable: true}
					     ]);
	
	var grid = new Ext.grid.GridPanel({
		store: store,
		cm : cm,
		sm: new Ext.grid.RowSelectionModel({singleSelect: true}),
		viewConfig: {
		    forceFit: true
		},
		renderTo:'example-grid',
		autoHeight : true,
		autoWidth : true
		//width:1000,
		//height:500
	    });
	
	grid.getSelectionModel().on('rowselect', function(sm, rowIdx, r) {
		grid.getSelectionModel().clearSelections();
		var detailPanel = Ext.getCmp('detailPanel');
		//		var orgname = r.data.Title;
		var orgname = r.data.KEGGName;
		var name = r.data.FullName;
		//		alert(orgname);
		//		maparea = orgname;
		//		GUnload(maparea);
		//		maparea = orgname; //1
		//		Ext.get("bodyid").
		addTab(orgname, name);
	    });
	
	store.load();



	//////////////////
	/// for use the 'attTab' out of this file @ main.cgi
	ATT = addTab;
	/// for use the 'attTab' out of this file @ main.cgi
	//////////////////

	//var preTabs = new Array();
	var preTabs = [];
	var index = 0;
	function addTab(orgname, name){
	    maparea = orgname; // 1
	    var orgtabid = maparea + "id";
	    var tabname = name;
	    tabid = orgtabid;

	    var checkflag = 0;
	    for(var i = 0, len = preTabs.length; i < len; i ++){
		if(maparea == preTabs[i]){
		    checkflag = 1;
		    var tab = Ext.getCmp(orgtabid);
		    centertabs.setActiveTab(tab);
		}
	    }

            if(tabname.match(/\(/)){
		    var hoge = [];
		    hoge = tabname.split(" ");
		    tabname = hoge[0]+' '+hoge[1];
	    }

	    tabnames = tabname;
	    if(checkflag == 0){
		centertabs.add({
		    title: tabname,
			       id : orgtabid,
			       contentEl: maparea,
			       html: '<div id="' + maparea + '">' + maparea + '</div>',
			       closable  : true,
			       autoScroll: true,

			       ////////			       
			       // CSS
			       //baseCls : 'nobunobu',
			       //baseCls : 'x-tab-panel-add',
			       // CSS
			       ////////

			       listeners : {activate : function(){
				   Ext.getCmp('east-panel').show();
				   document.getElementById('show-btn').disabled = false;
				   var acTab = centertabs.getActiveTab().contentEl;
				   //GUnload();
				   //load();
				   maparea = acTab;
				   mapfolder = "./MapFolder/" + maparea;
				   load();

				   //keyword = Ext.get('query').dom.value;
				   //increSearch(keyword);
			       }
		    }
		}).show();
		//GUnload();
		//load();
		maparea = orgname;
		preTabs.push(maparea);
		mapfolder = "./MapFolder/" + orgname;
		load();
	    }
	}
	// Organism grid
	//////////////////

	////////////////// 02 27
	// Input Query
	var formtext;
	Ext.get('formid').on('keyup', function(){
	    formtext = Ext.get('query').dom.value;
	});

	// Input Query
	//////////////////




	//////////////////
	// Input Query
//	Ext.get('formid').on('keyup', function(){
	Ext.get('formid').on('submit', function(){
	    store.clearFilter();
	    var orgid = centertabs.getActiveTab().contentEl;
	    if(orgid == "center2"){
		var keyword = Ext.get('query').dom.value;
		increSearch(keyword);
	    }else{
		if(mapfolder.match(/0/)){
		    searchSubmit(orgid, '', datafolder);
		}else{
		    searchSubmit(orgid, '');
		}
	    }
	});
	// Input Query
	//////////////////
	

	//////////////////
	// Incremental Search
	var increSearch = function(e) {
	    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;
		    });
	    }
	};
	// Incremental Search
	//////////////////

	
	//////////////////
	// add East Panel as Result
	// MADA!!!!!!!!!!
/*
	Ext.get('testid').on('submit', function(){
		var eastPanel = Ext.getCmp('east-panel');
		eastPanel.collapsed = "false";
		test = Ext.get('test').dom.value;
		addEastPanel(test);
	    });
*/

	var addEastPanel = function(test) {
	    viewport.add({
		    region : 'west',
			contentEl : 'west',
			split      : true,
			height     : 70,
			minSize    : 100,
			maxSize    : 200,
			collapsible: true,
			collapsed  : true,
			title      :'South',
			margins    :'0 0 0 0'
			});	
	}
        // add East Panel as Result
	//////////////////
	
	////////////////	////////////////	////////////////	////////////////
	////////////////  Main Viewport

	var centertabs;
	var viewport = new Ext.Viewport({
		layout:'border',
		items:[
		       new Ext.BoxComponent
		       ({ // raw
			   region:'north',
			   el: 'north',
			   height:80
		       }),{
			   region:'south',
  		           contentEl  : 'south',
  		           id         : 'south-panel',
			   split      : true,
			   height     : 70,
			   minSize    : 100,
			   maxSize    : 200,
			   collapsible: true,
			   collapsed  : true,
			   title      :'Information',
			   margins    :'0 0 0 0'
			  },{
			   contentEl   : 'east',
			   region      : 'east',
			   id          : 'east-panel',
			   title       : 'Search Result',
			   split       : false,
			   width       : 348,
			   minSize     : 175,
			   maxSize     : 400,
			   collapsible : true,
			   collapsed   : true,
			   autoScroll  : true,
			   margins     :'0 0 0 5',
			   layout      :'accordion',
			   listeners   : {
			       opacity: .50
			   },
			   layoutConfig:{
			       animate:true
			   }
		       },
		       centertabs = new Ext.TabPanel({
			       region         : 'center',
			       contentEl      : 'centerEl',
			       id             : 'centerid',
			       deferredRender : false,
			       activeTab      : "0",
			       //			       autoHeight     : true,
			       handleActivate : function(){
				   //alert("hoge");
			       },
			       //			       defaults: { autoWidth: true, autoHeight: true },
			       enableTabScroll: true,
			       items:[
				   {
				       contentEl:'map',
				       id       :'center-tab1id',
				       title: 'Reference Pathway',
				       closable : false,
				       listeners : {activate : function(){
					           Ext.getCmp('east-panel').show();
						   document.getElementById('show-btn').disabled = false;
						   var acTab = centertabs.getActiveTab().contentEl;
						   acTab = "map";
						   //GUnload(); //2
						   //load(); //3
						   maparea = acTab; // 1
						   //						   mapfolder = "./overlayer/nobu";
						   //						   mapfolder = "./gmap/ref_new";
						   mapfolder = "./gmap/ref";
						   load(); //3
						   
						   if(formtext){

						       searchSubmit(orgid, '', datafolder);
						       Ext.get('query').dom.value = formtext;

						   }
					   },
				       }
				   },
				   {
				       contentEl:'center2',
				       id       :'center-tab2id',
				       title: 'Organism Selection',
				       closable:false,
				       autoScroll:true,
				       listeners : {activate : function(){
					   /////////////////
					   //// When You Open the Organism Selection Tab
					   Ext.getCmp('east-panel').hide();
					   document.getElementById('show-btn').disabled = true;
					   document.getElementById('query').value = "";
				       },
				       }



				   }]
			   })
		       ]


	    });
    });



