var queryInteractor = null;
var queryCoordSys = null;
var numCols = 3;

var activeSources = new Array();
var allSources = new Array();
var allDots = new Array();

var t = null;
var usedCoordSys = new Array();
var sourcesCache = new Array();
var initialized = false;
var dotCounts = new Array();
var registryLocation = null;
var sourceResults = new Array();
var ie = false;
var opera = false;
var safari = false;
var firefox = false;
var noHiding = false;
var openDetDotsRow = new Object();
var OFFTOP = 0;
var OFFLEFT = 0;	
var seen = 0;
var globalq;
var globalcs;
var interactionCount = 0;
//test
var COLOR_EXPERIMENTAL = "#D5EF59";
var COLOR_PREDICTED = "#FDE685";
var COLOR_QM = "#A4D6F5"; //"#EBF8FE";
var COLOR_NORMAL = "#F7F4C8";

var INTERACTOR_LIMIT = 20;






/** 
* Function to be called when the sources page loads. Fills the table with the initial sources 
* list from the server.
*/
function dasmiInit(regLoc, q, cs) {
	//document.domain = "mpiat3502.ag3.mpi-sb.mpg.de";
	//alert(document.domain);
	if (!cookieTest(regLoc)){
		//alert("Your browser does not seem to accept cookies form our domain. DASMIweb requires cookies, however. Please have a look at <a href=\"faq.php#cookies\">this FAQ entry</a>");
		dwr.util.setValue("infoH1", "System Information");
		dwr.util.setValue("infoContent", "<p>Your browser does not seem to accept cookies form our domain. <span class=\"dasmiweb\">DASMIweb</span> will not be working without cookies, however. Please have a look at <a href=\"faq.php#cookies\">this FAQ entry</a> to see why we rely on cookies and how you can activate them in your browser.</p>", {escapeHtml:false});
		return;
	}
	setTooltips();
	var ua = window.navigator.userAgent.toLowerCase();
	if (ua.indexOf("opera") != -1){
		opera = true;
		noHiding = true;
	}
	else if (ua.indexOf("msie") != -1){
		ie = true;
		noHiding = true;
		OFFTOP = 2;
		OFFLEFT = 2;
	}
	else if (ua.indexOf("safari") != -1){
		safari = true;
		OFFTOP = 1;
		OFFLEFT = 1;
	}
	else if ((ua.indexOf("firefox") != -1) || (ua.indexOf("iceweasel") != -1)){
		firefox = true;
		OFFTOP = 2;
		OFFLEFT = 1;
	}

	registryLocation = regLoc;

	Dasmi.init(registryLocation, function(isNew){
//		if (isNew){
			//dwr.engine.setRpcType(dwr.engine.ScriptTag);

			dwr.engine.setActiveReverseAjax(true);
			dwr.util.useLoadingMessage("Loading ...");
			dwr.engine.setErrorHandler(errh);
	//	}
		
		// Get the current user setting for automatic id mapping, showing quick config
		// and proper config menu and whether empty sources should be hidden
		UserSettings.getShowQuickConfig(function(val){
			drawQuickConfig(val);
		});
		    
		UserSettings.getShowConfig(function(val){
			drawConfig(val);
		});
		    
		/*Dasmi.getAutoMapping(function(val){
			drawAutoMapping(val);
		});*/

		UserSettings.getShowEmptySources(function(val){
		
			drawEmptyCols(val);
		});
		
		Dasmi.isPerformLikeSearch(function(val){
			drawSearchMode(val);
		});
		
		if (typeof q != "undefined") {
			querySources(regLoc, q, cs);
		} else{
			initInfoArea(true);
		}		
		
		 dwr.engine.beginBatch(); 	
		Dasmi.getAllSources(function(sourcesMap) { 
			allSources = sourcesMap;
		
		});
		Dasmi.getAllSourcesQM(function(qmsources){
			//alert("why");
			for (var id in qmsources){
				allSources[id] = qmsources[id];
			}

		});
		
		Dasmi.getTabbingData(function(data){
		//alert(dump(data));
			for (var i=0; i < $("tabbingList").length; i++) {
				if ($("tabbingList")[i].value == data[2]) {
					$("tabbingList")[i].selected = true;
				}
			}
		});
		
		initSortList();
		/*
		sel = qmid;
			
		}*/	
		
		dwr.engine.endBatch();
	});
	
	
	/*document.getElementById('sourcesForm').onsubmit=function() {
		//if (!validateInput()){
		//	return false;
		//}
		document.getElementById('sourcesForm').target = 'upload_target'; //'upload_target' is the name of the iframe
	}*/
	
}



/**
* Calls the query routine on the server in order to get the interactions from all active sources
* Will refresh the info area when this is complete ...
* @param q ID of the query
* @param cs A coordinate system string
*/
function querySources(reg, q, cs){
	
	var diff = 20000;
	Dasmi.diffToLastQuery(function (difference){
		diff = difference
		
		if (diff < 5000){
			var text = "<img src=\"nogo.png\" />";
			text += "<p><strong>Your last query was less than five seconds ago.</strong></p>";
			text +=	"<p> To minimize the server load your current query has been ignored. Please wait some seconds before resubmiting your query!</p>";
			setInfo("System Information", text);
			return;
		}
		interactionCount = 0;
		clearMainArea();
		
		
		// if there is no q parameter try to read it from the input box	
		if (typeof q == "undefined"){
			q = dwr.util.getValue("userQuery");
			q = trim(q);
		}
		// if there is no cs, then there is none
		if (typeof cs =="undefined"){
			cs = null;
		}
		 
		if (q.length == 0){
			var text = "<img src=\"warning.png\" />";
			text += "<p><strong>No input specified</strong></p>";
			text +=	"<p>Please specifiy a query identifier. For example, you can query by UniProtKB, Entrez Gene, RefSeq, Ensembl, or Pfam identifiers.</p> ";
			setInfo("Query Error", text);
			return;
		}
		
		// if we have a query and a defined CS we can start issuing the query directly
		if (cs != null){
			Dasmi.querySources(q, cs, registryLocation, function(){
			
				//initInfoArea(false);
			});
		}else{ 
			// no coordinate system has been defined so try to determine one automatically
			// get all possible accession types for the query 
			Dasmi.getAccessionType(q, INTERACTOR_LIMIT, function(interactors){
			
				var ids = new Array();	
				var types = new Array();
				if (interactors == undefined){
					var text = "<img src=\"nogo.png\" />";
					text += "<p><strong>Your input contains invalid characters. </strong></p>";
					text +=	"<p>Please remove any special characters from your input. If you think that your input is valid, please <a href=\"contact.php\">tell us</a> the identifier so that we can update <span class=\"dasmiweb\">DASMIweb</span>.</p> ";
					setInfo("Query Error", text);
				}
				else if (interactors.length == 1){
					drawQueryInteractor(interactors[0]);
					Dasmi.setQueryInteractor(interactors[0]);
					// check if the main area is already visible ...
					if ($("mainArea").className == "mainHide"){
						$("mainArea").className = "mainShow";
						closeArea('downloadArea');
						redrawFixedDivs();
					}
					Dasmi.querySources(interactors[0]["dbAccessionId"], interactors[0]["dbCoordSys"], registryLocation, function(){
						//initMainArea(false);
					//alert("queried");
						 //initInfoArea(false);
					});
			   
					
					
					
				}else if (interactors.length == 0){
					var text = "<img src=\"warning.png\" />";
					text += "<p><strong>The identifier <span style=\"color:red\">"+q+"</span> is unknown.</strong></p> ";
					text +=	"<p>Currently, <span class=\"dasmiweb\">DASMIweb</span> supports identifiers from <a href=\"javascript:setUserQuery('ENSG00000196776')\">Ensembl</a>, <a href=\"javascript:setUserQuery('961')\">Entrez Gene</a>, <a href=\"javascript:setUserQuery('21336196')\">GeneInfo</a>, <a href=\"javascript:setUserQuery('PF00049')\">Pfam</a>, and <a href=\"javascript:setUserQuery('Q08722')\">UniProtKB</a>. In addition, instead of querying by names like \"BRCA1\", please try to use database identifiers like <a href=\"javascript:setUserQuery('P38398')\">P38398</a> or <a href=\"javascript:setUserQuery('672')\">672</a>. <br/> If you think that <span style=\"color:red\">"+q+"</span> is a valid identifier of the aforementioned databases, please <strong><a href=\"contact.php\">tell us</a></strong> so that we can update <span class=\"dasmiweb\">DASMIweb</span>.</p>"
					setInfo("Query Warning", text);
					
				}else{
					var text = "<img src=\"warning.png\" />";
					text += "<p><strong>The query "+q+" describes different biological entities.</strong></p>"; 
					
					if (interactors.length >= INTERACTOR_LIMIT){
						text += "<p>We found at least "+INTERACTOR_LIMIT+" entities in our database that contain " +q+" as their identifier or as part of their name. ";
						text += "If the list below does not contain your correct candidate, please try to refine your query."
					}else{
						text += "<p>We found "+interactors.length+" entities in our database that contain " +q+" as their identifier or as part of their name. Please select the correct canidate below. ";
					}
					text += "</p>";
					setInfo("Query Information", text);
					
				
					
					drawPotentialInteractors(interactors, q, false);
				}
					
			});
	    		
		    
		}
	});
}

function batchDecide(reg, q, cs){
	var oldIds = trim(dwr.util.getValue("okbox"));
	if (oldIds.length > 0 ){
		oldIds += "\n";
	}
	dwr.util.setValue("okbox", oldIds + q +" -> " + cs, { escapeHtml:false });
	
	var batchbox = trim(dwr.util.getValue("batchbox"));
	batchbox = batchbox.split("\n");
	batchbox.shift();
	var batchstring = "";
	for (var r = 0; r < batchbox.length; r++){
		batchstring += batchbox[r] + "\n" ;
	}
	dwr.util.setValue("batchbox", batchstring, { escapeHtml:false });
	$("choiceArea").className = "mainHide";
	dwr.util.removeAllRows("choicebody");
	queryBatch(reg);

} 

function loadBatchExample(){
	var batchstring = "1212\nCLH1_HUMAN\nHD\nQ08722\nbad identifier";
	dwr.util.setValue("batchbox", batchstring, { escapeHtml:false });
}

function updateBatchbox(q){
	var batchstring = "";
	for (var r = 0; r < q.length; r++){
	
		batchstring += trim(q[r]) + "\n" ;
	}
	dwr.util.setValue("batchbox", batchstring, { escapeHtml:false });
}

