/*
   MCP - Master Control Program
   by Brandon Tearse
   Designed for use with the TreeGenes Database Interface.
*/


function Entity(type,id)
{
	this.type = type;
	this.id = id;
	this.getWindowName = function() { return(type + '_' + id); }
}


var MCP = new function() {

	// Init function basically just initializes the new MCP.
	// Currently this does nothing but subscribe the MCP to the dojo internal
	// javascript messaging system so it can catch clicks on various parts of
	// the page.


	// MCP
	this.in_array = function(arr,obj)
	{
		var len = arr.length;
		for(var x=0;x<len;x++){
			if(arr[x] == obj ) return true;
		}
		return false;
	}


	// MCP   
	this.listRemove = function(obj)
	{
		var text = obj.contentText;
		var newContainer = obj.parentNode;
		var spot = false;
		while(newContainer.parentContainer) { newContainer = newContainer.parentContainer; }
		for(var i=0;i<newContainer.contents.length;i++)
		{
			if(newContainer.contents[i] == text)
			{
				spot = i;
				break;
			}
		}
		newContainer.contents.splice(spot,1);
		obj.parentNode.removeChild(obj);
	}


	// MCP
	this.listAdd = function(newContainer,text)
	{	
		//alert(newContainer);
		if(this.in_array(newContainer.contents,text)) { return ; }
		while(newContainer.parentContainer) { newContainer = newContainer.parentContainer; }
		newContainer.contents.push(text);

		var li = newContainer.appendChild(document.createElement('li'));
		li.className='normal';
		li.contentText = text;

		var img = li.appendChild(document.createElement('img'));
		img.src = 'images/Minus.png';
		img.className = 'listImg';

		dojo.event.connect(img,"onclick",function(evt) { MCP.listRemove(evt.target.parentNode);});

		li.appendChild(document.createTextNode(text));
		li.parentContainer = newContainer;

		dojo.event.connect(li,"onclick",function(evt) { MCP.chooseWindow(evt.target.contentText); });
		dojo.event.connect(li,"onmouseover", function(evt) { evt.target.className='hover';});
		dojo.event.connect(li,"onmouseout", function(evt) { evt.target.className='normal';});

		new dojo.dnd.HtmlDragSource(li,"titlebaricons");
	}


	// MCP
	this.broadcast = function(channel,message)
	{
		dojo.event.topic.publish("/" + channel,message);
	}


	// MCP
	this.chooseWindow = function(inp)
	{
		var arr = inp.split("_");
		var windowType 	= arr[0];
		var dbType 	= arr[1];
		var idNum 	= arr[arr.length-1];
		arr[0] = '';
		arr[1] = '';
		var str = arr.join("_");
		str = str.substr(2,str.length);

		var temp = WM.findWindow(inp);

		if(temp !== false)
		{
			WM.activateWindow(temp);
			return;
		}

		// DEBUG.
		//alert('windowType: ' + windowType);

		if(windowType == "search")
		{
			var index = WM.addSearchWindow(inp,dbType,{iconSrc:'images/Arrow.png',searchURL:'AjaxSearchResults.php',resultURL:'AjaxRslt.php'});	

			// Name, Type, Features

			var obj = WM.byIndex(index);
			WM.resizeWindow(index,190,150);

			var win = WM.byIndex(index);
			win.loading();
			win.ChannelTrigger = function(message) 
			{ 
				for(var i=0;i<message.length;i++)
				{
					win.addSearchElement(message[i][0],message[i][1]);
				}
				MCP.AjaxRemove(inp ,win,"ChannelTrigger");		// channel, obj, function name 
				win.ChannelTrigger = false;
		    }
			dojo.event.topic.subscribe("/" + inp,win,"ChannelTrigger");
	
			// DEBUG.
			//alert('AjaxSearch.php?searchtype=' + dbType + ' , Input: ' + inp);

			MCP.AjaxGetUrl('AjaxSearch.php?searchtype=' + dbType,inp,'text/json');
			//WM.activateWindow(index);
		}


		//--------------------------------------------------------------------------------
		//---------- Called after clicking the [Display] button. ----------
		//--------------------------------------------------------------------------------
		else if(windowType == "rslt")
		{
			var temp = standardList;
			var a = {text:'View Selected',func:function(evt){ evt.target.parentObject.viewSelected();}};
			temp.resizeBarButtons = [a];
			var index = ObjectCreator.addRsltWindow(inp,dbType,temp);
			temp.resizeBarButtons = false;
			WM.resizeWindow(index,600,200);

			var win = WM.byIndex(index);
			win.Loading();
			win.dbType = dbType;
			win.ChannelTrigger = function(message)
			{
				this.entityList = [];
				// Let's take apart the message to create entities
				for(var i =1;i<message.length;i++)
				{
					this.entityList.push(new Entity(this.dbType,message[i][0]));
				}

				this.createTable(message,'rslt_' + this.dbType,'table_' + inp,resultsTable);
				// this.finishTable('rslt_' + this.dbType,'table_' + inp,resultsTable);
				this.destroyToo = [this.sortableTable];
				MCP.AjaxRemove(inp,this,"ChannelTrigger");
				this.ChannelTrigger = false;
				var dragItem = new dojo.dnd.HtmlDragSourceReplacement(
					this.sortableTable.domNode,
					["titlebaricons"],
					function(){
						var a = document.createElement('div');
						a.containedItems=[];
						a.className = 'dragReplacement';
						var b=WM.byIndex(index).sortableTable.getValue().split(",");
						if(b[0] != '')
						{
							a.innerHTML = b.length + ' items: ';
							for(var i=0;i<b.length;i++) 
							{
								a.innerHTML += '<BR />data_' +this.dbType + "_" + b[i];
								a.containedItems.push("data_" + this.dbType + "_" + b[i]);
							}
						}
						return a;
					},
					function(){
						var arr = [];
						var b = WM.byIndex(index).sortableTable.getValue().split(",");
						if(b[0] != '')
						{
							for(var i=0;i<b.length;i++)
							{
								arr.push("data_" + this.dbType + "_" + b[i]);
							}
						}
						return arr;
					}
				);
				dragItem.dbType = this.dbType;
			}

			dojo.event.topic.subscribe("/" + inp,win,"ChannelTrigger");

			// DEBUG.
			//alert('AjaxRslt.php?type=' + dbType + '&str=' + str + ' , Input:' + inp);

			MCP.AjaxGetUrl('AjaxRslt.php?type=' + dbType + '&str=' + str,inp,'text/json');
			//WM.activateWindow(index);
		}


		//--------------------------------------------------------------------------------
		//---------- Called after double-clicking a row in a data window.       ----------
		//----------   Opens a detail window.                                   ----------
		//--------------------------------------------------------------------------------
		else if(windowType == "data")
		{
			// Ignore these.
			if (dbType == "NULL") {
			}

			// Check whether this is a chromatogram request.
			else if (dbType == "chromatogram") {
				// Grab the sequence name.
				var SequenceName = inp.substring(inp.indexOf('_') + 1);
				SequenceName = SequenceName.substring(SequenceName.indexOf('_') + 1);
				SequenceName = SequenceName.substring(SequenceName.indexOf('_') + 1);

				// Grab the Project Name.
				var Project = inp.substring(inp.indexOf('_') + 1);
				Project = Project.substring(Project.indexOf('_') + 1);
				Project = Project.substring(0, Project.indexOf('_'));

				// DEBUG.
				//alert("inp: " + inp + "\nSequenceName: " + SequenceName + "\nProject: " + Project);

				// Set the window properties. (see Options.js)
				var temp = {
					iconSrc:'images/Arrow.png',
					displayCloseAction:'true',
					constrainToContainer:'true',
					DnDable:'false'
				};

				// Create the window.
				var index = ObjectCreator.addWindow(inp,'SearchHelp',temp);

				// Resize the window.
				WM.resizeWindow(index,760,210);

				// Define the window contents.
				var WindowContents = document.createElement('div');

				// DEBUG.
				//WindowContents.innerHTML = 
				//	'SequenceName: ' + SequenceName +
				//	'<br/>SCF Path: http://loblolly.ucdavis.edu/chromatogram_scf_files/' + SequenceName + '.scf' +
				//	'<br/>EXP Path: http://loblolly.ucdavis.edu/chromatogram_exp_files/' + SequenceName + '.ab1.exp' +
				//	'<br/>SCF Path: AjaxDownload.php?file=' + SequenceName + '.scf' +
				//	'<br/>EXP Path: AjaxDownload.php?file=' + SequenceName + '.ab1.exp' +
				//	'<br/><br/>' +
				//	'<applet code="TraceViewerApplet.class" height="160" width="710">' +
				//	'<param name="trace-name" value="AjaxDownload.php?file=' + SequenceName + '.scf">' +
				//	'<param name="exp-name" value="AjaxDownload.php?file=' + SequenceName + '.ab1.exp">' +
				//	'</applet>';

				WindowContents.innerHTML = 
					'<applet code="TraceViewerApplet.class" height="160" width="710">' +
					'<param name="trace-name" value="AjaxDownload.php?file=' + SequenceName + '.scf&project=' + Project + '">' +
					'<param name="exp-name" value="AjaxDownload.php?file=' + SequenceName + '.ab1.exp&project=' + Project + '">' +
					'</applet>';

				// Attach the window contents to the window.
				WM.byIndex(index).containerNode.appendChild(WindowContents);
			}

			// NOTE: This is the "ORIGINAL" behavior.
			else {
				var index = ObjectCreator.addWindow(inp,windowType + "_" + dbType,standardList);
				WM.resizeWindow(index,450,150);
	
				var win = WM.byIndex(index);
				win.entityList = [new Entity(dbType,idNum)];
				win.ChannelTrigger = function(message)
				{
					this.tablePtr = ObjectCreator.createDataTable(message,this.containerNode);
					/*
					   // Big Chunk of code to resize windows down to their minimum size
					var rows = this.tablePtr.domNode.getElementsByTagName("tr");
					var width = 200;
					var height = 0;
					for(var i=0;i<rows.length;i++)
					{
						var num = rows[i].childNodes[0].childNodes[0].offsetWidth + 
					rows[i].childNodes[1].childNodes[0].offsetWidth;
						if(width < num) {width=num;}
						var num = rows[i].childNodes[0].childNodes[0].offsetHeight;
						if(height < num) { height=num;}
					}
					alert(height);
					if(width>450) {width = 450;}
					WM.resizeWindow(this.index,width,150);
					*/
					(win.destroyToo) ? win.destroyToo.push(this.tablePtr) : win.destroyToo = [this.tablePtr];
					MCP.AjaxRemove(inp ,win,"ChannelTrigger");		// channel, obj, function name 
					win.ChannelTrigger = false;
				}
				dojo.event.topic.subscribe("/" + inp,win,"ChannelTrigger");
	
				// DEBUG.
				//alert('AjaxData.php?type=' + dbType + '&str=' + str);
	
				MCP.AjaxGetUrl('AjaxData.php?type=' + dbType + '&str=' + str,inp,'text/json');
				// this.WM.activateWindow(index);
			}
		}

		else if(windowType == "user")
		{
			var temp = userWindow;
			var a = 
			{
				text:'Functions',func:function(evt)
				{
					openMenu(dojo.widget.manager.getWidgetById('submenu2'),evt.target);
				}
			};
			temp.resizeBarButtons = [a];
			var index = ObjectCreator.addWindow(inp,'user',temp);
			WM.resizeWindow(index,150,300);
			// this.WM.activateWindow(index);
			var newWindow = WM.byIndex(index);
			var newList = newWindow.containerNode.appendChild(document.createElement('ul'));
			newWindow.listPtr = newList;
			newList.contents = [];
			newList.style.height='90%';
			newList.className = 'UserWindowList';
			new dojo.dnd.HtmlDropTarget(newList,['titlebaricons']);
		}

		else if(windowType == "SearchHelp")
		{
			// Set the window properties. (see Options.js)
			var temp = {
				iconSrc:'images/Arrow.png',
				displayCloseAction:'true',
				constrainToContainer:'true',
				DnDable:'false'
			};

			// Create the window.
			var index = ObjectCreator.addWindow(inp,'SearchHelp',temp);

			// Resize the window.
			WM.resizeWindow(index,300,150);

			// Build the window contents.
			var HelpMessage = document.createElement('div');
			HelpMessage.setAttribute('style','font-family: arial; font-size: 10pt; padding: 5px 5px 5px 5px;');

			if (dbType == 'est') {
				HelpMessage.innerHTML = 'EST Search:<br/><p>This search returns a set of Genbank EST results based on a search phrase.</p>';
			}
			else if (dbType == 'contig') {
				HelpMessage.innerHTML = 'EST Contig:<br/><p>This search returns a set of EST Contig results based on a search phrase.</p>';
			}
			else if (dbType == 'seqassembly') {
				HelpMessage.innerHTML = 'Sequence Assembly Search:<br/><p>This search returns a set of Sequence Assembly results based on a search phrase.</p>';
			}
			else if (dbType == 'amplicon') {
				HelpMessage.innerHTML = 'Amplicon Search:<br/><p>This search returns a set of Amplicon results based on a search phrase.</p>';
			}
			else if (dbType == 'primer') {
				HelpMessage.innerHTML = 'Primer Search:<br/><p>This search returns a set of Primer results based on a search phrase.</p>';
			}
			else if (dbType == 'sequencingreaction') {
				HelpMessage.innerHTML = 'Sequencing Reaction Search:<br/><p>This search returns a set of Sequencing Reaction results based on a search phrase.</p>';
			}
			else if (dbType == 'treesamples') {
				HelpMessage.innerHTML = 'Tree Sample Search:<br/><p>This search returns a set of Tree Sample results based on a search phrase.</p>';
			}
			else if (dbType == 'dnaextractions') {
				HelpMessage.innerHTML = 'DNA Extractions Search:<br/><p>This search returns a set of DNA Extraction results based on a search phrase.</p>';
			}
			else if (dbType == 'sequencingchromat') {
				HelpMessage.innerHTML = 'Sequencing Chromat Search:<br/><p>This search returns a set of Sequencing Chromat results based on a search phrase.</p>';
			}
			else if (dbType == 'phenotype') {
				HelpMessage.innerHTML = 'Phenotype Search:<br/><p>This search returns a set of Phenotype results based on a search phrase.</p>';
			}
			else if (dbType == 'pdata') {
				HelpMessage.innerHTML = 'Phenotype Data Search:<br/><p>This search returns a set of Phenotype Data results based on a search phrase.</p>';
			}
			else if (dbType == 'snp') {
				HelpMessage.innerHTML = 'SNP Search:<br/><p>This search returns a set of SNP results based on a search phrase.</p>';
			}

			// Attach the window contents to the window.
			WM.byIndex(index).containerNode.appendChild(HelpMessage);
		}
	}

	/*
	* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	*	Example of a working AJAX transaction:							*
	*	tc 	= random div (or any other object)							*
	*	testing	= channel I used (this should be unique to the window)	*
	* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

	tc.ChannelTrigger = function(message) 
	{ 
		this.innerHTML=message; 
		MCP.AjaxRemove("testing",tc,"ChannelTrigger"); 
		this.ChannelTrigger = false;
	}
	dojo.event.topic.subscribe("/testing",tc,"ChannelTrigger");

	* * * The Ajax Query !! * * *
	MCP.AjaxGetUrl('AjaxSearch.php?type=contig&class=display','testing','text/plain');">
	*/

	// MCP   
	this.AjaxGetUrl = function(get_url,channel,mime)
	{
		dojo.io.bind({
			url:get_url,
			load: function(type,data,evt) { dojo.event.topic.publish("/" + channel,data); },
			mimetype:mime
		});
	}

	this.AjaxRemove = function(channel,obj,fun)
	{
		dojo.event.topic.unsubscribe("/" + channel, obj, fun);
	}
}


// MCP
this.numberSort = function(a,b)
{	
	//alert('sorting');
	if (Number(a[field])>Number(b[field])) return 1;
	if (Number(a[field])<Number(b[field])) return -1;
	return 0;
}


