
var iisIE = false; //global flag;
var ireq;  //global request and XML document objects;


window.onload = init;


function init() {

	var initURL;

	if ( pagename == "phenotype" ) {
		initURL = 'xml/phenotype/phenotype.xml';
	 }
	else if ( pagename == "biological" ) {
		initURL = 'xml/biological/biological.xml';
	 }
	else if ( pagename == "pathway" ) {
		initURL = 'xml/pathway/pathway.xml';
	 }
	else {	// show all diseases by default;
		initURL = 'xml/diseases/diseases.xml';
	}

	initLoadXMLDoc(initURL);

}


// retrieve XML document (reusable generic function); parameter is URL string
// (relative or complete) to an .xml file whose Content-Type is a valid XML
// type, such as text/xml; XML source must be from same domain as HTML file.
function initLoadXMLDoc(url) {

    if (window.XMLHttpRequest) { //branch for native XMLHttpRequest object.
		ireq = new XMLHttpRequest();
     }
    else if (window.ActiveXObject) { //branch for IE/Windows ActiveX version;
        iisIE = true;
        ireq = new ActiveXObject("Microsoft.XMLHTTP");
    }

    if (ireq.overrideMimeType) { //for browser override MimeType;
		ireq.overrideMimeType("text/xml");
    }

    ireq.onreadystatechange = initProcessReqChange;
    ireq.open("GET", url, true); // GET, POST
    ireq.send(null);
}


// handle 'onreadystatechange' event of 'ireq' object;
function initProcessReqChange() {

    if (ireq.readyState == 4) {   //only if ireq shows "loaded";
        if (ireq.status == 200) { //only if "OK";


			var isPageLoading = document.getElementById('page_loading');
			if ( isPageLoading ){
				window.setTimeout("iPreload()",7000);
			}

			 //clear all arrays first, any other method to clear an array?
			selectedGeneIDs = new Array();
			selectedHGeneIDs = new Array();
			selectedMGeneIDs = new Array();
			selectedQtlIDs = new Array();
			selectedHQtlIDs = new Array();
			selectedStrainIDs = new Array();

			 //show genes Info;
			iAppendTable('geneList','geneInfo');
			iPrintTable('geneList','geneInfo');

			 //display genes number on summary area;
			var theGeneSum = selectedGeneIDs.length;
			document.getElementById('genes-sum').innerHTML = theGeneSum;
			var theHGeneSum = selectedHGeneIDs.length;
			document.getElementById('human-genes-sum').innerHTML = theHGeneSum;
			var theMGeneSum = selectedMGeneIDs.length;
			document.getElementById('mouse-genes-sum').innerHTML = theMGeneSum;


			if ( pagename != 'biological' && pagename != 'pathway' ) {

				iAppendQtlTable('qtlList','ratsym','ratid','rat-qtl');	//show rat QTLs Info;
				iAppendQtlTable('qtlList','humansym','humanid','human-qtl'); //show human QTLs Info;

				 //display Rat and Human QTLs number on summary area;
				var theQtlSum = selectedQtlIDs.length;
				document.getElementById('qtls-sum').innerHTML = theQtlSum;
				var theHQtlSum = selectedHQtlIDs.length;
				document.getElementById('human-qtls-sum').innerHTML = theHQtlSum;

				if ( pagename == 'phenotype' ) { //show mouse QTLs Info only on phenotype page;
					selectedMQtlIDs = new Array();
					iAppendQtlTable('qtlList','mousesym','mouseid','mouse-qtl');
					 //display Mouse QTLs number on summary area;
					var theMQtlSum = selectedMQtlIDs.length;
					document.getElementById('mouse-qtls-sum').innerHTML = theMQtlSum;
				 }

				 //show strains Info;
				iAppendTable('strainList','strainInfo');
				iPrintTable('strainList','strainInfo');

				 //display Strains number on summary area;
				var theStrainSum = selectedStrainIDs.length;
				document.getElementById('strains-sum').innerHTML = theStrainSum;

			}


			 //build categories list;
			buildCategoriesList();

			createFlashTab('rat',portalname,'rgd_rat_ideo.xml','820','240','GViewer2.swf');
			setBgColor('rat-flash');	//rat-flash first;


			 //create Rat, Human and Mouse Gviewer links on the top-side of GViewer;
			var ratFlashLink = " <a href=\"javascript:createFlashTab('rat','" + portalname + "','rgd_rat_ideo.xml','820','240','GViewer2.swf');\" class=\"asubtitle\" onClick=\"createSyntenyTab('" + portalname + "','rat');\"> <b>Rat</b> </a> ";
			document.getElementById('rat-flash').innerHTML = ratFlashLink;

			var humanFlashLink = " <a href=\"javascript:createFlashTab('human','" + portalname + "','human_ideo.xml','820','240','GViewer2.swf');\" class=\"asubtitle\" onClick=\"createSyntenyTab('" + portalname + "','human');\"> <b>Human</b> </a> ";
			document.getElementById('human-flash').innerHTML = humanFlashLink;

			var mouseFlashLink = " <a href=\"javascript:createFlashTab('mouse','" + portalname + "','mouse_ideo.xml','820','240','GViewer2.swf');\" class=\"asubtitle\" onClick=\"createSyntenyTab('" + portalname + "','mouse');\"> <b>Mouse</b> </a> ";
			document.getElementById('mouse-flash').innerHTML = mouseFlashLink;


			 //create SyntenyTab on the  right-side of GViewer;
			createSyntenyTab(portalname,'rat');


			 //create Pie Graphics and Report;
			clearItem('cc-pie');
			loadingData('cc-report');
			clearItem('bp-pie');
			loadingData('bp-report');
			clearItem('mf-pie');
			loadingData('mf-report');
		//	clearItem('pw-pie'); //for pathway; 
		//	loadingData('pw-report'); //for pathway; 

			window.setTimeout("createFusionCharts('cc','cc-pie','cc-report')",7000);
			window.setTimeout("createFusionCharts('bp','bp-pie','bp-report')",8000);
			window.setTimeout("createFusionCharts('mf','mf-pie','mf-report')",9000);
		//	window.setTimeout("createFusionCharts('pw','pw-pie','pw-report')",10000); //for pathway; 


			 //print buttons to load charts;
			printButtons();

			 //set 'large-button' button background color;
			document.getElementById('large-button').setAttribute("bgcolor","#FFFFFF");

		 }
		else {
			alert("There was a problem retrieving the XML data: \n" + ireq.statusText);
        }
    }
}