function queryBatch(reg){
	
	var tempIds = trim(dwr.util.getValue("okbox"));
	 tempIds = tempIds.split("\n");
	 var goodIds = new Array();
	for (var j = 0; j < tempIds.length; j++){
		goodIds.push(trim(tempIds[j]));
	}
	
	var q = new Array();
	
	var batchbox = trim(dwr.util.getValue("batchbox"));
	//alert(dump(batchbox));
	var tempQ = batchbox.split("\n");
	for (var j = 0; j < tempQ.length; j++){
		q.push(trim(tempQ[j]));
	}

	var fileFormat = dwr.util.getValue("batchexport");
	
	//alert("q:" + dump(q));
	
	
	var diff = 20000;
	//Dasmi.diffToLastQuery(function (difference){
		//diff = difference
		
		if (diff < 5000){
			var text = "<img src=\"nogo.png\" />";
			text += "<p><strong>Your last query was less than five seconds ago.</strong></p>";
			text +=	"<p> To minimize the server load your current query has been ignored. Please wait some seconds before resubmiting your query!</p>";
			setInfo("System Information", text);
			return;
		}
		interactionCount = 0;
				
		if ((q.length == 0) || (q.length == 1 && trim(q[0]).length == 0)){
			var queries = new Array();
			var systems = new Array();
			if (goodIds.length > 0){
				$("batchstatus").innerHTML = "Will start querying the data sources now.";
				//alert("ready to roll:" + dump(goodIds));
				for (var h = 0; h < goodIds.length; h++){
					var id = goodIds[h].split(" -> ");
					queries.push(id[0]);
					systems.push(id[1]);
					//alert (id[0] +":" +id[1]);
				}
//				alert(dump(queries)+dump(systems));
				Dasmi.batchExport(queries, systems, reg, fileFormat, 30000, function(finished){
					
					/*if (finished){
						alert("finished, download the stuff");
					}else{
						alert("batch export not finished, do you want to keep waiting?");
					}*/
					
					//});
				});
				return;
			}else{
				var text = "<img src=\"warning.png\" />";
				text += "<p><strong>No input specified</strong></p>";
				text +=	"<p>Please specifiy a query identifier. For example, you can query by UniProtKB, Entrez Gene, RefSeq, Ensembl, or Pfam identifiers.</p> ";
				setInfo("Query Error", text);
				return;
			}
		}
		
		
		
		Dasmi.getAccessionType(q[0], INTERACTOR_LIMIT, function(interactors){
			
						
			//alert(dump(interactors));
			var ids = new Array();	
			var types = new Array();
			if (interactors == undefined){
				var unknwonstring = dwr.util.getValue("unknownbox");
				unknwonstring += q.shift() +"\n";
				dwr.util.setValue("unknownbox", unknwonstring, { escapeHtml:false });
				updateBatchbox(q);
				queryBatch(reg);
			}
			else if (interactors.length == 1){
				q.shift();
				var oldIds = trim(dwr.util.getValue("okbox"));
				if (oldIds.length > 0){
					oldIds += "\n";
				} 
				dwr.util.setValue("okbox", oldIds + interactors[0]["dbAccessionId"]+ " -> " + interactors[0]["dbCoordSys"], {escapeHtml:false});
				
				updateBatchbox(q);
				queryBatch(reg);
			}
			else if (interactors.length == 0){
				q.shift();
				
				var unknwonstring = dwr.util.getValue("unknownbox");
				unknwonstring += q.shift() +"\n";
				dwr.util.setValue("unknownbox", unknwonstring, { escapeHtml:false });
				
				updateBatchbox(q);
				queryBatch(reg);
			}else{
				var text = "<img src=\"warning.png\" />";
				text += "<p><strong>The identifier "+q[0]+" describes different biological entities.</strong></p>"; 
				
				if (interactors.length >= INTERACTOR_LIMIT){
					text += "<p>We found at least "+INTERACTOR_LIMIT+" entities in our database that contain " +q[0]+" as their identifier or as part of their name. ";
					text += "If the list below does not contain your correct candidate, please try to refine your query."
				}else{
					text += "<p>We found "+interactors.length+" entities in our database that contain " +q[0]+" as their identifier or as part of their name. Please select the correct canidate below. ";
				}
				text += "</p>";
				setInfo("Query Information", text);
				
				drawPotentialInteractors(interactors, q[0], true);
				// TODO store ids and cs in hidden variables
				// TODO alter drawpotint so that it issues batchqueries
			}
			
			
			//alert("cs:"+dump(cs)+"\n"+"q:" + dump(q));
		});
	
	
		
		//alert("cs:"+dump(cs)+"\n"+"q:" + dump(q));
		
		/*Dasmi.querySources(q, cs, registryLocation, function(){
		
		});
		
		
	*/
}



/**
* Queries the server for information on the current query interactor. If there is one its
* information will be printed in the info area and the main area will be initialised
*/
function initInfoArea(initBool){

	Dasmi.getQueryCoodSys( function(cs){
	//alert(dump(cs));
		if (cs == null)  {
			dwr.util.setValue("infoH1", "General Information")
			dwr.util.setValue("infoContent", "<p> <span class=\"dasmiweb\">DASMIweb</span> is a web server for the dynamic retrieval and sharing of molecular interaction datasets. It is based on a <a href=\"faq.php#dasmi\">distributed system</a> and allows the user to integrate and qualitatively assess interaction data from multiple external resources. </p> <p> To explore the functionalities of <span class=\"dasmiweb\">DASMIweb</span>, try the <a href=\"javascript:querySources('"+registryLocation+"','961','entrez');\">CD47 example</a> (Entrez Gene identifier 961), or browse through our detailed <a href=\"documents.php\">documentation</a>. </p>", {escapeHtml:false});
			clearMainArea();
		} else{
			queryCoordSys = cs;
			if (queryInteractor==undefined){
				Dasmi.getQueryInteractor( function(interactor){
				//alert("query: " + dump(interactor));
					drawQueryInteractor(interactor);
					initMainArea(initBool);
				});
			}else{
				initMainArea(initBool);
			}
        }
	});
 }
 
function drawQueryInteractor(interactor){
	//alert("interactor"+dump(interactor));
	
	queryInteractor = interactor;
	var cs = queryInteractor["dbCoordSys"];
	globalcs = queryInteractor["dbCoordSys"];
	globalq = interactor["dbAccessionId"];
	
	dwr.util.setValue("infoH1", "Interactor Information");
	
	
	var trSymbol = "<tr><td class=\"infotablehead\">Identifier:</td><td class=\"infotablebody\"> " + getXrefLink(interactor["dbCoordSys"], interactor["dbAccessionId"]) +" ("+ getXrefLink(interactor["dbCoordSys"]) +")"; 
	if (globalcs == "Pfam,Protein Sequence"){
		var trDbxrefs = "<tr><td class=\"infotablehead\">Database links: </td><td class=\"infotablebody\"><table>";
	}else{
		var trDbxrefs = "<tr><td class=\"infotablehead\">Database links: <br/> ("+getXrefLink('iproclass')+") </td><td class=\"infotablebody\"><table>";
	}
	// todo transfer into a table
	var uniqueIdTypes = interactor["uniqueIdTypes"];
	var idValues = interactor["idValues"];
	var idTypes = interactor["idTypes"];
	for (var i = 0; i < uniqueIdTypes.length; i++){
		
		trDbxrefs += "<tr><td class=\"infotablesubhead\">" + getXrefLink(uniqueIdTypes[i]) + "</td><td class=\"infotablesubbody\">"; 
		for (var j = 0; j < idValues.length; j++){
			if (idTypes[j] == uniqueIdTypes[i]){
				trDbxrefs += getXrefLink(idTypes[j], idValues[j]) + ", ";
			}
		}
		trDbxrefs += "</td></tr>";
	}
	trDbxrefs += "</table></td></tr>";
	
	
	var trDetails = "";  
	
	var trSpecies = "";
	var trPosition = "";
	
	var tdChromosome = "";
	var tdLocation = "";
		
	var details = interactor["details"];
	for (var det=0; det<details.length; det++){
		if (details[det]["property"].toLowerCase() == "description" || details[det]["property"] == "FullName" || details[det]["property"] == "full name"){
			trSymbol += " (" + details[det]["value"] + ")";
		}
		// pfam stuff 1
		if (details[det]["property"] == "Pfam type" ){
			trDetails += "<tr><td class=\"infotablehead\">Pfam type:</td><td class=\"infotablebody\">"+details[det]["value"] +"</td></tr>";
		}
		else if (details[det]["property"] == "comment" ){
			trDetails += "<tr><td class=\"infotablehead\">Comment:</td><td class=\"infotablebody\">"+details[det]["value"] +"</td></tr>";
		}
		else if (details[det]["property"] == "species" ){
			var species = getXrefLink("taxon", details[det]["value"]);
			trDetails += "<tr><td class=\"infotablehead\">Species:</td><td class=\"infotablebody\">"+species+"</td></tr>";
		}
		else if (details[det]["property"] == "chromosome"){
			trDetails += "<tr><td class=\"infotablehead\">Chromosome:</td><td class=\"infotablebody\">"+details[det]["value"] +"</td></tr>";
		}
		else if (details[det]["property"] == "location"){
			trDetails += "<tr><td class=\"infotablehead\">Location:</td><td class=\"infotablebody\">";
			trDetails += details[det]["value"];
			if (details[det]["value"].indexOf("|") != -1){
				trDetails = trDetails.replace("|", ", ");
			}
			trDetails += "</td></tr>";
		}else if (details[det]["property"] == "domain" ){
			var link = getXrefLink("Pfam", details[det]["value"]);
			trDetails += "<tr><td class=\"infotablehead\">Pfam domain:</td><td class=\"infotablebody\">"+link+"</td></tr>";
		}
		else{
			trDetails += "<tr><td class=\"infotablehead\">"+details[det]["property"]+":</td><td class=\"infotablebody\">"+details[det]["value"] +"</td></tr>";
		} 
	}	
	trSymbol += "</td></tr>";
	/*if (tdChromosome != "" || tdLocation != ""){
		trPosition = "<tr><td class=\"infotablehead\">Genomic context:</td><td class=\"infotablebody\">"+tdChromosome+tdLocation+"</td></tr>";
	}
	*/	
	dwr.util.setValue("infoContent", "<table style=\"width:100%\">" + trSymbol + trDbxrefs + trDetails + "</table>", {escapeHtml:false});
	
 }
 
 
 function drawPotentialInteractors(interactors, query, inBatch){
	
	var table = $("choicebody");
	for (var i = 0; i < interactors.length; i++){ 
	
		var interactor = interactors[i];
		
		//alert(interactor["name"]);
		newTR = table.insertRow(-1);
		if (i % 2 == 0){
			newTR.className = "even";
		}else{
			newTR.className = "odd";
		}
		// BUTTTON
		var newCell = document.createElement('td');
		if (inBatch){
			newCell.innerHTML = "<input type=\"button\" value=\"Select\" onclick=\"batchDecide('"+registryLocation+"' ,'"+interactor["dbAccessionId"]+"','"+interactor["dbCoordSys"]+"') \"/>";
		} else{
			newCell.innerHTML = "<input type=\"button\" value=\"Query\" onclick=\"querySources('"+registryLocation+"' ,'"+interactor["dbAccessionId"]+"','"+interactor["dbCoordSys"]+"') \"/>";
			
		} 
		newTR.appendChild(newCell);
		
		// NAME
		newCell = document.createElement('td');
		//alert(dump(interactor["name"].toLowerCase()));
		//alert(dump(query));
		if (interactor["name"].toLowerCase() == query.toLowerCase()){
			// name and accession are the same
			if (interactor["name"] == interactor["dbAccessionId"]){
				newCell.innerHTML = "<div><span class=\"highlight\">"+ getXrefLink(interactor["dbCoordSys"], interactor["dbAccessionId"]) + "</span>" + "</div><div>("+ getXrefLink(interactor["dbCoordSys"])  +")</div>";
			}else{
				newCell.innerHTML = "<div>"+ getXrefLink(interactor["dbCoordSys"], interactor["dbAccessionId"]) + " (<span class=\"highlight\">"+interactor["name"]+"</span>)" + "</div><div>("+ getXrefLink(interactor["dbCoordSys"])  +")</div>";
			}
		}else{
			newCell.innerHTML = "<div>"+getXrefLink(interactor["dbCoordSys"], interactor["dbAccessionId"])+ "</div><div>(" + getXrefLink(interactor["dbCoordSys"])  + ")</div>";
		}
		newTR.appendChild(newCell);
		
		// DESCRIPTION
		newCell = document.createElement('td');
		var details = interactor["details"];
        if (typeof(details) != "undefined"){
			for (var z=0; z<details.length; z++){
				var detLow = details[z]["property"].toLowerCase();
				if (detLow == "description" || detLow == "fullname" || detLow == "full name"){
					var value = details[z]["value"];
					var oldDesc = newCell.innerHTML;
					var regexp = new RegExp(query.toLowerCase());
					var search = value.toLowerCase().search(regexp);
					if (search != -1){
						oldDesc =  oldDesc + "<div>" + value.substring(0,search) + "<span class=\"highlight\">" + value.substring(search, search+query.length) + "</span> " + value.substring(search + query.length, value.length) +" </div>";
					}else{
						oldDesc =  oldDesc + "<div>" + value + "</div>";
					}
					newCell.innerHTML = oldDesc;
				}
			}
		}		
		newTR.appendChild(newCell);
		
		// DBXREFS
		newCell = document.createElement('td');
		var uniqueIdTypes = interactor["uniqueIdTypes"];
	//	alert(dump(interactor));
		var idValues = interactor["idValues"];
		var idTypes = interactor["idTypes"];
		var oldAcc = newCell.innerHTML;
		for (var k = 0; k < uniqueIdTypes.length; k++){
			oldAcc += "<div><span class=\"detailHeader\">" + getXrefLink(uniqueIdTypes[k]) + ": </span><span>"; 
			for (var l = 0; l < idValues.length; l++){
				if (idTypes[l] == uniqueIdTypes[k]){
					oldAcc += getXrefLink(idTypes[l], idValues[l]) + ", ";
					//oldAcc += idValues[l] + ", ";
				}
			}
			oldAcc += "</span></div>";
		}
		newCell.innerHTML = oldAcc;
		newTR.appendChild(newCell);

		// OTHER
		newCell = document.createElement('td');
		var details = interactor["details"];
        if (typeof(details) != "undefined"){
			for (var z=0; z<details.length; z++){
				var detLow = details[z]["property"].toLowerCase();
				if (detLow == "description" || detLow == "fullname" || detLow == "full name"){
				}
				else {
					var value = details[z]["value"];
					var oldDesc = newCell.innerHTML;
					var regexp = new RegExp(query);
					var search = value.search(regexp);
					if (search != -1){
						
						oldDesc =  oldDesc + "<div><span class=\"detailHeader\">"+detLow+": </span>";
						oldDesc += value.substring(0,search) + "<span class=\"highlight\">" + value.substring(search, search+query.length) + "</span> " + value.substring(search + query.length, value.length) +" </div>";
					}else{
						if (detLow == "species"){
							oldDesc =  oldDesc + "<div><span class=\"detailHeader\">"+detLow+": </span>" + getXrefLink("taxon", value) + "</div>";
							
						}else{
							oldDesc =  oldDesc + "<div><span class=\"detailHeader\">"+detLow+": </span>" + value + "</div>";
						}
					}
					newCell.innerHTML = oldDesc;
				}
			}
			
		}		
		newTR.appendChild(newCell);
	
	
	}
		
		
		
		
	
	$("choiceArea").className = "mainShow";
}

 
 
