
function intitRadLexTree(args){
	if(typeof args !== 'object'){ args = {}; }
	var treepanel;
	var target = Ext.get(args.target_id) || Ext.getBody();
	var iAlreadyFocusedSomething = false;
	
	// url rid path 
	var nodePath = path;
	//bool
	var iBool =0;
	
	var radlexTplMarkup = getRadlexViewerTplMarkup();   
	var radlexTpl = new Ext.XTemplate(radlexTplMarkup);	
	//var path_String = path_String;
	
	
	/**************************
		DETAILS PANEL
	**************************/
	var term_viewer = new Ext.Panel({
		id:'radlex_detail_panel'
		,title:'&nbsp;'
		,columnWidth:1
		,height:650
		,autoScroll:true
		,radlexTpl:radlexTpl
	});
	
	
	/**************************
		TREE PANEL
	**************************/
	var treepanel = new Ext.tree.TreePanel({
		id:'radlex_treepanel'
		,height:650
		,width:350
		,autoScroll:true
		,rootVisible:false
		
	//	,singleExpand:true
		
		,root: new Ext.tree.AsyncTreeNode({id:'RID1',text:'RadLex entity',expanded:true,iconCls:'radlex-tree-node'})
		
		,loader: new Ext.tree.RadlexTreeLoader({
			dataUrl:'/ajax/radlex_util.cfm'
			,baseParams:{ACTION:'GETCHILDREN',treeformat:true,q:''}
			,requestMethod:'POST'
			
			,listeners:{
				'beforeload':function(){
					treepanel.el.mask('Loading...','x-mask-loading');
					term_viewer.setTitle('&nbsp;');
					
				}
				,'load':function(){
					treepanel.el.unmask();
					
					//expand to path and focus on node by the URL RID
					if (iBool==0)
					{
						// in addition, here, we should expand any paths that are passed in as part of our new parameter
						// dependent continuant: RID0/RID1/RID29043/RID29045
						// independent continuant: RID0/RID1/RID29043/RID29044
						// radlex coordinated term: RID0/RID1/RID28638
						
						treepanel.expandPath('RID0/RID1/RID29043/RID29045');
						treepanel.expandPath('RID0/RID1/RID29043/RID29044');
						treepanel.expandPath('RID0/RID1/RID28638');
						
						treepanel.expandPath(nodePath);
						treepanel.selectPath(nodePath);
				
						node2 = treepanel.getSelectionModel().getSelectedNode();
						if (node2 != null && !iAlreadyFocusedSomething)
						{
							focusRadlexTerm(node2.attributes.radlexID);
						}
					
					}
				}
			}
		})
		
		,listeners:{
			'click':function(node,e){
					if(!node.expanded){node.ui.ecClick(e);}
					focusRadlexTerm(node.attributes.radlexID);
					
					iBool=1;
				}
		}
		,tbar:{
			xtype:'toolbar'
			,autoWidth:true
			,height:25
			,cls:'x-panel-header'
			,style:{paddingLeft:'5px'}	
			,items:[
				new Ext.ux.BioportalTwinTriggerField({
					id:'basic_searchfield_demo'
					,trigger2Class:'x-form-search-trigger'
					,emptyText:'Begin typing to seach...'
					,width:200
					,listWidth:300
					,store: new Ext.ux.BioportalJsonStore({ontology_id:ontology_id})
					,displayField:'label'
					,minChars:2
					,typeAhead: false
					,loadingText: 'Searching...'
					,onTrigger1Click : function(e){
						// Hide the "Clear" button.
						this.triggers[0].hide();
						this.el.dom.value = '';
						this.concept_id = '';

						term_viewer.body.unmask();
						term_viewer.update('');
						term_viewer.body.mask('Use the RadLex Tree Browser and integrated search feature to locate terms. Simply click on a RadLex term to view more information.','radlex-viewer-mask');
						treepanel.getRootNode().reload();
						treepanel.el.unmask();

						
						// Remove or clear any of your search results here.
					}	
					,onTrigger2Click : function(e){
						
						
						treepanel.el.mask('Loading...','x-mask-loading');
						// Add the "Clear" button.
						var w = this.wrap.getWidth();
						this.triggers[0].dom.style.display = '';
						this.el.setWidth(w-(this.triggers[0].getWidth()*2));
						var v = this.getValue();
						
						if(v.length > 0){
							Ext.Ajax.request({
								url:'/ajax/radlex_util.cfm'
								,method:'POST'
								,params:{action:'GETSEARCHRESULTS',q:v}
								,callback:function(){ treepanel.el.unmask(); }
								,success:function(responseObj,optionsObj){
										var JSON = Ext.decode(responseObj.responseText);
										if(JSON.success == false){
											handleActionFailure('Sorry, we were unable to retrieve the requested search results.');	
										}else{
											if( "" == JSON.path) {
												handleActionFailure('Sorry, we were unable to retrieve the requested search results.');
											} else {
												treepanel.expandPath(JSON.path);
												treepanel.selectPath(JSON.path);
												focusRadlexTerm(JSON.rid);
												iAlreadyFocusedSomething = true;
											}

										}
									}
								,failure:function(responseObj,optionsObj){
										handleActionFailure('Sorry, we were unable to retrieve the requested search results.');	
									}
							});	
						}
					}
					
					,listeners:{
						'select':function(combo,record,index){
							// Activate the search action when a result is selected.
							this.onTrigger2Click({});
						}
					}
				})
			]
		}

	}
	);
	
	
	var ct = new Ext.Container({
		id:'radlex_ct'
		,renderTo:target
		,height:650
		,width:1200
		,layout:'column'
		,items:[
			treepanel
			,term_viewer
		]
	});
}