// fill 'categories' select list with branchs from the current XML document.
function buildCategoriesList() {

	var categoriesList = new Array();
	clearList('categories');	//clear 'categories' area first;

	var selectc = document.getElementById('categories');
    var topnodes = ireq.responseXML.getElementsByTagName('topnodes');

    var initOpt = document.createElement('option');
	var initContent = document.createTextNode('Choose one ... ');
    initOpt.value = '';
    initOpt.appendChild(initContent);
    selectc.appendChild(initOpt);

	 //loop through <topnodes> elements, and add each nested <categoryname> element to category select element.
    for (i=0; i<topnodes.length; i++) {
		var selectCategory = new Array();
		var getCategoryName = getElementTextNS('categoryname', topnodes[i], 0);
		 //added a sort function below to order categories in alphabetic

	 	// does this row already exist in categoriesList? if no, push it in.
		if ( i == 0 ){	//first item should be pushed in;
			selectCategory.push(getCategoryName);
			selectCategory.push(i);
			categoriesList.push(selectCategory);
		 }
		var hasItin = 0;
		for ( n=0; n<categoriesList.length; n++ ){
			if ( categoriesList[n][0] == getCategoryName ){
				hasItin = 1;
				break;
			}
		 }
		if ( hasItin == 0 ){
			selectCategory.push(getCategoryName);
			selectCategory.push(i);
			categoriesList.push(selectCategory);
		}
    }

    categoriesList.sort(); //sort this array to order categories in alphabetic;

    for (i=0; i<categoriesList.length; i++){
    	var thiscontentc = document.createTextNode(categoriesList[i][0]);
    	var idvalue = categoriesList[i][1];
    	appendToSelect(selectc, idvalue, thiscontentc);

    }

}