function getXrefLink(cs, q){
	var link;
	if (q == undefined){
		//link = "<img class=\"outimg\" src=\"out.png\"/><a target=\"_blank\" href =\"";
		link = "<a target=\"_blank\" href =\"";
	}else{
		link = "<a target=\"_blank\" href =\"";
	}
	cs = cs.toLowerCase();
	if (cs == "entrez,gene_id" || cs == "entrez"){
		if (q == undefined){
			link += "http://www.ncbi.nlm.nih.gov/sites/entrez?db=gene";
			link += "\">Entrez Gene</a>";
		}else{
			link += "http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=gene&cmd=Retrieve&dopt=full_report&list_uids="+q; 
			link += "\">"+q+"</a>";
		}
	}
	else if (cs == "uniprot,protein sequence" || cs == "uniprot" || cs == "uniprot_ac" || cs == "uniprot_id"){
				if (q == undefined){
					link += "http://www.uniprot.org/uniprot/";
					link += "\">UniProtKB</a>";
				}else{
					link += "http://www.uniprot.org/uniprot/"+q; 
					link += "\">"+q+"</a>";
				}
	}
	else if (cs == "pfam,protein sequence" || cs == "pfam"){
				if (q == undefined){
					link += "http://pfam.sanger.ac.uk/";
					link += "\">Pfam</a>";
				}else{
					link += "http://pfam.sanger.ac.uk/family?acc="+q; 
					link += "\">"+q+"</a>";
				}
		  }
	else if (cs == "entrez,gene info identifier" || cs == "giid"){
				if (q == undefined){
					link += "http://www.ncbi.nlm.nih.gov/sites/entrez?db=gene";
					link += "\">Entrez GeneInfo</a>";
				}else{
					link += "http://www.ncbi.nlm.nih.gov/sites/entrez?cmd=Retrieve&db=protein&dopt=GenPept&list_uids="+q; 
					link += "\">"+q+"</a>";
				}
			}
	else if (cs == "ensembl,protein sequence" || cs == "ensembl"){
				if (q == undefined){
					link += "http://www.ensembl.org/";
					link += "\">Ensembl</a>";
				}else{
					link += "http://www.ensembl.org/Homo_sapiens/Search/Summary?species=all;idx=;q="+q; 
					link += "\">"+q+"</a>";
				}
		  }
	else if (cs == "ipi"){
		if (q == undefined){
			link += "http://www.ebi.ac.uk/IPI/IPIhelp.html";
			link += "\">IPI</a>";
		}else{
			link += "http://www.ebi.ac.uk/cgi-bin/dbfetch?db=IPI&id="+q; 
			link += "\">"+q+"</a>";
		}
	}
	else if (cs == "unigene"){
		if (q == undefined){
			link += "http://www.ncbi.nlm.nih.gov/sites/entrez?db=unigene";
			link += "\">UniGene</a>";
		}else{
			link += "http://www.ncbi.nlm.nih.gov/sites/entrez?db=unigene&cmd=search&term="+q; 
			link += "\">"+q+"</a>";
		}
	}
	else if (cs == "uniparc"){
		if (q == undefined){
			link += "http://www.ebi.ac.uk/uniparc/";
			link += "\">UniParc</a>";
		}else{
			link += "http://www.uniprot.org/uniparc/"+q; 
			link += "\">"+q+"</a>";
		}
	}
	else if (cs == "refseq"){
		if (q == undefined){
			link += "http://www.ncbi.nlm.nih.gov/RefSeq/";
			link += "\">RefSeq</a>";
		}else{
			link += "http://view.ncbi.nlm.nih.gov/protein/"+q; 
			link += "\">"+q+"</a>";
		}
	}
		  
	else if (cs == "iproclass"){
				if (q == undefined){
					link += "http://pir.georgetown.edu/pirwww/iprolink/biothesaurus.shtml";
					link += "\">iProClass</a>";
				}else{
					link += "http://pir.georgetown.edu/cgi-bin/textsearch_biot.pl?search=1&field0=ALL_IDS&option=Submit&query0="+q; 
					link += "\">"+q+"</a>";
				}
		  }
	else if (cs == "dasmi"){
				if (q == undefined){
					link += "http://dasmi.bioinf.mpi-inf.mpg.de/";
					link += "\">DASMI</a>";
				}else{
					link += "http://dasmi.bioinf.mpi-inf.mpg.de/"+q; 
					link += "\">"+q+"</a>";
				}
		  }
	else if (cs == "biomyn"){
				if (q == undefined){
					link += "http://biomyn.mpi-inf.mpg.de/";
					link += "\">BioMyn</a>";
				}else{
					link += "http://biomyn.mpi-inf.mpg.de/index.php?ispc=UniProtKB&mid="+q; 
					link += "\">"+q+"</a>";
				}
		  }
	else if (cs == "pubmed"){
				if (q == undefined){
					link += "http://www.ncbi.nlm.nih.gov/pubmed/";
					link += "\">PubMed</a>";
				}else{
					link += "http://www.ncbi.nlm.nih.gov/pubmed/"+q; 
					link += "\">"+q+"</a>";
				}
		  }
	else if (cs == "taxon"){
				if (q == undefined){
					link += "http://www.ncbi.nlm.nih.gov/Taxonomy/";
					link += "\">NCBI Taxonomy</a>";
				}else{
					link += "http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?mode=Info&lvl=3&p=mapview&p=has_linkout&p=blast_url&p=genome_blast&lin=f&keep=1&srchmode=5&unlock&id="+q; 
					link += "\">"+q+"</a>";
				}
	}
	else{
		if (q == undefined){
			link += "http://dasmi.bioinf.mpi-inf.mpg.de/";
			link += "\">DASMI</a>";
			}else{
			link += "http://www.google.com/search?hl=en&btnG=Google+Search&aq=f&oq=&q="+q; 
			link += "\">"+q+"</a>";
		}
	}
	//alert(link);
	return link;
}
 
 
function showBatch(){
	dwr.util.setValue("infoH1", "Batch query mode");
	dwr.util.setValue("infoContent", "<p>The <b>batch retrieval mode</b> can be used to request interactions for <b>up to 10 interactors</b> with a single query. The results will not be visualized, however, but <b>direct links to the result files</b> will be provided. For batch retrieval, insert the identifiers of your query proteins in the text box below and press the query button.</p>", {escapeHtml:false});
	dwr.util.setValue("batchbox", "");
	dwr.util.setValue("okbox", "");
	dwr.util.setValue("unknownbox", "");
	$("batchstatus").innerHTML = "";
	$("batchArea").className = "mainShow";
	$("batch").innerHTML = "<a href=\"javascript:hideBatch()\">Close batch</a>";
	redrawFixedDivs();
	redrawOpenDetDots();
}

function hideBatch(){
	$("batchArea").className = "mainHide";
	$("batch").innerHTML = "<a href=\"javascript:showBatch()\">Batch retrieval</a>";
	redrawFixedDivs();
	redrawOpenDetDots();
}
 
 function recreateAllImages(){
	var color = COLOR_EXPERIMENTAL;
	x_createAndStoreImage("IntAct", color, doNothing());
	x_createAndStoreImage("3did", color, doNothing());
	x_createAndStoreImage("MINT", color, doNothing());
	x_createAndStoreImage("DIP", color, doNothing());
	x_createAndStoreImage("iPfam", color, doNothing());
	x_createAndStoreImage("PiNS", color, doNothing());
	x_createAndStoreImage("CCSB-HI1", color, doNothing());
	x_createAndStoreImage("HPRD", color, doNothing());
	x_createAndStoreImage("MDC", color, doNothing());
	color = COLOR_PREDICTED;
	x_createAndStoreImage("Bioverse", color, doNothing());
	x_createAndStoreImage("Bioverse-core", color, doNothing());
	x_createAndStoreImage("LDSC", color, doNothing());
	x_createAndStoreImage("LDSC-core", color, doNothing());
	x_createAndStoreImage("APMM1", color, doNothing());
	x_createAndStoreImage("APMM2", color, doNothing());
	x_createAndStoreImage("DPEA", color, doNothing());
	x_createAndStoreImage("LP", color, doNothing());
	x_createAndStoreImage("DIMA-DPEA", color, doNothing());
	x_createAndStoreImage("DIMA-STRING", color, doNothing());
	x_createAndStoreImage("InterDom", color, doNothing());
	x_createAndStoreImage("LLZ", color, doNothing());
	x_createAndStoreImage("RCDP50", color, doNothing());
	x_createAndStoreImage("TW", color, doNothing());
	x_createAndStoreImage("DIMA-DPROF", color, doNothing());
	x_createAndStoreImage("RDFF", color, doNothing());
	x_createAndStoreImage("Sanger", color, doNothing());
	x_createAndStoreImage("Sanger-core", color, doNothing());
	x_createAndStoreImage("OPHID", color, doNothing());
	x_createAndStoreImage("POINT", color, doNothing());
	x_createAndStoreImage("HiMAP", color, doNothing());
	x_createAndStoreImage("HomoMINT", color, doNothing());
	x_createAndStoreImage("HiMAP-core", color, doNothing());
	
 }
 