function detectHeight() {
	var wh = 0;
	if(typeof(window.innerHeight)=="number"){
		wh = window.innerHeight;
	}else{	
		if(document.documentElement && document.documentElement.clientHeight) {wh = document.documentElement.clientHeight;}
		else if (document.body && document.body.clientHeight) {wh = document.body.clientHeight;}
	}
	return wh;
} 


function detectWidth() {
	var wh = 0;
	if (typeof(window.innerWidth)=="number") {
		wh = window.innerWidth;
	}else{
		if(document.documentElement && document.documentElement.clientWidth) {wh = document.documentElement.clientWidth;}
		else if (document.body && document.body.clientWidth) { wh = document.body.clientWidth; }
	}
	return wh;
} 

function launchExtWindow(image, title){
/**************************************************************************************************************
	Standardized function to open an image in a window.
	
	Params
	url (string):	The address of the site to be loaded.  Does not have to be on the same domain.
	titleitle (string):	Text used as the header of the window.
***************************************************************************************************************/
	
	var extTitle = Ext.value(title,'Radlex Sample Image');
	var myHtml = '<center><img class="radlex_img_link" src='+image+' /></center>';
	
	


	launchwin = new Ext.Window(
		{
			title:extTitle,
			modal:true,
			autoScroll:true,
			shadow:false,
			shim:false,
			html:myHtml
			,width:500
			,height:500
			,listeners:{
				'afterrender':function(win){
					var maxH = detectHeight()-10;
					var maxW = detectWidth()-10;			
					var img = Ext.DomQuery.selectNode('img.radlex_img_link',win.body.dom);
					var img_size = Ext.get(img).getSize();
					var window_width = img_size.width+35;
					var window_height = img_size.height+35;
					if( window_width > maxW ) {
						window_width = maxW;
					}
					if( window_height > maxH) {
						window_height = maxH;
					}
					
					win.setSize(window_width,window_height);
				}
			}
		}
	).show();
	
	
	/*
	if( launchwin.getHeight() > maxH ) {
		launchwin.setHeight(maxH);
	}*/
	/*if( launchwin.getWidth() > maxW ){
		launchwin.setWidth(maxW);
	}*/
	launchwin.setPosition(1,1);
	
}