function iAppendTable(thisItem,div) {

	var thisx = ireq.responseXML.getElementsByTagName(thisItem);

	var thisArray = new Array();

	for (i=0;i<thisx.length;i++)
	{
		var getRatNodeName = thisx[i].getElementsByTagName('ratsym');
		if (getRatNodeName[0]) { //if this node exists;
			var getRatNodeNameValue = getRatNodeName[0].firstChild.nodeValue; }
		else {
			var getRatNodeNameValue = ''; } //doesn't exist;
		var getRatNodeID = thisx[i].getElementsByTagName('ratid');
		if (getRatNodeID[0]) {
			var getRatNodeIDValue = getRatNodeID[0].firstChild.nodeValue; }
		else { 
			var getRatNodeIDValue = ''; }
		var ratArray = new Array();
		ratArray.push(getRatNodeNameValue);
		ratArray.push(getRatNodeIDValue);

		var getHumanNodeName = thisx[i].getElementsByTagName('humansym');
		var getHumanNodeID = thisx[i].getElementsByTagName('humanid');
		if (getHumanNodeName[0]) {
			var getHumanNodeNameLength = getHumanNodeName.length;
			var humanArray = new Array();
			for (m=0;m<getHumanNodeNameLength;m++) {
				var getHumanNodeNameValue = getHumanNodeName[m].firstChild.nodeValue;
				var getHumanNodeIDValue = getHumanNodeID[m].firstChild.nodeValue;
				humanArray.push(getHumanNodeNameValue);
				humanArray.push(getHumanNodeIDValue);
			}
		} else {
			var getHumanNodeNameValue = '';
			var getHumanNodeIDValue = '';
			var humanArray = new Array();
			humanArray.push(getHumanNodeNameValue);
			humanArray.push(getHumanNodeIDValue);
		}

		var getMouseNodeName = thisx[i].getElementsByTagName('mousesym');
		var getMouseNodeID = thisx[i].getElementsByTagName('mouseid');
		if (getMouseNodeName[0]) {
			var getMouseNodeNameLength = getMouseNodeName.length;
			var mouseArray = new Array();
			for (m=0;m<getMouseNodeNameLength;m++) {
				var getMouseNodeNameValue = getMouseNodeName[m].firstChild.nodeValue;
				var getMouseNodeIDValue = getMouseNodeID[m].firstChild.nodeValue;
				mouseArray.push(getMouseNodeNameValue);
				mouseArray.push(getMouseNodeIDValue);
			}
		} else {
			var getMouseNodeNameValue = '';
			var getMouseNodeIDValue = '';
			var mouseArray = new Array();
			mouseArray.push(getMouseNodeNameValue);
			mouseArray.push(getMouseNodeIDValue);
		}


	 	// does this row already exist in thisArray? if no, push it into thisArray.
		if ( i == 0 ){	//first item should be pushed in;
			thisArray.push([ratArray,humanArray,mouseArray]);
		 }
		var hasIt = 0;
		var compareArray = new Array();
		compareArray.push([ratArray,humanArray,mouseArray]);
		var compared = compareArray[0][0][1];
		var compared2 = compareArray[0][1][1];

		for (n=0; n<thisArray.length; n++){
			if ( thisArray[n][0][1] == compared && thisArray[n][1][1] == compared2 ){
				hasIt = 1;
				break;
			}
		 }
		if ( hasIt==0 ){
			thisArray.push([ratArray,humanArray,mouseArray]);
		}
	}

	sortedArray = thisArray.sort();

	for (i=0; i<sortedArray.length; i++) {
		var subArray = 3; //there are only rat, human and mouse 3 sub-array;
		for (n=0; n<subArray; n++) {

			for (j=0; j<sortedArray[i][n].length-1; j=j+2) {

				 //get theItemID (rgdid, such as '1325',...);
				var theItemID = sortedArray[i][n][j+1];

				if (thisItem == 'geneList') {
					if (n==0 && theItemID != '') {	//rat genes;
						selectedGeneIDs.push(theItemID);
					 }
					else if (n==1 && theItemID != '') {	//human genes;
						selectedHGeneIDs.push(theItemID);
					 }
					else if (n==2 && theItemID != '') {	//mouse genes;
						selectedMGeneIDs.push(theItemID);
					}
				 }
				else if (thisItem == 'strainList'){
					 if (n == 0 && theItemID != '') { //n=0 for rat strain, select all rat strains for summary;
						selectedStrainIDs.push(theItemID);
					 }
				}
			 } //end j-loop;
		 } //end n-loop;
	} //end i-loop;

}