/**
* 
*/
function initMainArea(initBool){
	$("mainArea").className = "mainShow";
	closeArea('downloadArea');
	initSortList();
	redrawFixedDivs();
	getAndDrawQualityMeasures();
	if(!initBool){
		//alert("false");
        return;
	}else{
	//alert("main");
		numCols = 3;
        dwr.engine.beginBatch(); 
		// batch mode required here, otherwise interactions will not be able to be drawn because the intpattern_ is missing
        Dasmi.getAllSources(function(sourcesMap) { 
			allSources = sourcesMap;
		//alert(dump(sourcesMap));
            activeSources = new Array();
            // clear everything in the head apart from the pattern
            dwr.util.removeAllRows("interactionshead", { 
          	    filter:function(tr) {
           	    	return (tr.id != "intheadpattern");
                }
            });
            // clear everything in the body apart from the pattern
            dwr.util.removeAllRows("interactionsbody", { 
          	    filter:function(tr) {
           	    	return (tr.id != "intpattern");
                }
            });
            dwr.util.cloneNode("intheadpattern", { idSuffix:"_" });
            dwr.util.cloneNode("intpattern", { idSuffix:"_" }); // helper pattern, will be deleted after next reload
            // add a new column for every active source
            for (var id in sourcesMap){
        		var source = sourcesMap[id];
				if (source != null){
				
				   // alert(dump(source));
					//if (source.isActive){
					if (source.isActive && source.isCompatible){
						addSortOption(source.nickname, source.id);
						
						activeSources[source.id] = source; 
						addColumn("interactions", source);
					//alert(source.nickname);
					}
				}
            }
            $("intheadpattern_").style.display = "";
        });
		
		Dasmi.getAllSourcesQM(function(qmsources){
			for (var id in qmsources){
				allSources[id] = qmsources[id];
			}
		});

		Dasmi.getSourceResults( function(res){
			sourceResults = res;
			for (var id in res){
				//alert(res[id]);
				if ($(id+"_stat") != null){
					
					if (res[id] == -1){
						$(id+"_stat").innerHTML = "<span class=\"sourceheadstatX\">X</span>";
					}else{
						$(id+"_stat").innerHTML = res[id];
					}
				}
			}
		});
		//alert(dump(queryInteractor));

        Dasmi.getInteractions( function(interactionsMap){
		
		
        	allDots = new Array();
			
	        interactionCount = 0;
	        for (var id in interactionsMap){

                interactionCount++;
                var interaction = interactionsMap[id];

                allDots[id] = new Array();
				dwr.util.cloneNode("intpattern_", { idSuffix:id });
                var participants = interaction["participants"];

                var self = false;
                // add the information for the interaction partner
                for (var j=0; j<participants.length; j++){
                    var interactor = participants[j]["interactor"];
				//if (interactionCount == 1) alert(dump(interactor["idTypes"]));

                    if ((interactor["dbAccessionId"] != queryInteractor["dbAccessionId"]) || (self == true)){
						var oldName = $("name_" + id).innerHTML;
						$("name_" + id).innerHTML = oldName + "<div>"+ interactor["name"] +"</div>";

						var oldAcc = $("dbaccession_" + id).innerHTML;
						
						// oid already used, hence a compelx
						if (oldAcc != ""){
							$("dbaccession_" + id).innerHTML = oldAcc + "<div>";
						}
						//$("description_"+ id).innerHTML = ""
                        var idTypes = interactor["idTypes"];
						var idValues = interactor["idValues"];
						if (typeof(idTypes) != "undefined"){
							var hadOne = false;
							for (var r = 0; r < idTypes.length; r++){
								if (idTypes[r] == "entrez" || idTypes[r] == "pfam"){
									
									var oldAcc = $("dbaccession_" + id).innerHTML;
									if (hadOne){
										oldAcc += ", ";
									}
									$("dbaccession_" + id).innerHTML = oldAcc +  "<span>"+ getXrefLink("entrez", idValues[r]) +"</span>";
									hadOne = true;
								}
							}
						}
						// no mapping was found, just print the primary id
						if ($("dbaccession_" + id).innerHTML == "") {
							$("dbaccession_" + id).innerHTML = "<div>"+ interactor["dbAccessionId"] ;
						}
						oldId = $("dbaccession_" + id).innerHTML;
						$("dbaccession_" + id).innerHTML = oldId + "</div>";
						
						var details = interactor["details"];
                        //alert(dump(details));	
						if (typeof(details) != "undefined"){
						
							for (var z=0; z<details.length; z++){
								//alert(details[z]["property"] + details[z]["value"]);
								//var oldDet = $("description_" + id).innerHTML;
								var detLow = details[z]["property"].toLowerCase();
								if (detLow == "description" || detLow == "fullname" || detLow == "full name"){
									if (participants.length > 2){
										var oldDesc = $("description_"+ id).innerHTML;
									}else{
										var oldDesc = "";
									}
									$("description_"+ id).innerHTML =  oldDesc + "<div>" + details[z]["value"] + "</div>";
	                            }
							}
						}
                    }else{
                        self = true;
                    }
                }
//alert("alive");
                // create the dots for each source that has reported this interaction
                var sources = interaction["sources"];
//alert(dump(sources));
                for (var k=0; k<sources.length; k++){ 
                	//alert(dump(sources));
                	var s = sources[k];
					//alert(dump(s));
	               	var theSource = activeSources[s];
	               	//alert(theSource);
					// source is a QM source
					if (theSource == undefined){
						continue;
					}
					
					$(s+"_"+id).className = "dot";
	               	allDots[id].push(s+"_"+id);
	               
					
					if (ie){
						$(s+"_"+id).onClick = "getDetails('"+sources[k].toLowerCase()+"','"+id+"')";
						$(s+"_"+id).parentNode.innerHTML = $(s+"_"+id).parentNode.innerHTML;	
					}
					else{
						$(s+"_"+id).setAttribute("onClick", "getDetails('"+sources[k].toLowerCase()+"','"+id+"')");
					}
                }
				
				
				if (participants.length > 2){
					$("intpattern_" + id).className = "complex";
				}
                else if (!(interactionCount % 2)){
                    $("intpattern_" + id).className = "odd";
                }else{
                	$("intpattern_" + id).className = "even";
                }
                $("intpattern_" + id).style.display = ""; // officially we should use table-row, but IE prefers "" for some reason
            }
			
			Dasmi.getTabbingData(function(tabbingData){
				drawInteractionHeader(tabbingData[0], tabbingData[1], tabbingData[2]);
			});
			
			getAndDrawEmptyCols();

			UserSettings.getSelectedQM(function(selqm){
//alert("Selection: "+selqm);
				getQM(selqm)						
			});

			Dasmi.getOpenDetDots(function(dd){
				openDetDotsRow = dd; 
				drawOpenDetDots();
			});

        });
     
     		
		getAndDrawQualityMeasures();

        dwr.engine.endBatch();      
    }   	
}

function getAndDrawQualityMeasures(){
	Dasmi.getAllQMMeasures( function(measures){
		measures.sort();
		dwr.util.removeAllOptions("qmList");
		if (measures.length == 0){
			dwr.util.addOptions("qmList", ['No confidence scores available']);
			UserSettings.setSelectedQM("No confidence scores available", function(){
		});
		}else{
			dwr.util.addOptions("qmList", ['Select confidence measure ...']);
			dwr.util.addOptions("qmList", measures);	
		}
	});
}


function drawInteractionHeader(count, tabbingStart, tabbingWidth){
	interactionCount = count;
	var standardString = "" + count + " interactions (showing " + tabbingStart + " to " + (tabbingStart + tabbingWidth - 1) + ")"
	var previousString = "<img style=\"cursor:pointer;vertical-align:middle;float:none\" src=\"previous.png\" alt=\"previous\" onClick=\"javascript:getPreviousTabbing()\"/>";
	var nextString = "<img style=\"cursor:pointer;vertical-align:middle;float:none\" src=\"next.png\" alt=\"next\" onClick=\"javascript:getNextTabbing()\"/>";
	// we have less interactions then we can show, no need for tabbing
	if (tabbingStart <= 1 && count < (tabbingStart + tabbingWidth)){
		$("mainH1").innerHTML =  "" + count + " interactions (showing " + tabbingStart + " to " + (count) + ")";
	}else{
		// already hit the next button once
		if (tabbingStart > 1){
			// and there are more interactions avaiblabe on the server
			if (count > tabbingStart + tabbingWidth){
				$("mainH1").innerHTML = standardString + previousString + nextString;
			}// but there are no more next interactions availabe
			else{
				standardString = "" + count + " interactions (showing " + tabbingStart + " to " + (count) + ")"
				$("mainH1").innerHTML = standardString + previousString;
			}
		}// iniital showing and there are more interactions available
		else{
			$("mainH1").innerHTML = standardString + nextString;
		}
	}
}

function getNextTabbing(){
	Dasmi.increaseTabbingStart( function(start){
		clearDetDots();
		initMainArea(true);
		
		//alert(dump(start));
	});
	
} 

function setTabbingWidth(num){
	num = parseInt(dwr.util.getValue("tabbingList"));
	//alert(dump(num));
	Dasmi.getTabbingData(function(data){
		//  if there are less interactions then we could show, always start with the first
		if (data[0] <= num){
			Dasmi.setTabbingStart(1, function(data){
			
			});
		}
		Dasmi.setTabbingWidth(num, function(){
			clearDetDots();
			initMainArea(true);
		});
		//alert(dump(nums));
	});
	
	
}

function queryQmSources(){
	//alert("Please note that it might take up to " + interactionCount + "sec to query all quality servers. ");
	var rough = "thousand";
	if (interactionCount < 50) {
		rough = "hundred";
	}
	
	showSourceDetails("Please be patient", "DASMIweb will now retrieve the confidence scores for all interactions from all available scoring servers. <br/><br/> Currently this requires one request for each of the "+interactionCount+" interactions. As we do not want to flood servers with too manyrequests, we delay their execution. <br/> <br/>We are working on a system that only requieres a single query for each server, thus there will be no noticable delay in the near future. ", "", "");
	
	//showSourceDetails("Function disabled", "We are currently experiencing load problems with the DASMIweb server. As the retrieval of confidence scores is computationally very demanding, we have temporarily disabled this functionality to assure that the rest of DASMIweb is working properly. We are working hard on solving the load problems and will reactivate this feature as soon as possible. We are very sorry for any inconveniences.", "", "");
	Dasmi.queryQMSources(function(){
		
	});

}
	
function getPreviousTabbing(){
	Dasmi.decreaseTabbingStart( function(start){
		clearDetDots();
		initMainArea(true);
		//alert(dump(start));
	});
}

/**
* Function to be called from DASMI Java servlet code. Required to modify the user interface
* as soon as any changed happen to the backend code. 
*@param actionId 
*/
function javaGate(actionId, rowId, cells, css){
//alert("javagate");
	// add a new table column for a source
	if (actionId == "interactionsbody" || actionId == "interactionshead"){
			
		var tab = $(actionId)
		newTR = tab.insertRow(-1);
		newTR.id = rowId;		
		if (css != ""){
			newTR.className = css;
		}
		numCols = cells.length;
		for (var i=0; i< cells.length; i++){
			var cell = cells[i];
			if (actionId == "interactionshead"){
				var newCell = document.createElement('th');
				//if (cell[3].indexOf("img/") > 0 ){
				//	cell[3] = cell[3].replace("img/", "");
					//alert(cell[3]);
				//}
				//alert(cell[3]);
			}else{
				//var newTD = newTR.insertCell(-1);
				var newCell = document.createElement('td');
			}		
			
			if (cell[0] != ""){
				newCell.id = cell[0];	
				
			}
			if (cell[1] != ""){
				newCell.setAttribute("name", cell[1]);
			}
			if (cell[2] != ""){
				newCell.className = cell[2];
			}
			newCell.innerHTML = cell[3];
			
			//if (actionId == "interactionshead"){
				newTR.appendChild(newCell);
			//}
			//addSortOption(rowId);
		}
		//interactionCount++;
	}
	// add a new dot for an interaction that has been determined
	else if (actionId == "dot"){
		if ($(rowId+"_"+cells) != null){
			
			$(rowId+"_"+cells).className = css;
			if (ie){
				$(rowId+"_"+cells).onClick = "getDetails('" + rowId + "','" + cells + "');";
				$(rowId+"_"+cells).parentNode.innerHTML = $(rowId+"_"+cells).parentNode.innerHTML;
			}
			else{
				$(rowId+"_"+cells).setAttribute("onClick", "getDetails('" + rowId + "','" + cells + "')");
			}
			
		}
	}
	// create a source image if it is not already present
	else if(actionId == "source"){
		var color = "#EFEFEF";
		for (var i=0; i< cells.length; i++){
			if (cells[i].toLowerCase() == "predicted"){
				color = COLOR_PREDICTED;
			}else if (cells[i].toLowerCase() == "y2h" || cells[i].toLowerCase() == "crystal structure analysis" || cells[i].toLowerCase() == "experimental" || cells[i].toLowerCase() == "literature curated" || cells[i].toLowerCase() == "manually curated"){
				color = COLOR_EXPERIMENTAL;
			}
		}	
		//alert(dump(colR+colG+colB));
		x_createAndStoreImage(rowId, color, doNothing());
	}
	// the results of a new qm methods have arrived, add it to the drop down box
	else if(actionId == "newQm"){
		getAndDrawQualityMeasures();
		//dwr.util.addOptions("qmList", [rowId]);
	}
	// a source has not returned interactions but errors, thus mark it with a red cross
	else if(actionId == "problem"){
		if (rowId =="activeQMThreads"){
			
			//showSourceDetails("We have a problem", "Currently there are too many requests "+cells+" on our DASMIweb server. As the retrieval of confidence scores is computationally very demanding, we can currently not handle your request. Please try again later. ", "", "");
		}
		
		
	}
	// the query interactor has been determined and is beeing pushed from the backend
	else if (actionId == "drawQueryInteractor"){
		drawQueryInteractor(rowId);
		// check if the main area is already visible ...
		if ($("mainArea").className == "mainHide"){
			$("mainArea").className = "mainShow";
			closeArea('downloadArea');
			redrawFixedDivs();
		}
	}
	else if (actionId == "mainH1"){
		drawInteractionHeader(rowId, cells, css);
	}
	else if (actionId == "sourceData"){
		//rowId = datasource
		//cells = number of interactions
		//alert(rowId["nickname"]+cells);
		var htmlId = rowId["id"]+"_stat";
		if ($(htmlId) != undefined){
			if (cells == "-1"){
				$(htmlId).innerHTML = "<span class=\"sourceheadstatX\">X</span>";
			}else{
				$(htmlId).innerHTML = "<span class=\"sourceheadstat\">"+cells+"</span>";
			}	
		}
		addSortOption(rowId.nickname, rowId.id);
	}
	else if (actionId == "batchStatus"){
		//rowId = status
		//cells = active threads
		// css = interactions
		
		// still pending
		if (rowId == "0"){
			$("batchstatus").innerHTML = "<b>" +cells + "</b> requests pending, already received <b>" + css + "</b> interactions.";
		}else if(rowId =="-1"){
			$("batchstatus").innerHTML = "<span style=\"color:red\">ERROR: The <b>server encountered a problem</b> when generating the export file. Please <b><a href=\"contact.php\">contact us</a></b>. We are sorry for any inconveniences.</span>" ;
			
		}
		else{
//		alert(rowId);
			// not fully finished
			if (cells == "0"){
				$("batchstatus").innerHTML = "<span style=\"color:green\">All requests finished, received <b>" + css + "</b> interactions. Download the results <a href=\"" +rowId+ "\">here</a>.</span>" ;
			}else{
				$("batchstatus").innerHTML = "<span style=\"color:darkorange\"><b>"+cells + "</b> requests are still pending, have received <b>" + css + "</b> interactions so far. Download the preliminary results <a href=\"" +rowId+ "\">here</a>.</span>" ;
				
			}
			//$("batchstatus").innerHTML = cells + " requests still pending. , already received " + css + " interactions.";
		}// finished
		
		
	}
	// some out of sync problem between java dasmi and javascript
	else{
	//alert(actionId);
		alert("A server error occured. If the error persists, please contact us and mention the error 'javagate'. Thank you and sorry for the inconveniences.");
	}
	
}