function focusRadlexTerm(radlex_id){
	
	//testing new tabs?
	//------------
	var term_viewer = Ext.getCmp('radlex_detail_panel');
	if(term_viewer && radlex_id && term_viewer.display_id != radlex_id){
		var radlexTpl = term_viewer.radlexTpl || new Ext.XTemplate(getRadlexViewerTplMarkup());
		Ext.Ajax.request({
			url:'/ajax/radlex_util.cfm'
			,method:'POST'
			,params:{action:'GETTERMDETAILS',tid:radlex_id}
			,callback:function(){ term_viewer.body.unmask(); }
			,success:function(responseObj,optionsObj){
					var JSON = Ext.decode(responseObj.responseText);
					if(JSON.success == false){
						
						//outputs   THIS NEVER HAPPENS
						//alert('FAIL1');
						
						handleActionFailure('Sorry, we were unable to retrieve more information about the selected RadLex Term.');	
					}else{
						
						//outputs
						//alert('success1  [' + JSON.LABEL+'] \n ['+JSON.toString()+']' );
						
						term_viewer.setTitle(Ext.util.Format.capitalize(JSON.LABEL));
						if(!JSON.SUPERCLASS){ JSON.SUPERCLASS = []; }
						radlexTpl.overwrite(term_viewer.body,JSON);
						term_viewer.display_id = radlex_id;
					}
				}
			,failure:function(responseObj,optionsObj){
					handleActionFailure('Sorry, we were unable to retrieve more information about the selected RadLex Term.');	
				}
		});	
	}
}

//---------------------------------primative caveman methods
  function toggle() {
	var ele = document.getElementById("toggleText");
	var text = document.getElementById("displayText");
	var ele2 = document.getElementById("toggleText2");
	if(ele.style.display == "block") {
    	ele.style.display = "none";
		text.innerHTML = "Term Details";}
	else {
		ele.style.display = "block";
		text.innerHTML = "Visualize";}
	if(ele2.style.display == "block") {
    	ele2.style.display = "none";}
	else {
		ele2.style.display = "block";}
} 
//---------------------------------