function iPrintTable(thisItem,div){
	var baseLink,trailLink,linkURL;

	var newTable = document.createElement('TABLE');
	newTable.setAttribute('cellPadding',1);
	var tbody = document.createElement('TBODY');
	newTable.appendChild(tbody);

	for (i=0; i<sortedArray.length; i++) {

		var row = document.createElement('TR');
		var subArray = 3; // there are only gene, qtl, strain 3 sub-array;

		for (n=0; n<subArray; n++) {
			 //define gene's list baseLink, trailLink;
			if (thisItem == 'geneList') {
				if (n==0) {		//rat genes;
					baseLink = 'http://rgd.mcw.edu/tools/genes/genes_view.cgi?id=';
					trailLink = '';
				 }
				else if (n==1) {	//human genes;
					baseLink = 'http://rgd.mcw.edu/tools/genes/genes_view.cgi?id=';
					// baseLink = 'http://rgd.mcw.edu/tools/homologs/homologs_view.cgi?id=';
					trailLink = '&species=1';
				 }
				else if (n==2) {	//mouse genes;
					baseLink = 'http://rgd.mcw.edu/tools/genes/genes_view.cgi?id=';
					// baseLink = 'http://rgd.mcw.edu/tools/homologs/homologs_view.cgi?id=';
					trailLink = '&species=2';
				}
			 }
			else if (thisItem == 'strainList'){ //for strain;
				baseLink = 'http://rgd.mcw.edu/tools/strains/strains_view.cgi?id='; //rat strains;
				trailLink = '';
			}

			var container = document.createElement('TD');
			container.setAttribute('width', 100);

			for (j=0; j<sortedArray[i][n].length-1; j=j+2) {
				var linker = document.createElement('A');

				 //get theItem, theItemID;
				var theTrans = sortedArray[i][n][j];
				var theItem = document.createTextNode(theTrans);
				var theItemID = sortedArray[i][n][j+1];

				linkURL = baseLink + theItemID + trailLink;
				linker.setAttribute('href', linkURL);
				linker.setAttribute('target', 'new');
				linker.appendChild(theItem);
				container.appendChild(linker);
				var thisSpace = document.createTextNode(' ');
				container.appendChild(thisSpace);
			 }
			row.appendChild(container);
		 }
		tbody.appendChild(row);
	}

	clearItem(div);
	document.getElementById(div).appendChild(newTable);
}