/*
* Creates a new table row containing all the details for this interactions. If the row is alreasy present its content
* will be update, e.g. with the details of a different source
*/
function getDetails(sourceId, intId, store){
	// if no initmain has been called, there will not be any acivteSources array.
	if (store == null){
		store = true;
	} 
	var newDiv = document.createElement("div");
	newDiv.innerHTML = "<br/>^";
	newDiv.className = "openDetailDot";
	newDiv.id = sourceId+"_"+intId+"_detDot";
	//newDiv.setAttribute("name", intId+"_detDot");
	
	if (ie){
		$(newDiv).onClick = "getDetails('"+sourceId+"','"+ intId+"')";
	}
	else{
		$(newDiv).setAttribute("onClick", "getDetails('"+sourceId+"','"+ intId+"')");
	}
	var pos = findPos($(sourceId + "_" + intId));
	newDiv.style.left = pos[0] + OFFLEFT + "px" ;
	newDiv.style.top = pos[1] + OFFTOP + "px" ;
		
	// first, create the row if not already present
	if ($("intpattern_"+intId+"_detail") == null){
		for (var i=0; i < $("interactionsbody").rows.length; i++) {
            if ($("interactionsbody").rows[i].id == "intpattern_"+intId){
				newTR = $("interactionsbody").insertRow(i+1);
	            newTR.id = "intpattern_"+intId+"_detail";
	            var newTD = document.createElement('td');
				newTD.className = "interDet";
				
				newTD.colSpan = numCols; 
	            newTD.id = intId;
	            newTR.appendChild(newTD);
					
					$("mainArea").appendChild(newDiv);
					
					//openDetDots.push(sourceId+"_"+intId);
					openDetDotsRow[intId] = [sourceId];
					if (store){
						Dasmi.setOpenDetDots(openDetDotsRow, function(){
						});	
					}
					if (ie){
						$(sourceId+"_"+intId+"_detDot").parentNode.innerHTML = $(sourceId+"_"+intId+"_detDot").parentNode.innerHTML;		
					}
					
	                break;
	            }
	        }
	    }// the details view was already shown
	    else{
			// if the user clicked the same dot that is alreay active, remove the activtion and delete the row
//		var detDots = document.getElementsByName(intId+"_detDot");
			var dotsInRow = openDetDotsRow[intId];
			if (store){
				openDetDotsRow[intId] = new Array();
			}
			for (var i=0; i< dotsInRow.length; i++){
				//var index = openDetDots.indexOf(dotsInRow[i]+"_"+intId); 
				//openDetDots.splice(index,1);
				$("mainArea").removeChild($(dotsInRow[i]+"_"+intId+"_detDot"));
				if (dotsInRow[i] == sourceId){
					$("interactionsbody").removeChild($("intpattern_"+intId+"_detail"));
					if (store){
						Dasmi.setOpenDetDots(openDetDotsRow, function(){
						});
					}				
					redrawOpenDetDots(pos[1]);
					return;
				}
	        }
			$("mainArea").appendChild(newDiv);
			if (store){
				openDetDotsRow[intId] = [sourceId];
				Dasmi.setOpenDetDots(openDetDotsRow, function(){
				});	
			}
			//openDetDots.push(sourceId+"_"+intId);
			if (ie){
				$(sourceId+"_"+intId+"_detDot").parentNode.innerHTML = $(sourceId+"_"+intId+"_detDot").parentNode.innerHTML;		
			}
		}
		
		var selectedQM = "";
		UserSettings.getSelectedQM(function(selqm){
			selqm = trim(selqm.substring(0,selqm.indexOf("(")));
			for (id in allSources){
				if (allSources[id]["nickname"] == selqm){
					selectedQM = id;
					//alert(selectedQM);
				} 
			}
			//alert(selectedQM);
		});
		
	   // and finally retrieve all details for this interaction and this source
	    Dasmi.getDetails(intId, sourceId, function(details){

	        var interactionDetails = new Array();
			var otherInteractionDetails = new Array();
			var interactorDetails = new Array();
			
			var i = 0;
			//alert(dump(details));

			for (i = 0; i < details.length; i++) {
			
				var property = details[i]["property"];
				var value = details[i]["value"];
				var sources = details[i]["sources"];
				
				if (trim(value).length == 0){
					continue;
				}	
				if (property == "pubmed"){
					value = getXrefLink("PubMed", value);
					property = getXrefLink("PubMed");
				}else if(property == "domain"){
					value = getXrefLink("Pfam", value);
					property = getXrefLink("Pfam");
				} 
				// if the value of the detail is a link, make it cliackable
				else if (value.indexOf("http://")  == 0){
					value = "<a href=\"" + value + "\" target=\"_blank\">"+value+"</a>";
				}
				else if (property.indexOf("db_xref") == 0){
					property = getXrefLink(property.substring(8)) + " IDs"; 
					
				}
									
				// if a detail has a source assigned, check if its the current one. details for the current soruce and details without source string will be printed first
				
				if (property.indexOf("@") != -1){
					//alert(property+value);
					var id = property.substring(0,property.indexOf("@"));
					property = property.substring(property.indexOf("@")+1);
					if (typeof interactorDetails[id] == "undefined"){
						interactorDetails[id] = "";
					}
					interactorDetails[id] += "<tr><td class='detailAttr'>" + property + "</td>"  + "<td class='detailValue'>" + value + "</td></tr>";
				}else{
					if (sources.length == 0){
						if (typeof interactionDetails[""] == "undefined"){
							interactionDetails[""] = "";
						}
						interactionDetails[""] += "<tr><td class='detailAttr'>" + property + "</td>" + "<td class='detailValue'>" + value + "</td></tr>";
					}else{ 
						for (var k = 0; k < sources.length; k++){
							if (sources[k] == sourceId || sources[k] == selectedQM){
								if (typeof interactionDetails[sources[k]] == "undefined"){
									interactionDetails[sources[k]] = "";
								}
								interactionDetails[sources[k]] += "<tr><td class='detailAttr'>" + property + "</td>" + "<td class='detailValue'>" + value + "</td></tr>";
							} else{ 
								if (typeof otherInteractionDetails[sources[k]] == "undefined"){
									otherInteractionDetails[sources[k]] = "";
								}
								otherInteractionDetails[sources[k]] += "<tr class=\"inactiveDetailAttr\"><td class='detailAttr'>" + property + "</td>" + "<td class='detailValue'>" + value + "</td></tr>";
							}
						}			
					}
				}
			}

			var finalText = "";
			if (i == 0){
	             finalText = "<div class='noDetail'>No additional details available</div>";
	        }			
			if (interactionDetails.length > 0){  
				finalText += "<div class='detailHead'>Additional details for interaction: </div>"
			}
			//alert(dump(interactorDetails));
			for (var id in interactionDetails){
				if (typeof(allSources[id]) != "undefined"){
					finalText += "<div class=\"detailOtherInteractions\">Details from source "+allSources[id]["nickname"]+"</div><table class=\"detailTable\">";
				} else{
					finalText += "<div class=\"detailOtherInteractions\">Details from source "+id+"</div><table class=\"detailTable\">";
				} 
				if (typeof(interactionDetails[id]) == "string"){
					finalText += interactionDetails[id];
				}
				finalText += "</table>";
			}
			
			for (var id in otherInteractionDetails){
				//alert(dump([id]));
				if (typeof(allSources[id]) != "undefined"){
					finalText += "<div class=\"detailOtherInteractions\">Details from source "+allSources[id]["nickname"]+"</div><table class=\"detailTable\">";
				}else{
					finalText += "<div class=\"detailOtherInteractions\">Details from source "+id+"</div><table class=\"detailTable\">";
				}
				 
				if (typeof(otherInteractionDetails[id]) == "string"){
					finalText += otherInteractionDetails[id];
				}
				finalText += "</table>";
			}
			
			for (var id in interactorDetails){
				finalText += "<div class='detailHeadInteractor'>Additional details for interactor "+id+":</div><table class=\"detailTable\">";
				if (typeof(interactorDetails[id]) == "string"){
					finalText += interactorDetails[id];
				}
				finalText += "</table>";
			}
			
			$(intId).innerHTML =  finalText + "</table>";
	     	redrawOpenDetDots();
	    });
	
}

function drawOpenDetDots(){
	for (var id in openDetDotsRow){
		if (id == "each"){
			break;	
		}
		var rowDots = openDetDotsRow[id];
		for (var j=0; j< rowDots.length; j++){
	var dotId = rowDots[j]+"_"+id;
//alert(dotId);
			getDetails(rowDots[j], id, false);
		}
	}	
}

function redrawOpenDetDots(topPos){
	//var topPos = newTopPos.substring(0,newTopPos.length-2); // cut the "px" off
	//alert(topPos);
//alert(dump(openDetDots));
//alert(dump(openDetDotsRow));
	for (var id in openDetDotsRow){
		if (id == "each"){
			break;	
		}
		var rowDots = openDetDotsRow[id];
//	alert(dump(rowDots));
		for (var j=0; j< rowDots.length; j++){
			var dotId = rowDots[j]+"_"+id;
			var pos = findPos($(dotId));
			//alert(pos[1]+"--"+topPos);
			if (topPos == null){
				$(dotId+"_detDot").style.left = pos[0] + OFFLEFT + "px";			
				$(dotId+"_detDot").style.top = pos[1] + OFFTOP + "px";
			}
			else if (pos[1] > topPos){
				//var dotPos = findPos($(dotId+"_detDot"));
				$(dotId+"_detDot").style.top = pos[1] + OFFTOP +"px";
			}	
		}
	}	
}



/*
* Deletes all the visible content from the interaction main area
*/
function clearMainArea(){

	Dasmi.clearCache( function(){
    		q = null;
			cs = null;
        });

	$("mainArea").className = "mainHide";
    dwr.util.removeAllRows("interactionshead", { 
        filter:function(tr) {
            return (tr.id != "intheadpattern");
        }
    });
	
	
	dwr.util.removeAllRows("choicebody");
	$("choiceArea").className = "mainHide";
	$("batchArea").className = "mainHide";
	
	initSortList();
	
    // clear everything in the body apart from the pattern
    dwr.util.removeAllRows("interactionsbody", { 
        filter:function(tr) {
            return (tr.id != "intpattern");
        }
    });
	dwr.util.setValue("mainH1", "No Interactions");
	dwr.util.removeAllOptions("qmList");
	dwr.util.addOptions("qmList", ['No confidence scores available']);
	UserSettings.setSelectedQM('No confidence scores available', function(){
		clearDetDots();
		closeArea('sourceDetailsArea');
	
	});
	


}

function clearDetDots(){
	for (var id in openDetDotsRow){
	/*	if (id == "each"){
			break;
		}*/
		var rowDots = openDetDotsRow[id];
		for (var j=0; j< rowDots.length; j++){
			var dotId = rowDots[j]+"_"+id+"_detDot";
			if ($(dotId) != null){
				$("mainArea").removeChild($(dotId));
			}
		}
	}
	openDetDotsRow = new Object();
	Dasmi.setOpenDetDots(openDetDotsRow, function(){
	});	
}


/*
* Adds a new table column for each active source. The table head will
* contain the rotated image containing the source nickname and the body
* will contain a pattern to be copied later
*/
function addColumn(tableId, source){
	numCols++;
	//alert(tableId);
	
    var tableHeadObj = $(tableId+"head");
	for (var h=0; h<tableHeadObj.rows.length; h++) {
        // check out not to change the pattern ...
        if (tableHeadObj.rows[h].id != "intheadpattern"){
    		var newTH = document.createElement('th');
    		newTH.setAttribute("name", source.id);
    	//	if (source.isConverted){
  		   //   	newTH.innerHTML = "<div id=\""+source.id+"_stat\" class=\"sourceheadstat\"></div><a href=\""+source.helperurl+"\" style=\"text-decoration:none\" target=\"_blank\"><img src=\"img/" + source.nickname + "_conv.png\" alt=\"" +source.nickname + "\" border=0/><a/>";
	      	//	newTH.className = "conv";
	      	//} else{
   		      	//newTH.innerHTML = "<div id=\""+source.id+"_stat\" class=\"sourceheadstat\"></div><a href=\""+source.helperurl+"\" style=\"text-decoration:none\" target=\"_blank\"><img src=\"img/" + source.nickname.toLowerCase() + ".png\" alt=\"" +source.nickname.toLowerCase() + "\" border=0/></a>";
				newTH.innerHTML = "<div id=\""+source.id+"_stat\" class=\"sourceheadstat\"></div><a href=\""+source.helperurl+"\" style=\"text-decoration:none\" target=\"_blank\"><img src=\"img/" + source.nickname.toLowerCase() + ".png\" alt=\"" +source.nickname.toLowerCase() + "\" border=0/></a>";
	            newTH.className = "sourcehead";
	      //  }
	      	tableHeadObj.rows[h].appendChild(newTH);           
        }
	}
    // here we want to change the pattern .. but not the original one, just the copy for this round ...
	var tableBodyObj = $(tableId+"body");
	for (var i=0; i<tableBodyObj.rows.length; i++) {
        if (tableBodyObj.rows[i].id != "intpattern"){
            var newCell = tableBodyObj.rows[i].insertCell(-1);
			newCell.innerHTML = "<div id=\""+(source.id)+"_\"/>&nbsp;</div>";	
			newCell.className = "dotarea";
			newCell.setAttribute("name", source.id);
			//newCell.style.padding = "0px";

 /*           if (source.isConverted){
	    		
	    	} else{

	    	}*/
        }
	}
}