function getRadlexViewerTplMarkup(){
	
	
	var tpl = [
	//!
	
	'<a id="displayText" href="javascript:toggle();">Visualize</a><br />',
	
'<div id="toggleText" style="display: block">',
	
		'<table align="left" width="96%">',
		'<br />',
			'<tr>',
				'<td style="white-space:nowrap;" width="75px"><b>Preferred Name:&nbsp;&nbsp;</b></td>',
				'<td align="left" colspan="2" width="100%">{[Ext.util.Format.capitalize(values.LABEL)]}</td>',
			'</tr>',
             
            //old code to link to bioportal
			//'<tr><td><b>RadLex&nbsp;ID:&nbsp;&nbsp;</b></td><td colspan="3"><a href="#" onClick="window.open(\'{FULLID}\');">{ID}</a></td></tr>',
			
			//new onto itsself
			'<tr><td><b>RadLex&nbsp;ID:&nbsp;&nbsp;</b></td><td colspan="3"><a href="http://www.radlex.org/RID/{ID}">{ID}</a></td></tr>',
			
			'<tr><td><b>PURL:&nbsp;&nbsp;</b></td><td colspan="3"><a href="http://www.radlex.org/RID/{ID}">http://www.radlex.org/RID/{ID}</a></td></tr>',
			
			
			'{[!values.DEFINITION ? "" : "<tr><td><b>Definition:</b></td><td colspan=\'3\'>"+values.DEFINITION+"</td></tr>"]}',
			
			
			'{[!values.SYNONYMS ? "" : "<br /><tr><td><b>Synonyms:</b></td><td colspan=\'3\'>"+values.SYNONYMS+"</td></tr>"]}',

			//'<br /><tpl if="xindex &gt; 1">values.xindex</tpl>',

			'<tpl if="SUBCLASS.length != 0">',
				'<tr><td><b>&nbsp;</b></td></tr>',
				'<tr><td><b>Subtypes:</b></td></tr>',
				'<tr><td  colspan="3">',
				'<tpl for="SUBCLASS">',
					'<tpl if="xindex &gt; 1">,&nbsp;</tpl>',
				//	'<a href="#" onClick="window.open(\'{FULLID}\');">{LABEL}</a>',
					//click subtypes to return url value back to tree
					' <a href="http://www.radlex.org/RID/{ID}">{LABEL}</a>',
				'</tpl>',
				'</td></tr>',
			'</tpl>',
			
			'<tpl if="SUPERCLASS.length != 0">',
				'<tr><td><b>&nbsp;</b></td></tr>',
				'<tr><td><b>Is a:</b></td></tr>',
				'<tr><td colspan="3">',
				'<tpl for="SUPERCLASS">',
					'<tpl if="xindex &gt; 1">,&nbsp;</tpl>',
					'<a href="http://www.radlex.org/RID/{ID}">{LABEL}</a>',
				'</tpl>',
				'</td></tr>',
			'</tpl>',
			
//			'<tpl if="typeof IMAGE_URL != \'undefined\'">',
			'<tr><td><b>&nbsp;</b></td></tr>',
			'<tr><td><b>Sample Images:</b></td></tr>',
			'<tr><td colspan="3">',
//			'<tpl for="IMAGE_URL">',
//				'<tpl if="xindex &gt; 1">&nbsp;</tpl>',
//				'<a href="#" onclick="launchExtWindow(\'{.}\', \'\' );"><img src="{.}" height="200px" /></a>',
//			'</tpl>',
			'<iframe  style="border-style: none;width: 100%; height: 190px;"  SRC="http://goldminer.arrs.org/inline-radlex.php?id={ID}"></iframe>',
			'</td></tr>',
//		'</tpl>',
			
		'</table>',
	'</div>',
	
	'<div id="toggleText2" style="display: none">',
		
		//adding in table for IE!!!! >:O
		//	'<table align="left" width="96%">',
		//'<tr>',
		//'<td>',
		
		//how to capitalize in ajax
		//'nodeid={[Ext.util.Format.capitalize(values.LABEL)]}',
		
			
			' <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="FlexoViz" width="100%" height="100%" codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">',
			'<param name="movie" value="http://keg.cs.uvic.ca/ncbo/flexviz/BasicFlexoViz.swf?v=1.0.9" /><param name="quality" value="high" /><param name="bgcolor" value="white" /><param name="allowScriptAccess" value="always" />',
			'<embed src="http://keg.cs.uvic.ca/ncbo/flexviz/BasicFlexoViz.swf?v=1.0.9" bgcolor="white" width="810" height="620" name="FlexoViz" align="left" play="true" loop="false" quality="high" allowScriptAccess="always" type="application/x-shockwave-flash"flashVars="widget=true&ontology=42801&nodeid={ID}&server=http://rest.bioontology.org/bioportal" pluginspage="http://www.adobe.com/go/getflashplayer">',
			'</embed>',
			'</object>',
			
			//'</td>',
			//'</tr>',
			//'</table>',
			
			'</div>'
			
	];

	return tpl;
}


function handleActionFailure(msg){
	var active_win = Ext.WindowMgr.getActive();
	var zindex = (active_win != null ? active_win.el.dom.style.zIndex : 9000);
	zindex = parseInt(zindex) + 100;
	var msg = '<div align="center">' + msg + '</div>';
	
	var win = Ext.Msg.show({
			title: 'Failure!'
			,msg: msg
			,minWidth:300
			,buttons: Ext.MessageBox.OK
			,alwaysOnTop:true
			,listeners:{deactivate:function(self){self.toFront();}}
	});
}