function iAppendQtlTable(thisItem,symbol,id,div) {

        var baseLink = 'http://rgd.mcw.edu/objectSearch/qtlReport.jsp?rgd_id=';


	var linkURL;

	var thisx = ireq.responseXML.getElementsByTagName(thisItem);

	var thisArray = new Array();

	for (i=0;i<thisx.length;i++)
	{	
		var getNodeName = thisx[i].getElementsByTagName(symbol);
		var getNodeID = thisx[i].getElementsByTagName(id);

		if (getNodeName[0]) { //if this node exists;
			var getNodeNameLength = getNodeName.length;
			var subArray = new Array();
			for (m=0; m<getNodeNameLength; m++) { //for case: [name1,id1, name2,id2];
				var getNodeNameValue = getNodeName[m].firstChild.nodeValue;
				var getNodeIDValue = getNodeID[m].firstChild.nodeValue;
				if (getNodeNameValue != ''){ //if this node value is null?;
					subArray.push(getNodeNameValue);
					subArray.push(getNodeIDValue);
				}
			}

			 // does this row already exist in thisArray? if no, push it into thisArray.
			if ( i == 0 ){	//first item should be pushed in;
				thisArray.push([subArray]);
			 }
			var hasItq = 0;
			var compareArray = new Array();
			compareArray.push([subArray]);
			var compared = compareArray[0][0][0];

			for (m=0; m<thisArray.length; m++){
				if ( thisArray[m][0][0] == compared ){
					hasItq = 1;
					break;
				}
			 }
			if ( hasItq==0 ){
				thisArray.push([subArray]);
			}
		}
	}

	sortedQtlArray = thisArray.sort();

	 //print QTLs list;
	var newTable = document.createElement('TABLE');
	newTable.setAttribute('cellPadding',1);
	var tbody = document.createElement('TBODY');
	newTable.appendChild(tbody);

	for (i=0; i<sortedQtlArray.length; i++) {

		var row = document.createElement('TR');
		var container = document.createElement('TD');	
		container.setAttribute('width',100);

		for (j=0; j<sortedQtlArray[i][0].length-1; j=j+2) { //for case: [name1,id1, name2,id2];
			var linker = document.createElement('A');

			 //get theItem, theItemID;
			var theTrans = sortedQtlArray[i][0][0];
			var theItem = document.createTextNode(theTrans);
			var theItemID = sortedQtlArray[i][0][1];

			 //store rat or human or mouse(only phenotype) QTL IDs for fulture displaying in Gviewer;
			if (id == "ratid" && theItemID != '') {
				selectedQtlIDs.push(theItemID);
			 }
			else if (id == 'humanid' && theItemID != ''){
				selectedHQtlIDs.push(theItemID);
			}
			else if (id == 'mouseid' && theItemID != ''){
				selectedMQtlIDs.push(theItemID);
			}

			linkURL = baseLink + theItemID;
			linker.setAttribute('href', linkURL);
			linker.setAttribute('target', 'new');
			linker.appendChild(theItem);
			container.appendChild(linker);
			var thisSpace = document.createTextNode(' ');
			container.appendChild(thisSpace);
		 }

		row.appendChild(container);
		tbody.appendChild(row);
	}

	clearItem(div);
	document.getElementById(div).appendChild(newTable);

}


function iPreload() {
	if (document.getElementById) {
		document.getElementById('page_loading').style.visibility = 'hidden';
	} else {
		if (document.layers) { //For NS4
			document.page_loading.visibility = 'hidden';
		} else { //For IE4
			document.all.page_loading.style.visibility = 'hidden';
		}
	}
}


var rssWindow;
var rssDoc;
function openRSS() {

	rssWindow = window.open("", "RSS_feeds", "menubar=no,toolbar=no,location=no,status=yes");
	rssDoc = rssWindow.document;
	//rssDoc.ContentType = "text/xml";
	
	printRssHeader(rssDoc);
	
	disease(rssDoc);
	summary(rssDoc);
	
	printRssFooter(rssDoc);
	
	rssDoc.close();
	rssWindow.status = "Right-click mouse to view source...";
}

function printRssHeader(thisDoc)
{
 // thisDoc.write('<?xml version="1.0" encoding="ISO-8859-1"?>' + '\n'); 
	thisDoc.write('<?xml version="1.0" encoding="utf-8"?>' + '\n');
	thisDoc.write('<rss version="2.0">' + '\n' + ' <channel>' + '\n');
}

function printRssFooter(thisDoc)
{
	thisDoc.write(' </channel>' + '\n' + '</rss>' + '\n');
}

function disease(thisDoc)
{
	thisDoc.write('    <title>Neurological Disease</title>' + '\n');
	thisDoc.write('    <link>http://rgd.mcw.edu/dportal/neurological</link>' + '\n');
	thisDoc.write('    <description>All genes, QTLs and strains information in the neurological disease portal.</description>' + '\n');
}


function summary(thisDoc)
{
	thisDoc.write('    <geneNumber>873</geneNumber>' + '\n');
	thisDoc.write('    <qtlNumber>87</qtlNumber>' + '\n');
	thisDoc.write('    <strainNumber>27</strainNumber>' + '\n');
}