function setUserQuery(value){
	dwr.util.setValue("userQuery",value);

}


function clearCache(){
    if (confirm("Do you really want to delete all interactions?")){
        Dasmi.clearCache( function(){
            initInfoArea(true);
			q = null;
			cs = null;
        });
		// not ideal, but better than checking in the file everythime ...
		recreateAllImages();
    }
	
	
}

function clearSources(){
    if (confirm("Do you really want to delete all the sources from your session? All currently stored interaction will be deleted as well!")){
        Dasmi.clearSources( function(){
            initSourcesArea();
            initInfoArea(true);
        });
    }
}


function loadSources(regUrl){
    Dasmi.loadSources(regUrl, function(){
        initSourcesArea();
    });
}





/**
* Retrieves the selected quality measure from the DASMI and colors the dots respectively.
*/
function getQM(id){
	//alert(dump(id));
	var qmid = id;
//	alert(id);
	Dasmi.getAllDots( function(dots){
	
		allDots = dots;
		var sel;
		// no id is used if the task to retrieve the qms was issued from the website
		// and id will be transerfered if the user settings are applied
		if (qmid == undefined){
			sel = dwr.util.getValue("qmList");
			
		}else{
			sel = qmid;
			for (var i=0; i < $("qmList").length; i++) {
				if ($("qmList")[i].value == sel) {
					$("qmList")[i].selected = true;
				}
			}
		}
		
		
		
		//alert(sel);
		// remove every highlighting and return to normal mode
		i = 0;
		for (var id in allDots){
			if (id == "each"){
				break;
			}
	        var rowDots = allDots[id];
			
	        if (rowDots != undefined){
			
	        	for (var j=0; j<rowDots.length; j++) {
				//if (i == 0 ) alert(dump(rowDots));	
					if ($(rowDots[j]) != undefined){
			     		$(rowDots[j]).innerHTML = "";
						$(rowDots[j]).style.backgroundColor = "";
						var stringtest = sel.toLowerCase();
						if (stringtest == "select confidence measure ..." || stringtest == "no confidence scores available"){
							$(rowDots[j]).className = "dot";
			            }else{
							$(rowDots[j]).className = "dotInactive";
			            }
					}
		        }
		    }
		}
		
		if (sel == "Select confidence measure ..." || sel == "No confidence scores available"){ 
			closeArea('sourceDetailsArea');
		}else{
			var found = false;
			// if its a proper QM source
			/*Dasmi.getAllSourcesQM(function(qmsources){
				for (var id in qmsources){
					//allSources[id] = qmsources[id];
					var qms = qmsources[id];
					if (sel.indexOf(qms.nickname) == 0){
						found = true
						var desc = qms.description;
						var range = "";
						var link = qms.helperurl;
						
						var method = sel.substring(sel.indexOf("(") + 1, sel.indexOf(")"));
						var methods = qms.description.split("@");
						for (var meti in methods){
							var test = methods[meti];
							//alert(dump(methods[i]).method);	
							if (test.indexOf(method) == 0){
								//desc = test;
								var parts = test.split("|");
								for (var parti in parts){
									var part = trim(parts[parti].toLowerCase());
									//alert(part+method.toLowerCase());
									
									if (part.indexOf(method.toLowerCase()) == 0){
										desc = parts[parti].substring(method.length+1);
									}
									else if (part.indexOf("range") == 0){
										range = part.substring(6);
									}else if (part.indexOf("link") == 0){
										link = part.substring(5);
									}
								}
							}
						}
						
						showSourceDetails("Details for "+sel, desc, range, link);
						
					}
				}
			});*/
			//. if its a score from a normal source
			//if (!found){
				//alert(dump(activeSources));
				for (var id in allSources){
					var qms = allSources[id];
					if (sel.indexOf(qms.nickname) == 0){
					//alert("found something");
						var desc = qms.description;
						var range = "";
						var link = qms.helperurl;
												
						var method = sel.substring(sel.indexOf("(") + 1, sel.indexOf(")"));
						var methods = qms.description.split("@");
						for (var meti in methods){
							var test = methods[meti];
							//alert(dump(methods[i]).method);	
							if (test.indexOf(method) == 0){
								//desc = test;
								var parts = test.split("|");
								for (var parti in parts){
									var part = trim(parts[parti].toLowerCase());
									//alert(part+method.toLowerCase());
									
									if (part.indexOf(method.toLowerCase()) == 0){
										desc = parts[parti].substring(method.length+1);
									}
									else if (part.indexOf("range") == 0){
										range = part.substring(6);
									}else if (part.indexOf("link") == 0){
										link = part.substring(5);
									}
								}
							}
						}
						
						showSourceDetails("Details for "+sel, desc, range, link);
					}
				}
			//}
		}
			

			
		

		// now get the respective selection and apply it
	    Dasmi.getQM(sel, function(inters){
		//alert(dump(inters));
//		alert(dump(allDots));
			// if there are QM interactions for the interactor
	        if (inters != undefined){
				var aboveOne = false;
				
	            // iterate through all interactions
				for (var id in inters) {
					if (inters[id] > 1){
						aboveOne = true;
					}
				}
				for (var id in inters) {
				//if (id == "1212-1213"){
				//	alert("wtf");
				//}
		             // if the interactions the QM scores are associated with are present in the HTML
	                var rowDots = allDots[id];
					
					var className = null;
		            if (rowDots != undefined){
						className = "Highlight";
                    	// then iterate through all active sources to change the dots
	                    for (var j=0; j<rowDots.length; j++) {
							// dot that should not actually be one, cause its a qm ... better fix this
							if ($(rowDots[j]) == undefined){
								continue;
							}
							//alert(rowDots[j]);
							var val = inters[id] * 100;
							var value = (255 - Math.floor(95 * inters[id]));
							var back = 'rgb(' + value + ',' + value + ',255)'; 
		                    var temp = new Array();
		                    temp = val.toString().split('.');
		                    val = temp[0];
		                    var op = 1-inters[id];
		                    $(rowDots[j]).className = "dotWhite";
							
							// values that do not range between 0 and 1 cannot be drawn nicely
							var valString = ""+inters[id];
							if (valString.indexOf(".") > 0){
								var print = valString.substring(0, valString.indexOf(".")+3);
							}else{
								var print = valString;
							}
							$(rowDots[j]).innerHTML = "<div class=\"nobp\">"+print+"</div>";
							if (inters[id] > 1 || aboveOne){
								$(rowDots[j]).style.backgroundColor = "#FFD2CF";
								
							}else{
								$(rowDots[j]).style.backgroundColor = back;
							}
	                    }
	                }
	            }
	//alert(dump(inters));				
	        }
	
	    });


		// store the shown qm in the user settings
		UserSettings.setSelectedQM(sel, function(){
		});
	});

}


function drawQuickConfig(bool){
	if (bool){
		$("quickConfigHide").style.backgroundImage = "url(open.jpg)";
		
		//$("quickConfigHide").onClick =  Effect.MoveBy('quickConfig', 0, -190);
		$("quickConfig").style.right = "-210px";
	}else{
		$("quickConfigHide").style.backgroundImage = "url(close.jpg)";
		//$("quickConfigHide").onClick =  Effect.MoveBy('quickConfig', 0, 190);
		$("quickConfig").style.right = "0px"
		
	}
}

function initSortList(){
	Dasmi.getSortingMode(function(mode){
		//alert(mode);
		if (mode == "desc"){
			$("sortMode").innerHTML = "<option selected=\"selected\" value=\"desc\">&darr;</option> <option value=\"asc\">&uarr;</option> ";
		}else{
			$("sortMode").innerHTML = "<option value=\"desc\">&darr;</option> <option selected=\"selected\" value=\"asc\">&uarr;</option> ";
		}
	});
	Dasmi.getSortingRef(function(ref){
		dwr.util.removeAllOptions("sortRef");
		dwr.util.addOptions("sortRef", ['Consensus', 'ID']);
		
		for (var i=0; i < $("sortRef").length; i++) {
			if ($("sortRef")[i].value == ref) {
				$("sortRef")[i].selected = true;
			}
		}
	});
} 


function addSortOption(text, key){
  var newOption = document.createElement('option');
  newOption.text = text;
  newOption.value = key;
  var list = $("sortRef");

  try {
    list.add(newOption, null);
  }
  catch(ex) {
    list.add(newOption); 
  }
}

	
	


function setSort(){
	var sortRef = dwr.util.getValue("sortRef");
	var sortMode = dwr.util.getValue("sortMode");
	
	Dasmi.setSorting(sortRef, sortMode);
	
	
		
} 

function sort(){
	dwr.engine.beginBatch(); 	
	setSort();
	Dasmi.sortInteractions(function (answer){
		//alert(dump(answer));
		clearDetDots();
		initMainArea(true);
	});
	dwr.engine.endBatch();
	
}


function showSourceDetails(head, description, range, link){

	$("sourceDetailsArea").style.display = "";
	$("sourceDetailsHeadText").innerHTML = head;
	var text = "<div> " + description + "</div>";
	if(range != ""){
		text += "<div>Range: " + range + "</div>";
	}if (link != ""){
		text += "<div><a href=\"" + link + "\" target=\"_blank\">"+link+"</a></div>";
	}
	$("sourceDetailsBody").innerHTML = text;
}

function redirect_to (destination) {
	window.location.href = destination;
}



function drawEmptyCols(bool){
	if (noHiding){
		$("toggleText").style.display = "none";
	
	}else{
		Dasmi.getSourceResults(function(sourceResults){
	//	alert(dump(sourceResults));
			if (bool){
				for (var id in sourceResults){
					if (sourceResults[id] == 0){
						var elems = document.getElementsByName(id);
						for (j = 0; j < elems.length; j++){
							$(elems[j]).style.display= "";		
						}
					}
					
				}
				$("emptyColsStatus").style.color = "green";
				$("emptyColsStatus").innerHTML = "YES";
			} else{
				for (var id in sourceResults){
					if (sourceResults[id] == 0){
						var elems = document.getElementsByName(id);
						for (j = 0; j < elems.length; j++){
							$(elems[j]).style.display = "none";
						}
					}
				}
				$("emptyColsStatus").style.color = "red";
				$("emptyColsStatus").innerHTML = "NO";
			}
			redrawOpenDetDots();
		});	
	}
}



function drawSearchMode(bool){
	if (bool){
		$("searchMode").innerHTML = "Partial/Full-text";
		$("searchMode").style.color = "red";
	}else{
		$("searchMode").innerHTML = "Exact";
		$("searchMode").style.color = "green";
		
	}
}

function drawConfig(bool){
	if (bool){
		//$("quickToggleConfig").innerHTML = "Close Source Configuration";
        $("configArea").style.display = "";
        $("confButton").value = "Close Source Configuration";
        initSourcesArea();
		
    }else{
		closeArea("configArea");
	
    }

}

function toggleEmptyCols(){
	UserSettings.switchShowEmptySources(function(val){
		drawEmptyCols(val);
	});
}

function getAndDrawEmptyCols(){
	UserSettings.getShowEmptySources(function(val){
		drawEmptyCols(val);
	});
}

function toggleQuickConfig(){
	
	UserSettings.switchShowQuickConfig(function(val){
		drawQuickConfig(val);
	});
}


function toggleSearchMode(){
	Dasmi.switchPerformLikeSearch(function(val){
		drawSearchMode(val);
	});
}


function toggleConfig(){
	UserSettings.switchShowConfig(function(val){
		drawConfig(val);
	});
}

function exportToFile(fileType){
	if (fileType == undefined){
		sel = dwr.util.getValue("expList");
	} else{
		sel = fileType;
	}
	if (sel != "nil"){
		Dasmi.saveToFile(sel, function(path){
			$("downloadArea").style.display = "inline";
			if (path == null){
				$("downloadArea").innerHTML = "The server encountered a problem when preparing the File for download. Please <a href=\"contact.php\">contact us</a>. <img id=\"downloadClose\" src=\"close.gif\" onclick=\"javascript:closeArea('downloadArea')\"></img>";
			}else{
				$("downloadArea").innerHTML = "To download the file, please click <b><a href=\""+path+"\">here</a></b><img id=\"downloadClose\" src=\"close.gif\" onclick=\"javascript:closeArea('downloadArea')\"></img>";
			}
//			window.open(path, "Download Interactions");
		});
	}
}

function closeArea(id){
	
	if (id == "downloadArea"){
		$("downloadArea").style.display = "none";
		$("expList")[0].selected = true;
		
	} else if(id == "configArea"){
		//$("quickToggleConfig").innerHTML = "Show Source Configuration";    
        $("configArea").style.display = "none";       
        $("confButton").value = "Show Source Configuration";
		redrawFixedDivs();
		redrawOpenDetDots();
		UserSettings.setShowConfig(false,function(val){

		});
	}else if (id == "sourceDetailsArea"){

		$("sourceDetailsArea").style.display = "none";
	}	

}

function stt(mes){
	var tmp = "sttTimeout('"+mes+"')";
	var t = setTimeout(tmp, 400);
}

function sttTimeout(mes){
	$("tooltip").innerHTML = mes;
	$("tooltip").className = "ttVis";
}

function htt(){
	clearTimeout(t);
	setTimeout(httTimeout, 800);
}

function httTimeout(){
	$("tooltip").innerHTML = "";
	$("tooltip").className = "ttUnvis";
}


/************************************************************************************
FORMER SERVER.JS
************************************************************************************/



var coordSysCache = {}; // later storing the coordinate systems coming from the server
var activeCs = null;
// array containg all the input fields in the server page. Usefull for validation purposes


function setStatus(text){
    dwr.util.setValue("statusText", text, {escapeHtml:false});
}

function setInfo(header,text){
	dwr.util.setValue("infoH1", header);
	$("infoContent").innerHTML = text;
}




/** 
* Function to be called when the sources page loads. Fills the table with the initial sources 
* list from the server.
*/
function initSourcesArea() {
    getCoordSystems();
}



function getCoordSystems(cs){
	
    var queryCs = null;
    Dasmi.getUsedCoordinateSystems(function(coords){
	
    	usedCoordSys = unmarshalCoordSys(coords);
    	var links = new Array();
    	var newEntry = "<a href=\"javascript:getNewSource()\" class =\"linkUnselected\">Add New Source</a>";
		var newLI = document.createElement('li');
		newLI.innerHTML = newEntry;
		if (cs != undefined){
			queryCs = cs;
		} 
		// if we have a query interactor than his cs is the active one (most likely)
		else if (queryCoordSys != null){
			queryCs = getCoordSysHash(queryCoordSys);
			//links.push("<a onClick=\"getCoordSystems()\" class=\"linkSelected\">"+getCoordSysHash(queryCoordSys)+"</a>");
		}
		var inThere = false;
		for (coor in usedCoordSys){
			if (usedCoordSys[coor] == queryCs){
				inThere = true;
			}
		}
	//alert(dump(usedCoordSys));
	//alert(dump(queryCs));
	    if (queryCs == null){
	    	getNewSource();
	    }
	    else{
			dwr.util.removeAllOptions("csList");
			$("csList").appendChild(newLI);
	        for (i=0; i<usedCoordSys.length; i++){
            	var link = "<a href=\"javascript:getCoordSystems('"+usedCoordSys[i]+"')\" ";
	            // an active query interactor, thus highlight the query coord sys
                if (queryCs == usedCoordSys[i]){
                    link += "class=\"linkSelected\">";
                } else {
                    link += "class=\"linkUnselected\">";
                }
           		link += usedCoordSys[i] + "</a>";
				newLI = document.createElement('li');
				newLI.innerHTML = link;
				$("csList").appendChild(newLI);
	        }
    	    
        	if (!inThere){
				fillTable("Entrez,Gene_ID");
			}else{
				fillTable(queryCs);
			}
		}
    });
}


	

function getNewSource(sourceType){

	$("sources").style.display = "none";
	dwr.util.removeAllOptions("csList");    
	var newEntry = "<a href=\"javascript:getNewSource()\" class =\"linkSelected\">Add New Source</a>";
	var newLI = document.createElement('li');
	newLI.innerHTML = newEntry;
	$("csList").appendChild(newLI);
    for (i=0; i<usedCoordSys.length; i++){
		var link = "<a href=\"javascript:getCoordSystems('"+usedCoordSys[i]+"')\" class=\"linkUnselected\">";
        link += usedCoordSys[i] + "</a>";
		newLI = document.createElement('li');
		newLI.innerHTML = link;
		$("csList").appendChild(newLI);
    }
	
	//if (sourceType == "server"){
		dwr.util.removeAllRows("newEntry");
	

		newTR = $("newEntry").insertRow(-1);
		newTR.style.display = "none";
		var newTD = document.createElement('td');
		newTD.className = "newEntryTableHead";
		newTD.innerHTML = "Active<img src=\"q.jpg\" class=\"help\" onmouseover=\"Tip(tt('newAct'))\"/>";
		newTR.appendChild(newTD);
		newTD = document.createElement('td');
		newTD.className = "newEntryTableBody";
		newTD.innerHTML = "<input type=\"checkbox\" id=\"isActive\" checked=\"checked\"/>    <div id=\"isActiveHelp\" class=\"formHelp\"></div>";
		newTR.appendChild(newTD);
		
		newTR = $("newEntry").insertRow(-1);
		newTR.style.display = "none";
		var newTD = document.createElement('td');
		newTD.className = "newEntryTableHead";
		newTD.innerHTML = "ID<img src=\"q.jpg\" class=\"help\" onmouseover=\"Tip(tt('newID'))\" />";
		newTR.appendChild(newTD);
		newTD = document.createElement('td');
		newTD.className = "newEntryTableBody";
		newTD.innerHTML = "<span id=\"id\">1</span>      	 	<span id=\"idHelp\" class=\"formHelp\"></span>";
		newTR.appendChild(newTD);
		
		newTR = $("newEntry").insertRow(-1);
		var newTD = document.createElement('td');
		newTD.className = "newEntryTableHead";
		newTD.innerHTML = "Name<img src=\"q.jpg\" class=\"help\" onmouseover=\"Tip(tt('newName'))\" />";
		newTR.appendChild(newTD);
		newTD = document.createElement('td');
		newTD.className = "newEntryTableBody";
		newTD.innerHTML = "<input type=\"text\" id=\"nickname\" size=\"20\" onChange=\"validate(this.id, this.value)\" size=\"8\"/>       	<span id=\"nicknameHelp\" class=\"formHelp\"></span>";
		newTR.appendChild(newTD);
		
		newTR = $("newEntry").insertRow(-1);
		var newTD = document.createElement('td');
		newTD.className = "newEntryTableHead";
		newTD.innerHTML = "Description<img src=\"q.jpg\" class=\"help\" onmouseover=\"Tip(tt('newDesc'))\" /><div class=\"newEntryOptional\">(optional)</div>";
		newTR.appendChild(newTD);
		newTD = document.createElement('td');
		newTD.className = "newEntryTableBody";
		newTD.innerHTML = "<input type=\"text\" id=\"description\" size=\"50\" onChange=\"validate(this.id, this.value)\"/>        	<span id=\"descriptionHelp\" class=\"formHelp\"></span>";
		newTR.appendChild(newTD);
		
	if (sourceType == "file"){
		newTR = $("newEntry").insertRow(-1);
		var newTD = document.createElement('td');
		newTD.className = "newEntryTableHead";
		newTD.innerHTML = "PSI-MI XML file<img src=\"q.jpg\" class=\"help\" onmouseover=\"Tip(tt('newFile'))\" />";
		newTR.appendChild(newTD);
		newTD = document.createElement('td');
		newTD.className = "newEntryTableBody";
		newTD.innerHTML = "<input type=\"file\" name=\"file\" id=\"file\" size=\"70\"/>			<span id=\"fileHelp\" class=\"formHelp\"></span>";
		newTR.appendChild(newTD);
	}else{
		newTR = $("newEntry").insertRow(-1);
		var newTD = document.createElement('td');
		newTD.className = "newEntryTableHead";
		newTD.innerHTML = "URL<img src=\"q.jpg\" class=\"help\" onmouseover=\"Tip(tt('newURL'))\" />";
		newTR.appendChild(newTD);
		newTD = document.createElement('td');
		newTD.className = "newEntryTableBody";
		newTD.innerHTML = "<input type=\"text\" id=\"url\" size=\"50\" value=\"http://\" onChange=\"validate(this.id, this.value)\"/>           	<span id=\"urlHelp\" class=\"formHelp\"></span>";
		newTR.appendChild(newTD);

		newTR = $("newEntry").insertRow(-1);
		var newTD = document.createElement('td');
		newTD.className = "newEntryTableHead";
		newTD.innerHTML = "Server type<img src=\"q.jpg\" class=\"help\" onmouseover=\"Tip(tt('newServer'))\" />";
		newTR.appendChild(newTD);
		newTD = document.createElement('td');
		newTD.className = "newEntryTableBody";
		//newTD.innerHTML = "<select id=\"coordinateSystem\" multiple=\"multiple\" size=\"6\" maxsize=\"6\"></select>            	<span id=\"coordinateSystemHelp\" class=\"formHelp\"></span>";
		newTD.innerHTML = "<select id=\"serverType\" size=\"2\" maxsize=\"2\"><option selected=\"selected\">DASMI</option><option>PSICQUIC</option></select>            	<span id=\"serverTypeHelp\" class=\"formHelp\"></span>";
		newTR.appendChild(newTD);
		
		newTR = $("newEntry").insertRow(-1);
		var newTD = document.createElement('td');
		newTD.className = "newEntryTableHead";
		newTD.innerHTML = "Identifier system<img src=\"q.jpg\" class=\"help\" onmouseover=\"Tip(tt('newCS'))\" />";
		newTR.appendChild(newTD);
		newTD = document.createElement('td');
		newTD.className = "newEntryTableBody";
		//newTD.innerHTML = "<select id=\"coordinateSystem\" multiple=\"multiple\" size=\"6\" maxsize=\"6\"></select>            	<span id=\"coordinateSystemHelp\" class=\"formHelp\"></span>";
		newTD.innerHTML = "<select id=\"coordinateSystem\" size=\"6\" maxsize=\"6\"></select>            	<span id=\"coordinateSystemHelp\" class=\"formHelp\"></span>";
		newTR.appendChild(newTD);
		
		newTR = $("newEntry").insertRow(-1);
		var newTD = document.createElement('td');
		newTD.className = "newEntryTableHead";
		newTD.innerHTML = "Confidence measure<img src=\"q.jpg\" class=\"help\" onmouseover=\"Tip(tt('newQM'))\" /><div class=\"newEntryOptional\">(optional)</div>";
		newTR.appendChild(newTD);
		newTD = document.createElement('td');
		newTD.className = "newEntryTableBody";
		newTD.innerHTML = "<input type=\"checkbox\" id=\"isQM\" />        <div id=\"isQMHelp\" class=\"formHelp\"></div>";
		newTR.appendChild(newTD);
	
	}
	
		newTR = $("newEntry").insertRow(-1);
		var newTD = document.createElement('td');
		newTD.className = "newEntryTableHead";
		newTD.innerHTML = "Labels<img src=\"q.jpg\" class=\"help\" onmouseover=\"Tip(tt('newLabels'))\" /><div class=\"newEntryOptional\">(optional)</div>";
		newTR.appendChild(newTD);
		newTD = document.createElement('td');
		newTD.className = "newEntryTableBody";
		newTD.innerHTML = "<select id=\"labels\" size=\"3\" maxsize=\"5\" value=\"notSelected\"></select>            	<span id=\"labelsHelp\" class=\"formHelp\"/></span>";
		newTR.appendChild(newTD);
		
		newTR = $("newEntry").insertRow(-1);
		newTR.id = "buttonRow";
		newTR.className = "buttonRow";
		var newTD = document.createElement('td');
		newTD.colSpan = 3;
		newTD.className = "buttons";
		newTD.innerHTML = "<button onClick=\"addSource();\" >Add Source</button>		 </form>         <!--button onClick=\"this.form.reset()\">Clear Values</button-->  ";
		newTR.appendChild(newTD);
		//       <button onClick=\"clearSources()\">Remove All Sources</button>        <button onClick=\"loadSources('"+registryLocation+"')\">Load Sources From Registry</button>         <button onClick=\"toggleConfig()\">Close Configuration</button>
		clearNewLine(sourceType);
	

	
	/*	var tab = $("newEntry");
		newTR = tab.insertRow(-1);
		var content = "<td class=\"newEntryTableHead\">Active<img src=\"q.jpg\" class=\"help\" onmouseover=\"Tip(tt('newAct'))\"/></td>			<td class=\"newEntryTableBody\">	     		<input type=\"checkbox\" id=\"isActive\" checked=\"checked\"/>	            <div id=\"isActiveHelp\" class=\"formHelp\"></div>	        </td> ";
		newTR.innerHTML = content;		
			*/
	if (sourceType == "file"){
	
		$("newEntrySelection").style.display = "none";
		$("newEntry").style.display = "";
	/*	var urlrows = document.getElementsByName("urlrows");
		for (i=0; i < urlrows.length; i++){
			urlrows[i].style.display = "none";
		}
		var filerows = document.getElementsByName("filerows");
		for (i=0; i < filerows.length; i++){
			filerows[i].style.display = "";
		}*/
	}
	else {
		$("newEntrySelection").style.display = "";
		$("newEntry").style.display = "";
	/*	var urlrows = document.getElementsByName("urlrows");
		for (i=0; i < urlrows.length; i++){
			urlrows[i].style.display = "";
		}
		var filerows = document.getElementsByName("filerows");
		for (i=0; i < filerows.length; i++){
			filerows[i].style.display = "none";
		}*/
	}
	
	
	redrawFixedDivs();
	redrawOpenDetDots();
}

/**
* Removes all the entries from the table and rebuilds it using the latest
* list from the server.
*/
function fillTable(csHash) {
	//$("newEntrySelection").style.display = "none";
    var coordSys = coordSysCache[csHash] // get the coord sys belonging to this hash
	
	Dasmi.getSources(coordSys, function(sourcesMap){
		sourcesCache = sourcesMap;
		//alert(dump(sourcesMap));
	  // $("allIsActive").setAttribute("onclick", "switchAllSourceIsActive(this.checked, '"+csHash+"')");
		if (ie){
			// FUKCING IE ONCLICK BUG .....
			$("allActive").parentNode.innerHTML = "<img id=\"allUnactive\" onClick=\"switchAllSourceIsActive('true', '"+csHash+"' )\" src=\"unchecked.png\"></img>&nbsp;<img id=\"allActive\"  onClick=\"switchAllSourceIsActive('false', '"+csHash+"' )\"  src=\"checked.png\"></img>";
			
		}
		else{
			$("allActive").setAttribute("onClick", "switchAllSourceIsActive('false', '"+csHash+"')");
			$("allUnactive").setAttribute("onClick", "switchAllSourceIsActive('true', '"+csHash+"')");
		}
       	dwr.util.removeAllRows("serverbody", { 
        	filter:function(tr) {
    	    	return (tr.id != "pattern" && tr.id != "newEntry" && tr.id != "buttonRow");
            }
        });
        var source;
        //  people.sort(function(p1, p2) { return p1.name.localeCompare(p2.name); });
		for (var id in sourcesMap){
			source = sourcesMap[id];
			
            //alert(dump(source));
          	dwr.util.cloneNode("pattern", { idSuffix:id });
          	$("tisActive"+id).checked = source.isActive;
          	// display inactive and active sources differntly
			var labels = source.labels;
			var isQM = false;
			var isExperimental = false;
			var isPredicted = false;
			for (var x in labels){
				if (labels[x] == "interaction quality measure"){
					isQM = true;
					break;
				}
				
				if (labels[x].toLowerCase() == "predicted"){
					isPredicted = true;
					break;
				} else if (labels[x].toLowerCase()  == "y2h" || labels[x].toLowerCase() == "crystal structure analysis" || labels[x].toLowerCase() == "experimental" || labels[x].toLowerCase() == "literature curated" || labels[x].toLowerCase() == "manually curated"){
					isExperimental = true;
					break;
				}
			}
          	if(source.isActive){
				if(isQM){
					$("tisActive"+id).parentNode.parentNode.className= "activeQMSource";
				}else if(isExperimental){
					$("tisActive"+id).parentNode.parentNode.className ="activeExpSource";
				}else if(isPredicted){
					$("tisActive"+id).parentNode.parentNode.className = "activePredSource";
				}
				 
           	}else{
           	    if(isQM){
					$("tisActive"+id).parentNode.parentNode.className= "inactiveQMSource";
				}else if(isExperimental){
					$("tisActive"+id).parentNode.parentNode.className ="inactiveExpSource";
				}else if(isPredicted){
					$("tisActive"+id).parentNode.parentNode.className = "inactivePredSource";
				}
          	}
          	//$("image").src = source.nickname;
          	dwr.util.setValue("tid" + id, source.id);
           	dwr.util.setValue("tnickname" + id, source.nickname);
    	    dwr.util.setValue("tdescription" + id, source.description);
			
          	
			// we actually use this webservice, its just dtunneld trough a das server
			//if (source.nickname == "IntAct"){
			//	dwr.util.setValue("turl" + id, "http://www.ebi.ac.uk/intact/binary-search-ws/binarysearch");
			//}//else{
				dwr.util.setValue("turl" + id, source.url);
			//}
			//
          	//dwr.util.setValue("tadminemail" + id, source.adminemail);
          	//dwr.util.addOptions("tcapabilities" + id, source.capabilities);
          	//dwr.util.addOptions("tcoordinateSystem" + id, unmarshalCoordSys(source.coordinateSystem));
          	dwr.util.addOptions("tlabels" + id, source.labels);
			
          	$("pattern" + id).style.display = ""; // officially we should use table-row, but IE prefers "" for some reason
    	}
		$("newEntry").style.display = "none";
		$("newEntrySelection").style.display = "none";
		$("sources").style.display = "";
		
		redrawFixedDivs();
		redrawOpenDetDots();
    });
}

function redrawFixedDivs(){
	$("export").style.top = ($("mainArea").offsetTop + 5) +"px" ;
	$("qm").style.top = ($("mainArea").offsetTop + 5) +"px" ;
	$("downloadArea").style.top = ($("export").offsetTop + 29) +"px" ;
	
}

/**
* Changes the isActive status of a source on the server side. Does not need a subsequent redraw
* of the table since nothing changes except the checkmark 
*/
function switchSourceIsActive(id, csHash){
	// strip the unwanted part from the id, i.e. get "DS_310" from "statusDS_310"
	//alert(id.substring(9));
	Dasmi.switchSourceIsActive(id.substring(9), function(result){
				
		var source = sourcesCache[id.substring(9)];
		var labels = source.labels;
		var isQM = false;
		var isPredicted = false;
		var isExperimental = false;
		for (var x in labels){
			if (labels[x] == "interaction quality measure"){
				isQM = true;
				break;
			}
			if (labels[x].toLowerCase() == "predicted"){
				isPredicted = true;
				break;
			} else if (labels[x].toLowerCase()  == "y2h" || labels[x].toLowerCase() == "crystal structure analysis" || labels[x].toLowerCase() == "experimental" || labels[x].toLowerCase() == "literature curated" || labels[x].toLowerCase() == "manually curated"){
				isExperimental = true;
				break;
			}
		}

		if (result){
			if(isQM){
				$(id).parentNode.parentNode.className= "activeQMSource";
			}else if(isExperimental){
				$(id).parentNode.parentNode.className ="activeExpSource";
			}else if(isPredicted){
				$(id).parentNode.parentNode.className = "activePredSource";
			}
		}else{
			if(isQM){
				$(id).parentNode.parentNode.className= "inactiveQMSource";
			}else if(isExperimental){
				$(id).parentNode.parentNode.className ="inactiveExpSource";
			}else if(isPredicted){
				$(id).parentNode.parentNode.className = "inactivePredSource";
			}
		}
		//initInfoArea(true);
		//clearDetDots();
    });
}




function switchAllSourceIsActive(isActive, csHash){
    var coordSys = coordSysCache[csHash];
	
    Dasmi.switchAllSourceIsActive(isActive, coordSys,  function(result){
		getCoordSystems(csHash);
		// sources switched off, just reload screeen
		//alert("alive");
		if (!result){
			initInfoArea(true);
			clearDetDots();
		} // loads of new sources, new query
		else{
		//alert(globalq+globalcs);
			querySources(registryLocation, globalq, globalcs);
			//initInfoArea(true);
		}
		//alert(result);
		//
    });
}


/**
* Adding a new soure to the users server side source list. Reads all values
* from the input fields and validates them. If everything is correct 
* the object will be added and the sources table will be redrawn
*/
function addSource(id){

	
//	alert("adding"+id);
	
	if (!validateInput()){
	//alert("2");
		return false;
	}
	//alert(id);
	if ($("url") == undefined && id == undefined){
	//alert("1" + id);
		if (ie){
			document.forms[0].submit();
			//alert(dump(document.sourcesForm));
		}else{
		//alert("3");
			return false;
		}
	}
	//alert('about to add a source ' + id);
	var source = { isActive:null,
				   id:null,
				   nickname:null,
				   description:null,
				   url:null,
				   coordinateSystem: null,
				   labels:null
				   };	

	dwr.util.getValues(source);
	//alert(dump(source));
	
	var labelsArr = new Array();
	if ($("isQM") != undefined){
		if (dwr.util.getValue("isQM")){
			labelsArr.push("interaction quality measure");
		}
	}
	if ($("serverType") != undefined){
		if (dwr.util.getValue("serverType") == "PSICQUIC"){
			labelsArr.push("psicquic");
		}
	}
	if (source["labels"] != ""){
		labelsArr.push(source["labels"]);
	}
	source["labels"] = labelsArr;
	//alert(dump(source["labels"]));
	
	// recreate the coordinate system from the hash and make it ready for DWR marhalling
	
	source.capabilities = ['interaction'];
	source.adminemail = "";
	//alert("about to add" + id + dump(source));
	if (id == undefined){
		//alert("without id");
		//alert(dump(source));
		var csHashString = source.coordinateSystem;
		var csHash = new Array();
		csHash.push(csHashString);
		csHash = marshalCoordSys(csHash);
		if (csHash.length == 0){
			dwr.util.setValue("coordinateSystemHelp", "There was a problem adding the coordinate sytem. Please try again.");
			return;
		}else{
			source.coordinateSystem = csHash;
		}
	}else{
	//alert("almost made it");
		//alert("with id");
		
		var cs = {NCBITaxId: "0",
				category:"Protein Sequence",
				name: "UniProt",
				organismName : "",
				testCode: "",
				uniqueId : "CS_DS06",
				version: ""};
			//alert(dump(cs));//cs = ret[1];
			csHash = "UniProt,Protein Sequence";
			var cse = new Array();
			cse.push(cs);
			source.coordinateSystem = cse;
			//alert(dump(source));
			var url = "http://dasmi.bioinf.mpi-inf.mpg.de/";
			try
			{
				if (window.location.href.indexOf("dasmiweb.php") > 0){
					url = window.location.href.substr(0,window.location.href.indexOf("dasmiweb.php"));
				}else{
					url = window.location.href;
				}
			}
			catch(err)
			{
				//alert(err);
			}
			source.url = url + "das/meta/";
			var reqParams = {};
			reqParams[id] = 'sourceid';
			//reqParams["psimiurl"] = ["test1", "test2"];
			source.requiredParameters = reqParams;
			//alert(dump(source));
	}

	var color = "#EFF8FF";
	for (id in source["labels"]){
		var label = source["labels"][id];
		if (label == "experimental" || label == "literature curated"){
			color = COLOR_EXPERIMENTAL;
		}else if(label == "predicted"){
			color = COLOR_PREDICTED;
		}	
	}
	//alert(dump(color));
	x_createAndStoreImage(source.nickname, color, "255,0,0", doNothing()); //create the images ...
	//}
	//alert(dump(source["labels"]));
	
	// finally save the source and redraw the table containing the new entry

    //alert(dump(source));
	Dasmi.addSource(source, function(so){
		//alert(dump(so));
		getCoordSystems(csHash);
	});
	
}


function uploadEnd(success, response){
	//alert(success+response);
	if (!success){
		if (document.getElementById('fileHelp') != undefined){
			document.getElementById('fileHelp').innerHTML = response;
		}
	}else{
		var resp = response.split("+++++");
		//var resp = document.getElementById('fileHelp').innerHTML.split("+++++");
		if (resp.length > 1){
			Dasmi.loadDataFromFile(resp[0], function(id){
				if (id == undefined){
					document.getElementById('fileHelp').innerHTML = "Unable to parse and load the file. Please make sure it is a valid PSI MI 2.5 file.";
				}else{
					//document.getElementById('fileHelp').innerHTML = id;
					//document.getElementById('fileId').value = id;
					//alert("about to add " + dump(id));
					addSource(id);
				}
			});
			//document.getElementById('fileHelp').innerHTML = resp[0];
			//alert(resp[0]);
		}else{
			document.getElementById('fileHelp').innerHTML = response;
		}
	}
}


