// JavaScript Document
/**
* load the xml alignment file fom the server
*/
function ajaxCall(url,callback){
	var http_request = false;
	if (window.XMLHttpRequest) { 
		http_request = new XMLHttpRequest();
	} else if (window.ActiveXObject) { // IE.
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	http_request.open('GET', url, true);
	http_request.onreadystatechange = function(){
		if (http_request.readyState == 4) {
			if (http_request.status == 200) { 
				if(http_request.responseXML && http_request.responseXML.contentType=="text/xml"){
					callback(http_request.responseXML);
				}else
				if(http_request.responseText){
					callback(http_request.responseText);
				}else
					alert("error");	
			}else
				alert("error");
		}
	}
	http_request.send(null);
}
//------------------------------------------------------------------------------------------		  
// AJAX FUNCTION TO CREATE A http_resquest OBJECT // WHICH WILL FACILITATE THE PARSING OF XML FILES
//------------------------------------------------------------------------------------------	
            function ajax()
			{

                if (window.XMLHttpRequest) { // Mozilla, Safari,...
                    http_request = new XMLHttpRequest();
                    if (http_request.overrideMimeType) {
                        http_request.overrideMimeType('text/xml');
                    }
                } else if (window.ActiveXObject) { // IE
                    try {
                        http_request = new ActiveXObject("Msxml2.XMLHTTP");
                    } catch (e) {
                        try {
                        http_request = new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (e) {}
                    }
                }

                if (!http_request) {
                    alert('Giving up :( Cannot create an XMLHTTP instance');
                    return false;
                }
				
				if(query_id_null == 1)
					{
						document.getElementById("system_information").innerHTML = "<span style=\"color:#CC0000\">Please enter a \"Protein ID\" to start to use Dasty2.</span>";
					}
				else
					{
						if(use_das_registry == true)
							{
								makeDasRegistryRequest();
							}
						else
							{
								das_registry_label = [];
								das_registry_label.push("any");
								createLabelOptions(das_registry_label, "feature_label_list_select");
								makeSequenceRequest();
							}
					}
				
			}	
			
			
			
            function ajax_feature(featureXML_num)
			{

                if (window.XMLHttpRequest) { // Mozilla, Safari,...
                    feature_http_request[featureXML_num] = new XMLHttpRequest();
                    if (feature_http_request[featureXML_num].overrideMimeType) {
                        feature_http_request[featureXML_num].overrideMimeType('text/xml');
                    }
                } else if (window.ActiveXObject) { // IE
                    try {
                        feature_http_request[featureXML_num] = new ActiveXObject("Msxml2.XMLHTTP");
                    } catch (e) {
                        try {
                        feature_http_request[featureXML_num] = new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (e) {}
                    }
                }

                if (!feature_http_request[featureXML_num]) {
                    alert('Giving up :( Cannot create an XMLHTTP instance');
                    return false;
                }
			}	
			
			
			// "ajax_elements(num)" not in uset yet
            function ajax_elements(num)
			{
				// num 0 = sequence 
				// num 1 = stylesheet
				// num 2 = das_registry


                if (window.XMLHttpRequest) { // Mozilla, Safari,...
                    elements_http_request[num] = new XMLHttpRequest();
                    if (elements_http_request[num].overrideMimeType) {
                        elements_http_request[num].overrideMimeType('text/xml');
                    }
                } else if (window.ActiveXObject) { // IE
                    try {
                        elements_http_request[num] = new ActiveXObject("Msxml2.XMLHTTP");
                    } catch (e) {
                        try {
						elements_http_request[num] = new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (e) {}
                    }
                }

                if (!elements_http_request[num]) {
                    alert('Giving up :( Cannot create an XMLHTTP instance');
                    return false;
                }
			}				// JavaScript Document
//------------------------------------------------------------------------------------------	
// Change Graphic width
//------------------------------------------------------------------------------------------			
function change_graphic_width(graphic_width_ID)
	{
		document.getElementById("system_information").innerHTML = "Dasty2 is resizing the graphic ...";
		var pixels = parseInt(document.getElementById(graphic_width_ID).value);
		//alert(pixels);
		var minimun_feature_size = 50;
		var minimun_size = (col_category_width * show_col_category) + (col_method_width * show_col_method) + (col_type_width * show_col_type) + (col_id_width * show_col_id) + (col_server_width * show_col_server) + (col_warning_width * show_col_warning) + minimun_feature_size;
		if(pixels > minimun_size)
			{
				graphic_width = parseInt(pixels);
				document.getElementById("graphic_width_px").value = graphic_width;
				sorting();
				document.getElementById("system_information").innerHTML = "<span style=\"color:#999999\">... Dasty2 finished to resize the graphic.</span>";
			}
		else
			{
				document.getElementById("system_information").innerHTML = "<span style=\"color:#CC0000\">The graphic width can not be lower than the minimun width (" + minimun_size + " px)</span><br />If you wish to reduce the minimun width value try to hide some graphic columns.";
			}
	}
	

/*
function info_message(type)
	{
		switch (type)
		  {
			case "sort" :
				document.getElementById("system_information").innerHTML = "Dasty2 is sorting the graphic ...";
				break;
			case "zoom" :
				document.getElementById("system_information").innerHTML = "Dasty2 is zooming the graphic ...";
				break;
			case "resize" :
				document.getElementById("system_information").innerHTML = "Dasty2 is resizing the graphic ...";
				break;
			case "show_hide" :
				document.getElementById("system_information").innerHTML = "Dasty2 is modifying the columns of the graphic ...";
				break;
			case "show_hide" :
				document.getElementById("system_information").innerHTML = "Dasty2 is modifying the columns of the graphic ...";
				break;
		  }	
	}
*/// JavaScript Document

/**
*  CONFIGURATION VARIABLES
*/

function configuration()
{
	/**
	*  TEMPLATES VARIABLES
	*/
	if(dasty_mainpage_name == "ebi.php")
		{
			/**
			* VARIABLES FOR THE EBI TEMPLATE
			*/
				isPDBVisible=true;
				isOntologyTreeVisible=true;
				collapsedOntologyTypeTerms = ['binding_site','polypeptide_region','polypeptide_sequencing_information'];
				
				sequence_limit = 110; // Define the "number" of aa per line in the sequence view. 75
				
				graphic_width = 1100; //1100
				height_graphic_feature = 7; // Height for the features shown in the graphic.
				tittle_height = height_graphic_feature + 6;
				
				col_category_width = 170;
				col_type_width = 190;
				col_method_width = 110;
				col_id_width = 110; //110
				col_warning_width = 26;
				col_server_width = 110;
		
				// 0=no / 1=yes
				show_col_category = 1; 
				show_col_type = 1;
				show_col_method = 0;
				show_col_id = 1; //label
				show_col_graphic = 1;
				show_col_warning = 1;
				show_col_server = 1;
				
				// 0=no / 1=yes
				show_graphic_tittle = 1;
				show_scale_bar = 1;
				show_slide_bar =1;
				show_popup =2;
				
				// boolean 0/1. 0=no / 1=yes
				color_line_background = 0;
				
				vertical_bars = 12;
				
				// If true it allows to group features from the same source with the have the same ID
				dasty2_grouping = false;
				
				// Do you want to exclude DAS sources from the visuzlization?
				excluded_das_sources = []; // No
				//excluded_das_sources = ['netphos', 'tmhmm']; // Yes, Netphos and Tmhmm
				excluded_das_sources = ['CATH Structural Domains in UniProt', 'cath_uniprot_mapping', 'cbs_ptm', 'cbs_func', 'cbs_sort', 'PDBsum_protprot', 'PDBsum_ligands', 'PDBsum_DNAbinding', 'UniProt Tryptic Peptides', 'UniProt GO Annotation', 'uniprot aristotle'];
				
				
				// Do you want to load at the beggining one specific DAS source?
				first_das_source = []; // No
				//first_das_source = ['pride', 'uniprot']; // Yes, Pride and Uniprot following this order.
				
				non_positional_features_coulmns = ["type_id", "method_data", "feature_label", "note_data", "link_data", "score_data", "annotation_server", "type_category"];
				
				non_positional_feature_table_width= "98%";
				//non_positional_feature_table_width= "900px";
				
				use_das_registry = true;
				
		}
	else if(dasty_mainpage_name == "uniprot.php")
		{
			/**
			* VARIABLES FOR THE UNIPROT BETA TEMPLATE
			*/
				isPDBVisible=true;
				isOntologyTreeVisible=true;
				collapsedOntologyTypeTerms = ['binding_site','polypeptide_region','polypeptide_sequencing_information'];
				
				sequence_limit = 110; // Define the "number" of aa per line in the sequence view. 75
				
				graphic_width = 770;
				height_graphic_feature = 7; // Height for the features shown in the graphic.
				tittle_height = height_graphic_feature + 6;
				
				col_category_width = 170;
				col_type_width = 200;
				col_method_width = 110;
				col_id_width = 110;
				col_warning_width = 26;
				col_server_width = 140;
		
				// boolean 0/1. 0=no / 1=yes
				show_col_category = 0; 
				show_col_type = 1;
				show_col_method = 0;
				show_col_id = 1;
				show_col_graphic = 1;
				show_col_warning = 1;
				show_col_server = 1;
				
				// boolean 0/1. 0=no / 1=yes
				show_graphic_tittle = 1;
				show_scale_bar = 1;
				show_slide_bar =1;
				show_popup =2;
				
				// boolean 0/1. 0=no / 1=yes
				color_line_background = 0;
				
				vertical_bars = 12;
				
				// If true it allows to group features from the same source with the have the same ID
				dasty2_grouping = false;
				
				// Do you want to exclude DAS sources from the visuzlization?
				//excluded_das_sources = []; // No
				//excluded_das_sources = ['netphos', 'tmhmm']; // Yes, Netphos and Tmhmm
				excluded_das_sources = ['uniprot', 'CATH Structural Domains in UniProt', 'cath_uniprot_mapping', 'cbs_ptm', 'cbs_func', 'cbs_sort', 'PDBsum_protprot', 'PDBsum_ligands', 'PDBsum_DNAbinding', 'UniProt Tryptic Peptides', 'UniProt GO Annotation', 'uniprot aristotle'];
				
				
				// Do you want to load at the beggining one specific DAS source?
				first_das_source = []; // No
				//first_das_source = ['pride', 'uniprot']; // Yes, Pride and Uniprot following this order.
				//first_das_source = ['signal'];
				
				non_positional_features_coulmns = ["type_id", "score_data", "method_data", "link_data", "feature_id", "note_data", "annotation_server", "type_category"];
				
				non_positional_feature_table_width= "98%";
				//non_positional_feature_table_width= "900px";
				
				use_das_registry = true;
				
		}
	else if(dasty_mainpage_name == "biosapiens.html")
		{
			/**
			* VARIABLES FOR THE BIOSAPIENS TEMPLATE
			*/
				isPDBVisible=true;
				isOntologyTreeVisible=true;
				collapsedOntologyTypeTerms = ['binding_site','polypeptide_region','polypeptide_sequencing_information'];
				
				sequence_limit = 110; // Define the "number" of aa per line in the sequence view. 75
				
				graphic_width = 900;
				height_graphic_feature = 7; // Height for the features shown in the graphic.
				tittle_height = height_graphic_feature + 6;
				
				col_category_width = 170;
				col_type_width = 200;
				col_method_width = 110;
				col_id_width = 110;
				col_warning_width = 26;
				col_server_width = 140;
		
				// boolean 0/1. 0=no / 1=yes
				show_col_category = 0; 
				show_col_type = 1;
				show_col_method = 0;
				show_col_id = 0;
				show_col_graphic = 0;
				show_col_warning = 0;
				show_col_server = 0;
				
				// boolean 0/1. 0=no / 1=yes
				show_graphic_tittle = 1;
				show_scale_bar = 1;
				show_slide_bar =1;
				show_popup =2;
				
				// boolean 0/1. 0=no / 1=yes
				color_line_background = 0;
				
				vertical_bars = 8;
				
				// If true it allows to group features from the same source with the have the same ID
				dasty2_grouping = false;
				
				// Do you want to exclude DAS sources from the visuzlization?
				excluded_das_sources = []; // No
				//excluded_das_sources = ['netphos', 'tmhmm']; // Yes, Netphos and Tmhmm
				excluded_das_sources = ['CATH Structural Domains in UniProt', 'cath_uniprot_mapping', 'cbs_ptm', 'cbs_func', 'cbs_sort', 'PDBsum_protprot', 'PDBsum_ligands', 'PDBsum_DNAbinding', 'UniProt Tryptic Peptides', 'UniProt GO Annotation', 'uniprot aristotle'];
				
				
				// Do you want to load at the beggining one specific DAS source?
				first_das_source = []; // No
				//first_das_source = ['pride', 'uniprot']; // Yes, Pride and Uniprot following this order.
				//first_das_source = ['signal'];			
				
				non_positional_features_coulmns = ["type_id", "method_data", "score_data", "link_data", "feature_id", "note_data", "annotation_server", "type_category"];
				
				non_positional_feature_table_width= "98%";
				//non_positional_feature_table_width= "900px";
				
				use_das_registry = true;
		}
	else
		{
			/**
			* VARIABLES FOR OTHER TEMPLATES. EXAMPLE: INTERACTOR VIEW
			*/
				isPDBVisible=false;
				isOntologyTreeVisible=true;
				collapsedOntologyTypeTerms = ['binding_site','polypeptide_region','polypeptide_sequencing_information'];
				
				sequence_limit = 110; // Define the "number" of aa per line in the sequence view. 75
				
				graphic_width = 870;
				height_graphic_feature = 7; // Height for the features shown in the graphic.
				tittle_height = height_graphic_feature + 6;
				
				col_category_width = 170;
				col_type_width = 200;
				col_method_width = 110;
				col_id_width = 110;
				col_warning_width = 26;
				col_server_width = 140;
		
				// boolean 0/1. 0=no / 1=yes
				show_col_category = 0; 
				show_col_type = 1;
				show_col_method = 0;
				show_col_id = 0;
				show_col_graphic = 0;
				show_col_warning = 0;
				show_col_server = 0;
				
				// boolean 0/1. 0=no / 1=yes
				show_graphic_tittle = 1;
				show_scale_bar = 1;
				show_slide_bar =0;
				show_popup =1;
				
				// boolean 0/1. 0=no / 1=yes
				color_line_background = 0;
				
				vertical_bars = 12;
				
				// If true it allows to group features from the same source with the have the same ID
				dasty2_grouping = false;
				
				// Do you want to exclude DAS sources from the visuzlization?
				excluded_das_sources = []; // No
				//excluded_das_sources = ['netphos', 'tmhmm']; // Yes, Netphos and Tmhmm
				//excluded_das_sources = ['CATH Structural Domains in UniProt', 'cath_uniprot_mapping', 'cbs_ptm', 'cbs_func', 'cbs_sort', 'PDBsum_protprot', 'PDBsum_ligands', 'PDBsum_DNAbinding', 'UniProt Tryptic Peptides', 'UniProt GO Annotation', 'uniprot aristotle', 'netphos', 'everest', 'interpro', 'Gene3D-CATH Domain Assigments', 'tmhmm', 'cbs_total', 'gene3d_cath'];
				
				
				
				// Do you want to load at the beggining one specific DAS source?
				first_das_source = []; // No
				//first_das_source = ['pride', 'uniprot']; // Yes, Pride and Uniprot following this order.
				//first_das_source = ['signal'];			
				
				non_positional_features_coulmns = ["type_id", "link_data", "note_data", "annotation_server"];

				//non_positional_feature_table_width= "98%";
				non_positional_feature_table_width= "900px";	
				
				use_das_registry = false;
		}
	
	/**
	* DAS SOURCES VARIALES
	*/
		stylesheet_url = [];
		sequence_url = [];
		feature_url = [];
		
		/**
		* PROXY
		*/
			/**
			* PHP PROXY
			*/
				proxy_url = '/7tm/dasty2/server/proxy.php';	
			/**
			* CGI PROXY
			*/
				//proxy_url = 'http://www.ebi.ac.uk/cgi-bin/dasty/proxy.cgi';
				//proxy_url = 'http://www.ebi.ac.uk/~rafael/cgi-bin/proxy.cgi';
				//proxy_url = 'http://localhost/cgi-bin/proxy.cgi';
				//proxy_url = 'http://wwwdev.ebi.ac.uk/cgi-bin/dasty/proxy.cgi';
					
					
		/**
		* STYLESHEET
		*/		
			//stylesheet_url[0] = ['uniprot', proxy_url + '?t=' + timeout + '&m=stylesheet&s=http://www.ebi.ac.uk/das-srv/uniprot/das/aristotle/'];
			stylesheet_url[0] = ['uniprot', proxy_url + '?t=' + timeout + '&m=stylesheet&s=http://www.ebi.ac.uk/das-srv/uniprot/das/uniprot/'];
			//stylesheet_url[0] = ['uniprot', 'files/stylesheet.xml']; // LOCAL STYLESHEET

		/**
		* REFERENCE SERVER
		*/		
			//sequence_url[0] = ['uniprot', proxy_url + '?t=' + timeout + '&m=sequence&q=' + query_id + '&s=http://www.ebi.ac.uk/das-srv/uniprot/das/aristotle/']; // UNIPROT REFERENCE SERVER
			sequence_url[0] = ['uniprot', proxy_url + '?t=' + timeout + '&m=sequence&q=' + query_id + '&s=http://www.ebi.ac.uk/das-srv/uniprot/das/uniprot/']; // UNIPROT REFERENCE SERVER
			//sequence_url[0] = ['uniprot', 'files/seq_A4_Human_uniprot02.xml']; // LOCAL SEQUENCE (just for testing purposes)
					
		/**
		* ANNOTATION SERVERS
		*  - If use_das_registry = false please Set specific DAS annotation servers
		*/	
			
			if(use_das_registry == true)
				{
					/**
					* ANNOTATIONS FROM THE DAS REGISTRY
					*/	
						das_registry_url = proxy_url + '?t=' + timeout + '&m=registry&c=protein%20sequence&a=UniProt&s=http://www.dasregistry.org/das1/sources';
						//das_registry_url = proxy_url + '?m=registry&s=http://das.sanger.ac.uk/registry/das1/sources/'; 
						//das_registry_url = 'files/dasregistry250508.xml'; // LOCAL REGISTRY
							
							// Exceptions. For example ...
							if(dasty_mainpage_name.indexOf("interactor") != -1)
								{
									das_registry_url = 'files/dasregistry020208.xml';
								}
				}
			else
				{
					/**
					* SPECIFIC DAS ANNOTATION SERVERS
					*/	
						feature_url_prefix = proxy_url + '?m=features&q=' + query_id + '&t=' + timeout + '&s=';
						feature_url[0] = {id : 'uniprot', url : feature_url_prefix + 'http://www.ebi.ac.uk/das-srv/uniprot/das/uniprot/'};
						//feature_url[1] = {id : 'msdmotif', url : feature_url_prefix + 'http://www.ebi.ac.uk/msd-srv/msdmotif/das/s3dm/'};
						//feature_url[2] = {id : 'netphos', url : feature_url_prefix + 'http://genome.cbs.dtu.dk:9000/das/netphos/'};
						//feature_url[3] = {id : 'uniprot2', url : feature_url_prefix + 'http://tc-test-1.ebi.ac.uk:8113/tc-test/proteomics/das-srv/uniprot/das/uniprot/'};
						//feature_url[4] = {id : 'interpro', url : feature_url_prefix + 'http://das.ensembl.org/das/interpro/'};
					
					/**
					* SPECIFIC DAS ANNOTATION SERVERS. LOCAL COPIES.
					*/	
				//		feature_url[0] = {id : 'uniprot', url : 'files/fea_A4_Human_uniprot03.xml'};
				//		feature_url[1] = {id : 'cbs_total', url : 'files/fea_A4_Human_cbs_total.xml'};
				//		feature_url[2] = {id : 'netphos', url : 'files/fea_A4_Human_netphos.xml'};
						//feature_url[3] = {id : 'intact', url : 'files/intact_EBI-466029.xml'};

				}
		
			/**
			* ALIGNMENTS
			*/	
					//uniprot_pdb_alignment = proxy_url + '?t=30&m=alignment&q=' + query_id + '&s=http://das.sanger.ac.uk/das/msdpdbsp/';
			//		uniprot_pdb_alignment = proxy_url + '?t=30&m=alignment&q=' + query_id + '&s=http://das.sanger.ac.uk/das/biojavapdbuniprot/';
			/**
			* ONTOLOGY
			*/	
		//		onto_path_type = proxy_url + '?t=30&m=ontology&q=biosapiens.obo_types_250508.xml&s=http://www.ebi.ac.uk/dasty/server/pdb/';
		//		onto_path_category = proxy_url + '?t=30&m=ontology&q=categories.xml&s=http://www.ebi.ac.uk/dasty/server/pdb/';
				//onto_path_type = proxy_url + '?t=30&m=ontology&q=biosapiens.obo_types_250508.xml&s=http://localhost/dasty/server/pdb/';
				//onto_path_category = proxy_url + '?t=30&m=ontology&q=categories.xml&s=http://localhost/dasty/server/pdb/';
				//onto_path_type = proxy_url + '?t=30&m=ontology&q=biosapiens_lite.xml&s=http://psidev.cvs.sourceforge.net/*checkout*/psidev/psi/mi/controlledVocab/biosapiens/';
				//onto_path_category = proxy_url + '?t=30&m=ontology&q=categories.xml&s=http://www.ebi.ac.uk/dasty/client/pdb/';

			
			/**
			* Path to load pdb files
			*/	
		//		path_pdb_files="../server/pdb/";
}


/**
* DEFAULT QUERY PARAMETERS
*/	
function default_query_parameters()
{	
	//default_query_id = "P05067";
	default_query_id = "";
	default_filterLabel = "BioSapiens";
	default_timeout = 10;
	default_dasty_mainpage_name = "biosapiens.html"
}
//------------------------------------------------------------------------------------------	
// CREATE FEATURE DETAILS FIELD // display_feature_details
//------------------------------------------------------------------------------------------	

			function createFeatureDetails(object_row, xmlnumber)
			{
					var fetureDetails = feature_info[xmlnumber][object_row];
					var tagId = "display_feature_details";
					
					fields = ["feature_id", "feature_label", "type_data", "type_id", "type_category", "method_data", "start_data", "end_data", "score_data", "orientation_data", "phase_data", "note_data", "link_data"];
					fields_names = ["Feature ID: ", "Feature label: ", "Type: ", "Type ID: ", "Category: ", "Method: ", "Start: ", "End: ", "Score: ", "Orientation: ", "Phase: ", "Note: ", "Link: "];
					
					var div = document.getElementById(tagId);
					div.innerHTML = '';
					
					
					for(var i = 0; i < fields.length; i++) 
						{
							var feature_details_content = fetureDetails[fields[i]];
							//printOnTest(fields[i] + " / " + typeof(feature_details_content) + " / " + feature_details_content.length);
							
							if(typeof(feature_details_content) == "object") // Content is an array of information. Ex: note_data
								{
									
									for(var a = 0; a < feature_details_content.length; a++) 
										{	
										
											if(fields[i] == "link_data")
												{
													var content_link = fetureDetails["link_href"][a];
												}
											else
												{
													var content_link = null;
												}
											
											var fieldElements = createFieldFeatureDetails(fields[i], fields_names[i], feature_details_content[a], content_link);
											div.appendChild(fieldElements[0]);
											div.appendChild(fieldElements[1]);
											div.appendChild(fieldElements[2]);	
											
										}
								}
							else // Content just have one variable
								{
									var fieldElements = createFieldFeatureDetails(fields[i], fields_names[i], feature_details_content, null);
									
									div.appendChild(fieldElements[0]);
									div.appendChild(fieldElements[1]);
									div.appendChild(fieldElements[2]);	
								
								}
						}
					var contentDiv = div.innerHTML;
					div.innerHTML = contentDiv + "<br><a target=\"_blast\" href=\"http://beta.uniprot.org/blast/?about=" + sequence_info.sequence_id + "[" + fetureDetails["start_data"] + "-" + fetureDetails["end_data"] + "]\"><img  border=\"0\" src=\"http://www.gpcr.org/7tm/dasty2/client/img/blast_icon.gif\" /></a>";
				 
			}	  
			
			
function createFieldFeatureDetails(fieldType, fieldTitle, content, fdlink)
	{	
		var textNode = document.createTextNode(content);
	
		var a = document.createElement("span");
		a.setAttribute("id", "display_feature_details_" + fieldType);
		a.setAttribute("class", "title");
		a.setAttribute("className", "title");
		a.appendChild(document.createTextNode(fieldTitle));				  
							
		var b = document.createElement("span");
		b.setAttribute("id", "display_feature_details_" + fieldType + "_content");
		//b.appendChild(document.createTextNode(content));	
		
		if(fdlink != null)
			{
				var link_href = document.createElement("a");
				link_href.setAttribute("target", "_featurelinks");
				link_href.setAttribute("href", fdlink);
				link_href.appendChild(textNode);	
				b.appendChild(link_href);	
			}
		else
			{
				b.appendChild(textNode);	
			}
							
		var c = document.createElement("br");
		
		var fieldElements = [a, b, c];
		
		return fieldElements;
	}
//------------------------------------------------------------------------------------------	
// CREATE GRAPHIC
//------------------------------------------------------------------------------------------			

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
// When Dasty2 is executed and displays asyncronously annotations, the function
// createGraphic2 is called as many times as DAS sources are retrieved by AJAX. After
// any other operation like sorting, zoom, etc. the function crreateGraphic2 is called
// just once.

// So the firt time the graphic is composed of several <UL>, as many as DAS sources
// displyed. Nonthless after a modification is performed on the graphic, the annotations
// are rearragend in just one <UL>
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

function createGraphic2(featureXML_num, tagId, segment_start, segment_stop, origin)
{
	 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
	 // The origin attributes 'sorting' and 'exapanding' are defined in this function when the
	 // user wants to modify the view of the first graphic loaded. Then the first graphic is
	 // deleted from the main display, the annotation are rearraged acording to the users 
	 // request and a new graphic is created by calling the createGraphic2 function. If origin
	 // is different to one of these two mentioned before Dasty2 will perform a multiple
	 // asyncronous load.
	 
	 // Dasty2 doesn't display one annotation per line but it rearrages as many annotation
	 // one line as possible considering they belong to the same type. Information about this
	 // rearragement is stored in the "feature_list" variable. "finfo" contains all the
	 // properties of the annotation being loaded like attribute, note, link, etc. This
	 // information comes from parse feature.
	 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
	 
	 if(origin == 'sorting')
	 	{
			var feature_list = one_feature_list;
			var finfo = feature_info;
			features_row_number = feature_list.length; // features_row_number is Global
		}
	 else if(origin == 'expanding')
		{
			var feature_list = expanded_feature_list;
			var finfo = feature_info;
			features_row_number = feature_list.length; // features_row_number is Global
		}
	 else if(origin == 'noresults')
	 	{
			var feature_list = [];
		}
	 else
	    {
			var feature_list = new_feature_list_info2[featureXML_num];
			var finfo = feature_info[featureXML_num];
			features_row_number = features_row_number + feature_list.length; // features_row_number is Global
	    }
	 
	 var firstTimeSortByType_temp = dasty2.firstTimeSortByType;
	

	 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
	 // Defining variables used to create the graphic
	 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
	 
	 if(feature_list.length > 0)
     {
		show_col_graphic = 1;
		
		//if(isExpanded == 1 && show_col_id == 1)
		if(show_col_id == 1)
			{
				var show_col_id_temp = 1;
			}
		else
			{
				var show_col_id_temp = 0;
			}
			
		var seq_start = segment_start -1;
		var seq_stop = segment_stop;
		var seq_width = (seq_stop - seq_start);
		var gr_gap = 1;
		var cols = show_col_category + show_col_type + show_col_method + show_col_id_temp + show_col_graphic + show_col_warning + show_col_server;
		var total_gap = (cols + 1) * gr_gap;
		
		var width_ul = graphic_width; // 523 for short and 700 for long display in the dasty2 website. Graphic_width is global!
		var width_div_category = col_category_width * show_col_category; // col_category_width is global!
		var width_div_type = col_type_width * show_col_type; // col_type_width is global!
		var width_div_method = col_method_width * show_col_method; // col_method_width is global!
		var width_div_id = col_id_width * show_col_id_temp; // col_id_width is global!
		var width_div_server = col_server_width * show_col_server; // col_server_width is global!
		var width_div_warning = col_warning_width * show_col_warning; // col_server_width is global!
		var width_div_graphic = width_ul - (width_div_category + width_div_type + width_div_method + width_div_id + width_div_warning + width_div_server) - (total_gap);
		width_div_graphic_correction = width_div_graphic - 2; // Border correction. The border is actually adding two pixels more.
		
		
		//var left_div_category = (show_col_category * gr_gap) - gr_gap; //show_col_category * gr_gap;
		//var left_div_type = left_div_category + width_div_category + (show_col_type * gr_gap);
		var left_div_type = (show_col_type * gr_gap) - gr_gap; //show_col_category * gr_gap;
		var left_div_method = left_div_type + width_div_type + (show_col_method * gr_gap);
		var left_div_id = left_div_method + width_div_method + (show_col_id_temp * gr_gap);
		var left_div_graphic = left_div_id + width_div_id + (show_col_graphic * gr_gap);
		var left_div_warning = left_div_graphic + width_div_graphic + (show_col_server * gr_gap);
		var left_div_server = left_div_warning + width_div_warning + (show_col_warning * gr_gap);
		var left_div_category = left_div_server + width_div_server + (show_col_server * gr_gap);
		
		var height_div = height_graphic_feature + 6; // height_graphic_feature is global!

		var feature_unique_id = [];

		if(browser_name == "Microsoft Internet Explorer")
			{
				var height_graphic_feature_correction = height_graphic_feature; //IE6
				var height_li = height_div -2; //IE6
				//printOnTest("Microsoft Internet Explorer");
			}
		else
			{
				var height_graphic_feature_correction = height_graphic_feature;
				var height_li = height_div;
			}
		
        var div = document.getElementById(tagId);
	
	
	// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
	// SHOW ZOOM SLIDE BAR
	// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		if(show_slide_bar == 1)
		  {		
			if(origin == "grouping")
			  {
			  	if(show_slide_bar_temp == 1)
				  {
					 var slidebar_ul = createSlideBar(width_ul,left_div_graphic, width_div_graphic);
					 div.appendChild(slidebar_ul);

					 activateSlideBar(zoom_start,zoom_end,'gr_slidebar_div_thumb_01','gr_slidebar_div_thumb_02','gr_slidebar_div_track','zoom_start_px','zoom_end_px');
					 show_slide_bar_temp = 0;
				  } // if(show_graphic_tittle_temp == 1)
		 	  }
			else
		  	  {
				var slidebar_ul = createSlideBar(width_ul,left_div_graphic, width_div_graphic);
				div.appendChild(slidebar_ul);
				activateSlideBar(zoom_start + 1,zoom_end,'gr_slidebar_div_thumb_01','gr_slidebar_div_thumb_02','gr_slidebar_div_track','zoom_start_px','zoom_end_px');
		  	  } // if(origin == "grouping")
		   } // (show_graphic_tittle == 1)				
		
		
	
		// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 	
		// SHOW SCALE-BAR
		// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		if(show_scale_bar == 1)
		  {		
			if(origin == "grouping")
			  {
			  	if(show_scale_bar_temp == 1)
				  {
					 var scalebar_ul = createScaleBar(vertical_bars, seq_width, width_ul, left_div_graphic, width_div_graphic);
					 div.appendChild(scalebar_ul);
					 show_scale_bar_temp = 0;
				  } // if(show_graphic_tittle_temp == 1)
		 	  }
			else
		  	  {
				var scalebar_ul = createScaleBar(vertical_bars, seq_width, width_ul, left_div_graphic, width_div_graphic);
				div.appendChild(scalebar_ul);
				//alert(bar_px_distance_list);
				//alert(bar_aa_distance_list);
				//fillScaleBar();
		  	  } // if(origin == "grouping")
		   } // (show_graphic_tittle == 1)	
		   
			
			
			
			
			
		// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		// SHOW TITTLE
		// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		if(show_graphic_tittle == 1)
		  {		
			if(origin == "grouping")
			  {
			  	if(show_graphic_tittle_temp == 1)
				  {
					 createGraphicTittle(tagId, width_ul, left_div_category, width_div_category, left_div_type, width_div_type, left_div_method, width_div_method,left_div_id, width_div_id, left_div_graphic, width_div_graphic, left_div_server, width_div_server, height_div, show_col_id_temp, left_div_warning, width_div_warning);
					 show_graphic_tittle_temp = 0;
				  } // if(show_graphic_tittle_temp == 1)
		 	  }
			else
		  	  {
			  		 createGraphicTittle(tagId, width_ul, left_div_category, width_div_category, left_div_type, width_div_type, left_div_method, width_div_method, left_div_id, width_div_id, left_div_graphic, width_div_graphic, left_div_server, width_div_server, height_div, show_col_id_temp, left_div_warning, width_div_warning);
		  	  } // if(origin == "grouping")
		   } // (show_graphic_tittle == 1)			
			
				
				
				
	// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
	// DEFINE UL TAG
	// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 	
     var my_ul = document.createElement("ul");
		
	 if(origin == 'sorting' || origin == 'expanding')
	 	{		
		  my_ul.setAttribute("id", "gr_list0");
		}
	  else
	    {
		  my_ul.setAttribute("id", "gr_list" + featureXML_num);
		}
		
		my_ul.setAttribute("class", "gr_list_class");
		my_ul.setAttribute("className", "gr_list_class");
		//my_ul.setAttribute("style", "width:" + width_ul + "px;");
		my_ul.style.cssText = "width:" + width_ul + "px;";
		
		
		// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		// Reading the information about the rearragement of annotations (one or many annotation per line)
		// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		
		for(var c = 0; c < feature_list.length; c++)
		 {
			 
			 	// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
			    // TAKING COLORS FROM THE STYLESHEET
				// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
				feature_color_loop: 
				for(var p = 0; p < stylesheet_properties_info.length; p++)
				  {
				    if(stylesheet_properties_info[p]["type_id"] == feature_list[c]["type"] )
					  {
					   feature_border_color = stylesheet_properties_info[p]["fgcolor_data"];
					   feature_background_color = stylesheet_properties_info[p]["bgcolor_data"];
					   var aborder_type = 'solid';
					   break feature_color_loop;
					  } else
					  {
					   feature_border_color = stylesheet_properties_info[0]["fgcolor_data"];
					   feature_background_color = stylesheet_properties_info[0]["bgcolor_data"];
					   var aborder_type = 'dotted';
					  }
				  }	
				  
				  
				  
				// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
			    // DEFINING COLORS FROM THE BACKGOUNG OF THE LINES IN THE GRAPHIC. Alterning two colors
				// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
				if(color_line_background == 1)
					{
					// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 	
					// DEFINING COLORS BY LINE
					// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
					if(feature_list[c]["version"] == 1)
						{
							if (feature_list[c]["feature_group"] == 1)
								{
									if ( bg_color == 2 || bg_color == 4 || bg_color == 6 || bg_color == 8) { bg_color = 3 } else { bg_color = 4 }
								}
							else
								{
									if ( bg_color == 2 || bg_color == 4 || bg_color == 6 || bg_color == 8) { bg_color = 1 } else { bg_color = 2 }
								}						
						}
					else
						{
							if (feature_list[c]["feature_group"] == 1)
								{
									if ( bg_color == 2 || bg_color == 4 || bg_color == 6 || bg_color == 8) { bg_color = 7 } else { bg_color = 8 }
								}
							else
								{
									if ( bg_color == 2 || bg_color == 4 || bg_color == 6 || bg_color == 8) { bg_color = 5 } else { bg_color = 6 }
								}		
						}
					} // if(color_line_background == 1)
				else
					{
						if ( bg_color == 2 ) { bg_color = 1 } else { bg_color = 2 }
					}
					
					
					
		  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		  // FINDING das sources loaded.
		  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 	
		  if(dasty2.loadedDasSources.length == 0)
			{   
			   var lds_temp = dasty2.loadedDasSources_temp.length;
			   var duplicated_source = 0;
			   
			   for(var w = 0; w < lds_temp; w++)
					{
						if(dasty2.loadedDasSources_temp[w] == feature_list[c]["server"])
							{
								duplicated_source = 1;
							}
					}
				
				if(duplicated_source == 0)
					{
						dasty2.loadedDasSources_temp.push(feature_list[c]["server"]);
					}
			}
		   
	
				
			// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
			// CREATE LISTS <LI> (one line) inside the <UL>
 			// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
						
				var mycurrent_li = document.createElement("li");
				
				  if(origin == 'sorting' || origin == 'expanding')
					{
					  var feature_xmlnumber = feature_list[c]["xmlnumber"];
					  var li_id_name = "gr_item" + feature_xmlnumber + "_" + feature_list[c]["type"] + "_" + feature_list[c]["line"];
					  mycurrent_li.setAttribute("id", li_id_name);
					}
				  else
					{
					  var li_id_name = "gr_item" + featureXML_num + "_" + feature_list[c]["type"] + "_" + feature_list[c]["line"];
					  mycurrent_li.setAttribute("id", li_id_name);
					}
					
				  if(dasty2.line_id_name2[li_id_name] == 1)
				  	{
						dasty2.countVisibleLines++;
						mycurrent_li.style.cssText = "height:" + height_li + "px; display:block;";
					}
				  else
				  	{
						mycurrent_li.style.cssText = "height:" + height_li + "px; display:none;";
					}


			
			
			// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
			// CREATE CATEGORY COLUMN INSIDE THE LIST <LI>
			// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
			
			if (show_col_category == 1)
			   {			
				var mycurrent_div_category = document.createElement("div");
				mycurrent_div_category.setAttribute("class", "gr_div gr_row_0" + bg_color + " gr_cell_01");
				mycurrent_div_category.setAttribute("className", "gr_div gr_row_0" + bg_color + " gr_cell_01");
				//mycurrent_div_category.setAttribute("style", "top:0px; left:" + left_div_category + "px; width:" + width_div_category + "px; height:" + height_div + "px;");	
				mycurrent_div_category.style.cssText = "top:0px; left:" + left_div_category + "px; width:" + width_div_category + "px; height:" + height_div + "px;";
				
				//var mycurrent_category_text = document.createElement("a");
				//mycurrent_category_text.setAttribute("class", "gr_text_01");
				//mycurrent_category_text.setAttribute("className", "gr_text_01");
				//mycurrent_category_text.setAttribute("href", "");
				
				var mycurrent_category_text = document.createElement("span");
				mycurrent_category_text.setAttribute("class", "gr_text_01");
				mycurrent_category_text.setAttribute("className", "gr_text_01");
				
				var mycurrent_category_text_content = document.createTextNode(feature_list[c]["category"]);
				
				mycurrent_category_text.appendChild(mycurrent_category_text_content);
				mycurrent_div_category.appendChild(mycurrent_category_text);
				
				mycurrent_li.appendChild(mycurrent_div_category);
			   }
	

		    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
			// CREATE METHOD COLUMN INSIDE THE LIST <LI>
			// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
			
			if (show_col_method == 1)
			   {			
				var mycurrent_div_method = document.createElement("div");
				mycurrent_div_method.setAttribute("class", "gr_div gr_row_0" + bg_color + " gr_cell_01");
				mycurrent_div_method.setAttribute("className", "gr_div gr_row_0" + bg_color + " gr_cell_01");
				//mycurrent_div_category.setAttribute("style", "top:0px; left:" + left_div_category + "px; width:" + width_div_category + "px; height:" + height_div + "px;");	
				mycurrent_div_method.style.cssText = "top:0px; left:" + left_div_method + "px; width:" + width_div_method + "px; height:" + height_div + "px;";
				
				//var mycurrent_method_text = document.createElement("a");
				//mycurrent_method_text.setAttribute("class", "gr_text_01");
				//mycurrent_method_text.setAttribute("className", "gr_text_01");
				//mycurrent_method_text.setAttribute("href", "");
				
				var mycurrent_method_text = document.createElement("span");
				mycurrent_method_text.setAttribute("class", "gr_text_01");
				mycurrent_method_text.setAttribute("className", "gr_text_01");
				
				var mycurrent_method_text_content = document.createTextNode(feature_list[c]["method"]);
				
				mycurrent_method_text.appendChild(mycurrent_method_text_content);
				mycurrent_div_method.appendChild(mycurrent_method_text);
				
				mycurrent_li.appendChild(mycurrent_div_method);
			   }

	
	
			// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
			// CREATE TYPE COLUMN INSIDE LIST <LI>
			// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
			if (show_col_type == 1)
			   {			
				var mycurrent_div_type = document.createElement("div");
				mycurrent_div_type.setAttribute("class", "gr_div gr_row_0" + bg_color + " gr_cell_01");
				mycurrent_div_type.setAttribute("className", "gr_div gr_row_0" + bg_color + " gr_cell_01");
			
				mycurrent_div_type.style.cssText = "top:0px; left:" + left_div_type + "px; width:" + width_div_type + "px; height:" + height_div + "px;";	
				
				var mycurrent_type_text_content = document.createTextNode(feature_list[c]["type_data"]);
				
				var useOlsUrl = false;
				for(var w = 0; w < ontologyPrefix.length; w++)
					{
						if(feature_list[c]["type"].indexOf(ontologyPrefix[w]) != -1)
							{
								useOlsUrl = true;
							}
					}
					
				if(useOlsUrl == true)
					{
						var mycurrent_type_text = document.createElement("a");
						mycurrent_type_text.setAttribute("class", "gr_text_01");
						mycurrent_type_text.setAttribute("className", "gr_text_01");
						mycurrent_type_text.setAttribute("target", "_type");
						mycurrent_type_text.setAttribute("href", "http://www.ebi.ac.uk/ontology-lookup/?termId=" + feature_list[c]["type"]);
						
					}
				else
					{
						var mycurrent_type_text = document.createElement("span");
						mycurrent_type_text.setAttribute("class", "gr_text_01");
						mycurrent_type_text.setAttribute("className", "gr_text_01");
					}
					
				mycurrent_type_text.appendChild(mycurrent_type_text_content);
				mycurrent_div_type.appendChild(mycurrent_type_text);

				
				mycurrent_li.appendChild(mycurrent_div_type);
			   }
			
			
			
			
			// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
			// CREATE ID COLUMN INSIDE LIST <LI>
			// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
			
			if (show_col_id_temp == 1)
			  {			
				var mycurrent_div_id = document.createElement("div");
				mycurrent_div_id.setAttribute("class", "gr_div gr_row_0" + bg_color + " gr_cell_01");
				mycurrent_div_id.setAttribute("className", "gr_div gr_row_0" + bg_color + " gr_cell_01");
				//mycurrent_div_id.setAttribute("style", "top:0px; left:" + left_div_id + "px; width:" + width_div_id + "px; height:" + height_div + "px;");	
				mycurrent_div_id.style.cssText = "top:0px; left:" + left_div_id + "px; width:" + width_div_id + "px; height:" + height_div + "px;";
				
				var mycurrent_id_text = document.createElement("a");
				mycurrent_id_text.setAttribute("class", "gr_text_01");	
				mycurrent_id_text.setAttribute("className", "gr_text_01");
				mycurrent_id_text.style.cssText = "color:#7E7E7E;"
				//mycurrent_id_text.setAttribute("href", "");
				
				//var id_row = feature_list[c]["features"][0];
				//var mycurrent_id_text_content = document.createTextNode(finfo[feature_xmlnumber][id_row]["feature_id"]);
				var mycurrent_id_text_content = document.createTextNode(feature_list[c]["feature_label"].slice(0,12) + "...");
				
				mycurrent_id_text.appendChild(mycurrent_id_text_content);
				mycurrent_div_id.appendChild(mycurrent_id_text);
				
				mycurrent_li.appendChild(mycurrent_div_id);
			  }
			  
			  
			  
				
			// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
			// CREATE FEATURE COLUMN INSIDE LIST <LI>
			// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
				
				var mycurrent_div_graphic = document.createElement("div");
				mycurrent_div_graphic.setAttribute("class", "gr_div gr_row_0" + bg_color + " gr_cell_02");	
				mycurrent_div_graphic.setAttribute("className", "gr_div gr_row_0" + bg_color + " gr_cell_02");	
				//mycurrent_div_graphic.setAttribute("style", "top:0px; left:" + left_div_graphic + "px; width:" + width_div_graphic + "px; height:" + height_div + "px;");	
				mycurrent_div_graphic.style.cssText = "top:0px; left:" + left_div_graphic + "px; width:" + width_div_graphic + "px; height:" + height_div + "px;";
				
				
				
					// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
					// RECALCULATE FEATURE SIZE TO FIT IT IN THE GRAPHIC
					// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
					
					for(var n = 0; n < feature_list[c]["features"].length; n++)
					{
					  var row = feature_list[c]["features"][n];
						
					  if(origin == 'sorting' || origin == 'expanding')
					   {	
						// var feature_xmlnumber is defined in the creation of "LISTs"
						var feature_id = finfo[feature_xmlnumber][row]["feature_id"];
						var feature_start = finfo[feature_xmlnumber][row]["start_data"];
						var feature_end =finfo[feature_xmlnumber][row]["end_data"];
					   }
					  else
					   {
						var feature_id = finfo[row]["feature_id"];
						var feature_start = finfo[row]["start_data"]; 
						var feature_end =finfo[row]["end_data"];
						var feature_xmlnumber = finfo[row]["xmlnumber"];
					   }
					   var feature_width = feature_end - feature_start;
					   
					   var original_feature_start = feature_start;
					   var original_feature_end = feature_end;
					   var original_feature_width = feature_width;
					   
					   feature_start = feature_start -1;
					   feature_width = feature_end - feature_start; // It is 1 pixel bigger
			   
			   
			   
			   
					   // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
					   // ZOOM IMPLEMENTATION
					   // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
					   if( zoom_end != 0)
							{
								var zoom_width = zoom_end - zoom_start;
								feature_start = feature_start - zoom_start;
								feature_end = feature_start + feature_width;
								
								var temp_feature_start = feature_start;
								var temp_feature_end = feature_end;
		
								if(temp_feature_start > zoom_end)
								  {
									  feature_start = -1;
								  } // -1 => out of range
								else if(temp_feature_start < 0)
								  {
									  feature_start = 0;
								  } // (feature_start > zoom_end)
								  
								var new_zoom_width = zoom_width; 
								
								if(temp_feature_end > new_zoom_width && temp_feature_start > new_zoom_width)
								  {
									  feature_end = -1;
								  }
								else if(temp_feature_end > new_zoom_width)
								  {
									  feature_end = zoom_width;
								  }
								else if (temp_feature_end < 0)
								  {
									  feature_end = -1;
								  }  // -1 => out of range
								  
								var seq_width = zoom_width;
								feature_width = feature_end - feature_start;
							}
						else
							{
								var temp_feature_start = feature_start;
								var temp_feature_end = feature_end;
								
								if(temp_feature_start > (seq_stop -1))
								  {
									  feature_start = -1;
								  } // -1 => out of range
								// else if(temp_feature_start < seq_stop && temp_feature_end > seq_stop)
								if(temp_feature_end > seq_stop)
								  {
									  feature_end = seq_stop;
								  }
							}


				// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
				// IF ANNOTATION IS OUT OF THE RAGE OF AMINOACIDS TO DISPLAY THEN DON'T DISPLAY, OTHERWISE DISPLAY
				// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
				if(feature_start == -1 || feature_end == -1)
					{
						// Don't create features
					}
				else
					{
						var feature_start_value = ((width_div_graphic_correction * feature_start) / seq_width);
						var feature_end_value = ((width_div_graphic_correction * feature_end) / seq_width);
						var feature_width_value = ((width_div_graphic_correction * feature_width) / seq_width);	
		
						var mycurrent_graphic_feature = document.createElement("a");
						mycurrent_graphic_feature.setAttribute("id", feature_id + "_" + feature_start); // feature_id is not unique
						mycurrent_graphic_feature.setAttribute("class", "feature");	
						mycurrent_graphic_feature.setAttribute("className", "feature");	
						//mycurrent_graphic_feature.setAttribute("href", "");
						
						mycurrent_graphic_feature.style.cssText = "font-size:1px; top:2px; left:" + feature_start_value + "px; width:" + feature_width_value + "px; height:" + height_graphic_feature_correction + "px; border: 1px " + aborder_type + " " + feature_border_color + "; background-color:" + feature_background_color + ";";
						
						mycurrent_graphic_feature.onmouseover = new Function("this.style.backgroundColor = '" + feature_border_color + "';" +  "feature_mouse_action(findPosX(this), findPosY(this), '" + feature_id + "', " + feature_xmlnumber + ", " + row + ", 'mouseover');");
						
						mycurrent_graphic_feature.onmouseout = new Function("this.style.backgroundColor = '" + feature_background_color + "';");
	
						mycurrent_graphic_feature.onclick = new Function("highlightSequence(" + original_feature_start + ", " + original_feature_end + ", " + sequence_limit + ", '" + feature_border_color + "'); " + "feature_mouse_action(findPosX(this), findPosY(this), '" + feature_id + "', " + feature_xmlnumber + ", " + row + ", 'mouseclick');");

						feature_unique_id.push(feature_id + "_" + feature_start);
					
						mycurrent_div_graphic.appendChild(mycurrent_graphic_feature); // DIV with the Graphic
					} // if(feature_start == -1 || feature_end == -1)
			   
			} // for(var n = 0; n < feature_list[c]["features"].length; n++)	

			mycurrent_li.appendChild(mycurrent_div_graphic);

			
			
			

			// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
			// WARNING ICONS
			// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
			if (show_col_warning == 1)
			   {			
				var mycurrent_div_warning = document.createElement("div");
				mycurrent_div_warning.setAttribute("class", "gr_div gr_row_0" + bg_color + " gr_cell_01");
				mycurrent_div_warning.setAttribute("className", "gr_div gr_row_0" + bg_color + " gr_cell_01");

				mycurrent_div_warning.style.cssText = "top:0px; left:" + left_div_warning + "px; width:" + width_div_warning + "px; height:" + height_div + "px;";
				
				var mycurrent_warning_img_01 = document.createElement("img");
				if(feature_list[c]["version"] == 1)
					{
						mycurrent_warning_img_01.setAttribute("src", "/site_media/js/dasty2/client/img/checkmark.gif");
					}
				else
					{
						mycurrent_warning_img_01.setAttribute("src", "/site_media/js/dasty2/client/img/warning.gif");
					}
				
				var mycurrent_warning_img_02 = document.createElement("img");
				if (feature_list[c]["feature_group"] == 1)
					{
						mycurrent_warning_img_02.setAttribute("src", "/site_media/js/dasty2/client/img/group.gif");
					}
				else
					{
						mycurrent_warning_img_02.setAttribute("src", "/site_media/js/dasty2/client/img/group2.gif");
					}

				mycurrent_div_warning.appendChild(mycurrent_warning_img_01);
				mycurrent_div_warning.appendChild(mycurrent_warning_img_02);
				
				mycurrent_li.appendChild(mycurrent_div_warning);
			   }


	
	
			// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
			// SERVERs
			// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
			if (show_col_server == 1)
			   {			
				var mycurrent_div_server = document.createElement("div");
				mycurrent_div_server.setAttribute("class", "gr_div gr_row_0" + bg_color + " gr_cell_01");
				mycurrent_div_server.setAttribute("className", "gr_div gr_row_0" + bg_color + " gr_cell_01");

				mycurrent_div_server.style.cssText = "top:0px; left:" + left_div_server + "px; width:" + width_div_server + "px; height:" + height_div + "px;";
				
				var mycurrent_server_text = document.createElement("a");
				mycurrent_server_text.setAttribute("class", "gr_text_01");	
				mycurrent_server_text.setAttribute("className", "gr_text_01");
				mycurrent_server_text.setAttribute("target", "_dasregistry")
				mycurrent_server_text.setAttribute("href", "http://www.dasregistry.org/showdetails.jsp?auto_id=" + feature_list[c]["registry_uri"]);
				
				var mycurrent_server_text_content = document.createTextNode(feature_list[c]["server"]);
				
				mycurrent_server_text.appendChild(mycurrent_server_text_content);
				mycurrent_div_server.appendChild(mycurrent_server_text);
				
				mycurrent_li.appendChild(mycurrent_div_server);
	
			   }
			
			my_ul.appendChild(mycurrent_li);
			
		   
	
		   
		   
		 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		 // FINISHED Reading the information about the rearragement of annotations
		 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -   
		 } // for(var c = 0; c < feature_list.length; c++)
		
		
		// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		// CLOSING UL TAG
		// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 			 
	    div.appendChild(my_ul);




	// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
	// Tooltip Manager creates HTML code embeded below the BODY for each annotation to
	// be able to display feature deatails Pop-Ups on on mouse-over.
	// I don't like but this is what I've got at the moment.
	// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 	
	for(var n = 0; n < feature_unique_id.length; n++)
			{
				TooltipManager.addHTML(feature_unique_id[n], "display_feature_details");
			}


	// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
	// FINISH condition if there are annotations
    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
	} // if(feature_list.length > 0) 


		if(origin == "grouping" || origin == "noresults")
			{
			count_displayed_groups++;		
			
		     // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
			 // ONCE ALL THE ANNOTATIONS HAVE BEEN LOADED FROM ALL THE SERVERS ...
    		 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
			if(count_displayed_groups == feature_url.length) // feature_url is global!
				{
						 
						 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 	
						 // CREATE POSITIONAL VERTICAL LINES ON THE GRAPHIC
						 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
						 fillScaleBar();
						 dasty2.countVisibleLines = 0;
						 
						 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
						 // MESSAGE TO DISPLAY WHEN FINISH LOADING 
						 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
						 document.getElementById("system_information").innerHTML = "<span style=\"color:#999999\">... Dasty2 has finished loading the data.</span>";
						
						 
						 
						 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
						 // CREATE TABLE WITH DAS SOURCES DISPLAYED IN DASTY
						 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
						 if(dasty2.loadedDasSources.length == 0)
							{
								dasty2.loadedDasSources = dasty2.loadedDasSources_temp;
							}
							
						 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
						 // CREATE ONTOLOGY
						 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 	
						 if (isOntologyTreeVisible==true)
						 	{
							 create_ontology_tree();
						    }
						 create_server_tree();
						 
						 
						 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
						 // MAKE NPF SORTABLE
						 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
						 sortables_init();
						 
						 
						 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
						 // MESSAGE - NO ENTRIES FOUND
						 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
						 if(feature_results_count == 0)
							{
								var system_information = document.getElementById("system_information").innerHTML
								document.getElementById("system_information").innerHTML = system_information + "<br><span style=\"color:#CC0000\">There were no entries found with the Protein ID: \"<strong>" + query_id + "</strong>\" and the Registry label: \"<strong>" + filterLabel + "</strong>\" </span>";
							}
		
						 
						
						if(firstTimeSortByType_temp == true)
							{
								dasty2.firstTimeSortByType = false;
								sorting('type');
							}
							
							
				// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
			    // AFTER EVERY ASYCRONOUS LOADING ...
    		    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 	
				/*
				else
					{
	
						// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
						// CREATE SORTABLE LISTS BETWEEN UL - It just works with the first <UL>s
						// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
						var gr_list_array = [];
						for(var fu = 0; fu < results_XML_order.length; fu++)
							  {
								  gr_list_array.push('gr_list' + results_XML_order[fu]);
							  }
						
						for(var fu = 0; fu < results_XML_order.length; fu++)
							  {
								if(fu== 0)
										{
											Sortable.create('gr_list' + results_XML_order[fu], {dropOnEmpty:true,containment:gr_list_array,constraint:false});
										}
									  else
										{
											Sortable.create('gr_list' + results_XML_order[fu], {dropOnEmpty:true,handle:'handle',containment:gr_list_array,constraint:false});
										} // if(fu== 0)
							   } // for(var fu = 0; fu < results_XML_order.length; fu++)
											
					 } //if(feature_url.length == 1)
				*/
					 

				} // if(count_displayed_groups == feature_url.length)
				
	 		} // if(origin == "grouping" || origin == "noresults")
		else 
			{
				fillScaleBar();
				dasty2.countVisibleLines = 0;
			}
			
} // function createGraphic(tagId, segment_start, segment_stop)	





// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
// Calculate Position X and Y for the mouse
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

  function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }

  function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }
//------------------------------------------------------------------------------------------	
// GRAPHIC TITTLE
//------------------------------------------------------------------------------------------			
function createGraphicTittle(tagId, width_ul, left_div_category, width_div_category, left_div_type, width_div_type, left_div_method, width_div_method, left_div_id, width_div_id, left_div_graphic, width_div_graphic, left_div_server, width_div_server, height_div, show_col_id_temp, left_div_warning, width_div_warning)
	{
        var div = document.getElementById(tagId);
        var my_ul = document.createElement("ul");
		my_ul.setAttribute("id", "gr_list_tittle");
		my_ul.setAttribute("class", "gr_list_class");
		my_ul.setAttribute("className", "gr_list_class");
		//my_ul.setAttribute("style", "width:" + width_ul + "px;"); // tagId, width_ul
		my_ul.style.cssText = "width:" + width_ul + "px;";
		
		//------------------------------------------
		// LIsts
		//------------------------------------------
		var mycurrent_li = document.createElement("li");
		mycurrent_li.setAttribute("id", "gr_item_tittle");
		//mycurrent_li.setAttribute("style", "height:" + tittle_height + "px;"); // height_li // tittle_height is global!
		mycurrent_li.style.cssText = "height:" + tittle_height + "px;";
		
		//------------------------------------------
		// CATEGORIes
		//------------------------------------------
		if (show_col_category == 1)
		   {			
			var mycurrent_div_category = document.createElement("div");
			mycurrent_div_category.setAttribute("class", "gr_div gr_row_tittle");
			mycurrent_div_category.setAttribute("className", "gr_div gr_row_tittle");
			//mycurrent_div_category.setAttribute("style", "top:0px; left:" + left_div_category + "px; width:" + width_div_category + "px; height:" + height_div + "px;");	
			mycurrent_div_category.style.cssText = "top:0px; left:" + left_div_category + "px; width:" + width_div_category + "px; height:" + height_div + "px;";
				
			var mycurrent_category_text = document.createElement("a");
			mycurrent_category_text.setAttribute("class", "gr_text_02");	
			mycurrent_category_text.setAttribute("className", "gr_text_02");
			//mycurrent_category_text.setAttribute("href", "");
			
			
			//mycurrent_category_text.setAttribute("onclick", "sorting('category')");
			mycurrent_category_text.onclick = new Function("sorting('category');");
				
			var mycurrent_category_text_content = document.createTextNode("EVIDENCE (Category) ");
			var mycurrent_category_img_content = document.createElement("img");
			if(sortOrderCategory == 1)
				{
					mycurrent_category_img_content.setAttribute("src", "http://www.gpcr.org/7tm/dasty2/client/img/arrowup.gif");				
				}
			else if(sortOrderCategory == -1)
				{
					mycurrent_category_img_content.setAttribute("src", "http://www.gpcr.org/7tm/dasty2/client/img/arrowdown.gif");
				}
			else
				{
					mycurrent_category_img_content.setAttribute("src", "http://www.gpcr.org/7tm/dasty2/client/img/arrownone.gif");
				}
				
			mycurrent_category_text.appendChild(mycurrent_category_text_content);
			mycurrent_category_text.appendChild(mycurrent_category_img_content);
			mycurrent_div_category.appendChild(mycurrent_category_text);
			
			mycurrent_li.appendChild(mycurrent_div_category); // left_div_category, width_div_category, height_div 
		   }
		   


		//------------------------------------------
		// METHOD
		//------------------------------------------
		if (show_col_method == 1)
		   {			
			var mycurrent_div_method = document.createElement("div");
			mycurrent_div_method.setAttribute("class", "gr_div gr_row_tittle");
			mycurrent_div_method.setAttribute("className", "gr_div gr_row_tittle");
			//mycurrent_div_method.setAttribute("style", "top:0px; left:" + left_div_method + "px; width:" + width_div_method + "px; height:" + height_div + "px;");	
			mycurrent_div_method.style.cssText = "top:0px; left:" + left_div_method + "px; width:" + width_div_method + "px; height:" + height_div + "px;";
				
			var mycurrent_method_text = document.createElement("a");
			mycurrent_method_text.setAttribute("class", "gr_text_02");	
			mycurrent_method_text.setAttribute("className", "gr_text_02");
			//mycurrent_category_text.setAttribute("href", "");
			
			
			//mycurrent_category_text.setAttribute("onclick", "sorting('category')");
			mycurrent_method_text.onclick = new Function("sorting('method');");
				
			var mycurrent_method_text_content = document.createTextNode("METHOD ");
			var mycurrent_method_img_content = document.createElement("img");
			if(sortOrderMethod == 1)
				{
					mycurrent_method_img_content.setAttribute("src", "http://www.gpcr.org/7tm/dasty2/client/img/arrowup.gif");				
				}
			else if(sortOrderMethod == -1)
				{
					mycurrent_method_img_content.setAttribute("src", "http://www.gpcr.org/7tm/dasty2/client/img/arrowdown.gif");
				}
			else
				{
					mycurrent_method_img_content.setAttribute("src", "http://www.gpcr.org/7tm/dasty2/client/img/arrownone.gif");
				}
				
			mycurrent_method_text.appendChild(mycurrent_method_text_content);
			mycurrent_method_text.appendChild(mycurrent_method_img_content);
			mycurrent_div_method.appendChild(mycurrent_method_text);
			
			mycurrent_li.appendChild(mycurrent_div_method); // left_div_category, width_div_category, height_div 
		   }

		   
		//------------------------------------------
		// TYPEs
		//------------------------------------------
		if (show_col_type == 1)
		   {			
			var mycurrent_div_type = document.createElement("div");
			mycurrent_div_type.setAttribute("class", "gr_div gr_row_tittle");
			mycurrent_div_type.setAttribute("className", "gr_div gr_row_tittle");
			//mycurrent_div_type.setAttribute("style", "top:0px; left:" + left_div_type + "px; width:" + width_div_type + "px; height:" + height_div + "px;");	
			mycurrent_div_type.style.cssText = "top:0px; left:" + left_div_type + "px; width:" + width_div_type + "px; height:" + height_div + "px;";
				
			var mycurrent_type_text = document.createElement("a");
			mycurrent_type_text.setAttribute("class", "gr_text_02");	
			mycurrent_type_text.setAttribute("className", "gr_text_02");
			//mycurrent_type_text.setAttribute("href", "");
			
			//mycurrent_type_text.setAttribute("onclick", "sorting('type')");
			mycurrent_type_text.onclick = new Function("sorting('type');");
				
			var mycurrent_type_text_content = document.createTextNode("FEATURE TYPE ");
			var mycurrent_type_img_content = document.createElement("img");
			if(sortOrderType== 1)
				{
					mycurrent_type_img_content.setAttribute("src", "http://www.gpcr.org/7tm/dasty2/client/img/arrowup.gif");				
				}
			else if(sortOrderType == -1)
				{
					mycurrent_type_img_content.setAttribute("src", "http://www.gpcr.org/7tm/dasty2/client/img/arrowdown.gif");
				}
			else
				{
					mycurrent_type_img_content.setAttribute("src", "http://www.gpcr.org/7tm/dasty2/client/img/arrownone.gif");
				}
				
			mycurrent_type_text.appendChild(mycurrent_type_text_content);
			mycurrent_type_text.appendChild(mycurrent_type_img_content);
			mycurrent_div_type.appendChild(mycurrent_type_text);
				
			mycurrent_li.appendChild(mycurrent_div_type); // left_div_type, width_div_type, height_div
		   }
		   
		//------------------------------------------
		// IDs
		//------------------------------------------
		if (show_col_id_temp == 1)
		  {			
			var mycurrent_div_id = document.createElement("div");
			mycurrent_div_id.setAttribute("class", "gr_div gr_row_tittle");
			mycurrent_div_id.setAttribute("className", "gr_div gr_row_tittle");
			//mycurrent_div_id.setAttribute("style", "top:0px; left:" + left_div_id + "px; width:" + width_div_id + "px; height:" + height_div + "px;");
			mycurrent_div_id.style.cssText = "top:0px; left:" + left_div_id + "px; width:" + width_div_id + "px; height:" + height_div + "px;";
				
			var mycurrent_id_text = document.createElement("a");
			mycurrent_id_text.setAttribute("class", "gr_text_02");	
			mycurrent_id_text.setAttribute("className", "gr_text_02");	
			//mycurrent_id_text.setAttribute("href", "");
			
			//mycurrent_id_text.setAttribute("onclick", "sorting('id')");
			mycurrent_id_text.onclick = new Function("sorting('id');");
				
			var mycurrent_id_text_content = document.createTextNode("LABELS ");
				
			mycurrent_id_text.appendChild(mycurrent_id_text_content);
			mycurrent_div_id.appendChild(mycurrent_id_text);
				
			mycurrent_li.appendChild(mycurrent_div_id); // left_div_id, width_div_id, height_div
		  }
		  
		//------------------------------------------
		// FEATUREs
		//------------------------------------------
				
			var mycurrent_div_graphic = document.createElement("div");
			mycurrent_div_graphic.setAttribute("class", "gr_div gr_row_tittle gr_cell_02");	
			mycurrent_div_graphic.setAttribute("className", "gr_div gr_row_tittle gr_cell_02");	
			//mycurrent_div_graphic.setAttribute("style", "top:0px; left:" + left_div_graphic + "px; width:" + width_div_graphic + "px; height:" + height_div + "px;");	
			mycurrent_div_graphic.style.cssText = "top:0px; left:" + left_div_graphic + "px; width:" + width_div_graphic + "px; height:" + height_div + "px;";
			
			//var mycurrent_graphic_text = document.createElement("a");
			var mycurrent_graphic_text = document.createElement("span");
			mycurrent_graphic_text.setAttribute("class", "gr_text_02");	
			mycurrent_graphic_text.setAttribute("className", "gr_text_02");	
			//mycurrent_graphic_text.setAttribute("href", "");
				
			var mycurrent_graphic_text_content = document.createTextNode("FEATURE ANNOTATONS ");
				
			mycurrent_graphic_text.appendChild(mycurrent_graphic_text_content);
			mycurrent_div_graphic.appendChild(mycurrent_graphic_text);
				
			mycurrent_li.appendChild(mycurrent_div_graphic); // left_div_graphic, width_div_graphic, height_div
			
			
/*
		//------------------------------------------
		// VERSION
		//------------------------------------------
		if (show_col_warning == 1)
		   {			
			var mycurrent_div_warning = document.createElement("div");
			mycurrent_div_warning.setAttribute("class", "gr_div gr_row_tittle");
			mycurrent_div_warning.setAttribute("className", "gr_div gr_row_tittle");
			mycurrent_div_warning.style.cssText = "top:0px; left:" + left_div_warning + "px; width:" + width_div_warning + "px; height:" + height_div + "px;";
				
			var mycurrent_warning_text = document.createElement("a");
			mycurrent_warning_text.setAttribute("class", "gr_text_02");	
			mycurrent_warning_text.setAttribute("className", "gr_text_02");
			//mycurrent_warning_text.setAttribute("href", "");
			
			//mycurrent_warning_text.setAttribute("onclick", "sorting('type')");
			mycurrent_warning_text.onclick = new Function("sorting('version');");
				
			var mycurrent_warning_text_content = document.createTextNode("");
			var mycurrent_warning_img_content = document.createElement("img");
			if(sortOrderVersion== 1)
				{
					mycurrent_warning_img_content.setAttribute("src", "http://www.gpcr.org/7tm/dasty2/client/arrowup.gif");				
				}
			else if(sortOrderVersion == -1)
				{
					mycurrent_warning_img_content.setAttribute("src", "http://www.gpcr.org/7tm/dasty2/client/arrowdown.gif");
				}
			else
				{
					mycurrent_warning_img_content.setAttribute("src", "http://www.gpcr.org/7tm/dasty2/client/arrownone.gif");
				}
				
			mycurrent_warning_text.appendChild(mycurrent_warning_text_content);
			mycurrent_warning_text.appendChild(mycurrent_warning_img_content);
			mycurrent_div_warning.appendChild(mycurrent_warning_text);
				
			mycurrent_li.appendChild(mycurrent_div_warning); // left_div_type, width_div_type, height_div
		   }
*/
			
			
		//------------------------------------------
		// SERVERs
		//------------------------------------------
		if (show_col_server == 1)
		   {			
			var mycurrent_div_server = document.createElement("div");
			mycurrent_div_server.setAttribute("class", "gr_div gr_row_tittle");
			mycurrent_div_server.setAttribute("className", "gr_div gr_row_tittle");
			//mycurrent_div_server.setAttribute("style", "top:0px; left:" + left_div_server + "px; width:" + width_div_server + "px; height:" + height_div + "px;");	
			mycurrent_div_server.style.cssText = "top:0px; left:" + left_div_server + "px; width:" + width_div_server + "px; height:" + height_div + "px;";	
				
			var mycurrent_server_text = document.createElement("a");
			mycurrent_server_text.setAttribute("class", "gr_text_02");	
			mycurrent_server_text.setAttribute("className", "gr_text_02");
			//mycurrent_server_text.setAttribute("href", "");
			
			//mycurrent_server_text.setAttribute("onclick", "sorting('server')");
			mycurrent_server_text.onclick = new Function("sorting('server');")
				
			var mycurrent_server_text_content = document.createTextNode("SERVER NAME ");
			var mycurrent_server_img_content = document.createElement("img");
			if(sortOrderServer == 1)
				{
					mycurrent_server_img_content.setAttribute("src", "http://www.gpcr.org/7tm/dasty2/client/img/arrowup.gif");				
				}
			else if(sortOrderServer == -1)
				{
					mycurrent_server_img_content.setAttribute("src", "http://www.gpcr.org/7tm/dasty2/client/img/arrowdown.gif");
				}
			else
				{
					mycurrent_server_img_content.setAttribute("src", "http://www.gpcr.org/7tm/dasty2/client/img/arrownone.gif");
				}
				
			mycurrent_server_text.appendChild(mycurrent_server_text_content);
			mycurrent_server_text.appendChild(mycurrent_server_img_content);
			mycurrent_div_server.appendChild(mycurrent_server_text);
				
			mycurrent_li.appendChild(mycurrent_div_server); // left_div_server, width_div_server, height_div
		   }
			
		my_ul.appendChild(mycurrent_li);

	    div.appendChild(my_ul);
	}
			
//------------------------------------------------------------------------------------------	    
// CREATE NON POSITIONAL FEATURE TABLE
//------------------------------------------------------------------------------------------	
	function createNPFeatureTable(featureXML_num, array, tagId, npf_num)
	{

	if(npf_num == 0)
	 	{
	  // There are not positional features
	  	}
	 else
	 	{		
			var title_var = non_positional_features_coulmns;

			/**
			* The first time that a DAS source is loaded:
			*/
			var countNPF = dasty2.countNPF
			if(countNPF == 0)
				{
					dasty2.countNPF++;
					//Principio
					var title = new Array();
					title["type_category"] = "EVIDENCE (Category)";
					title["type_data"] = "TYPE NAME";
					title["type_id"] = "FEATURE TYPE";
					//title["feature_id"] = "FEATURE ID";
					title["feature_label"] = "LABEL";
					title["note_data"] = "NOTE";
					title["method_data"] = "METHOD";
					title["score_data"] = "S.";
					title["annotation_server"] = "SERVER NAME";
					title["link_data"] = "";
					title["version"] = "";
					
					var title_width = new Array();
					title_width["type_category"] = col_category_width;
					title_width["type_data"] = col_type_width;
					title_width["type_id"] = col_type_width;
					title_width["feature_label"] = col_id_width;
					title_width["note_data"] = "";
					title_width["method_data"] = "";
					title_width["score_data"] = 40;
					title_width["annotation_server"] = col_server_width;
					title_width["link_data"] = 5;
					title_width["version"] = 5;
	
					
					var mybody = document.getElementById(tagId);
					var mytable = document.createElement("table");
					mytable.setAttribute("id","non_positional_features");
					mytable.setAttribute("class","sortable feature_table");
					mytable.setAttribute("className","sortable feature_table");
					mytable.style.cssText = "width:" + non_positional_feature_table_width + ";";
				
					//mytable.setAttribute("class","sortable");
					//mytable.setAttribute("className","sortable");
					
					//var mythead = document.createElement('thead');
					
					var mytbody = document.createElement('tbody');
					mytbody.setAttribute("id","non_positional_features_tbody");
					
					var mycurrent_row = document.createElement("tr");
					mycurrent_row.setAttribute("class", "feature_table_row_title_decor");
					mycurrent_row.setAttribute("className", "feature_table_row_title_decor");
					for(var i = 0; i < title_var.length; i++)
					  {
						  var mycurrent_cell = document.createElement("th");
						  if(title_var[i] == "note_data" || title_var[i] == "link_data")
						  	{
								mycurrent_cell.setAttribute("class", "feature_table_cell_title_decor" + i + " unsortable");
						 		mycurrent_cell.setAttribute("className", "feature_table_cell_title_decor" + i + " unsortable");
							}
						  else
						  	{
								mycurrent_cell.setAttribute("class", "feature_table_cell_title_decor" + i);
						  		mycurrent_cell.setAttribute("className", "feature_table_cell_title_decor" + i);
							}
							
						  if(title_width[title_var[i]] != "")
						  	{
						  		mycurrent_cell.style.cssText = "width:" + title_width[title_var[i]] + "px;";
							}
						  var content = document.createTextNode(title[title_var[i]]);
						  mycurrent_cell.appendChild(content);
						  mycurrent_row.appendChild(mycurrent_cell);
					  }
					  
					//mythead.appendChild(mycurrent_row);
					mytbody.appendChild(mycurrent_row);
					//mytable.appendChild(mythead);
					mytable.appendChild(mytbody);
					mybody.appendChild(mytable);
				}

						// Lo del medio

			var mytbody = document.getElementById("non_positional_features_tbody");
			var npfTypes = new Array();
			var newType = false;

			
			for(var j = 0; j < array.length; j++)
				{	
					  if (array[j]["start_data"]==0 && array[j]["end_data"]==0)
						 { // non positional feature	
						 
							newType = false;
							
							if(typeof npfTypes[array[j]["type_id"]] == "undefined")
								{
									newType = true;
								}
								
							if(newType == true)
								{
									npfTypes[array[j]["type_id"]] = 0;
								}
							else
								{
									npfTypes[array[j]["type_id"]]++;
								}
					
	
							var mycurrent_row = document.createElement("tr");
							
							var tr_name = "npf_item" + featureXML_num + "_" + array[j]["type_id"] + "_" + npfTypes[array[j]["type_id"]];
							var tr_id_name = [];
							tr_id_name.push(tr_name);
							
							dasty2.IdlinesPerType.push([array[j]["type_id"], tr_id_name, 1]);
							dasty2.IdlinesPerCategory.push([array[j]["type_category"], tr_id_name, 1]);
							dasty2.IdlinesPerServer.push([array[j]["annotation_server"], tr_id_name, 1]);	
							
							
							
					  		mycurrent_row.setAttribute("id", tr_id_name);
							mycurrent_row.style.cssText = "display: table-row;"; //display: block;
							
							if(dasty2.decor_tr_npf == 0)
								{
									mycurrent_row.setAttribute("class", "feature_table_row_decor0");
									mycurrent_row.setAttribute("className", "feature_table_row_decor0");
									dasty2.decor_tr_npf++;
								}
							else
								{
									mycurrent_row.setAttribute("class", "feature_table_row_decor1");
									mycurrent_row.setAttribute("className", "feature_table_row_decor1");
									dasty2.decor_tr_npf--;
								}
									  
							for(var i = 0; i < title_var.length; i++)
								{
									var mycurrent_cell = document.createElement("td");
									//mycurrent_cell.setAttribute("class", "featuretable_cell_decor" + i);
									//mycurrent_cell.setAttribute("className", "featuretable_cell_decor" + i);
									
									if(title_var[i] == "link_data")
										{
											for(var w = 0; w < array[j][title_var[i]].length; w++)
												{
													var content = document.createElement("img");
													content.setAttribute("src", "/site_media/js/dasty2/client/img/ico_info2.gif");
													content.setAttribute("alt", array[j][title_var[i]][w]);
													content.setAttribute("border","0");
													
													var link_content = document.createElement("a");
													link_content.setAttribute("target", "_featurelinks");
													link_content.setAttribute("href", array[j]["link_href"][w]);
													link_content.appendChild(content);	

													mycurrent_cell.appendChild(link_content);
												}
										}
									else if(title_var[i] == "version")
										{
											for(var w = 0; w < array[j][title_var[i]].length; w++)
												{
													var content = document.createElement("img");
													content.setAttribute("src", "/site_media/js/dasty2/client/img/checkmark.gif");
													//content.setAttribute("alt", array[j][title_var[i]][w]);
													content.setAttribute("border","0");
													
													//var link_content = document.createElement("a");
													//link_content.setAttribute("target", "_version");
													//link_content.setAttribute("href", array[j]["link_href"][w]);
													//link_content.appendChild(content);	

													mycurrent_cell.appendChild(content);
												}
												
										}
									else if(title_var[i] == "note_data")
										{
											
											for(var w = 0; w < array[j][title_var[i]].length; w++)
												{
													var content = document.createTextNode(array[j][title_var[i]][w]);
													mycurrent_cell.appendChild(content);
													var br = document.createElement("br");
													mycurrent_cell.appendChild(br);
												}
										}
									else
										{
											var content = document.createTextNode(array[j][title_var[i]]);
											mycurrent_cell.appendChild(content);
										}
									
									//title_width["link_data"] = 5;
					
					//title["link_href"] = "LINK";
					
					
					
									
									mycurrent_row.appendChild(mycurrent_cell);
								}
							mytbody.appendChild(mycurrent_row);
						 } // if (array[j]["start_data"]==0 && array[j]["end_data"]==0)
					
					
				
					
					
				} // for(var j = 0; j < array.length; j++)
			
	


		
		
		
	    } //if(npf_num == 0)
	
    }
	
	
/*
* data used for some of the javascript tree examples. share! :-)
*/
function create_ontology_tree() 
{
//	parseOntology(1, onto_path_type);
//	parseOntology(2, onto_path_category);
}

/**
* Create Server Tree for the Server secction in the Ontology panel
*/

function create_server_tree() 
{
	var elementChecked = 2;
	var server_tree_element = new Array;
	server_tree_element[0] = new Array;
	server_tree_element[0]['dataContainer'] = "Servers";
	server_tree_element[0]['caption']          = "Servers";
	server_tree_element[0]['isOpen']           = true;
	server_tree_element[0]['isChecked']        = 2;
	server_tree_element[0]['children']         = new Array;
	
	for(var c = 0; c < dasty2.loadedDasSources.length; c++)
		{
			elementChecked = 2;
			for(var n = 0; n < excluded_das_sources.length; n++)
				{
					if(excluded_das_sources[n].toLowerCase() == dasty2.loadedDasSources[c].toLowerCase())
						{
							elementChecked = 0;
						}
				}
			server_tree_element[0]['children'][c] = new Array;
			server_tree_element[0]['children'][c]['dataContainer'] = dasty2.loadedDasSources[c];
			server_tree_element[0]['children'][c]['caption'] = dasty2.loadedDasSources[c];
			server_tree_element[0]['children'][c]['isChecked'] = elementChecked;
			server_tree_element[0]['children'][c]['onChangeCheckbox'] = display_ontology_servers;
			server_tree_element[0]['children'][c]['onClick'] = "javascript:printOnSystemInformation('" + dasty2.loadedDasSources[c] + " DAS Source')";
		}
	server_tree = new Bs_Tree();
	server_tree.imageDir = 'http://www.gpcr.org/7tm/dasty2/client/library/blueshoes46/components/tree/img/win98/';
	server_tree.checkboxSystemImgDir = 'http://www.gpcr.org/7tm/dasty2/client/library/blueshoes46/components/checkbox/img/win2k_noBorder/';
	server_tree.useCheckboxSystem = true;
	server_tree.checkboxSystemWalkTree = 3;
	server_tree.initByArray(server_tree_element);
	server_tree.drawInto('display_maniputation_options3_server_div');
	
}


/**
* Hide or display ontology types on the graphic
*/

function display_ontology_servers(treeElement)
	{
		if(treeElement.isChecked == 2 || treeElement.isChecked == 0)
			{
				display_ontology(treeElement, "server");
			}
	}

function display_ontology_types(treeElement)
	{
		if(treeElement.isChecked == 2 || treeElement.isChecked == 0)
			{
				display_ontology(treeElement, "type");
			}
	}
	
function display_ontology_categories(treeElement)
	{
		if(treeElement.isChecked == 2 || treeElement.isChecked == 0)
			{
				display_ontology(treeElement, "category");
			}
	}


function display_ontology(treeElement, classification)
{
		var linesPerClassification = lookForIdLines(treeElement.dataContainer, classification);
		var display_block = 'block';
			
		for(var j = 0; j < linesPerClassification[0].length; j++)
			{
				display_block = 'block';
				//printOnTest("LINES: " + linesPerClassification[j]);
				if(linesPerClassification[0][j].indexOf("npf_item") != -1)
					{
						if(browser_name != "Microsoft Internet Explorer")
							{
								display_block = "table-row";
							}
					}
				
				var e=document.getElementById(linesPerClassification[0][j]);
				var element_display = e.style.display;
				if(treeElement.isChecked == 2 && element_display == 'none')
					{
						e.style.display = display_block;
						var style_change = true;
						
						if(typeof dasty2.line_id_name2[linesPerClassification[0][j]] != "undefined")
							{
								dasty2.line_id_name2[linesPerClassification[0][j]] = 1;
							}

					}
				else if(treeElement.isChecked == 0 && element_display == display_block)
					{
						e.style.display = 'none';
						var style_change = true;
						
						if(typeof dasty2.line_id_name2[linesPerClassification[0][j]] != "undefined")
							{
								dasty2.line_id_name2[linesPerClassification[0][j]] = 0;
							}

					}
				//printOnTest(linesPerClassification[j]);
			}
			
		var height_difference = parseInt((linesPerClassification[0].length - linesPerClassification[1]) * (height_graphic_feature + 7));
		
		for(var j = 0; j < vertical_bars; j++)
			{
				if(treeElement.isChecked == 2 && style_change == true)
					{
						var new_height = parseInt(getPxHeightFromStyle("gr_scalebar_div_" + j)) + height_difference;
					}
				else if(treeElement.isChecked == 0 && style_change == true)
					{
						var new_height = parseInt(getPxHeightFromStyle("gr_scalebar_div_" + j)) - height_difference;
					}


				//printOnTest("gr_scalebar_div_" + j);
				//printOnTest(getPxHeightFromStyle("gr_scalebar_div_" + j));
				//printOnTest(new_height);
				
				resize_height = document.getElementById("gr_scalebar_div_" + j);
				resize_height.style.height = new_height + "px";
				//resize_height.style.cssText = "height:" + new_height + "px";
				
				//printOnTest(resize_height.style.height);
				
			}
		//dasty2.IdlinesPerType[treeElement.dataContainer].length
				//
}

	   // TYPE name: dasty2.IdlinesPerType[w][0]
	   // Lines ID with one TYPE: dasty2.IdlinesPerType[w][1]
	   // CATEGORY name: dasty2.IdlinesPerType[w][2]
	   // Number of lines: dasty2.IdlinesPerType[w][3]
	   
function lookForIdLines(target, classification)
	{
		var npf_item_perClassification = 0;
		var idLines = [];
		if(classification == "type")
			{
				for(var j = 0; j < dasty2.IdlinesPerType.length; j++)
					{
						if(dasty2.IdlinesPerType[j][0].toLowerCase() == target.toLowerCase())
							{
								for(var r = 0; r < dasty2.IdlinesPerType[j][2]; r++)
									{
										if(dasty2.IdlinesPerType[j][1][r].indexOf("npf_item") != -1)
											{	
												npf_item_perClassification++;
											}
										idLines.push(dasty2.IdlinesPerType[j][1][r]);
									}
							}
					}
			}
	 	else if(classification == "category")
 			{
				for(var j = 0; j < dasty2.IdlinesPerCategory.length; j++)
					{
						var category_name = dasty2.IdlinesPerCategory[j][0].toLowerCase();
						if(target == "")
							{
								if(category_name == target)
									{
										for(var r = 0; r < dasty2.IdlinesPerCategory[j][2]; r++)
											{
												if(dasty2.IdlinesPerCategory[j][1][r].indexOf("npf_item") != -1)
													{	
														npf_item_perClassification++;
													}
												idLines.push(dasty2.IdlinesPerCategory[j][1][r]);
											}
									}
							}
						else
							{
								if(category_name.indexOf(target.toLowerCase()) > -1)
									{
										for(var r = 0; r < dasty2.IdlinesPerCategory[j][2]; r++)
											{
												if(dasty2.IdlinesPerCategory[j][1][r].indexOf("npf_item") != -1)
													{	
														npf_item_perClassification++;
													}
												idLines.push(dasty2.IdlinesPerCategory[j][1][r]);
											}
									}
							}
						
					}
			}
		else if(classification == "server")
 			{
				for(var j = 0; j < dasty2.IdlinesPerServer.length; j++)
					{
						if(dasty2.IdlinesPerServer[j][0].toLowerCase() == target.toLowerCase())
							{
								for(var r = 0; r < dasty2.IdlinesPerServer[j][2]; r++)
									{
										if(dasty2.IdlinesPerServer[j][1][r].indexOf("npf_item") != -1)
											{	
												npf_item_perClassification++;
											}
										idLines.push(dasty2.IdlinesPerServer[j][1][r]);
									}
							}
					}
			}
 		
		//printOnTest(target + " / " +idLines + " / " + idLines.length);
 		return [idLines, npf_item_perClassification];
 		
 	}

function printOnSystemInformation(message)
	{
		document.getElementById("system_information").innerHTML = message;
	}

/**¨
  *		The algorithm go through the tree from the root to the leafs, when 
  *		find a leaf calls the method isType to see if is a currently used type. 
  *		If is not, the leaf is deleted.  
  *		When all the leafs are deleted its parent is also deleted
  *		@return 
  *			0: if the element wasn't pruned 
  *			1: if the element was pruned 
  *
  **/
function recursivePrune(elem){
	
	var children=elem.getChildren();
	var i=0;
	for (i=0;i<children.length;i++){
		var child = children[i];
		if (child.hasChildren()){
			i=i-recursivePrune(child);
		}else{
			if (!isInArray(child.dataContainer)){
				dasty2.temporalTree.removeElement(child.id);
				i--;
			}else{
				child.isOpen=true;
				child.isChecked=2;
			}
		}
	}

	if (i==0){
		if (!isInArray(elem.dataContainer)){
			dasty2.temporalTree.removeElement(elem.id);
			return 1;
		}
	}
	elem.isOpen=true;
	elem.isChecked=2;


	return 0;
}

/**
* the prune function is not used since it has been included in the parsing
*/

function prune(tree,array,ontoType){
//	printOnTest("Arreglo original");
//	printArray(array);
	dasty2.temporalArray=[];
	for(var i=0;i<array.length;i++){
		if ((array[i].indexOf("SO:")!=-1)||(array[i].indexOf("ECO:")!=-1)||(array[i].indexOf("MOD:")!=-1)){
			dasty2.temporalArray=dasty2.temporalArray.concat(array.splice(i,1));
			i--;
		}
	}
//	printOnTest("Arreglos antes de la poda");
//	printArray(array);
//	printArray(dasty2.temporalArray);

	dasty2.temporalTree=tree;
	var elem=dasty2.temporalTree.getElement(0);
	
	recursivePrune(elem);
	
	var root=elem.getChildren();
	
	
	var elementData = new Array;
	elementData.caption 		= 'Other Terms (Not in the ontology)';
	elementData.dataContainer	= "other_types";
	elementData.isOpen			= false;
	elementData.isChecked		= 2;
	elementData.children		= new Array;
	if (ontoType==1){
		elementData.onChangeCheckbox = display_ontology_types;
	}else{
		elementData.onChangeCheckbox = display_ontology_categories;
	}

	var newElement=elem.addChildByArray(elementData);
	
	for (var i=0;i<array.length;i++){
		var term = new Array;
		term.caption 		= array[i];
		term.dataContainer	= array[i];
		term.isOpen			= true;
		term.isChecked		= 2;
		if (ontoType==1){
			term.onChangeCheckbox = display_ontology_types;
		}else{
			term.onChangeCheckbox = display_ontology_categories;
		}

		newElement.addChildByArray(term);
	}

//	tree.draw();
//	printOnTest("Arreglos despues de la poda");
//	printArray(array);
//	printArray(dasty2.temporalArray);
	
	//Adding terms o

}

function isInArray(value){
	var i=0;
	for(i=0;i<dasty2.temporalArray.length;i++){
		if (dasty2.temporalArray[i].indexOf(value)!=-1){
			dasty2.temporalArray.splice(i,1);
			return true;
		}
	}
	return false;
}
// JavaScript Document
//------------------------------------------------------------------------------------------	
// SCALE BAR
//------------------------------------------------------------------------------------------			
function createScaleBar(num_of_bars, seq_width, width_ul, left_div_graphic, width_div_graphic)
	{
		var num_of_bars = num_of_bars - 1;
		bar_aa_distance_list = [];
		bar_px_distance_list = [];
		
		if( zoom_end != 0)
			{		   
				var zoom_width = zoom_end - zoom_start;
				var seq_width = zoom_width;
				
				//var opa = document.getElementById("display_test");
				//var content_opa = opa.innerHTML;
				//opa.innerHTML = (content_opa + " <br>------------<br>temp_zoom_start:" + temp_zoom_start + " zoom_end:" + zoom_end + " zoom_width:" + zoom_width + " temp_zoom_end:" + temp_zoom_end + " seq_stop:" + seq_stop);	
			}
	
		
		createAaDistanceList(num_of_bars, seq_width);
		createPixelDistanceList(seq_width, left_div_graphic);
		
		//alert(bar_px_distance_list);
		
	 var scalebar_ul = document.createElement("ul");
	 scalebar_ul.setAttribute("id", "gr_scalebar_ul");
	 scalebar_ul.setAttribute("class", "gr_scalebar");
	 scalebar_ul.setAttribute("className", "gr_scalebar");
	 //scalebar_ul.setAttribute("style", "width:" + width_ul + "px;");
	 scalebar_ul.style.cssText = "width:" + width_ul + "px;";
	 
	 var scalebar_li = document.createElement("li");
	 scalebar_li.setAttribute("id", "gr_scalebar_li");
	 //scalebar_li.setAttribute("style", "height:" + tittle_height + "px;"); // tittle_height is gloabal!
	 scalebar_li.style.cssText = "height:" + tittle_height + "px;";
	 scalebar_ul.appendChild(scalebar_li);
	 
	 return scalebar_ul;
	}
	
function fillScaleBar()
	{

		if( zoom_end != 0)
			{  
				var zoom_width = zoom_end - zoom_start;
				var seq_width = zoom_width;			
				//alert(zoom_width);
			}
		else
			{
			 var seq_start = sequence_info.sequence_start -1;
			 var seq_stop = sequence_info.sequence_stop;
			 var seq_width = seq_stop - seq_start;
			}

		
			 var height_div = (dasty2.countVisibleLines * (height_graphic_feature + 7)) + (tittle_height * 2) + 1;
			 
			 if(browser_name == "Microsoft Internet Explorer")
				{
					height_div = height_div + 3;
				}
			 
			 var scalebar = document.getElementById("gr_scalebar_li");
			 
			 var div_width = setDivLength(seq_width);
			 
			 for(var b = 0; b < bar_px_distance_list.length; b++)
				{
				 //if(b == 0 || b == (bar_px_distance_list.length -1))
				 	//{
						 // skip drawing
					//}
				 //else
				 	//{
						 // ----------------------------------------------------------------------------------
						 // POSITION BARS
						 // ----------------------------------------------------------------------------------
						 var scalebar_div_graphic = document.createElement("div");
						 //scalebar_div_graphic.setAttribute("class", "gr_div gr_row_0" + bg_color + " gr_cell_02");
						 scalebar_div_graphic.setAttribute("id", "gr_scalebar_div_" + b);
						 scalebar_div_graphic.setAttribute("class", "gr_div gr_scalebar_div");
						 scalebar_div_graphic.setAttribute("className", "gr_div gr_scalebar_div");
						 if( zoom_end != 0)
							{
								//scalebar_div_graphic.setAttribute("style", "top:0px; left:" + (bar_px_distance_list[b] - div_width + 1) + "px; width:" + div_width + "px; height:" + height_div + "px;");
								scalebar_div_graphic.style.cssText = "top:0px; left:" + (bar_px_distance_list[b] - div_width + 1) + "px; width:" + div_width + "px; height:" + height_div + "px;";
							}
						 else
							{
								//scalebar_div_graphic.setAttribute("style", "top:0px; left:" + (bar_px_distance_list[b] - div_width + 1) + "px; width:" + div_width + "px; height:" + height_div + "px;");
								
								scalebar_div_graphic.style.cssText = "top:0px; left:" + (bar_px_distance_list[b] - div_width + 1) + "px; width:" + div_width + "px; height:" + height_div + "px;";
							} // if( zoom_end != 0)
							
						 scalebar.appendChild(scalebar_div_graphic);
						 
						 
				//var opa = document.getElementById("display_test");
				//var content_opa = opa.innerHTML;
				//opa.innerHTML = (content_opa + " <br>------------<br>value:" + bar_px_distance_list[b] + " div:" + div_width);
				//opa.innerHTML = (content_opa + " <br>------------<br>temp_zoom_start:" + temp_zoom_start + " zoom_end:" + zoom_end + " zoom_width:" + zoom_width + " temp_zoom_end:" + temp_zoom_end + " seq_stop:" + seq_stop);
						 
						 
						 // ----------------------------------------------------------------------------------
						 // POSITION NUMBERS
						 // ----------------------------------------------------------------------------------
						 var left_position = bar_px_distance_list[b] + 3;
						 var scalebar_position = document.createElement("span");
						 scalebar_position.setAttribute("class", "gr_scalebar_span");
						 scalebar_position.setAttribute("className", "gr_scalebar_span");
						 //scalebar_position.setAttribute("style", "top:0px; left:" + left_position + "px;");
						 scalebar_position.style.cssText = "top:0px; left:" + left_position + "px;";
						 
						 var scalebar_position_content = document.createTextNode(bar_aa_distance_list[b]);
						 scalebar_position.appendChild(scalebar_position_content);
						 scalebar.appendChild(scalebar_position);
				 
					//} // if(b == 0 || b == (bar_px_distance_list.length -1))
				}  // for(var b = 0; b < bar_px_distance_list.length; b++)	
	}
	
	
function createAaDistanceList(num_of_bars, seq_width)
	{
		var num_of_bars_temp = num_of_bars;
		if(seq_width < 16 && num_of_bars_temp > 4)
			{
				var num_of_bars = 4;
			}
		if(seq_width < 8 && num_of_bars_temp > 2)
			{
				var num_of_bars = 2;
			}
			
		var bar_aa_distance = (seq_width / num_of_bars);
		//alert(bar_aa_distance);
		var bar_aa_distance_correction = parseInt(bar_aa_distance/10);
		//alert(bar_aa_distance_correction);
		if(bar_aa_distance_correction > 0)
			{

				var bar_aa_distance_correction_value = parseInt(bar_aa_distance_correction.toString() + "0");
			}
		else
			{
				var bar_aa_distance_correction_value = parseInt(bar_aa_distance);
			}
		//bar_aa_distance_correction = bar_aa_distance;
		//alert(bar_aa_distance_correction);
		//var num_of_bars_correction = num_of_bars -1;
		
		bar_aa_distance_list.push(1);
		for(var b = 1; b < num_of_bars; b++)
			{
				bar_aa_distance_list.push(bar_aa_distance_correction_value * b);
			}
		bar_aa_distance_list.push(seq_width);
		 
		//alert(bar_aa_distance_list);
	}
	
	
	
	

function createPixelDistanceList(seq_width, left_div_graphic)
	{
		for(var b = 0; b < bar_aa_distance_list.length; b++)
			{
				bar_px_distance_list.push(((width_div_graphic_correction * bar_aa_distance_list[b])/seq_width) + left_div_graphic);
				// bar_px_distance_list.push(((width_div_graphic_correction * bar_aa_distance_list[b])/seq_width) + 1 + left_div_graphic);
			}	
		if( zoom_end != 0)
			{
				if(zoom_start == 0 || zoom_start == 1)
					{
						// Don't add startZoom to bar_aa_distance_list
					}
				else
					{
						addZoomToBar_aa_distance_list();
					}
			}
	}
	
function addZoomToBar_aa_distance_list()
	{
		//var aa_start = parseInt(zoom_start/10);
		for(var b = 0; b < bar_aa_distance_list.length; b++)
			{
				// bar_aa_distance_list[b] = bar_aa_distance_list[b] + parseInt(aa_start.toString() + "0");
				bar_aa_distance_list[b] = bar_aa_distance_list[b] + (zoom_start);
			}
	}
	
	
function setDivLength(seq_width)
	{
		var div_width_temp = width_div_graphic_correction / seq_width;
		var div_width = 0;
		
		if (div_width_temp < 1)
			{
				div_width = 1;
			}
		else
			{
				div_width = div_width_temp;
			}
		return div_width
	}//------------------------------------------------------------------------------------------	
// CREATE QUERY INFORMATION FIELD
//------------------------------------------------------------------------------------------	
	  
	  		function createQueryInformationField(object, tagId)
			{
			var div = document.getElementById(tagId);
			
	        var a = document.createElement("span");
			a.setAttribute("id", "display_query_id_title");
			a.setAttribute("class", "title");
			a.setAttribute("className", "title");
			a.appendChild(document.createTextNode("Sequence ID: "));				  
			div.appendChild(a);
			
			var uniprot_link = document.createElement("a");
			uniprot_link.setAttribute("target", "_uniprot");
			uniprot_link.setAttribute("href", "http://beta.uniprot.org/uniprot/" + object["sequence_id"]);			
			
				var uniprot_acc = document.createTextNode(object["sequence_id"]);
			
			uniprot_link.appendChild(uniprot_acc);
			
			var b = document.createElement("span");
			b.setAttribute("id", "display_query_id_content");
			b.appendChild(uniprot_link);				  
			div.appendChild(b);		
			
			var c = document.createElement("br");
			div.appendChild(c);
			
			var d = document.createElement("span");
			d.setAttribute("id", "display_query_length_title");
			d.setAttribute("class", "title");
			d.setAttribute("className", "title");
			d.appendChild(document.createTextNode("Sequence length: "));				  
			div.appendChild(d);
			
			var e = document.createElement("span");
			e.setAttribute("id", "display_query_length_content");
			e.appendChild(document.createTextNode(object["sequence_length"]));				  
			div.appendChild(e);
			
			document.getElementById('zoom_start_px').value = 1;
			document.getElementById('zoom_end_px').value = object["sequence_length"];
			
			}
	  ////------------------------------------------------------------------------------------------	
// CREATE SEQUENCE TEXT CONTENT
//------------------------------------------------------------------------------------------	
	  
	  		function createSequenceField(tagId)
			{
        	var sequenceDiv = document.createElement("div");
			sequenceDiv.setAttribute("id", "display_seque_protein");
			sequenceDiv.setAttribute("class", "sequence_format");
			sequenceDiv.setAttribute("className", "sequence_format");

//			sequenceDiv.setAttribute("onmouseup", "getSequenceRangeSelected(this)");
			//sequenceDiv.appendChild(document.createTextNode(text));				  
			document.getElementById(tagId).appendChild(sequenceDiv);
			
			//highlightSequence(0, 0, sequence_limit); // this function will take the "sequence" global variable with the aa sequence
			
			//makeRequest('xml/server_list.xml', 'serverListXML');
			//makeStylesheetRequest();
			sequenceDiv.innerHTML = sequence;//(new_sequence);		
			}
	  //// JavaScript Document
//------------------------------------------------------------------------------------------	
// ZOOM SLIDE BAR
//------------------------------------------------------------------------------------------			
function createSlideBar(width_ul, left_div_graphic, width_div_graphic)
	{		
	 var slidebar_ul = document.createElement("ul");
	 slidebar_ul.setAttribute("id", "gr_slidebar_ul");
	 slidebar_ul.setAttribute("class", "gr_slidebar");
	 slidebar_ul.setAttribute("className", "gr_slidebar");
	 //slidebar_ul.setAttribute("style", "width:" + width_ul + "px;");
	 //slidebar_ul.style.setAttribute('cssText', "width:" + width_ul + "px;");
	 slidebar_ul.style.cssText = "width:" + width_ul + "px;";
	 
	 var slidebar_li = document.createElement("li");
	 slidebar_li.setAttribute("id", "gr_slidebar_li");
	 //slidebar_li.setAttribute("style", "height:" + tittle_height + "px;"); // tittle_height is gloabal!
	 //slidebar_li.style.setAttribute('cssText', "height:" + tittle_height + "px;");
	 slidebar_li.style.cssText = "height:" + tittle_height + "px;";
	 slidebar_ul.appendChild(slidebar_li);
	 
	 var slidebar_div = document.createElement("div");
	 slidebar_div.setAttribute("id", "gr_slidebar_div_track");
	 //slidebar_div.setAttribute("style", "width:"+ width_div_graphic +"px;background-color:#E4E4E4;height:5px;position:relative;left:" + (left_div_graphic + 1) + "px;");
	 //slidebar_div.style.setAttribute('cssText', "width:"+ width_div_graphic +"px;background-color:#E4E4E4;height:5px;position:relative;left:" + (left_div_graphic + 1) + "px;");
	 slidebar_div.style.cssText = "width:"+ width_div_graphic +"px;background-color:#E4E4E4;height:5px;position:relative;left:" + (left_div_graphic + 1) + "px;display:none;";
	 slidebar_li.appendChild(slidebar_div);
	 
	 var slidebar_div_thumb_01 = document.createElement("div");
	 slidebar_div_thumb_01.setAttribute("id", "gr_slidebar_div_thumb_01");
	 //slidebar_div_thumb_01.setAttribute("style", "cursor:e-resize;position:absolute;top:0;left:0;width:5px;height:10px;background-color:#f00;opacity:.70; filter: alpha(opacity=70);");
	 //slidebar_div_thumb_01.style.setAttribute('cssText', "cursor:e-resize;position:absolute;top:0;left:0;width:5px;height:10px;background-color:#f00;opacity:.70; filter: alpha(opacity=70);");
	 slidebar_div_thumb_01.style.cssText = "cursor:e-resize;position:absolute;top:0;left:0;width:5px;height:10px;background-color:#f00;opacity:.70; filter: alpha(opacity=70);";
	 slidebar_div.appendChild(slidebar_div_thumb_01);

	 var slidebar_div_thumb_02 = document.createElement("div");
	 slidebar_div_thumb_02.setAttribute("id", "gr_slidebar_div_thumb_02");
	 //slidebar_div_thumb_02.setAttribute("style", "cursor:w-resize;position:absolute;top:0;left:0;width:5px;height:10px;background-color:#f00;opacity:.70; filter: alpha(opacity=70);");
	 //slidebar_div_thumb_02.style.setAttribute('cssText', "cursor:w-resize;position:absolute;top:0;left:0;width:5px;height:10px;background-color:#f00;opacity:.70; filter: alpha(opacity=70);");
	 slidebar_div_thumb_02.style.cssText = "cursor:w-resize;position:absolute;top:0;left:0;width:5px;height:10px;background-color:#f00;opacity:.70; filter: alpha(opacity=70);";
	 slidebar_div.appendChild(slidebar_div_thumb_02);
	 

  //<div id="track6" style="width:500px;background-color:#aaa;height:5px;position:relative;">
    //<div id="handle6-1" style="position:absolute;top:0;left:0;width:5px;height:10px;background-color:#f00;"> </div>
    //<div id="handle6-2" style="position:absolute;top:0;left:0;width:5px;height:10px;background-color:#0f0;"> </div>
  //</div>
	 
	 return slidebar_ul;
	}
	

	
	
function activateSlideBar(start_feature, end_feature, handle_start_id, handle_end_id, track_id, show_start_id, show_end_id)
  {
	  	var end_feature_temp = end_feature;
	  	if(end_feature_temp == 0 || end_feature_temp == "")
			{
				start_feature = sequence_info.sequence_start;
				end_feature = sequence_info.sequence_stop;
			}	
			
	    var slider = new Control.Slider([handle_start_id,handle_end_id],track_id,{
		range:$R(parseInt(start_feature),parseInt(end_feature)), // start seq, end seq
        sliderValue:[parseInt(start_feature),parseInt(end_feature)], // start seq, end seq
        restricted:true,
		//onSlide:function(v){document.getElementById(show_start_id).value = parseInt(v[0]); document.getElementById(show_end_id).value =parseInt(v[1]);}});
		onSlide:function(v){v = v; document.getElementById(show_start_id).value = parseInt(v[0]); document.getElementById(show_end_id).value =parseInt(v[1]);}});
        //onChange:function(v){$('debug6').innerHTML='Changed: '+ v[0]; $(name_debug).innerHTML='Changed: '+ v[1];}});
        //onSlide:function(v){$('debug6').innerHTML='slide: '+ v},
        //onChange:function(v){$('debug6').innerHTML='changed! '+v.inspect()}});
  }
// JavaScript Document
//------------------------------------------------------------------------------------------	
// Hide/Show columns in the graphic
//------------------------------------------------------------------------------------------			
function define_graphic_column(column_name)
	{
		var plus_icon = "<img src=\"/site_media/js/dasty2/client/img/tick01.gif\" border=\"0\" align=\"absbottom\">&#160;";
		var minus_icon = "<img src=\"/site_media/js/dasty2/client/img/notick01.gif\" border=\"0\" align=\"absbottom\">&#160;";
		
		switch (column_name)
		  {
			case "category" :
				if(show_col_category == 1)
					{
						show_col_category = 0;
						var icon = document.getElementById("menu_mo_img_category_column");
						icon.innerHTML = minus_icon;
					}
				else
					{
						show_col_category = 1;
						var icon = document.getElementById("menu_mo_img_category_column");
						icon.innerHTML = plus_icon;
					}
				break;
				
			case "method" :
				if(show_col_method == 1)
					{
						show_col_method = 0;
						var icon = document.getElementById("menu_mo_img_method_column");
						icon.innerHTML = minus_icon;
					}
				else
					{
						show_col_method = 1;
						var icon = document.getElementById("menu_mo_img_method_column");
						icon.innerHTML = plus_icon;
					}
				break;
						
			case "type" :
				if(show_col_type == 1)
					{
						show_col_type = 0;
						var icon = document.getElementById("menu_mo_img_type_column");
						icon.innerHTML = minus_icon;
					}
				else
					{
						show_col_type = 1;
						var icon = document.getElementById("menu_mo_img_type_column");
						icon.innerHTML = plus_icon;
					}
				break;
				
			case "server" :
				if(show_col_server == 1)
					{
						show_col_server = 0;
						var icon = document.getElementById("menu_mo_img_server_column");
						icon.innerHTML = minus_icon;
					}
				else
					{
						show_col_server = 1;
						var icon = document.getElementById("menu_mo_img_server_column");
						icon.innerHTML = plus_icon;
					}
				break;
				
			case "id" :
				if(show_col_id == 1)
					{
						show_col_id = 0;
						var icon = document.getElementById("menu_mo_img_id_column");
						icon.innerHTML = minus_icon;
					}
				else
					{
						show_col_id = 1;
						var icon = document.getElementById("menu_mo_img_id_column");
						icon.innerHTML = plus_icon;
					}
				break;
		  }	
		sorting();
	}

//------------------------------------------------------------------------------------------	
// EXPANDING
//------------------------------------------------------------------------------------------			
function expanding()
	{
	document.getElementById("system_information").innerHTML = "Dasty2 is modifying the columns of the graphic ...";
	if(isExpanded == 0)	
	  {
	  isExpanded = 1;
	  e=document.getElementById('id_column');
	  e.style.display = 'block';
	  
	  var plus_icon = "<img src=\"http://www.gpcr.org/7tm/dasty2/client/tick01.gif\" border=\"0\" align=\"absbottom\">&#160;";
	  var icon = document.getElementById("menu_mo_img_expand");
	  icon.innerHTML = plus_icon;
	  
	  if(expanded_feature_list.length == 0)
	 	{
			var row = 0;
			for(var a = 0; a < new_feature_list_info2.length; a++)
				{
				  if(new_feature_list_info2[a])
				   {
					for(var b = 0; b < new_feature_list_info2[a].length; b++)
						{
							for(var c = 0; c < new_feature_list_info2[a][b]["features"].length; c++)
								{
									expanded_feature_list[row] = [];
									//expanded_feature_list[row]["features"] = [];
									expanded_feature_list[row]["features"] = [new_feature_list_info2[a][b]["features"][c]];
									expanded_feature_list[row]["feature_group"] = new_feature_list_info2[a][b]["feature_group"];
									expanded_feature_list[row]["method"] = new_feature_list_info2[a][b]["method"];
									expanded_feature_list[row]["type"] = new_feature_list_info2[a][b]["type"];
									expanded_feature_list[row]["category"] = new_feature_list_info2[a][b]["category"];
									//expanded_feature_list[row]["feature_id"] = new_feature_list_info2[a][b]["feature_id"];
									expanded_feature_list[row]["feature_label"] = new_feature_list_info2[a][b]["feature_label"];
									expanded_feature_list[row]["server"] = new_feature_list_info2[a][b]["server"];
									expanded_feature_list[row]["xmlnumber"] = a;
									expanded_feature_list[row]["version"] = annotation_version[a];
									//one_feature_list[row] = new_feature_list_info2[a][b];
									//one_feature_list[row]["xmlnumber"] = a;
									row++
								} // for(var c = 0; c < new_feature_list_info2[a][b]["features"].length; c++)
						} // for(var b = 0; b < new_feature_list_info2[a].length; b++)
					} // if(new_feature_list_info2[a])
				} // for(var a = 0; a < new_feature_list_info2.length; a++)
		} // if(expanded_feature_list.length == 0)
	  var graphic_content = document.getElementById("display_graphic");
      graphic_content.innerHTML = '';
	  createGraphic2(0, "display_graphic", sequence_info.sequence_start, sequence_info.sequence_stop, "expanding");
	  //Sortable.create('gr_list0',{ghosting:true,constraint:false}); // Simpler
	  Sortable.create('gr_list0', {onUpdate:function(){new Effect.Highlight('gr_list0', {startcolor:'#CCCCCC'});}});
	  
	  }
	else
	  {
		  isExpanded = 0;
		  e=document.getElementById('id_column');
		  e.style.display = 'none';
		  
		  var minus_icon = "<img src=\"http://www.gpcr.org/7tm/dasty2/client/img/notick01.gif\" border=\"0\" align=\"absbottom\">&#160;";
		  var icon = document.getElementById("menu_mo_img_expand");
		  icon.innerHTML = minus_icon;
		  
		  sorting();
		  
	  }
	document.getElementById("system_information").innerHTML = "<span style=\"color:#999999\">... Dasty2 finished to modify the columns of the graphic.</span>";
	
	
//--------------------------------

	

		//for(var lu = 0; lu < expanded_feature_list.length; lu++)
			//{
				//var new_feature_list = expanded_feature_list;
				//var opa = document.getElementById("display_test");
				//var content_opa = opa.innerHTML;
				//opa.innerHTML = (content_opa + " <br>------------<br>new_feature_list[" + lu + "][features]: " + new_feature_list[lu]["features"] + "::::: new_feature_list[" + lu + "][feature_group]: " + new_feature_list[lu]["feature_group"] + "::::: new_feature_list[" + lu + "][type]: " + new_feature_list[lu]["type"] + new_feature_list[lu]["category"] + new_feature_list[lu]["server"] + new_feature_list[lu]["xmlnumber"]);
			//}
	}

	



//------------------------------------------------------------------------------------------
//PRINT FUNCTION
//------------------------------------------------------------------------------------------
function printOnTest(arg)
	{
		var opa = document.getElementById("display_test");
		var content_opa = opa.innerHTML;
		opa.innerHTML = (content_opa + " <br>------------<br>Test:" + arg);	
	}

//------------------------------------------------------------------------------------------	    
// FUNCTIONS TO HIGHLIGHT SEQUENCE AND STRUCTURE
//------------------------------------------------------------------------------------------		

	/**
	* stores start position of a new highlight request 
	*/
	function addPos(x){
		//document.getElementById("output").innerHTML = x;
		selStart = x;
	}
	
	/**
	* highlight the structure as per highlighted sequence 
	*/
	function highlightStru(x){
		var segUniprot;
		if (x>selStart){
			segUniprot=new segment(sequence_info.sequence_id,selStart,x);
		}else { 
			segUniprot=new segment(sequence_info.sequence_id,x,selStart);
		}
		var segPDB=extrapolateSegment(segUniprot);
		if (segPDB!=null)
	    	selectPDBResidues(segPDB.start,segPDB.end);
	}
	
	  
function highlightSequence(fstart, fend, aa_num_per_line, color)
	{ 
		fstart-=1;fend-=1;
	   	for(var i=0;i<sequence_info["sequence_length"];i++){
			var spanBase = document.getElementById("aa_"+(i+1));
	   		if ((i>=fstart)&&(i<=fend)){
	   			 spanBase.setAttribute("class","highlightSequence");
	   			 spanBase.style.color=color;
//	   			 spanBase.style.border-bottom="1px";
	   		}else{
	   			 spanBase.setAttribute("class","");
	   			 
	   			 spanBase.style.color="black";
//	   			 spanBase.style.border-bottom="1px";
	   		}
	   	}	
/*	
	var start = fstart - 1;
	var end = fend;
	var span_start = "<span class=\"highlightSequence\" style=\"color:" + color + "; border-bottom: 1px dotted " + color + "; \">";
	//var span_start = "<span style=\" color:" + color + "; font-weight:bold;\">"; // "<span style=\" color:#3399FF;\">";
	//var span_start = "<span style=\"border:solid " + color + "; font-weight:bold;\">"; //opacity:0.2;background-color: border:#009933;
	var span_end = "</span>";
	var aa_num = aa_num_per_line; // 60
	//alert(sequence);
	//TEST
	var text = '';
	var new_sequence = '';
	
	//var regex = /\W+/g;
	//var regex = /\n+/g;
	text = sequence; // sequence is Global
	//text = text.replace(regex,""); //commented, must discuss if essential. It interferes with highlight idea
	//alert(text);
	var count = 0;
	var count2 = 0;
	var control = 0;
	while (count < text.length)
		{
			count2 = count + aa_num;
			control = 0;
			if(count <= start && start < count2)
			   {
				 if(count <= end && end < count2)
				   {
					 new_sequence = new_sequence + text.substring(count, start) + span_start + text.substring(start, end) + span_end + text.substring(end, count2) + "<br>";
				   }
				 else
				   {
				     new_sequence = new_sequence + text.substring(count, start) + span_start + text.substring(start, count2) + "<br>";
				   }
			   }
			else
			   {
			   	 if(count <= end && end < count2)
				   {
			         new_sequence = new_sequence + text.substring(count, end) + span_end + text.substring(end, count2) + "<br>";
				   }
				 else
				   {
				     new_sequence = new_sequence + text.substring(count, count2) + "<br>";
				   }
			   }
			count = count2;
		}
	*/
//	var opa = document.getElementById("display_seque_protein");
//	var content_opa = opa.innerHTML;
//	opa.innerHTML = seq;//(new_sequence);		
	}
	//

//------------------------------------------------------------------------------------------	
// FUNCTION TO SHOW AND HIDE CONTENT
//------------------------------------------------------------------------------------------	
	function changeDisplayState(child, img_span, img_num)
	{
				//d=document.getElementById(father);
				e=document.getElementById(child);
				if (e.style.display == 'none' || e.style.display =="") {
					e.style.display = 'block';
					if( img_span == null || img_span == "")
				  		{
							// Do nothing
					  	}
					else
						{
							var img_display = document.getElementById(img_span);
							img_display.innerHTML = "<img src=\"/7tm/dasty2/client/img/minus0" + img_num + ".gif\" border=\"0\" align=\"absbottom\">&#160;";	
						}
					
				} else {
					e.style.display = 'none';
					if( img_span == null || img_span == "")
				  		{
							// Do nothing
					  	}
					else
						{
							var img_display = document.getElementById(img_span);
							img_display.innerHTML = "<img src=\"/7tm/dasty2/client/img/plus0" + img_num + ".gif\" border=\"0\" align=\"absbottom\">&#160;";	
						}
				}
	}
	

//------------------------------------------------------------------------------------------	
// CHECK AND PUT THE RIGHT +/- ICONS IN THE MAIN HTML PAGE
//------------------------------------------------------------------------------------------	
	function checkSectionIcons()
		{

					var plus_icon = "<img src=\"/7tm/dasty2/client/img/minus02.gif\" border=\"0\" align=\"absbottom\">&#160;";
					var plus_icon_white = "<img src=\"/7tm/dasty2/client/img/minus01.gif\" border=\"0\" align=\"absbottom\">&#160;";
					
					var display_query_box = document.getElementById("display_query_box_div");
					var menu_query_box_img = document.getElementById("menu_query_box_img");
					if (display_query_box.style.display == 'block')
						{
							menu_query_box_img.innerHTML = plus_icon;
						}

					var display_checking = document.getElementById("display_checking_div");
					var menu_checking_img = document.getElementById("menu_checking_img");
					if (display_checking.style.display == 'block')
						{
							menu_checking_img.innerHTML = plus_icon;
						}

					var display_server_checking = document.getElementById("display_server_checking_div");
					var menu_server_checking_img = document.getElementById("menu_server_checking_img");
					if (display_server_checking.style.display == 'block')
						{
							menu_server_checking_img.innerHTML = plus_icon;
						}	
						
					var display_query = document.getElementById("display_query_div");
					var menu_query_img = document.getElementById("menu_query_img");
					if (display_query.style.display == 'block')
						{
							menu_query_img.innerHTML = plus_icon;
						}
						
					var display_seque = document.getElementById("display_seque_div");
					var menu_seque_img = document.getElementById("menu_seque_img");
					if (display_seque.style.display == 'block')
						{
							menu_seque_img.innerHTML = plus_icon;
						}

					var display_feature_details = document.getElementById("display_feature_details_div");
					var menu_feature_details_img = document.getElementById("menu_feature_details_img");
					if (display_feature_details.style.display == 'block')
						{
							menu_feature_details_img.innerHTML = plus_icon;
						}

					var display_maniputation_options = document.getElementById("display_maniputation_options_div");
					var menu_maniputation_options_img = document.getElementById("menu_maniputation_options_img");
					if (display_maniputation_options.style.display == 'block')
						{
							menu_maniputation_options_img.innerHTML = plus_icon;
						}	
						
						
					var display_maniputation_options3 = document.getElementById("display_maniputation_options3_div");
					var menu_maniputation_options3_img = document.getElementById("menu_maniputation_options3_img");
					if (display_maniputation_options3.style.display == 'block')
						{
							menu_maniputation_options3_img.innerHTML = plus_icon;
							//menu_maniputation_options2_img.innerHTML = plus_icon_white;
						}	
						
					var display_maniputation_options3_type = document.getElementById("display_maniputation_options3_type_div");
					var menu_maniputation_options3_type_img = document.getElementById("menu_maniputation_options3_type_img");
					if (display_maniputation_options3_type.style.display == 'block')
						{
							menu_maniputation_options3_type_img.innerHTML = plus_icon;
							//menu_maniputation_options2_img.innerHTML = plus_icon_white;
						}	
						
					var display_maniputation_options3_category = document.getElementById("display_maniputation_options3_category_div");
					var menu_maniputation_options3_category_img = document.getElementById("menu_maniputation_options3_category_img");
					if (display_maniputation_options3_category.style.display == 'block')
						{
							menu_maniputation_options3_category_img.innerHTML = plus_icon;
							//menu_maniputation_options2_img.innerHTML = plus_icon_white;
						}	
						
					var display_maniputation_options3_server = document.getElementById("display_maniputation_options3_server_div");
					var menu_maniputation_options3_server_img = document.getElementById("menu_maniputation_options3_server_img");
					if (display_maniputation_options3_server.style.display == 'block')
						{
							menu_maniputation_options3_server_img.innerHTML = plus_icon;
							//menu_maniputation_options2_img.innerHTML = plus_icon_white;
						}	

					var display_graphic = document.getElementById("display_graphic_div");
					var menu_graphic_img = document.getElementById("menu_graphic_img");
					if (display_graphic.style.display == 'block')
						{
							menu_graphic_img.innerHTML = plus_icon;
						}
		
					var display_nonpositional = document.getElementById("display_nonpositional_div");
					var menu_nonpositional_img = document.getElementById("menu_nonpositional_img");
					if (display_nonpositional.style.display == 'block')
						{
							menu_nonpositional_img.innerHTML = plus_icon;
						}
		
					var display_test = document.getElementById("display_test_div");
					var menu_test_img = document.getElementById("menu_test_img");
					if (display_test.style.display == 'block')
						{
							menu_test_img.innerHTML = plus_icon;
						}		
		} // function checkIcons()
		
		
	
//------------------------------------------------------------------------------------------	
// CHECK AND PUT THE RIGHT +/- ICONS IN THE MANIPULATION OPTIONS
//------------------------------------------------------------------------------------------	
	function checkMoColumnIcons()
		{

					var plus_icon = "<img src=\"/7tm/dasty2/client/img/tick01.gif\" border=\"0\" align=\"absbottom\">&#160;";
					var minus_icon = "<img src=\"/7tm/dasty2/client/img/notick01.gif\" border=\"0\" align=\"absbottom\">&#160;";

					
					var mo_img_category_column = document.getElementById("menu_mo_img_category_column");
					if (show_col_category == 1)
						{
							mo_img_category_column.innerHTML = plus_icon;
						}
					else
						{
							mo_img_category_column.innerHTML = minus_icon;
						}
					var mo_img_method_column = document.getElementById("menu_mo_img_method_column");
					if (show_col_method == 1)
						{
							mo_img_method_column.innerHTML = plus_icon;
						}
					else
						{
							mo_img_method_column.innerHTML = minus_icon;
						}
						
					var mo_img_type_column = document.getElementById("menu_mo_img_type_column");
					if (show_col_type == 1)
						{
							mo_img_type_column.innerHTML = plus_icon;
						}
					else
						{
							mo_img_type_column.innerHTML = minus_icon;
						}

					var mo_img_server_column = document.getElementById("menu_mo_img_server_column");
					if (show_col_server == 1)
						{
							mo_img_server_column.innerHTML = plus_icon;
						}
					else
						{
							mo_img_server_column.innerHTML = minus_icon;
						}
					
					var mo_img_id_column = document.getElementById("menu_mo_img_id_column");
					if (show_col_id == 1)
						{
							mo_img_id_column.innerHTML = plus_icon;
						}
					else
						{
							mo_img_id_column.innerHTML = minus_icon;
						}
						
					if (show_popup == 2)
						{
							var menu_mo_img_popups = document.getElementById("menu_mo_img_popups");
							menu_mo_img_popups.innerHTML = plus_icon;
						}	
						
					//if(show_popup == 0)
						//{
							//var mo_img_popup_no = document.getElementById("menu_mo_img_popup_no");	
							//mo_img_popup_no.innerHTML = radio_icon;
						//}
					//else if(show_popup == 1)
						//{
							//var mo_img_popup_mouseover = document.getElementById("menu_mo_img_popup_mouseover");	
							//mo_img_popup_mouseover.innerHTML = radio_icon;
						//}
					//else
						//{
							//var mo_img_popup_mouseclick = document.getElementById("menu_mo_img_popup_mouseclick");
							//mo_img_popup_mouseclick.innerHTML = radio_icon;
						//}
	
		} // function checkIcons()
	

//------------------------------------------------------------------------------------------		  
// FUNCTION TO FIND DOTS
//------------------------------------------------------------------------------------------	
	function isDot(s)
	{
		var dot;
		var i;
		var u = String(s);
		loop:
		for (i = 0; i < u.length; i++)
		{   
			if (u[i] == ".") {
			  dot = "true";
			  break loop;
			} else { 
			  dot = "false";
			}
		}
		if (dot == "false") { return false; } else { return true; }
	}	
	//	
	
//------------------------------------------------------------------------------------------		  
// IS NUMERIC
//------------------------------------------------------------------------------------------		
function isNumeric(x)
	{
		var RegExp = /^(-)?(\d*)(\.?)(\d*)$/; // Note: this WILL allow a number that ends in a decimal: -452.
		// compare the argument to the RegEx
		// the 'match' function returns 0 if the value didn't match
		var result = x.match(RegExp);
		if (result==null) result=false;
		return result;
	} 
	
	
//------------------------------------------------------------------------------------------		  
// Getting window size and scroll bars position
//------------------------------------------------------------------------------------------
// by http://www.softcomplex.com/docs/get_window_size_and_scrollbar_position.html

function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}	

//------------------------------------------------------------------------------------------	
// PRELOAD IMAGES
//------------------------------------------------------------------------------------------	
// http://elouai.com/javascript-preload-images.php
//------------------------------------------------------------------------------------------	

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

//------------------------------------------------------------------------------------------	
// STRUCTURE RELATED FUNCTIONS
//------------------------------------------------------------------------------------------	
// adapted from <a href='http://cargo.bioinfo.cnio.es'>Cargo</a> and JMol by Fernando <a href="mailto:fernando@softlech.com">Fernando@softlech.com</a>	
//------------------------------------------------------------------------------------------	

/**
*  Initialize the Jmol Applet and load (so far hardcoded) a .pdb file 
*/
function iniStructPanel(){
	if (alignments==null)
		{
			//document.getElementById("applet").innerHTML="<b>WARNING:</b><i>Dasty2 could not find PDBs associated to this protein ID</i>";
			document.getElementById("display_protstru_div").innerHTML="<br>&#160;&#160;<span class='title' style='font-style:italic;'>Dasty2 could not find PDBs associated to this protein ID on the 'biojavapdbuniprot' DAS aligment server</span><br>&#160;";
			return;
		}
	else
		{
			document.getElementById("display_protstru_div").innerHTML="<div id='applet3d' style='width:100%; height:100%'></div><table width='100%'><tr><td><div id='Applet_Size'></div></td><td rowspan='3' align='right' valign='top'><div id='dropdown'></div></td></tr><tr><td><div id='StruPane_Title'>Structure [Id here]</div></td></tr><tr><td><div id='structureInfo'><p id='structureInfoP'>Additional info here</p></div></td></tr><tr><td colspan='2'><span style='border-top: 1px dotted #999999; display:block; text-align:right;'><a style='text-decoration:none;color:#999999;' href='javascript:changeStructure();'>view/restore image</a></span></td></tr></table>"
		}
	
	var divDd=document.getElementById("dropdown");
	if (divDd!=null){
		var select=document.createElement("select");
		select.setAttribute("id","PDBlist");
		//select.setAttribute("size","4"); // Rafael
		select.size = 4;
		//select.setAttribute("onchange","changeStructure(this);"); // Rafael
		select.onchange = function() {changeStructure(this);};
		var fileNames= getPDBfileNames();
		for (i=0;i<fileNames.length;i++){
			var idPDB=fileNames[i];
			var punt=idPDB.indexOf(".");
			if (punt!=-1){
				var chain=trim(idPDB.substring(punt+1));
				if (chain=="A"){
					var option2=document.createElement("option");
					option2.innerHTML=idPDB.substring(0,punt+1); 
					select.appendChild(option2);
				}
			} 
			var option=document.createElement("option");
			if (i==0)
				option.setAttribute("selected","true");
				//option.selected = true;			
			option.innerHTML=idPDB; 
			select.appendChild(option);
		}
		divDd.appendChild(select);
		segmentUniprot=null;
		segmentPDB=null;
	
		jmolInitialize("library/jmol");
		//jmolSetDocument(document.getElementById("applet3d").document);
		jmolSetDocument(0);
		jmolSetAppletColor("white");
		//document.getElementById("applet").style.cssText = " z-index:99999;";
		//document.getElementById("applet").innerHTML=jmolApplet("340");
		document.getElementById("applet3d").innerHTML=jmolApplet("100%");
		changeStructure();
	}
}

/**
*  Public function. Called when a new pdb file is selected.
*  
*/
function changePDBFile(){ 
		var script=getJmolLoadScript();  
		if (script!=null){
			jmolScriptWait(script);
			loadedPDBMessage();
		}
}


function changeStructure(){
	loadingPDBMessage();
	var PDBList=document.getElementById("PDBlist");
	//var PDBname=PDBList.value; // Rafael
	var PDBname = PDBList.options[PDBList.selectedIndex].text
	//alert(PDBList.selectedIndex);
  	//alert(PDBList.options[PDBList.selectedIndex].text);
	var punto=PDBname.indexOf(".");
	PDBid="";
	if (punto!=-1){
		PDBid=PDBname.substring(0,punto);
		structureChain=trim(PDBname.substring(punto+1));
		var pathPDB="pdb/"+PDBid+".pdb";
		ajaxCall(proxy_url+"?t=10&s=http://www.rcsb.org/pdb/files&m=pdb&q="+PDBid+".pdb",changePDBFile);

		//Find the block with the PDB block target
		for(i=0;i<alignments.length;i++){
			if(alignments[i].blocks!=null)
			for(j=0;j<alignments[i].blocks.length;j++){
				if (alignments[i].blocks[j].segments[0].objid.indexOf(PDBid)!=-1){
					segmentPDB=alignments[i].blocks[j].segments[0];
					segmentUniprot=alignments[i].blocks[j].segments[1];
					entro=true;
				}
			}
		}
		//If don't found the block choose the first alignment
		if (entro!=true){
			if (alignments.length>0){
				if(alignments[0].blocks!=null){
					segmentPDB=alignments[0].blocks[0].segments[0];
					segmentUniprot=alignments[0].blocks[0].segments[1];
				}
			}
		}


	}  
}
/**
*  Private function to erase the spaces at the end and at the beggining of a String
*/
function trim(cadena){
    var i=0;
	for(i=0; i<cadena.length; )	{
		if(cadena.charAt(i)==" ")
			cadena=cadena.substring(i+1, cadena.length);
		else
			break;
	}
	for(i=cadena.length-1; i>=0; i=cadena.length-1)	{
		if(cadena.charAt(i)==" ")
			cadena=cadena.substring(0,i);
		else
			break;
	}
	return cadena;
}

/**
*  Private function to get the initial jmol script to load a model
*/
function getJmolLoadScript() { 
	if  (PDBid!="") {
		var script ="load "+path_pdb_files+PDBid+".pdb; select all; cartoon on; wireframe off; spacefill off; color chain;";
		return script;
   }
   alert("error in pdb file");
   return null;
}

/**
*  Public function. Call when selecting a range of PDB residues is needed
*  @params: - start: first PDB residue to select, - end: final PDB residue to select
*/
function selectPDBResidues(start, end){
	var divDd=document.getElementById("dropdown");
	if (divDd!=null){
		jmolScriptWait('selectionHalos ON');
		var scr='select '+start+'-'+end;
		if (structureChain!="")
		scr=scr+':'+structureChain;
		jmolScriptWait(scr);
	}
}

/**
*  Public Function. Call when selecting the region of a anotation is needed
* @params: - feature_row:  , - feature_xmlnumber:
*/
function selectAnotationRegion(feature_row, feature_xmlnumber){
    var objectTest = [];
    objectTest = feature_info[feature_xmlnumber];
	var segUniprot=new segment(sequence_info.sequence_id,objectTest[feature_row]["start_data"],objectTest[feature_row]["end_data"]);
	var segPDB=extrapolateSegment(segUniprot);
	if (segPDB!=null)
    	selectPDBResidues(segPDB.start,segPDB.end);
}

/**
*  ON DEVELOPMENT
*  Public Function. Get the value of some sequence position in the structure
*  @params: - sequencePosition: Integer value for a position in the sequence.
*  @return: Integer value for the position in the structure.
*/
function getValueInStructure(sequencePosition){
    //TODO: call the alignment to get the value of some sequence position in the structure
	var PDBList=document.getElementById("PDBlist");
	if (PDBList!=null){
		var PDBname=PDBList.value;
	    var structurePosition=extrapolatePosition(sequencePosition, PDBname);
		return structurePosition;
	}
}

/*
*  ON DEVELOPMENT
*  Public Function. get the number of the limits of a selection in the sequence DIV
*  @params: - sequenceDiv: The DIV element in dasty, where a sequence is showed
*/
function getSequenceRangeSelected(sequenceDiv){
	var tags=sequenceDiv.getElementsByTagName("*");
	var salida='selecciono secuencia';
	for (i=0; i<sequenceDiv.childNodes.length; i++){
		salida=salida+' - '+sequenceDiv.childNodes[i].nodeValue;
	}
    var txt = '';
	if (window.getSelection){
        txt = window.getSelection();
    } else if (document.getSelection) {
        txt = document.getSelection();
    } else if (document.selection) {
        txt = document.selection.createRange().text;
    } else return;	
	alert(salida+' - - - - - - - '+txt);
}

function loadingPDBMessage(){
	var div=document.getElementById("StruPane_Title");
	div.innerHTML="<img src='/7tm/dasty2/client/img/loading.gif' width='20px' /> <i>Loading the PDB file...</i>";
	var div2=document.getElementById("structureInfo");
	div2.innerHTML="";
}
function loadedPDBMessage(){
	var div=document.getElementById("StruPane_Title");
	div.innerHTML="Structure ["+PDBid+"]";
	if ((segmentUniprot!=null) && (segmentPDB!=null)){
		var div2=document.getElementById("structureInfo");
		div2.innerHTML="PDB Region: "+segmentPDB.start+" To:"+segmentPDB.end+"<br/>Uniprot Region: "+segmentUniprot.start+" To:"+segmentUniprot.end;
	}
	var div3=document.getElementById("Applet_Size");
	div3.innerHTML="";
	div3.appendChild(createDivOfSize());
	
}

function createDivOfSize(){
	var div=document.createElement("div");
	var small=document.createElement("input");
	small.setAttribute("type","button");
	small.setAttribute("value","Small");
	small.setAttribute("onclick","changeAppletSize(330,330)");
	
	div.appendChild(small);
	var medium=document.createElement("input");
	medium.setAttribute("type","button");
	medium.setAttribute("value","Medium");
	medium.setAttribute("onclick","changeAppletSize(600,600)");
	div.appendChild(medium);
	var large=document.createElement("input");
	large.setAttribute("type","button");
	large.setAttribute("value","Large");
	large.setAttribute("onclick","changeAppletSize(800,800)");
	div.appendChild(large);
	return div;
}

function changeAppletSize(width, height){
	var applet=document.getElementById("jmolApplet0");
	applet.setAttribute("width",width);
	applet.setAttribute("height",height);
	var div=document.getElementById("display_protstru_div");
	//div.setAttribute("width",width+100);
	var div_width = width+20;
	var div_height = height+120;
	//div.style.cssText = "width:" + div_width + "px; height:" + div_height + "px;";
	div.style.cssText = "width:" + div_width + "px;";
}
function printArray(array){
		var texto="L="+array.length+" >";
		var k=0;
		for(k=0;k<array.length;k++){
			texto += "-"+array[k]+"-";
		}
		printOnTest(texto+" <");
}


function printTest()
	{
		printOnTest(PDBid);
	}
//------------------------------------------------------------------------------
//START_DASTY. REQUIRED! <body onload="start_dasty(1);">
//------------------------------------------------------------------------------
//
// start_dasty(0)
//
// Makes Dasty2 independent from the URL. You need to tell dasty2 what default
// configuration values you want to use. Use set_query to define them ...
// set_query('P05067', 'BioSapiens', 3, 'index.html'). Recommended option if you
// embed dasty2 in your own web site.
//------------------------------------------------------------------------------
//
// start_dasty(1)
//
// Dasty2 check first the attributes from the URL. Recomended!
//------------------------------------------------------------------------------
//
// start_dasty(2)
//
// Use it for redirections
//------------------------------------------------------------------------------

function start_dasty(url_control)
	{
		dasty_url_control = url_control;
		query_id_null = 0; // "0" means that query ID is not null
		if(url_control == 0)
			{
				start_globals();
			}
		else if(url_control == 1)
			{
				start_url();
			}
		else
			{
				//createDastyURLNewID('');
				DastyRedirector();
			}
	}


// Use this function in body load when start_dasty(0) and when the serach module is hidden or off.
// onLoad="set_query('P05067', 'BioSapiens', 3), start_dasty(0);"
function set_query(q_id, q_label, q_timeout, q_template)
	{
		query_id = "";
		filterLabel = "";
		timeout = 3;
		dasty_mainpage_name = "";

		default_query_parameters();
		
		if( q_id == null || q_id == "") { query_id = default_query_id; } else { query_id = q_id; };
		if( q_label == null || q_label == "") { filterLabel = default_filterLabel; } else { filterLabel = q_label; };
		if( q_id == null || q_id == "") { timeout = default_timeout; } else { timeout = q_timeout; };
		if( q_template == null || q_template == "") { dasty_mainpage_name = default_dasty_mainpage_name; } else { filterLabel = template; };
		
	}


function start_url()
	{	
		query_id = "";
		filterLabel = "";
		timeout = 3;	
		
		dasty_mainpage_name = findDastyHtmlPageName('page_name') + "." + findDastyHtmlPageName('ext_name');
		configuration();
		//dasty_mainpage_name = findDastyHtmlPageName('page_name') + "." + findDastyHtmlPageName('ext_name');
		default_query_parameters();
		
		setDastyURLParam();
		
		//if(dasty_mainpage_name.indexOf("interactorview") != -1)
			//{
				//populate_interactorview();
			//}

		
		// Query parameter keys : by Antony
		// var QueryParamKeys = {
			//id:             "q",
			//registryServer: "registry",
			//registryLabel:  "label",
			//logLevel:       "l",
			//timeout:        "t"
		//};

	}
	  
function start_globals()
	{	
	MM_preloadImages("/site_media/js/dasty2/client/img/blast_icon.gif", "/site_media/js/dasty2/client/css/window/mac_os_x/B.png", "/site_media/js/dasty2/client/css/window/mac_os_x/B_Main.png", "/site_media/js/dasty2/client/css/window/mac_os_x/BL.png", "/site_media/js/dasty2/client/css/window/mac_os_x/BL_Main.png", "/site_media/js/dasty2/client/css/window/mac_os_x/BR.png", "/site_media/js/dasty2/client/css/window/mac_os_x/BR_Main.png", "/site_media/js/dasty2/client/css/window/mac_os_x/close.gif", "/site_media/js/dasty2/client/css/window/mac_os_x/L.png", "/site_media/js/dasty2/client/css/window/mac_os_x/L_Main.png", "/site_media/js/dasty2/client/css/window/mac_os_x/maximize.gif", "/site_media/js/dasty2/client/css/window/mac_os_x/minimize.gif", "/site_media/js/dasty2/client/css/window/mac_os_x/R.png", "/site_media/js/dasty2/client/css/window/mac_os_x/R_Main.png", "/site_media/js/dasty2/client/css/window/mac_os_x/T.png", "/site_media/js/dasty2/client/css/window/mac_os_x/T_Main.png", "/site_media/js/dasty2/client/css/window/mac_os_x/TL.png", "/site_media/js/dasty2/client/css/window/mac_os_x/TL_Main.png", "/site_media/js/dasty2/client/css/window/mac_os_x/TR.png", "/site_media/js/dasty2/client/css/window/mac_os_x/TR_Main.png");
	
	ontologyPrefix = ["GO:", "BS:", "ECO:", "MOD:", "SO:"];
	
	browser_name = navigator.appName;
	browser_version = navigator.appVersion;
	
	// feature_url roperties: id, url, state, XML_num, general_order
	// [].state => / 1 => have features / 2 => do not have features / 3 => Warning /
	
	dasty_mainpage_name = findDastyHtmlPageName('page_name') + "." + findDastyHtmlPageName('ext_name');
	configuration();
	//dasty_mainpage_name = findDastyHtmlPageName('page_name') + "." + findDastyHtmlPageName('ext_name');
	default_query_parameters();
	
	if (typeof query_id == "undefined") { query_id = default_query_id; };
	if (typeof filterLabel == "undefined") { filterLabel = default_filterLabel; };
	if (typeof timeout == "undefined") { timeout = default_timeout; };
	
	checkSectionIcons();
	checkMoColumnIcons();
	
/*	
// Set up a windows observer, check ou debug window to get messages
	var myObserver = {
		onClose: function(eventName, pdbWin) {
			debug(eventName + " on " + pdbWin.getId())
			if(pdbWin.getId() == "pdbWin")
				{
					printOnTest("ok");
					changeStructure();
				}
		}
	}
	Windows.addObserver(myObserver);
*/


//------------------------------------------------------------------------------------------	
//  NECESSARY GLOBAL VARIABLES USED BY DASTY2
//------------------------------------------------------------------------------------------	
	
	dasty2 = new Object;
	
    http_request = false;
	// CREATED_IN: ajax.js 				// USED_IN: parse_sequence.js, parse_sequece.js, parse_serverlist.js, parse_stylesheet.js, request_xml.js
	feature_http_request = [];
	// CREATED_IN: request_xml.js		// USED_IN: parse_feature.js
	
	feature_info = [];
	// CREATED_IN: parse_feature.js		// USED_IN: create_graphic.js, create_feature_details.js
	
	annotation_version = [];
	
	stylesheet_properties_info = [];
	// CREATED_IN: parse_stylesheet.js 	// USED_IN: create_graphics.js

	//type_counter = [];
	// CREATED_IN: parse_feature.js 	// USED_IN: create_graphic.js
	
	//category_counter = [];
	// CREATED_IN: parse_features.js 	// USED_IN: No yet!!!
	
	new_feature_list_info = [];
	new_feature_list_info2 = [];
	// CREATED_IN: reorganize_types.js		// USED_IN: create_graphic.js 

	sequence = '';
	// CREATED_IN: parse_sequence.js	// USED_IN: functions.js => highlightSequence()
	
	//sequence_info = [];
	sequence_info = new Object();
	
	selStart = 1; // stores selection starting position
	useHighlight = true;  // if true, sequence will be transformed to support highlight technique
	// CREATED_IN: parse_sequence.js	// USED_IN:
	
	//das_server = '';
	// CREATED_IN: request_features.js 	// USED_IN: parse_feature.js
	
	//featureXML_num = -1;
	
	// CREATED_IN: request_features.js	// USED_IN: request_xmls.js, parse_feature.js
	
	bg_color = 1;
	// CREATED_IN: global.js			// USED_IN: create_graphic.js

	one_feature_list = [];
	
	expanded_feature_list = [];
	
	sortOrderType = 0;
	sortOrderMethod = 0;
	sortOrderCategory = 0;
	sortOrderServer = 0;
	sortOrderVersion = 0;
	
	zoom_start = 0;
	zoom_end = 0;
	
	
	show_graphic_tittle_temp = 1; // boolean 0/1. 0=no / 1=yes
	show_scale_bar_temp = 1;  // boolean 0/1. 0=no / 1=yes
	show_slide_bar_temp = 1;
	
	features_row_number = 0;
	
	width_div_graphic_correction = 0;
	
	bar_aa_distance_list = [];
	
	bar_px_distance_list = [];
	
	isExpanded = 0; // boolean 0/1. 0=no / 1=yes
	

	
	
	//display = "free";
	//standby = [];
	count_displayed_groups = 0;
	
	elements_http_request = [];
	
	//das_registry_label = [];
	
	progress_bar_width = getPxWidthFromStyle("progress_bar_empty");
	
	servers_count = 0;
	
	server_checking = "";
	
	warning_count = 0;
	no_feature_results_count = 0;
	feature_results_count = 0;
	
	results_XML_order = [];
	
	popup_num = 0;
	
	
	
	dasty2.loadedDasSources = [];
	dasty2.excludedDasSources = [];
	dasty2.loadedDasSources_temp = [];
	
	dasty2.firstRequestNumber = 0;
	dasty2.validFirstSources = [];
	
	dasty2.typesLoaded = []; // It seems it is not beeing used. Try "dasty2.typesLoaded2".
	dasty2.categoriesLoaded = [];
	dasty2.IdlinesPerType = [];
	dasty2.IdlinesPerCategory =[];
	dasty2.IdlinesPerServer = [];
	dasty2.temporalTree =[];
	dasty2.temporalArray =[];
	
	dasty2.line_id_name2 = new Array(); // Hash
	dasty2.line_id_name2_length = 0;
	
	dasty2.countVisibleLines = 0;
	
	dasty2.firstTimeSortByType = true;
	


	dasty2.typesLoaded2 = [];
	dasty2.countIdType = [];

	dasty2.countNPF = 0;
	
	dasty2.decor_tr_npf = 0;
	
	
	//PDB CHAIN
	structureChain="";
	segmentUniprot=null;
	segmentPDB=null;
	


//------------------------------------------------------------------------------------------	
// START APPLICATION
//------------------------------------------------------------------------------------------
		//alert(filterLabel);
		//alert(query_id);
		//alert(timeout);
	
	document.getElementById("system_information").innerHTML = "... please be patient, Dasty2 is loading data from the DAS servers";
	document.getElementById("progress_bar_1").innerHTML = "";
 	document.getElementById("progress_bar_2").style.width = 0;
	document.getElementById('feature_id_box').value = query_id;
	document.getElementById("graphic_width_px").value = graphic_width;
	filterLabel = filterLabel.replace(/%20/g, " ")
	ajax();
	
	
  } // function start_globals()
//------------------------------------------------------------------------------------------	
// GROUPING
//------------------------------------------------------------------------------------------			
	function grouping(featureXML_num, type_counter,  segment_start, segment_stop)
	  { 
	  	new_feature_list_info2[featureXML_num] = [];
	  	for(var a = 0; a < type_counter.length; a++)
	  		{
				lookforSameIdType(featureXML_num, type_counter[a][1]);
			}
		createGraphic2(featureXML_num, "display_graphic", segment_start, segment_stop, "grouping");
		
		//alert(new_feature_list_info2[featureXML_num].length);
		
		//for(var lu = 0; lu < new_feature_list_info2[featureXML_num].length; lu++)
		//	{
		//		var new_feature_list = new_feature_list_info2[featureXML_num];
		//		var opa = document.getElementById("display_test");
		//		var content_opa = opa.innerHTML;
		//		opa.innerHTML = (content_opa + " <br>------------<br>new_feature_list[" + lu + "][features]: " + new_feature_list[lu]["features"] + "::::: new_feature_list[" + lu + "][feature_group]: " + new_feature_list[lu]["feature_group"] + "::::: new_feature_list[" + lu + "][type]: " + new_feature_list[lu]["type"] + new_feature_list[lu]["category"] + new_feature_list[lu]["server"]);
		//	}
	  }//------------------------------------------------------------------------------------------	  
// Create arrays "fids" and "same_fids" to be able to group features in the graphic.
//------------------------------------------------------------------------------------------	
function lookforSameIdType(featureXML_num, type_counter)
 {	
	//----------------------------------------------------------------------------------
	// Look for features of the same feature ID and put this info in fids
	// fids = [feature_id, [ids]]
	//----------------------------------------------------------------------------------
	var same_fids = []; // rows in fids with more than one feature id.
	var fids = []; // feature ids
	var feature_row_num = 0;
	var add_fids = 0;
	var add_same_fids = 0;
	var tcounter = type_counter; // example: type_counter[0][1]; number of features rows for one type
	var finfo = feature_info[featureXML_num];
	
	//alert(finfo[0]["feature_id"]);
	
	for(var i = 0; i < tcounter.length; i++)
	{
	  feature_row_num = tcounter[i];
	  fids_length = fids.length;
	  if (fids_length == 0)
	   {
		  fids[fids_length] = [];
		  fids[fids_length][0] = finfo[feature_row_num]["feature_id"];
		  fids[fids_length][1] = [];
		  fids[fids_length][1].push(feature_row_num);
	   }
	  else
	   {
		  add_fids = 0;
		  for(var m = 0; m < fids_length; m++)
		     {
				   if(fids[m][0] == finfo[feature_row_num]["feature_id"])
					  {
						fids[m][1].push(feature_row_num);
						add_fids = 1;
						//----------------------------------------------------------------------------------
						// Get same_fids
						// same_fids = [fids rows where there is more than one feature ID]
						//----------------------------------------------------------------------------------
						same_fids_length = same_fids.length;
						if (same_fids_length == 0)
						   {
								 same_fids[same_fids_length] = m;
						   }
						 else
						   { 
								 add_same_fids = 0;
								 for(var e = 0; e < same_fids_length; e++)
								   {
									 if(same_fids[e] == m) {add_same_fids = 1;}
								   }
								 if(add_same_fids == 0) {same_fids[same_fids_length] = m;}
						   }
						 //----------------------------------------------------------------------------------	
					  }
			 }
		  if(dasty2_grouping == false) // RC. 03.05.08
		  	{
		  		same_fids = [];
		  		add_fids = 0;
			}
		  if(add_fids == 0)
		     {
			   fids[fids_length] = [];
			   fids[fids_length][0] = finfo[feature_row_num]["feature_id"];
			   fids[fids_length][1] = [];
			   fids[fids_length][1].push(feature_row_num);
			 }
	     }				   
	 }
	 //reorganizeIdTypes(finfo, fids, same_fids); 
	 organizeIdTypes(featureXML_num, fids, same_fids); 
	 
						   //for(var lu = 0; lu < fids.length; lu++)
						   //{
						   //var opa = document.getElementById("display_test");
						   //var content_opa = opa.innerHTML;
						   //opa.innerHTML = (content_opa + " <br>------------<br>fids[" + lu +"][0]:" + fids[lu][0] + " fids[" + lu +"][0]:" + fids[lu][1]);
						   //}
						   
						   //for(var lu = 0; lu < same_fids.length; lu++)
						   //{
						   //var opa = document.getElementById("display_test");
						   //var content_opa = opa.innerHTML;
						   //opa.innerHTML = (content_opa + " <br>------------<br>same_fids[" + lu + "]:" + same_fids[lu]);
						   //}	

 }	  // JavaScript Document

//------------------------------------------------------------------------------------------	
// REQUEST INFORMATION FROM DIFFERENT XML SPECIFIYING A LOCAL URL.
//------------------------------------------------------------------------------------------		
			
	  function newid(id, label)
		{
			//var labelName = "";
			//if(label == null || label == ""){labelName = default_filterLabel} else {labelName = label};
			
			//var opa = document.getElementById("display_test");
			//var content_opa = opa.innerHTML;
			//opa.innerHTML = (content_opa + " <br>------------<br>info: " + document.getElementById(label) );
			
			var new_feature_id = document.getElementById(id).value;
			
			if(document.getElementById(label) == null)
				{
					filterLabel = default_filterLabel;
				}
			else
				{
					filterLabel = document.getElementById(label).value;
				}
			

			//var new_feature_label = document.getElementById(label).value;
			
			//var display_query = document.getElementById("display_query");
			//display_query.innerHTML = "";
			//var display_seque = document.getElementById("display_seque");
			//display_seque.innerHTML = "";
			//var display_server_checking = document.getElementById("display_server_checking");
			//display_server_checking.innerHTML = "";
			//var display_feature_details = document.getElementById("display_feature_details");
			//display_feature_details.innerHTML = "";
			//var display_graphic = document.getElementById("display_graphic");
			//display_graphic.innerHTML = "";
			//var display_nonpositional = document.getElementById("display_nonpositional");
			//display_nonpositional.innerHTML = "";
			
			//var display_test = document.getElementById("display_test");
			//display_test.innerHTML = "";
			
			query_id = new_feature_id;
			//filterLabel = new_feature_label;
			
			if (dasty_url_control == 0)
				{
					var display_query = document.getElementById("display_query");
					display_query.innerHTML = "";
					var display_seque = document.getElementById("display_seque");
					display_seque.innerHTML = "";
					var display_server_checking = document.getElementById("display_server_checking");
					display_server_checking.innerHTML = "";
					var display_feature_details = document.getElementById("display_feature_details");
					display_feature_details.innerHTML = "";
					
					var display_ontology_types = document.getElementById("display_maniputation_options3_type_div");
					display_graphic.innerHTML = "";
					var display_ontology_types = document.getElementById("display_maniputation_options3_category_div");
					display_graphic.innerHTML = "";
					
					
					var display_graphic = document.getElementById("display_graphic");
					display_graphic.innerHTML = "";
					var display_nonpositional = document.getElementById("display_nonpositional");
					display_nonpositional.innerHTML = "";
					
					var display_test = document.getElementById("display_test");
					display_test.innerHTML = "";
					
					start_globals();
				}
			else
				{
					document.location.href = createDastyURL();
				}
		}
				
////------------------------------------------------------------------------------------------	
// reorganize features ID in Types
//------------------------------------------------------------------------------------------
 function organizeIdTypes(featureXML_num, fids, same_fids)
 {
 	//------------------------------------------------------------------------------------------	
	// put the features with the same ID in the same line
	//------------------------------------------------------------------------------------------
	 //alert("fids[0][1]:" + fids[0][1]);
	 //alert("same_fids:" + same_fids);
	 //alert("array:" + array[1]["feature_id"]);
	 var do_push = 0;
	 var non_same_fids = [];
	 var new_feature_list = [];
	 var line = [];
	 var line_length = 0;
	 var eline_length = 0;
	 var start_end = [];
	 var con_eline01 = 0;
	 var con_eline02 = 0;
	 var con_eline = 0;
	 var feature_included = 0;
	 var con_line = 0;
	 var array_row_num = 0;
	 var nfl_length =0;
	 var last_c = 0;
	 var line_id_name = [];
	 var line_name = "";
	 var lineIdValue = 1;
	 
	 var finfo = feature_info[featureXML_num];
	 
	 
	 // new_feature_list_info = [];
	 //new_feature_list_info2 = [];
	 
	 
	 
	//------------------------------------------------------------------------------------------	
	// create an array with the features with the same id (same feature group id)
	//------------------------------------------------------------------------------------------
	 
	 for(var i = 0; i < same_fids.length; i++)
	   {
	    new_feature_list[i] = [];
		new_feature_list[i]["line"] = i;
		new_feature_list[i]["features"] = [];		// FEATURES: Contains references to the features for the array "feature_info"
		new_feature_list[i]["feature_group"] = 1;	// FEATURE GROUP: boolean "1/0". "1" means feature with the same ID o group
		new_feature_list[i]["type"] = finfo[fids[same_fids[i]][1][0]]["type_id"];		// TYPE
		new_feature_list[i]["type_data"] = finfo[fids[same_fids[i]][1][0]]["type_data"];		// TYPE
		new_feature_list[i]["category"] = finfo[fids[same_fids[i]][1][0]]["type_category"];	// CATEGORY
		new_feature_list[i]["method"] = finfo[fids[same_fids[i]][1][0]]["method_data"];	// METHOD
		//new_feature_list[i]["feature_id"] = finfo[fids[same_fids[i]][1][0]]["feature_id"];	// ID		
		new_feature_list[i]["feature_label"] = finfo[fids[same_fids[i]][1][0]]["feature_label"];	// ID
		new_feature_list[i]["server"] = finfo[fids[same_fids[i]][1][0]]["annotation_server"];	// SERVER
		new_feature_list[i]["registry_uri"] = finfo[fids[same_fids[i]][1][0]]["annotation_server_uri"];	// SERVER ID (REGISTRY URI)
		new_feature_list[i]["version"] = annotation_version[finfo[fids[same_fids[i]][1][0]]["xmlnumber"]];	// ANNOTATION VERSION boolean "1/0". "1" means the feature file has the same version than the sequence file.
		
		for(var a = 0; a < fids[same_fids[i]][1].length; a++)
		   {
		      new_feature_list[i]["features"].push(fids[same_fids[i]][1][a]); 
		   }
		line_name = "gr_item" + featureXML_num + "_" + new_feature_list[i]["type"] + "_" + new_feature_list[i]["line"];  
		line_id_name.push(line_name);
		
		
		for(var n = 0; n < excluded_das_sources.length; n++)
			{
				if(excluded_das_sources[n].toLowerCase() == new_feature_list[0]["server"].toLowerCase())
					{
						lineIdValue = 0;
					}
			}
		dasty2.line_id_name2[line_name] = lineIdValue;
		dasty2.line_id_name2_length++;
		
	   }
	   
	   if(same_fids.length > 0)
	   		{
				dasty2.IdlinesPerType.push([new_feature_list[0]["type"], line_id_name, line_id_name.length]);
				dasty2.IdlinesPerCategory.push([new_feature_list[0]["category"], line_id_name, line_id_name.length]);
				dasty2.IdlinesPerServer.push([new_feature_list[0]["server"], line_id_name, line_id_name.length]);
			}		
	   
	   line_id_name = [];
	   //add_new_type = 0;
	 
	//------------------------------------------------------------------------------------------	
	// create an array with the feature id that are not reapeted => non_same_fids
	//------------------------------------------------------------------------------------------
	 for(var i = 0; i < fids.length; i++)
	   {
	     do_push = 0;
	     for(var a = 0; a < same_fids.length; a++)
		    {
		        if(i == same_fids[a]) { do_push = 1; }
		    }
		 if(do_push == 0)
		    {
		        non_same_fids.push(i);
		    }
	    }
			
	//------------------------------------------------------------------------------------------	
	// look for the rest of features IDs, check their ends and starts and try to overlap in the same line if possible
	//------------------------------------------------------------------------------------------
	 for(var i = 0; i < non_same_fids.length; i++)
	   {
	    array_row_num = fids[non_same_fids[i]][1][0];

         if (i == 0)
		   { 
		     line[i] = [];
			 line[i].push(array_row_num);
			 start_end[i] = [];
			 start_end[i][0] = []; // START DATA
			 start_end[i][0].push(finfo[array_row_num]["start_data"]);
			 start_end[i][1] = []; // END DATA
			 start_end[i][1].push(finfo[array_row_num]["end_data"]);
		   }
		  else // (i == 0)
		   {
		     con_line = 0;
		     line_length = line.length;
			 line_loop: 
		     for(var a = 0; a < line_length; a++)
			    {
				   con_eline = 0;
				   con_eline01 = 0;
				   con_eline02 = 0;
				   eline_length = line[a].length;
				   for(var b = 0; b < eline_length; b++)
				      {
					  	 start01 = finfo[array_row_num]["start_data"];
						 start02 = start_end[a][0][b];
						 end01 = finfo[array_row_num]["end_data"];
						 end02 = start_end[a][1][b];
						 
						 con_eline01 = end02 - start01;
						 con_eline02 = end01 - start02;
						 
						 if(con_eline01 < 0) { con_eline++ }
						 if(con_eline02 < 0) { con_eline++ } 
					  }
				   if(con_eline == eline_length)
				      { // include in the line
						 line[a].push(array_row_num);
						 start_end[a][0].push(finfo[array_row_num]["start_data"]);
						 start_end[a][1].push(finfo[array_row_num]["end_data"]);
						 break line_loop;
					  }
				   else
				      { // not include in the line
					  	 con_line++;
					  }
				  } // for(var a = 0; a < line_length; a++)
			      if(con_line == line_length)
					   { // include new line
							 line[line_length] = [];
							 line[line_length].push(array_row_num);
							 start_end[line_length] = [];
							 start_end[line_length][0] = []; // START DATA
							 start_end[line_length][0].push(finfo[array_row_num]["start_data"]);
							 start_end[line_length][1] = []; // END DATA
							 start_end[line_length][1].push(finfo[array_row_num]["end_data"]);
					   }
		     } // if (i == 0)
   	   } // for(var i = 0; i < non_same_fids.length; i++)

	//------------------------------------------------------------------------------------------	
	// concatenate "new_feature_list" with "line"
	//------------------------------------------------------------------------------------------

	nfl_length = new_feature_list.length;
	for(var i = 0; i < line.length; i++)
	   {
	    new_feature_list[i+nfl_length] = [];
		new_feature_list[i+nfl_length]["line"] = i+nfl_length;
		new_feature_list[i+nfl_length]["features"] = [];	// Contains references to the features for the array "feature_info"
		new_feature_list[i+nfl_length]["feature_group"] = 0;		// boolean. 1 mean feature with the same ID o group
		new_feature_list[i+nfl_length]["type"] = finfo[fids[non_same_fids[i]][1][0]]["type_id"];		// TYPE ID
		new_feature_list[i+nfl_length]["type_data"] = finfo[fids[non_same_fids[i]][1][0]]["type_data"];		// TYPE DATA
		new_feature_list[i+nfl_length]["method"] = finfo[fids[non_same_fids[i]][1][0]]["method_data"];	// CATEGORY 
		new_feature_list[i+nfl_length]["category"] = finfo[fids[non_same_fids[i]][1][0]]["type_category"];	// CATEGORY 
		//new_feature_list[i+nfl_length]["feature_id"] = finfo[fids[non_same_fids[i]][1][0]]["feature_id"];	// ID
		new_feature_list[i+nfl_length]["feature_label"] = finfo[fids[non_same_fids[i]][1][0]]["feature_label"];	// ID		
		new_feature_list[i+nfl_length]["server"] = finfo[fids[non_same_fids[i]][1][0]]["annotation_server"];	// SERVER
		new_feature_list[i+nfl_length]["registry_uri"] = finfo[fids[non_same_fids[i]][1][0]]["annotation_server_uri"];	// SERVER ID (REGISTRY URI)
		new_feature_list[i+nfl_length]["version"] = annotation_version[finfo[fids[non_same_fids[i]][1][0]]["xmlnumber"]];	// ANNOTATION VERSION
		
		for(var a = 0; a < line[i].length; a++)
		   {
		      new_feature_list[i+nfl_length]["features"].push(line[i][a]); 
		   }
		   
		line_name = "gr_item" + featureXML_num + "_" + new_feature_list[i+nfl_length]["type"] + "_" + new_feature_list[i+nfl_length]["line"];
		line_id_name.push(line_name);
		
		for(var n = 0; n < excluded_das_sources.length; n++)
			{
				if(excluded_das_sources[n].toLowerCase() == new_feature_list[nfl_length]["server"].toLowerCase())
					{
						lineIdValue = 0;
					}
			}
		dasty2.line_id_name2[line_name] = lineIdValue;
		dasty2.line_id_name2_length++;
		
	   }

	   if(line_id_name.length > 0)
	   		{
				dasty2.IdlinesPerType.push([new_feature_list[nfl_length]["type"], line_id_name, line_id_name.length]);
				dasty2.IdlinesPerCategory.push([new_feature_list[nfl_length]["category"], line_id_name, line_id_name.length]);
				dasty2.IdlinesPerServer.push([new_feature_list[nfl_length]["server"], line_id_name, line_id_name.length]);
			}
	

	for(var b = 0; b < new_feature_list.length; b++)
	   {
		 new_feature_list_info2[featureXML_num].push(new_feature_list[b]);
	   }
	
	//create_graphic2("display_graphic", segment_start, segment_stop);
				
 } // function reorganizeIdTypes(array) // Fernando's code to get started with pasing alignments
var testing = false,  		  // used for testing
	alignments = new Array(), // array of parsed alignments
	nalignments = 0;		  // number of alignments	

/**
* called with url of alignment file to load and parse
*/
function parseAlignment(url){
	loadAlignment(url);
}

// <------------- definition of an alignment -------------->

/**
*  defines an alignObject contained withing an alignment
*  @params: accessionid,type,dbsource: attributes of the alignmentObject
*           header,title,description: this three are properties of alignObjectDetail for a PDB
*/
function alignObject(accessionid,type,dbsource,header,title,description){
	this.accessionid = accessionid;
	this.type = type;
	this.dbsource = dbsource;
	this.header = header;
	this.title =title;
	this.description = description;
}

/**
*  defines a segment contained withing an alignment block
*  @params: objid: intObjectId, start: start attribute, end: end attribute
*/
function segment(objid,start,end){
	this.objid = objid;
	this.start = start;
	this.end = end;
}
/**
*  Compare 2 segments and return a boolean
*/
segment.prototype.equals=function(segm){
	if ((this.objid==segm.objid)&&(this.start==segm.start)&&(this.end==segm.end)){
		return true;
	}
	return false;
}

/**
*  defines a block contained withing an alignment
*  @params: order: blockOrder attribute, segments: segments found in block
*/
function block(order,segments){
	this.order = order;
	this.segments = segments;
}

/**
*  defines an alignment
*  @params: atype: alignType attribute, blocks: blocks found in the alignment
*/
function alignment(atype,alignObjects,blocks){
	this.atype = atype;
	this.alignObjects = alignObjects;
	this.blocks = blocks;
	
}

// <------------ Loading and Parsing --------------->

/**
* parse the xml alignment file received in doc
*/
function doParseAligment(doc){ 
	var alignElms = doc.documentElement.getElementsByTagName("alignment");
	if (alignElms.length==0){
		alignments=null;
	}
	if(testing){
		document.getElementById("nalgn").innerHTML = alignElms.length;
	}
	adata = document.getElementById("algdata");
	var s = "";
	for(var i=0;i<alignElms.length;i++){
		algn = alignElms.item(i);
		atype = algn.attributes.getNamedItem("alignType").value;
		blocks = new Array();nblocks = 0;
		alignObjs = new Array();nalobjs = 0;
		for(var j=0;j<algn.childNodes.length;j++){
			//if(algn.childNodes[j].nodeType == document.ELEMENT_NODE){ // Rafael
				if(algn.childNodes[j].nodeName == "block"){
					blocks[nblocks++] = parseBlock(algn.childNodes[j]);
				}else
				if(algn.childNodes[j].nodeName == "alignObject"){
					alignObjs[nalobjs++] = parseAlignObject(algn.childNodes[j]);
				}
			//}
		}
		alignments[nalignments++] = new alignment(atype,alignObjs,blocks);
		alg = new alignment(atype,blocks);
	}
	if(testing){
		var segUniprot=new segment('P00974',40,93);
		var segPDB=segmentUniprot2segmentPDB(segUniprot);
		var extra='';
		if (segPDB!=null){
			extra='<br/><br/><br/><b>ID:</b> '+segPDB.objid+'<br/><b>Start:</b> '+segPDB.start+'<br/><b>End:</b> '+segPDB.end;
		}
		adata.innerHTML = listAlignments()+extra;
	}
}

/**
* parse an xml alignObject
*/
function parseAlignObject(obj){
	accessionid = obj.attributes.getNamedItem("dbAccessionId").value;
	type = obj.attributes.getNamedItem("type").value;
	dbsrc = obj.attributes.getNamedItem("dbSource").value;
	adetails = new Array();ndets = 0;header="";title="";descr="";
	for(var k=0;k<obj.childNodes.length;k++){
		if(obj.childNodes[k].nodeName == "alignObjectDetail"){
			detail = obj.childNodes[k];
			if(detail.attributes.length>0)
			{
				property = detail.attributes.getNamedItem("property").value; // printOnTest("type:"+type+" ,prop:"+property);
				switch(property){
					case "header":
						header = getNodeData(detail);
					break;
					case "title":
						title = getNodeData(detail);
					break;
					case "molecule description":
						descr = getNodeData(detail);
					break;
				}
			}
		}
	}
	return new alignObject(accessionid,type,dbsrc,header,title,descr);
}

/**
* return content if text node, empty string otherwise
*/
function getNodeData(node){
	if(!node.hasChildNodes)
		return "";
	for(var j=0;j<node.childNodes.length;j++){
		//if(node.childNodes[j].nodeType == document.TEXT_NODE){ // Rafael
			return "value:"+node.childNodes[j].data;	
		//}
	}
	return "";
}

/**
* parse an xml alignment block
*/
function parseBlock(blk){
	blockOrder = blk.attributes.getNamedItem("blockOrder").value;
	segments = new Array();nsegms = 0;
	for(var k=0;k<blk.childNodes.length;k++){
		if(blk.childNodes[k].nodeName == "segment"){
			segm = blk.childNodes[k];
			if(segm.attributes.length>0)
			{
				intObjectId = segm.attributes.getNamedItem("intObjectId").value;
				start = segm.attributes.getNamedItem("start").value;
				end = segm.attributes.getNamedItem("end").value;
				segments[nsegms++] = new segment(intObjectId,start,end);
			}
		}
	}
	return new block(blockOrder,segments);
}

function listAlignments(){
	s = "";
	for(i=0;i<alignments.length;i++){
		s+= (i+1)+".<b>AlignmentType:</b> "+alignments[i].atype+"<br>";
		if(alignments[i].blocks!=null)
		for(j=0;j<alignments[i].blocks.length;j++){
			s+="...Found block with order="+alignments[i].blocks[j].order+"<br>";
			for(k=0;k<alignments[i].blocks[j].segments.length;k++){
				s+=".....Block contains segment objectid="+alignments[i].blocks[j].segments[k].objid+" start="+alignments[i].blocks[j].segments[k].start+" end="+alignments[i].blocks[j].segments[k].end+"<br>"; 
			}
		}
		
		if(alignments[i].alignObjects!=null)
		for(j=0;j<alignments[i].alignObjects.length;j++){
			s+="...Found alignObject with accessionid="+alignments[i].alignObjects[j].accessionid+"<br>";
			s+="......type: "+alignments[i].alignObjects[j].type+"<br>";
			s+="......dbsource: "+alignments[i].alignObjects[j].dbsource+"<br>";
			s+="......header: "+alignments[i].alignObjects[j].header+"<br>";
			s+="......title: "+alignments[i].alignObjects[j].title+"<br>";
			s+="......description: "+alignments[i].alignObjects[j].description+"<br>";
		}
	}
	return s;
}

/**
*	Assume that a block has the segment[0] as the PDB segment and the segment[1] as the Uniprot segment
*   then go through the alignments to get the PDB segment which is with the Uniprot segment.
*   Return null if it doesn't have a match.
*/
function segmentUniprot2segmentPDB(segmentUniprot){
	for(i=0;i<alignments.length;i++){
		if(alignments[i].blocks!=null)
		for(j=0;j<alignments[i].blocks.length;j++){
			if (alignments[i].blocks[j].segments[1].equals(segmentUniprot)){
				return alignments[i].blocks[j].segments[0];
			}
		}
	}
	return null;
}

function extrapolatePosition(position,pdb){
	var term=0;
	var top=0
	var bottom=0
	var entro=false;
	//Find the block with the PDB block target
	for(i=0;i<alignments.length;i++){
		if(alignments[i].blocks!=null)
		for(j=0;j<alignments[i].blocks.length;j++){
			if (alignments[i].blocks[j].segments[0].objid==pdb){
				term= alignments[i].blocks[j].segments[1].start - alignments[i].blocks[j].segments[0].start;
				top=alignments[i].blocks[j].segments[0].end;
				bottom=alignments[i].blocks[j].segments[0].start;
				entro=true;
			}
		}
	}
	//If don't found the block choose the first alignment
	if (entro!=true){
		if (alignments.length>0){
			if(alignments[0].blocks!=null){
				term= alignments[0].blocks[0].segments[1].start - alignments[0].blocks[0].segments[0].start;
				top=alignments[0].blocks[0].segments[0].end;
				bottom=alignments[0].blocks[0].segments[0].start;
			}
		}
	}
	if (1>position-term)
		return bottom;
	if (position-term>top)
		return top;
	return position-term;
}
function extrapolateSegment(segmentQuery){
	var term=0;
	var top=0
	var bottom=0
	var entro=false;
//	segmentUniprot=null;
//	segmentPDB=null;
	if ((segmentUniprot!=null)&&(segmentPDB!=null)){
		var segmentResult;
		segmentResult= new segment();
		segmentResult.objid=segmentPDB.objid;
		if ((Math.round(segmentQuery.start)<Math.round(segmentUniprot.start))&&(Math.round(segmentQuery.end)<Math.round(segmentUniprot.start))){
			segmentResult.start=0;
			segmentResult.end=0;
		}else if ((Math.round(segmentQuery.start)>Math.round(segmentUniprot.end))&&(Math.round(segmentQuery.end)>Math.round(segmentUniprot.end))){
			segmentResult.start=0;
			segmentResult.end=0;
		}else{
			if (Math.round(segmentQuery.start)<Math.round(segmentUniprot.start)){
				segmentResult.start=segmentPDB.start;
			} else{
				segmentResult.start=segmentQuery.start - (segmentUniprot.start - segmentPDB.start);
			}
			if (Math.round(segmentQuery.end)>Math.round(segmentUniprot.end)){
				segmentResult.end=segmentPDB.end;
			} else{
				segmentResult.end=segmentQuery.end - (segmentUniprot.end - segmentPDB.end);
			}
		}
		return segmentResult;
	}
	return null;
}
 
/**
* load the xml alignment file from the server
*/
function loadAlignment(url){
	var http_request = false;
	if (window.XMLHttpRequest) { 
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) { http_request.overrideMimeType('text/xml');} // Rafa
	} else if (window.ActiveXObject) { // IE.
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	http_request.open('GET', url, true);
	http_request.onreadystatechange = function(){
		if (http_request.readyState == 4) {
			if (http_request.status == 200) { 
				if(http_request.responseText && testing)
					document.getElementById("xmlalgn").value= http_request.responseText;
				//if(http_request.responseXML && http_request.responseXML.contentType=="text/xml") // Rafa
				if(http_request.responseXML){
					doParseAligment(http_request.responseXML);
					//Only load the applet and the dropdown after parse the alignment
					iniStructPanel();
				}else
					alert("wrong type alignment");	
			}else
				alert("wrong code");
		}
	}
	http_request.send(null);
}

/**
*  get an array of the parsed structure with the name of the pdb's files
*/
function getPDBfileNames(){
	var fileNames = new Array();
	for(i=0;i<alignments.length;i++){
		//printOnTest(alignments[i].alignObjects);
		if(alignments[i].blocks!=null)
		for(j=0;j<alignments[i].alignObjects.length;j++){
			if (alignments[i].alignObjects[j].dbsource == "PDB"){
				fileNames[i]=alignments[i].alignObjects[j].accessionid;
			}
		}
	}
	//alert(fileNames.length);
	return fileNames;
	
}//------------------------------------------------------------------------------------------	
<!-- "PASRSE DAS REGISTRY"
//------------------------------------------------------------------------------------------	
function parseDasRegistryXML()
{
//DasRegistryHelper.prototype.parseResponse = function(response, filterLabel)   {
    
	// var servers = new Array();
	das_registry_label = [];
	das_registry_label.push("any");
	var serverCount = 0;

    // Get SOURCE elements
	
 // if (elements_http_request[2].readyState == 4)
 if (http_request.readyState == 4)
 {
  // if (elements_http_request[2].status == 200)
  if (http_request.status == 200)
  {
	document.getElementById("system_information").innerHTML = "... loading list of servers from the DAS registry";
    // var xmldoc = elements_http_request[2].responseXML;
	var xmldoc = http_request.responseXML;
	
	var excep = xmldoc.getElementsByTagName('exception').item(0);
	
    var sources = xmldoc.getElementsByTagName("SOURCE");
    for (var i=0; i < sources.length; i++)
	{
        var source = sources.item(i);
        var id = source.getAttributeNode("title").value;
		
		if (id != 's3dm')
		{
		
		var registry_uri = source.getAttributeNode("uri").value;
        // Get VERSION elements
        var versions = source.getElementsByTagName("VERSION");
        for (var j=0; j < versions.length; j++)
		{
            var version = versions.item(j);
            // Get PROPERTY elements
            var labelsFound = 0; //RC 250508
			var properties = version.getElementsByTagName("PROP");
		    for (var k=0; k < properties.length; k++)
			{ 
                var property = properties.item(k);
                var name = property.getAttributeNode("name").value;
                if (name == "label")
				 {
                    var label = property.getAttributeNode("value").value;
					
					var drl_length = das_registry_label.length;
					//if(drl_length == 0) {das_registry_label[0] == label}
					
					var new_label = 0;
					
					das_registry_label_loop:
					for (var m=0; m < drl_length; m++)
						{
							if (das_registry_label[m] == label)
								{
									new_label = 1;
									break das_registry_label_loop;
								}
							else
								{
									new_label = 0;
								}
						}
					if (new_label == 0) { das_registry_label.push(label); }
					
					
					
                    if (label.toUpperCase() == filterLabel.toUpperCase() || filterLabel.toUpperCase() == "ANY")
					{
						labelsFound++; //RC 250508							
                        var url = "";
                        // Get CAPABILITY elements
                        var capabilities = version.getElementsByTagName("CAPABILITY");
                        for (var m=0; m < capabilities.length; m++)
						  {
                            var capability = capabilities.item(m);
                            var type = capability.getAttributeNode("type").value;
                            if (type == "das1:features")
							  {
                                var uri = capability.getAttributeNode("query_uri").value;
                                url = uri.substring(0, uri.indexOf("features"));
                              }
                          }
                        
						//if (url != "" && url != 'http://www.ebi.ac.uk/msd-srv/msdmotif/das/s3dm/')
						if (url != "" && labelsFound==1)	//RC 250508
							{
                            var server = new Object();
                            server.id  = id;
							server.url = proxy_url + '?m=features&q=' + query_id + '&t=' + timeout + '&s=' + url;
							
							if(dasty_mainpage_name.indexOf("interactor") != -1)
								{
									if(id.toUpperCase() == 'INTACT' || id.toUpperCase() == 'CHEBI')
										{
                            				server.url = proxy_url + '?m=features&q=' + dgi_id + '&t=' + timeout + '&s=' + url;
										}
								}
							
							server.registry_uri = registry_uri;
                            //server.label = label;
                            //servers[serverCount] = server;
							feature_url[serverCount] = server;
                            serverCount++
                           } // if (url != "" && labelsFound==1)	
                    	} // if (label == filterLabel || filterLabel = "any")
               	 	} // if (name == "label")
            } // for (var k=0; k < properties.length; k++)
        } // for (var j=0; j < versions.length; j++)
	  } //if (id != 's3dm')
    } // for (var i=0; i < sources.length; i++)
    //return servers;
//	


	
    if (excep != null)
		{
		  document.getElementById("system_information").innerHTML = "<span style=\"color:#CC0000\">Das Registry warning:<br/><a href=\"" + das_registry_url + "\" target=\"_blank\">" + excep.firstChild.data + "</a><br/>Dasty2 could not load data from the servers</span>";
		}
	else
		{
			createLabelOptions(das_registry_label, "feature_label_list_select");
			if(serverCount == 0)
				{
					document.getElementById("system_information").innerHTML = "<span style=\"color:#CC0000\">Das Registry warning:<br/>Dasty2 did not find protein sequence annotation server for this label. Please chose another label.</span>";
				}
				else
				{
		 			makeSequenceRequest();
				}
		}
  //makeFeatureRequest();		
  } else {
    alert('There was a problem with the request.');
  } //if (http_request.status == 200)
 }
}

//------------------------------------------------------------------------------------------	
// CREATE LABELS IN SEARCH FIELD
//------------------------------------------------------------------------------------------	
function createLabelOptions(das_registry_label, tagId)
	{	
		var div = document.getElementById("feature_label_list");
		var content = "";
		content = content + "<label><a style=\"text-decoration:none;\" href=\"http://www.dasregistry.org/help_label.jsp\" target=\"_blank\"><img src=\"http://www.gpcr.org/7tm/dasty2/client/img/info01.gif\" border=\"0\">&#160;Registry label:</a>&#160;<select id=\"feature_label_list_select\" name=\"feature_label_list_select\" class=\"label_list\">"; // align=\"baseline\"
		for ( var i = 0; i < das_registry_label.length; i++ )
			{
				if(filterLabel.toUpperCase() == das_registry_label[i].toUpperCase())
					{
						content = content + " <option value=\"" + das_registry_label[i] + "\" selected=\"selected\">" + das_registry_label[i] + "</option>";
					}
				else
					{
						content = content + " <option value=\"" + das_registry_label[i] + "\">" + das_registry_label[i] + "</option>";
					}
			}
		content = content + "</select></label>&#160;&#160;";
		div.innerHTML = content;
		
	}
//

//function createLabelOptions(das_registry_label, tagId)
	//{	
		//for ( var i = 0; i < das_registry_label.length; i++ )
			//{
				//var form_select = document.getElementById("feature_label_list_select");
				//var content_form_select = form_select.innerHTML;
				//form_select.innerHTM =  (content_form_select + " <option value=\"" + das_registry_label[i] + "\">" + das_registry_label[i] + "</option>");		
			//}
	//}
//------------------------------------------------------------------------------------------	
// "PASRSE A FEATURE XML AND POPULATE GRAPHIC AND NP TABLE"
//------------------------------------------------------------------------------------------	
            function parseFeatureXML(featureXML_num) {
                if (feature_http_request[featureXML_num].readyState == 4) {
                    if (feature_http_request[featureXML_num].status == 200) {
					  
					  document.getElementById("system_information").innerHTML = "... loading features from " + feature_url[featureXML_num].id;
					  // DRAWING PROGRESS BAR
					  servers_count++;
					  var percentage = parseInt(servers_count*100/feature_url.length);
					  if(percentage == 100)
					  	{
							allSourcesLoaded = true;
						}
	
					  
				      progBar(percentage);
						
					  var npf_num = 0; // Count number of non positional features
					  var row_num = 0;
					  var update = 0;
					  var type_counter = [];
					  var tc_length = 0;
					  feature_info[featureXML_num] = [];
					  var parsing_error = 0;
					  
					  var url = feature_url[featureXML_num].url;
					  
					  feature_url[featureXML_num].XML_num = featureXML_num;
					  feature_url[featureXML_num].general_order = servers_count;
					  
					  var firstRequestNumberTemp = dasty2.firstRequestNumber;
						
                      var xmldoc = feature_http_request[featureXML_num].responseXML;
					  var excep = xmldoc.getElementsByTagName('exception').item(0);
					  if (excep != null)
					  	{
							warning_count++;
							var server_checking = document.getElementById("display_server_checking").innerHTML;
							document.getElementById("display_server_checking").innerHTML = server_checking + "<br/><span title=\""+ excep.firstChild.data + "\" style=\"color:#FF6600\"><strong>" + servers_count + ".- </strong><a href=\"" + url + "\" target=\"_blank\">" + feature_url[featureXML_num].id + "</a> ... Warning: " + excep.firstChild.data.slice(0,40) + "...</span>";
							feature_url[featureXML_num].state = 3;
					  	}
					  
					  var tf = xmldoc.getElementsByTagName('FEATURE').item(0);
					  if (tf != null)
					  {
						results_XML_order[feature_results_count] = featureXML_num;
						feature_results_count++;
						var server_checking = document.getElementById("display_server_checking").innerHTML;
						document.getElementById("display_server_checking").innerHTML = server_checking + "<br/><span style=\"color:#006600\"><strong>" + servers_count + ".- </strong><a href=\"" + url + "\" target=\"_blank\">" + feature_url[featureXML_num].id + "</a> ... have feature annotations.</span>";
						feature_url[featureXML_num].state = 1;
						//feature_url[featureXML_num].results_order = feature_results_count;
						
                        var gff_node = xmldoc.getElementsByTagName('GFF').item(0);
						
						// var opa = document.getElementById("display_test");
						// var content_opa = opa.innerHTML;
						// opa.innerHTML = (content_opa + " <br>------------<br>tf:" + tf);		
						
						var gff_attrs = gff_node.attributes;
						gff_loop: 
						for(var g=gff_attrs.length-1; g>=0; g--)
							{
							if (gff_attrs[g].name == 'version') { var gff_version = gff_attrs[g].value; }
							else if (gff_attrs[g].name == 'href') { var gff_href = gff_attrs[g].value; };
							}
							
							// var opa = document.getElementById("display_test");
							// var content_opa = opa.innerHTML;
							// opa.innerHTML = (content_opa + " <br>------------<br>gff_href:" + gff_href);
							
						
						   var segment_node = gff_node.childNodes;
						   segment_loop: 
						   for (var s = 0; s < segment_node.length; s++) 
						   {
						   		if (segment_node[s].nodeName == 'SEGMENT')
								{
									//var segment_data = segment_node[s].firstChild.data;
									var segment_attrs = segment_node[s].attributes;
									for(var i=segment_attrs.length-1; i>=0; i--)
									{
										if (segment_attrs[i].name == 'id') { var segment_id = segment_attrs[i].value; }
										else if (segment_attrs[i].name == 'version')
										  {
											var segment_version = segment_attrs[i].value;
											if(segment_version == sequence_info.sequence_version)
												{
													annotation_version[featureXML_num] = 1; // ok
												}
											else
												{
													annotation_version[featureXML_num] = 0; // different
												}
										  }
										else if (segment_attrs[i].name == 'start')
										  { 
											//if(segment_attrs[i].value == '')
											  //{
											  var segment_start = sequence_info.sequence_start;
											  //} // sequence_info is glogal!
											//else
											  //{ var segment_start = segment_attrs[i].value;}
										  }
										else if (segment_attrs[i].name == 'stop')
										  {
											//if(segment_attrs[i].value == '' || segment_attrs[i].value == '-1')
											  //{ 
											  var segment_stop = sequence_info.sequence_stop;
											  //} // sequence_info is glogal!
											//else
											  //{ 
											  //var segment_stop = segment_attrs[i].value;
											  //}
										  }
									 }
								   var feature_node = segment_node[s].childNodes;
								   feature_loop: 
								   for (var f = 0; f < feature_node.length; f++) 
								   {
									   var feature_id = '';
									   var feature_label = '';
									   var type_data = '';
									   var type_id = '';
									   var type_category = '';
									   var method_data = '';
									   var method_id = '';
									   var start_data = '';
									   var end_data = '';
									   var score_data = '';
									   var orientation_data = '';
									   var phase_data = '';
									   var note_data = [];
									   var link_data = [];
									   var link_href = [];
									   var group_id = '';
									   
										if (feature_node[f].nodeName == 'FEATURE')
										{
											//var segment_data = segment_node[s].firstChild.data;
											var feature_attrs = feature_node[f].attributes;
											for(var i=feature_attrs.length-1; i>=0; i--)
											{
												if (feature_attrs[i].name == 'id') { feature_id = feature_attrs[i].value; }
												else if (feature_attrs[i].name == 'label') { feature_label = feature_attrs[i].value; };
											 }
										   // Exception for "http://cathwww.biochem.ucl.ac.uk:9000/das/cath_pdb/"
										 if(feature_id == "Query_failed") { break feature_loop; parsing_error = 1; }

										   var feature_child_node = feature_node[f].childNodes;
										   feature_child_loop: 
										   for (var c = 0; c < feature_child_node.length; c++) 
										   {
												if (feature_child_node[c].nodeName == 'TYPE')
												{
													if(feature_child_node[c].firstChild == null)
														{
															//var type_data = "";
															var type_data_temp = "";
															type_data = "";
														}
													else
														{
															//var type_data = feature_child_node[c].firstChild.data;
															var type_data_temp = feature_child_node[c].firstChild.data;
															type_data = feature_child_node[c].firstChild.data;
														}
													var feature_child_attrs = feature_child_node[c].attributes;
													for(var i=feature_child_attrs.length-1; i>=0; i--)
													{
														if (feature_child_attrs[i].name == 'id')	
															{
																type_id = feature_child_attrs[i].value;
																if (type_data_temp == "")
																	{
																		type_data = type_id;
																	}
																//if (type_data_temp.toLowerCase() == type_id.toLowerCase() || type_data_temp == "" )
																	//{
																	//	// do nothing
																	//}
																//else
																	//{
																	//	type_data = type_data_temp + " (" + type_id + ")";
																	//}
															}
														else if (feature_child_attrs[i].name == 'category')
															{
																type_category = feature_child_attrs[i].value;
															}
													} // for(var i=feature_child_attrs.length-1; i>=0; i--)
													
													
													
													/**
													* Create an list of non redundant types
													*/
													
													//if(type_id != "")
														//{
															var typesLoadedLength = dasty2.typesLoaded.length;
															var typeDuplicated = 0;
															for(var w = 0; w < typesLoadedLength; w++)
																{
																	if(dasty2.typesLoaded[w].toUpperCase() == type_id.toUpperCase())
																		{
																			typeDuplicated = 1;
																		}
																}
																if(typeDuplicated == 0)
																	{
																			dasty2.typesLoaded.push(type_id);
																	}
														//}
													
													/**
													* Create an list of non redundant categories
													*/
													
													//if(type_category != "")
														//{
															var categoriesLoadedLength = dasty2.categoriesLoaded.length;
															var categoryDuplicated = 0;
															for(var w = 0; w < categoriesLoadedLength; w++)
																{
																	if(dasty2.categoriesLoaded[w].toUpperCase() == type_category.toUpperCase())
																		{
																			categoryDuplicated = 1;
																		}
																}
																if(categoryDuplicated == 0)
																	{
																			dasty2.categoriesLoaded.push(type_category);
																	}
														//}
													
															
													
													
													
												}	 
												else if (feature_child_node[c].nodeName == 'METHOD')
												{
													if(feature_child_node[c].firstChild == null)
														{
															var method_data_temp = "";
															method_data = "";
														}
													else
														{
															method_data = feature_child_node[c].firstChild.data;
															var method_data_temp = feature_child_node[c].firstChild.data;
														}
													//var method_data = feature_child_node[c].firstChild.data;
													var feature_child_attrs = feature_child_node[c].attributes;
													for(var i=feature_child_attrs.length-1; i>=0; i--)
													{
														if (feature_child_attrs[i].name == 'id')
															{
																method_id = feature_child_attrs[i].value;
																if (method_data_temp == "")
																	{
																		method_data = method_id;
																	}
																if (method_data_temp.toLowerCase() == method_id.toLowerCase() || method_data_temp == "" )
																	{
																		// do nothing
																	}
																else
																	{
																		method_data = method_data_temp + " (" + method_id + ")";
																	}
															}
													 }	 
												}
												else if (feature_child_node[c].nodeName == 'START')
												{
													start_data = feature_child_node[c].firstChild.data;
												}
													else if (feature_child_node[c].nodeName == 'END')
												{
													end_data = feature_child_node[c].firstChild.data;
												}
												else if (feature_child_node[c].nodeName == 'SCORE')
												{
													if(feature_child_node[c].firstChild == null)
														{
															score_data = "0.0";
														}
													else
														{
															score_data = feature_child_node[c].firstChild.data;
														}
												}
												else if (feature_child_node[c].nodeName == 'ORIENTATION')
												{
													orientation_data = feature_child_node[c].firstChild.data;
												}
												else if (feature_child_node[c].nodeName == 'PHASE')
												{
													phase_data = feature_child_node[c].firstChild.data;
												}
												else if (feature_child_node[c].nodeName == 'NOTE')
												{
													note_data.push(feature_child_node[c].firstChild.data);
												}
												else if (feature_child_node[c].nodeName == 'LINK')
												{
													link_data.push(feature_child_node[c].firstChild.data);
													var feature_child_attrs = feature_child_node[c].attributes;
													for(var i=feature_child_attrs.length-1; i>=0; i--)
													{
														if (feature_child_attrs[i].name == 'href') { link_href.push(feature_child_attrs[i].value); };
													 }
												}
												else if (feature_child_node[c].nodeName == 'GROUP')
												{
													var feature_child_attrs = feature_child_node[c].attributes;
													for(var i=feature_child_attrs.length-1; i>=0; i--)
													{
														if (feature_child_attrs[i].name == 'id') { group_id = feature_child_attrs[i].value; };
													}
												}
										   // FOR feature_child_loop
										   }
										 //} // if(feature_id != "Query_failed")
										   
										 //if(type_category) { /* defined */ } else { var type_category = ''; } 
										 
										 var feature_row = {feature_id: feature_id, feature_label: feature_label, type_data: type_data, type_id: type_id, type_category: type_category, method_data: method_data, method_id: method_id, start_data: start_data, end_data: end_data, score_data: score_data, orientation_data: orientation_data, phase_data: phase_data, note_data: note_data, link_data: link_data, link_href: link_href, group_id: group_id, annotation_server: feature_url[featureXML_num].id, annotation_server_uri: feature_url[featureXML_num].registry_uri, xmlnumber: featureXML_num };
										 //feature_info[row_num] = feature_row; 
										 feature_info[featureXML_num][row_num] = feature_row;
										 
										 if (start_data==0 && end_data==0)
		  									{
											  npf_num++;	
											}

							if (start_data == 0 && end_data ==0)
									{ // non positional feature
									} else {
										//----------------------------------------------------------------------------------
										// ARRAY THAT SAYS WHERE A "type" IS HAPPENING IN THE "feature_info" ARRAY
										//----------------------------------------------------------------------------------
										tc_length = type_counter.length;
										
										if(tc_length == 0)
										  {
											type_counter[0] = [];
											type_counter[0][0] = type_id;
											type_counter[0][1] = [];
											type_counter[0][1] = [row_num];
										   }
										
										tc_update = 0;
										for(var h = 0; h < tc_length; h++)
										  {									  
											if(type_counter[h][0] == type_id)
											  {
											    type_counter[h][1].push(row_num);
												tc_update = 1;
											  }
										   }
										   
										if(tc_update == 0 && tc_length != 0)
										  {
											 type_counter[tc_length] = [];
											 type_counter[tc_length][0] = type_id;
											 type_counter[tc_length][1] = [];
											 type_counter[tc_length][1] = [row_num];
										   }
											
									 } // finish => if (start_data == 0 && end_data ==0)
										row_num++;
										// IF 'FEATURE'   	
										}
								   // FOR feature_loop	
								   }
								}
						   }	
						   
						  if(parsing_error == 0)
						   {
								createNPFeatureTable(featureXML_num, feature_info[featureXML_num], "display_nonpositional", npf_num);
								grouping(featureXML_num, type_counter,  segment_start, segment_stop);
								
								
								if(firstRequestNumberTemp <= dasty2.validFirstSources.length)		
									{
										if(firstRequestNumberTemp == dasty2.validFirstSources.length)
						  					{
												dasty2.firstRequestNumber++;
												makeFeatureRequest2();
											}
						   				else
						   					{
												makeFeatureRequest(dasty2.firstRequestNumber);
											}
						   			}
						   }
						  else
						   {
							    createGraphic2(featureXML_num, "display_graphic", 0, 0, "noresults");
								if(firstRequestNumberTemp <= dasty2.validFirstSources.length)		
									{
										if(firstRequestNumberTemp == dasty2.validFirstSources.length)
						  					{
												dasty2.firstRequestNumber++;
												makeFeatureRequest2();
											}
						   				else
						   					{
												makeFeatureRequest(dasty2.firstRequestNumber);
											}
									}
						   }

					    } // if (tf != "null" && tf != "" && tf != null)
					   else
					    {
							
						  //var opa = document.getElementById("display_test");
						  //var content_opa = opa.innerHTML;
						  //opa.innerHTML = (content_opa + " <br>------------<br>tf:" + tf);		
							
							
						  //var opa = document.getElementById("display_test");
					      //var content_opa = opa.innerHTML;
						  //opa.innerHTML = (content_opa + " <br>------------<br>featureXML_num:" + featureXML_num);
						  
						  if (excep == null)
					  		{
							  no_feature_results_count++;
							  var server_checking = document.getElementById("display_server_checking").innerHTML;
							  document.getElementById("display_server_checking").innerHTML = server_checking + "<br/><span style=\"color:#CC0000\"><strong>" + servers_count + ".- </strong><a href=\"" + url + "\" target=\"_blank\">" + feature_url[featureXML_num].id + "</a> ... do not have feature annotations available.</span>";
							  feature_url[featureXML_num].state = 2;
							}
						  
						  createGraphic2(featureXML_num, "display_graphic", 0, 0, "noresults");
						  
						  if(firstRequestNumberTemp <= dasty2.validFirstSources.length)		
								{
									if(firstRequestNumberTemp == dasty2.validFirstSources.length)
						  				{
											dasty2.firstRequestNumber++;
											makeFeatureRequest2();
										}
					  				else
					   					{
											makeFeatureRequest(dasty2.firstRequestNumber);
										}
								}					
							
					    } // if (tf != "null" && tf != "" && tf != null)
						
                    } else {
                        alert('There was a problem with the request: Parse feature');
                    } // if (feature_http_request[featureXML_num].status == 200)
                } // if (feature_http_request[featureXML_num].readyState == 4)
				
				//alert(standby.length);
				
            } // function parseFeatureXML()
      //
	  
	// Fernando's code to get started with parsing ontologies
var testing = false;  	 // used for testing
	
/**
* called with url of ontology file to load and parse
* @params: otype: ontology to parse (either 1 for type or 2 for category)
*/
function parseOntology(otype,url){
	loadOntology(otype,url);
}

// <------------ Loading and Parsing --------------->

/**
* parse the xml ontology file received in doc
*/
function doParseOntology(doc,otype){ 
	//Preparing the arrays of types and categories. The graphic must be loaded
	dasty2.temporalArray=[];
	dasty2.temporalArray2=[];
	dasty2.leaves=[];
	
	if(otype==1){
		//Types
		dasty2.temporalArray2=dasty2.typesLoaded;
	}else{
		//Categories
		dasty2.temporalArray2=dasty2.categoriesLoaded;
	}
	for(var i=0;i<dasty2.temporalArray2.length;i++){
		if ((dasty2.temporalArray2[i].indexOf("SO:")!=-1)||(dasty2.temporalArray2[i].indexOf("ECO:")!=-1)||(dasty2.temporalArray2[i].indexOf("MOD:")!=-1)){
			dasty2.temporalArray=dasty2.temporalArray.concat(dasty2.temporalArray2.splice(i,1));
			i--;
		}
	}	
	
	
	xmlterms = doc.documentElement.getElementsByTagName("term");

	
	if(testing){
		document.getElementById("nalgn").innerHTML = xmlterms.length;
	}
	this.terms = new Array(), // array of parsed ontology terms
	this.nterms = 1;		  	 // number of terms in ontology. Init to 1, pos. 0 reserved for root	
	this.rootptr = -1;		 // pointer to root
	var s = "";this.termsidx = new Array();
	for(var i=0;i<xmlterms.length;i++){
		xmlterm = xmlterms.item(i);
		relations = new Array();definition = "";is_definition = false;rel_count = 0;isroot = 0;isobsolete = 0;
		for(var j=0;j<xmlterm.childNodes.length;j++){
			//if(xmlterm.childNodes[j].nodeType == document.ELEMENT_NODE){ // Rafael
				if(xmlterm.childNodes[j].nodeName == "id"){
					id = getNodeData(xmlterm.childNodes[j]);
				}else
				if(xmlterm.childNodes[j].nodeName == "name"){
					name = getNodeData(xmlterm.childNodes[j]);
				}else
				if(xmlterm.childNodes[j].nodeName == "is_a"){
					relations[rel_count] = new Array();
					relations[rel_count]['type'] = 'is_a';
					relations[rel_count++]['termid'] = getNodeData(xmlterm.childNodes[j]);
				}else
				if(xmlterm.childNodes[j].nodeName == "has_a"){
					relations[rel_count] = new Array();
					relations[rel_count]['type'] = 'has_a';
					relations[rel_count++]['termid'] = getNodeData(xmlterm.childNodes[j]);
				}else
				if(xmlterm.childNodes[j].nodeName == "is_root"){
					isroot = getNodeData(xmlterm.childNodes[j]);
				}else // Rafael ->
				if(xmlterm.childNodes[j].nodeName == "def"){
					for(var h=0;h<xmlterm.childNodes[j].childNodes.length;h++){
						if(xmlterm.childNodes[j].childNodes[h].nodeName == "defstr"){
							definition = getNodeData(xmlterm.childNodes[j].childNodes[h]);
							is_definition = true;
						}
					}
					// <- Rafael
				}else
				if(xmlterm.childNodes[j].nodeName == "is_obsolete"){
					isobsolete = getNodeData(xmlterm.childNodes[j]);
				}
			//} // if(xmlterm.childNodes[j].nodeType == document.ELEMENT_NODE)
		}
		// Rafael ->
		if(is_definition == false){
			definition = "Description not available";
		}
		// <- Rafael
		if(isobsolete==0){
			if(isroot!=null && isroot==1){
				this.rootptr = 0;
				this.terms[0] = addTerm(id,name,relations,otype,definition);
				this.termsidx[id] = 0;
			}else{ 
				if(this.rootptr==-1){ 
					this.terms[0]= new Array();
					this.terms[this.nterms] = addTerm(id,name,relations,otype,definition);
					this.rootptr = 0;
				}else{
					this.terms[this.nterms] = addTerm(id,name,relations,otype,definition);
				}
				this.termsidx[id] = this.nterms++;
			}
		}
	}
}

/**
* return a new term in Tree component format
* @params: id=term id, name = term name, relations = relations found for the term
*/
function addTerm(id,name,relations,otype,definition){
	term = new Array(); 
	term['dataContainer'] = id;
	term['caption'] = name;
	term['visible'] = false;
	term['relations'] = relations;
	term['onClick']  = "javascript:printOnSystemInformation('" + id + "; " + definition + "')";
	if(otype==1)
		term['onChangeCheckbox'] = display_ontology_types;
	else
		term['onChangeCheckbox'] = display_ontology_categories;
	return term;
}

/**
* return content if text node, empty string otherwise
*/
function getNodeData(node){
	if(!node.hasChildNodes)
		return "";
	for(var j=0;j<node.childNodes.length;j++){
		//if(node.childNodes[j].nodeType == document.TEXT_NODE){	 // Rafael
			return node.childNodes[j].data;	
		//}
	}
	return "";
}

/**
* generate the data structure required by the Tree component
*/
doParseOntology.prototype.genTreeData = function(otype){
	if(this.rootptr==-1){
		// error condition
		printOnTest("Dasty2 could not load the ontology information");
		document.getElementById("system_information").innerHTML = "Dasty2 could not load the ontology information";
		//alert("root not found");
	}
	for(i=0;i<this.terms.length;i++){
		if(this.terms[i]['relations']!=null && this.terms[i]['relations'].length>0){
			for(j=0;j<this.terms[i]['relations'].length;j++){
				if(this.terms[i]['relations'][j]['type']=='is_a'){
					if(this.terms[this.termsidx[this.terms[i]['relations'][j]['termid']]]==null)
						alert("null for i="+i+" and dc="+this.terms[i]['dataContainer']+" rel with="+this.terms[i]['relations'][j]['termid']+" idx="+this.termsidx[this.terms[i]['relations'][j]['termid']]);
					parent(this.terms[this.termsidx[this.terms[i]['relations'][j]['termid']]],this.terms[i]
					);
				}
			}
		}
	}
	n=this.terms.length;i=0;
	while(i<n && n>0){
		if(this.terms[i]['added']!=null){ 
			this.terms.splice(i,1);
			n=this.terms.length;i=0;
		}else
			i++;
	}
	
	//tag all the leaves and its ancesters as visibles
	for(var i=0;i<dasty2.leaves.length;i++){
			setAncestorsVisible(dasty2.leaves[i]);			
	}  
	
	//Delete the not visible children
	for(var i=0;i<this.terms.length;i++){
		delNotVisibleChildren(this.terms[i]);
	}
	
	//Add the subtree of non-ontology terms
	var other = addTerm("other_types","Other Terms (Not in the ontology)",null,otype);
	other['visible'] = true;
	other['isOpen'] = false;
	other['isChecked'] = 2;
	dasty2.temporalArray2=dasty2.temporalArray2.concat(dasty2.temporalArray);
	for (var i=0;i<dasty2.temporalArray2.length;i++){
		var termO = addTerm(dasty2.temporalArray2[i],dasty2.temporalArray2[i],null,otype,"Description not available");
		termO['visible'] = true;
		termO['isOpen'] = true;
		termO['isChecked'] = 2;
		if(other['children']==null){
			other['children'] = new Array();
			other['children'][0] = termO;
		}else{
			other['children'][other['children'].length] = termO;
		}
	}
	this.terms[this.terms.length] = other;
}

/**
* family reunion: connects a child with its parent term
*/
function parent(p,child){
	if(p['children']==null){
		p['children'] = new Array();
		p['children'][0] = child;
	}else{
		p['children'][p['children'].length] = child;
	}
	child['parent']=p;
	if (isInArray(child['dataContainer'])){
		dasty2.leaves[dasty2.leaves.length]=child;
	}
	child['added'] = true;
}

function setAncestorsVisible(child){
	nodeLoop: 
	for(var i=0;i<collapsedOntologyTypeTerms.length;i++){
		if(child['caption'] == collapsedOntologyTypeTerms[i]){
			child['isOpen'] = false;
			break nodeLoop;
		} else {
			child['isOpen'] = true;
		}
	}

	child['visible'] = true;
	//child['isOpen'] = true;
	child['isChecked'] = 2;
	if (child['parent']!=null){
		setAncestorsVisible(child['parent']);
	}
}
function delNotVisibleChildren(parent){
	if(parent['children']!=null){
		for(var i=0;i<parent['children'].length;i++){
			var child=parent['children'][i];
			if (child['visible']!=true){
				parent['children'].splice(i,1);
				i--;
			}else{
				delNotVisibleChildren(child);
			}
		}
	}
}


/**
* list parsed terms for testing purposes
*/
function listTerms(t,indent){
	var s= indent+t['dataContainer']+"<br>";
	if(t['children']!=null){
		for(var j=0;j<t['children'].length;j++){
			s+=listTerms(t['children'][j],indent+".");
		}
	}
	return s;
}

/**
* list parsed terms for testing purposes
*/
function listTerms2(){
	s = "";
	for(i=0;i<this.terms.length;i++){
		s+= (i+1)+".<b>TermId:</b> "+this.terms[i]['dataContainer']+"<br>";
		if(this.terms[i]['relations']!=null)
		for(j=0;j<this.terms[i]['relations'].length;j++){
			s+="...Found that "+this.terms[i]['dataContainer']+" "+this.terms[i]['relations'][j]['type']+" "+this.terms[i]['relations'][j]['termid']+"<br>";
		}
	}
	return s;
}

/**
* display ontology for testing purposes
*/
doParseOntology.prototype.showOntologyTree = function(ontoType){
	if(ontoType==1){
		t = new Bs_Tree();
		t.imageDir = 'http://www.gpcr.org/7tm/dasty2/client/library/blueshoes46/components/tree/img/win98/';
		t.checkboxSystemImgDir = 'http://www.gpcr.org/7tm/dasty2/client/library/blueshoes46/components/checkbox/img/win2k_noBorder/';
		t.useCheckboxSystem      = true;
		//t.useAutoSequence =  false;
		t.checkboxSystemWalkTree = 3;
		t.initByArray(this.terms);
		//prune(t,dasty2.typesLoaded,ontoType);
		t.drawInto('display_maniputation_options3_type_div');
		
		//Close Ontology terms (nodes) in the tree
		// This does not work. Probably because the tree takes some time to load and
		// when this script tries to access is still too early.
	 	/* 
	 	var termArray = ['binding_site','polypeptide_region'];
		for(i=0;i<termArray.length;i++){
			var caption = new Array(termArray[i]);
			var ontologyTerm = t.getElementByCaptionPath(caption);
			t.elementToggleOpenClose(ontologyTerm.id);
		}	  
		*/

	}else if(ontoType==2){
		category_tree = new Bs_Tree();
		category_tree.imageDir = 'http://www.gpcr.org/7tm/dasty2/client/library/blueshoes46/components/tree/img/win98/';
		category_tree.checkboxSystemImgDir = 'http://www.gpcr.org/7tm/dasty2/client/library/blueshoes46/components/checkbox/img/win2k_noBorder/';
		category_tree.useCheckboxSystem      = true;
		category_tree.checkboxSystemWalkTree = 3;
		category_tree.initByArray(this.terms);
		//prune(category_tree,dasty2.categoriesLoaded,ontoType);
		category_tree.drawInto('display_maniputation_options3_category_div');
	}
}

/**
* load the xml ontology file from the server
*/
function loadOntology(otype,url){
	var http_request = false;
	if (window.XMLHttpRequest) { 
		http_request = new XMLHttpRequest();
	} else if (window.ActiveXObject) { // IE.
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	http_request.open('GET', url, true);
	http_request.onreadystatechange = function(){
		if (http_request.readyState == 4) {
			if (http_request.status == 200) { 
				if(http_request.responseText && testing)
					document.getElementById("xmlalgn").value= http_request.responseText;
				//if(http_request.responseXML && http_request.responseXML.contentType=="text/xml") // Rafa
				if(http_request.responseXML)
						{	
						parser = new doParseOntology(http_request.responseXML,otype);
						parser.genTreeData(otype);
						if(testing){
							adata = document.getElementById("algdata");
						}
						parser.showOntologyTree(otype);
				}else
					alert("wrong type ontology");	
			}else
				alert("wrong code");
		}
	}
	http_request.send(null);
}
//------------------------------------------------------------------------------------------	
// "PASRSE A SEQUENCE XML AND POPULATE QUERY AND SEQUENCE FIELDS"
//------------------------------------------------------------------------------------------	
            
			/**
			* author: fernando
			* used to transform the sequence data for the highlight technique
			*/
			function transformSeqData(seqData){ //return seqData;
            	if(seqData == null || seqData.length == 0)
            		return "";
            	var seq = "";
				var seqDataArray = new Array;
				seqDataArray = seqData.toArray();
            	for(var i=0;i<seqDataArray.length;i++){
            		seq +="<span id='aa_"+(i+1)+"' onmousedown='addPos("+(i+1)+");' onmouseup='highlightStru("+(i+1)+");'>"+seqDataArray[i]+"</span>";
            		if ((i+1)%sequence_limit==0){
            			seq +="<br/>";
            		}
            	}	
            	return seq;
            }
            
            function parseSequenceXML() {
				//sequence_info = [];
				//alert(http_request.readyState);
                if (http_request.readyState == 4) {
                    if (http_request.status == 200) {
						document.getElementById("system_information").innerHTML = "... loading sequence information from the Reference Server";
                        var xmldoc = http_request.responseXML;
						
						var excep = xmldoc.getElementsByTagName('exception').item(0);
						
                        var root_node = xmldoc.getElementsByTagName('DASSEQUENCE').item(0);
						
					if(root_node)
					 {
						if (root_node.hasChildNodes())
						// So, first we check if the object is not empty, if the object has child nodes
						 {
						   var children = root_node.childNodes;
						   sequence_loop: 
						   for (var j = 0; j < children.length; j++) 
						   {
						   		if (children[j].nodeName == 'SEQUENCE')
								{
									if(useHighlight)
										{
										sequence = transformSeqData(children[j].firstChild.data);
										}
									else
										{
										sequence = children[j].firstChild.data;
										}
									var sequence_attrs = children[j].attributes;
									for(var i=sequence_attrs.length-1; i>=0; i--)
									{
										if (sequence_attrs[i].name == 'id') { var sequence_id = sequence_attrs[i].value; }
										else if (sequence_attrs[i].name == 'version') { var sequence_version = sequence_attrs[i].value; }
										else if (sequence_attrs[i].name == 'start') { var sequence_start = sequence_attrs[i].value; }
										else if (sequence_attrs[i].name == 'stop') { var sequence_stop = sequence_attrs[i].value; }
										else if (sequence_attrs[i].name == 'moltype') { var sequence_moltype = sequence_attrs[i].value; };
									  }
									 var sequence_length = sequence_stop - (parseInt(sequence_start) - 1);
									 //insertElement("div", "display_query_id", "display_query", sequence_id);
									 //insertElement("div", "display_query_length", "display_query", sequence_length);
									 //insertElement("div", "display_seque_sequence2", "display_seque", sequence);
									 
									 var sequence_row = {sequence: sequence, sequence_id: sequence_id, sequence_version: sequence_version, sequence_start: sequence_start, sequence_stop: sequence_stop, sequence_moltype: sequence_moltype, sequence_length: sequence_length };
									 
									 //sequence_info.push(sequence_row); //Convert to object! 
									 
									 sequence_info = sequence_row;
									 
									 //alert(sequence_info.sequence_stop);
									 
									 createQueryInformationField(sequence_info, "display_query");
									 //createSequenceField(sequence, "display_seque"); 
									 createSequenceField("display_seque"); 
									 
									 break sequence_loop;
								}
						   }
						 }
					  } // if(root_node)
					if (excep != null)
						{
							document.getElementById("system_information").innerHTML = "<span style=\"color:#CC0000\">Das Reference Server warning:<br/><a href=\"" + sequence_url[0][1] + "\" target=\"_blank\">" + excep.firstChild.data + "</a><br/>Dasty2 could not load data from the servers</span>";
						}
					else
						{	
							makeStylesheetRequest();
						}
                    } else {
                        alert('There was a problem with the request.');
                    }
                }
            }
      ////------------------------------------------------------------------------------------------	
// "PASRSE A STYLESHEET XML"
//------------------------------------------------------------------------------------------	
            function parseStylesheetXML() {
                if (http_request.readyState == 4) {
                    if (http_request.status == 200) {
						document.getElementById("system_information").innerHTML = "... loading stylesheet from the server";
                        var xmldoc = http_request.responseXML;
						
						var excep = xmldoc.getElementsByTagName('exception').item(0);
						
                        var category_node = xmldoc.getElementsByTagName('CATEGORY').item(0);
					if(category_node)
					  {
						var category_attrs = category_node.attributes;
						for(var g=category_attrs.length-1; g>=0; g--)
							{
							if (category_attrs[g].name == 'id') { var category_id = category_attrs[g].value; }
							}
						
						   var type_node = category_node.childNodes;
						   type_loop: 
						   for (var s = 0; s < type_node.length; s++) 
						   {
						   	 if (type_node[s].nodeName == 'TYPE')
							 { 
									var type_attrs = type_node[s].attributes;
									for(var i=type_attrs.length-1; i>=0; i--)
									{
										if (type_attrs[i].name == 'id') { var type_id = type_attrs[i].value; }
									 }
								   var glyph_node = type_node[s].childNodes;
								   glyph_loop: 
								   for (var gl = 0; gl < glyph_node.length; gl++) 
								   {
										if (glyph_node[gl].nodeName == 'GLYPH')
										{
										   var shape_node = glyph_node[gl].childNodes;
										   shape_loop: 
										   for (var f = 0; f < shape_node.length; f++) 
										   {
												if (shape_node[f].nodeName == 'ARROW' || shape_node[f].nodeName =='ANCHORED_ARROW' || shape_node[f].nodeName =='BOX' || shape_node[f].nodeName =='CROSS' || shape_node[f].nodeName =='EX' || shape_node[f].nodeName =='HIDDEN' || shape_node[f].nodeName =='LINE' || shape_node[f].nodeName =='SPAN' || shape_node[f].nodeName =='TEXT' || shape_node[f].nodeName =='TOOMANY' || shape_node[f].nodeName =='TRIANGLE' || shape_node[f].nodeName =='PRIMERS')
												{
												   var shape_nodeName = shape_node[f].nodeName;
												   var color_node = shape_node[f].childNodes;
												   color_loop: 
												   for (var c = 0; c < color_node.length; c++) 
												   {
														if (color_node[c].nodeName == 'FGCOLOR')
														{
															var fgcolor_data = color_node[c].firstChild.data;
														}	
														else if (color_node[c].nodeName == 'BGCOLOR')
														{
															var bgcolor_data = color_node[c].firstChild.data;
														}	
												   } // FOR color_loop
												 // TEST	
													// var opa = document.getElementById("display_test");
													 //var content_opa = opa.innerHTML;
													// opa.innerHTML = (content_opa + " <br>BF:" + fgcolor_data + " BG:" + bgcolor_data + " TYPEID:" + type_id);
									
												 var stylesheet_properties = {type_id: type_id, shape_nodeName: shape_nodeName, fgcolor_data: fgcolor_data, bgcolor_data: bgcolor_data};
												 stylesheet_properties_info.push(stylesheet_properties);
												} // IF 'SHAPE' 
										   } // FOR shape_loop
										} // IF 'SHAPE' 
								   } // FOR shape_loop	
							 }
						   }
					    } // if(category_node)
					if (excep != null)
						{
							document.getElementById("system_information").innerHTML = "<span style=\"color:#CC0000\">" + stylesheet_url[0][0] + " Das Stylesheet warning:<br/><a href=\"" + stylesheet_url[0][1] + "\" target=\"_blank\">" + excep.firstChild.data + "</a><br/>Dasty2 could not load data from the servers</span>";
						}
					else
						{				 
							makeFeatureRequest();
						}
                    } else {
                        alert('There was a problem with the request.');
                    }
				//makeRequest('xml/features2_c.xml', 'featureXML');
				//makeRequest('xml/fea_A4_Human.xml', 'featureXML');
				//makeRequest('xml/fea_A4_Human_short.xml', 'featureXML');
				//makeRequest('xml/fea_A4_Human_mod2.xml', 'featureXML');
				//alert("hello");
				//makeFeatureRequest();
                }

            }
      //// JavaScript Document


function feature_mouse_action(posX, posY, feature_title, feature_xmlnumber, feature_row, action)
	{

	if(action == 'mouseover')
			{
				createFeatureDetails(feature_row, feature_xmlnumber);
				if (isPDBVisible==true){
					selectAnotationRegion(feature_row, feature_xmlnumber);
				}
				if(show_popup == 1)
					{
						//var rafa = document.getElementById('__tooltip__');
						//rafa.style.display = "none";
						//var opa = document.getElementById("display_test");
						//var content_opa = opa.innerHTML;
						//opa.innerHTML = (content_opa + " <br>------------<br>unique_id: " + unique_id + " / show_popup: " + show_popup);
						
					}
			}
	else if(action == 'mouseclick')
			{
				if(show_popup == 2)
					{
						createFeatureDetails(feature_row, feature_xmlnumber);
						win2(posX, posY, feature_title);
						
						
						
						//TooltipManager = null;
						
						
						
						//TooltipManager.tooltipWindow.removeEventListener('mouseover',arguments.callee,false);
						
						//var rafa = document.getElementById('Pfam-B_2235_529');
						
						//rafa.removeEventListener('mouseover',arguments.callee,false);
						//removeEventListener('click',arguments.callee,false);
						
					}
			}
	}




function win2(setX, setY, feature_id)
{

		  //var scrollbar_height = f_scrollTop();
		  var newX = setX - 14;
		  //var newY = setY + height_graphic_feature - 2;
		  var newY = setY + height_graphic_feature + 2;
		  var feature_content = document.getElementById('display_feature_details').innerHTML;
		  
		  popup_num = popup_num + 1;
		  //Windows.closeAll();
		  //var win = new Window('window_id_' + popup_num, {className: "mac_os_x", title: feature_id});
		  var win = new Window('window_id_' + popup_num, {className: "mac_os_x", title: feature_id, width:260, height:170});
		  win.keepMultiModalWindow=false;
		  //win.getContent().innerHTML = "<h1>Constraint inside  page !!</h1>";
		  win.getContent().innerHTML = feature_content;
		  win.setDestroyOnClose();
		  //win.setHTMLContent(html)
		  //win.setContent('display_feature_details', false, false)
		  win.toFront();
		  
		  //win.showCenter();
		  //win.setConstraint(true, {left:0, right:0});
		  win.setLocation(newY, newX);
		  win.show();
}

function pdbOnWindow(div_id)
	{
		var pdbWin = new Window('pdbWin', {className: "mac_os_x", title: "PROTEIN STRUCTURE", hideEffect:Element.hide, showEffect:Element.show, maximizable: false, resizable: true, zIndex:9999});
		pdbWin.setContent(div_id, true, true);
		pdbWin.setDestroyOnClose();
		pdbWin.show();
		//changeStructure();
	}
	

/*
contentWin = new Window({maximizable: false, resizable: false, hideEffect:Element.hide, showEffect:Element.show, minWidth: 10, destroyOnClose: true}) contentWin.setContent('test_content', true, true) contentWin.show();



function openModalDialog() {
	  debug($('modal_window_content'))
		var win = new Window('modal_window', {className: "dialog", title: "Ruby on Rails",top:100, left:100,  width:300, height:200, zIndex:150, opacity:1, resizable: true})
		//win.getContent().innerHTML = "Hi"
		win.setContent("select")
		win.setDestroyOnClose();
		win.show(true);	
	}

function pdbOnWindow(div_id)
	{
		var pdbWin = new Window('pdbWin', {className: "mac_os_x", maximizable: false, resizable: true, hideEffect:Element.hide, showEffect:Element.show, minWidth: 10);
		pdbWin.setContent(div_id);
		setDestroyOnClose();
		pdbWin.show();
	}
	
*/	


  //TooltipManager.init("tooltip", {url: "tooltip_ajax.html", options: {method: 'get'}}, {showEffect: Element.show, hideEffect: Element.hide});
  //TooltipManager.addHTML("tooltip1", "tooltip_content2");
  //TooltipManager.addAjax("tooltip2", {url: "tooltip_ajax.html", options: {method: 'get'}});
  //TooltipManager.addURL("tooltip3", "tooltip_url.html", 200, 300);

function define_popups()
	{
		if(show_popup == 2)
			{
				show_popup = 1;
				var minus_icon = "<img src=\"/site_media/js/dasty2/client/img/notick01.gif\" border=\"0\" align=\"absbottom\">&#160;";
				var icon = document.getElementById("menu_mo_img_popups");
				icon.innerHTML = minus_icon;
			}
		else
			{
				show_popup = 2;
				var plus_icon = "<img src=\"/site_media/js/dasty2/client/img/tick01.gif\" border=\"0\" align=\"absbottom\">&#160;";
				var icon = document.getElementById("menu_mo_img_popups");
				icon.innerHTML = plus_icon;
			}
	}

		
		
// JavaScript Document

function progBar(percentage)
{
	//alert(percentage);
	var total_px = parseInt(progress_bar_width*percentage/100);
   	if (total_px <= progress_bar_width )
   	{
	    if (total_px > 40){document.getElementById("progress_bar_1").innerHTML = percentage + "%";}
     	document.getElementById("progress_bar_2").style.width = total_px + "px";	
   	}
}

function getPxWidthFromStyle(TagId)
{
	var width = document.getElementById(TagId).style.width;
	var width_value = width.split("px");
	return width_value[0];
}

function getPxHeightFromStyle(TagId)
{
	var height = document.getElementById(TagId).style.height;
	var height_value = height.split("px");
	return height_value[0];
}//------------------------------------------------------------------------------------------	
// MAKE A SEQUENCE REQUESTS
//------------------------------------------------------------------------------------------
	function makeSequenceRequest()
		{	
			makeRequest(sequence_url[0][1], 'sequenceXML'); // sequence_url is Global!
		}

//

//------------------------------------------------------------------------------------------	
// MAKE A STYLESHEET REQUESTS
//------------------------------------------------------------------------------------------
// I Should retrieve one stylesheet by Annotation server. By now I just will recover the uniprot one.

	function makeStylesheetRequest()
		{
			makeRequest(stylesheet_url[0][1], 'styleSheetXML'); // stylesheet_url is Global!
		}
//

//------------------------------------------------------------------------------------------	
// MAKE A DAS REGISTRY REQUESTS
//------------------------------------------------------------------------------------------


	function makeDasRegistryRequest()
		{
			makeRequest(das_registry_url, 'dasRegistryXML'); // stylesheet_url is Global!
		}
//

//------------------------------------------------------------------------------------------	
// MAKE SEVERAL FEATURE REQUESTS
//------------------------------------------------------------------------------------------
	  
function makeFeatureRequest(requestNumber)
	  {	
	    dasty2.validFirstSources = lookForSpecificSources(first_das_source);
		//printOnTest(dasty2.validFirstSources);
		
		if(dasty2.validFirstSources.length > 0)
			{	
				if(typeof requestNumber == "undefined")
					{
						var requestNumberTemp = 0;
					}
				else
					{
						var requestNumberTemp = requestNumber;
					} //if(requestNumber == null || requestNumber = '')	
					
					dasty2.firstRequestNumber = requestNumberTemp + 1;
					var featureXML_num = dasty2.validFirstSources[requestNumberTemp];
					var url = feature_url[featureXML_num].url;
					makeRequest(url, 'featureXML', featureXML_num);

			}
		 else
		 	{	dasty2.firstRequestNumber++;
				makeFeatureRequest2();
			} //if(first_das_source.length > 0)
	  }	  	  
	  
// Look for specific source names in the Source array file	"feature_url"  
function lookForSpecificSources(sources)
	{
		var sourceFound = [];
		for(var i = 0; i < sources.length; i++)
			{
				for(var h = 0; h < feature_url.length; h++)
					{
						//printOnTest(feature_url[h].id.toLowerCase() + " " + sources[i].toLowerCase());
						if(feature_url[h].id.toLowerCase() == sources[i].toLowerCase())
							{
								sourceFound.push(h);
							}
					}
			}
		return sourceFound;
	}
	


	  
				
function makeFeatureRequest2()
	  {				
	  			// RCJ: Make a aligment request
	  			
				if (isPDBVisible==true){
							parseAlignment(uniprot_pdb_alignment);
				}
				
	  			// RCJ: Make multiple feature request leaving out sources in "first_das_source"
				
				for(var h = 0; h < feature_url.length; h++)
					{
						duplicated = 0;
						
						for(var i = 0; i < first_das_source.length; i++)
				  		  {
							if(feature_url[h].id.toLowerCase() == first_das_source[i].toLowerCase())
								{
									duplicated = 1;
								}
						  }
						  
						if(duplicated == 0)
							{
								var featureXML_num = h;
								var url = feature_url[featureXML_num].url;
								makeRequest(url, 'featureXML', featureXML_num);
							}
					}
	  }


//------------------------------------------------------------------------------------------	
// REQUEST INFORMATION FROM DIFFERENT XML SPECIFIYING A LOCAL URL.
//------------------------------------------------------------------------------------------		
			
	  function makeRequest(url, xml_type, featureXML_num)
			{
				//alert("fn:" + featureXML_num);
				if (xml_type=='sequenceXML')
					{
						http_request.open('GET', url, true);
						http_request.onreadystatechange = parseSequenceXML;
                		http_request.send(null);
					}
				else if (xml_type=='featureXML')
					{
						ajax_feature(featureXML_num);
						//feature_http_request[featureXML_num] =  http_request;
						//feature_http_request[featureXML_num].onreadystatechange = parseFeatureXML;
						feature_http_request[featureXML_num].onreadystatechange = function()
							{
									parseFeatureXML(featureXML_num);
							};
						feature_http_request[featureXML_num].open('GET', url, true);
                		feature_http_request[featureXML_num].send(null);
						
						//alert("featureXML_num: " + featureXML_num);
					}
				else if (xml_type=='serverListXML')
					{
						http_request.open('GET', url, true);
						http_request.onreadystatechange = parseServerListXML;
                		http_request.send(null);
					}
				else if (xml_type=='styleSheetXML')
					{
						http_request.open('GET', url, true);
						http_request.onreadystatechange = parseStylesheetXML;
                		http_request.send(null);
					}
				else if (xml_type=='dasRegistryXML')
					{
						
						http_request.open('GET', url, true);
						http_request.onreadystatechange = parseDasRegistryXML;
                		http_request.send(null);						
						//ajax_elements("das_registry");
						//elements_http_request["das_registry"].open('GET', url, true);
						//elements_http_request["das_registry"].onreadystatechange = parseDasRegistryXML;
                		//elements_http_request["das_registry"].send(null);
					};
                
            }	// JavaScript Document
//------------------------------------------------------------------------------------------	
// SORTING
//------------------------------------------------------------------------------------------			
function sorting(sortby)
	{
	if(one_feature_list.length == 0 && isExpanded == 0)
	 	{
			var row = 0;
			

			for(var a = 0; a < new_feature_list_info2.length; a++)
				{
			//var opa = document.getElementById("display_test");
			//var content_opa = opa.innerHTML;
			//opa.innerHTML = (content_opa + " <br>------------<br>new_feature_list_info2[a]: " + new_feature_list_info2[a]);
				 if(new_feature_list_info2[a])
				   {
					for(var b = 0; b < new_feature_list_info2[a].length; b++)
						{
							one_feature_list[row] = new_feature_list_info2[a][b];
							one_feature_list[row]["xmlnumber"] = a;
							row++
						}
				   } // if(new_feature_list_info2[a])
				}
				
			
		//for(var lu = 0; lu < one_feature_list.length; lu++)
			//{
				//var new_feature_list = one_feature_list;
				//var opa = document.getElementById("display_test");
				//var content_opa = opa.innerHTML;
				//opa.innerHTML = (content_opa + " <br>------------<br>new_feature_list[" + lu + "][features]: " + new_feature_list[lu]["features"] + "::::: new_feature_list[" + lu + "][feature_group]: " + new_feature_list[lu]["feature_group"] + "::::: new_feature_list[" + lu + "][type]: " + new_feature_list[lu]["type"] + new_feature_list[lu]["category"] + new_feature_list[lu]["server"] + new_feature_list[lu]["xmlnumber"]);
			//}
	 	} //if(one_feature_list.length == 0 && isExpanded == 0)

	 
	 if (sortby)
	 	{ 
		  document.getElementById("system_information").innerHTML = "Dasty2 is sorting the graphic by " + sortby + " ...";
		  //alert("zoom beggining");
		  
/* NOT NECESSARY BECAUSE SORTING INCLUDED IN THE GRAPHIC  
		//------------------------------------------------
		// DRAW +/- ICON
		//------------------------------------------------
			var img_display_type = document.getElementById("menu_mo_img_type");
			var img_display_category = document.getElementById("menu_mo_img_category");
			var img_display_server = document.getElementById("menu_mo_img_server");
			var img_display_version = document.getElementById("menu_mo_img_version");
			
			var minus_icon = "<img src=\"img/noradio01.gif\" border=\"0\" align=\"absbottom\">&#160;";
			var plus_icon = "<img src=\"img/radio01.gif\" border=\"0\" align=\"absbottom\">&#160;";
			
			if(sortby == "type")
				{
					img_display_type.innerHTML = plus_icon; img_display_category.innerHTML = minus_icon;
					img_display_server.innerHTML = minus_icon; img_display_version.innerHTML = minus_icon;
				}
			else if (sortby == "category")
				{
					img_display_type.innerHTML = minus_icon; img_display_category.innerHTML = plus_icon;
					img_display_server.innerHTML = minus_icon; img_display_version.innerHTML = minus_icon;
				}
			else if (sortby == "server")
				{
					img_display_type.innerHTML = minus_icon; img_display_category.innerHTML = minus_icon;
					img_display_server.innerHTML = plus_icon; img_display_version.innerHTML = minus_icon;
				}
			else if (sortby == "version")
				{
					img_display_type.innerHTML = minus_icon; img_display_category.innerHTML = minus_icon;
					img_display_server.innerHTML = minus_icon; img_display_version.innerHTML = plus_icon;
				}
			
*/		  
		  
		  
		  //-------------------------------------------------
		  // ASC DES by Type
		  //-------------------------------------------------
		  if(sortOrderType == -1)
		     {
				sortOrderType = 1; // Descending
				sortOrderType2 = -1;
			 }
		   else
		     {
				 sortOrderType = -1; // Ascending
				 sortOrderType2 = 1;
			 }
			 
	      //-------------------------------------------------
		  // ASC DES by Method
		  //-------------------------------------------------
		  if(sortOrderMethod == -1)
		     {
				sortOrderMethod = 1; // Descending
				sortOrderMethod2 = -1;
			 }
		   else
		     {
				 sortOrderMethod = -1; // Ascending
				 sortOrderMethod2 = 1;
			 }			 
			 
		  //-------------------------------------------------
		  // ASC DES by Category
		  //-------------------------------------------------
		  if(sortOrderCategory == -1)
		     {
				sortOrderCategory = 1; // Descending
				sortOrderCategory2 = -1;
			 }
		   else
		     {
				 sortOrderCategory = -1; // Ascending
				 sortOrderCategory2 = 1;
			 }
		  //-------------------------------------------------
		  // ASC DES by Server
		  //-------------------------------------------------
		  if(sortOrderServer == -1)
		     {
				sortOrderServer = 1; // Descending
				sortOrderServer2 = -1;
			 }
		   else
		     {
				 sortOrderServer = -1; // Ascending
				 sortOrderServer2 = 1;
			 }
			 
		  //-------------------------------------------------
		  // ASC DES by Version
		  //-------------------------------------------------
		  if(sortOrderVersion == -1)
		     {
				sortOrderVersion = -1; // Ascending
				sortOrderVersion2 = 1;
			 }
		   else
		     {
				 sortOrderVersion = 1; // Descending
				 sortOrderVersion2 = -1;
			 }
		  //---------------------------------------------------------------------
		  // SORT "one_feature_list" by "sortby". Sort by indicate a colum number
		  //---------------------------------------------------------------------
		  if(isExpanded == 0)
		  	{
				sortCompactArray(sortby);
			}
		  else
		    {
				sortExpandedArray(sortby);
			}
		}	
	 
	 resetSortingVariables(sortby);
	 
	 var graphic_content = document.getElementById("display_graphic");
     graphic_content.innerHTML = '';
	 if(isExpanded == 0)
	 	{
			createGraphic2(0, "display_graphic", sequence_info.sequence_start, sequence_info.sequence_stop, "sorting");
		}
	 else
	 	{
			createGraphic2(0, "display_graphic", sequence_info.sequence_start, sequence_info.sequence_stop, "expanding");
		}
	 //Sortable.create('gr_list0',{ghosting:true,constraint:false}); // Simpler
	 Sortable.create('gr_list0', {onUpdate:function(){new Effect.Highlight('gr_list0', {startcolor:'#CCCCCC'});}});
	 
	 if (sortby) { document.getElementById("system_information").innerHTML = "<span style=\"color:#999999\">... Dasty2 finished to sort the graphic by " + sortby + "</span>"; }
	 
	} // function sorting(sortby)


  
function sortCompactArray(sortby)
  {

	switch (sortby)
	{
		case "type" :
			one_feature_list.sort(sortByType);
			break;
		case "method" :
			one_feature_list.sort(sortByMethod);
			break;
		case "category" :
			one_feature_list.sort(sortByCategory);
			break;
		case "server" :
			one_feature_list.sort(sortByServer);
			break;
		case "version" :
			one_feature_list.sort(sortByVersion);
			break;
	}
  } // function sortArray(column)
  
  
function sortExpandedArray(sortby)
  {

	switch (sortby)
	{
		case "type" :
			expanded_feature_list.sort(sortByType);
			break;
		case "method" :
			expanded_feature_list.sort(sortByType);
			break;
		case "category" :
			expanded_feature_list.sort(sortByCategory);
			break;
		case "server" :
			expanded_feature_list.sort(sortByServer);
			break;
		case "version" :
			expanded_feature_list.sort(sortByVersion);
			break;
	}
  } // function sortArray(column)
  
  
function sortByType(a, b)
  {
	var x = a.type.toLowerCase();
	var y = b.type.toLowerCase();
	return ((x < y) ? sortOrderType : ((x > y) ? sortOrderType2 : 0));
  } // function sortByType(a, b)

  
function sortByMethod(a, b)
  {
	var x = a.method.toLowerCase();
	var y = b.method.toLowerCase();
	return ((x < y) ? sortOrderMethod : ((x > y) ? sortOrderMethod2 : 0));
  } // function sortByType(a, b)
  

function sortByCategory(a, b)
  {
	var x = a.category.toLowerCase();
	var y = b.category.toLowerCase();
	return ((x < y) ? sortOrderCategory : ((x > y) ? sortOrderCategory2 : sortByType(a, b)));
  } // function sortByCategory(a, b)
  
function sortByServer(a, b)
  {
	var x = a.server.toLowerCase();
	var y = b.server.toLowerCase();
	return ((x < y) ? sortOrderServer : ((x > y) ? sortOrderServer2 : sortByType(a, b)));
  } // function sortByServer(a, b)

function sortByVersion(a, b)
  {
	var x = a.version;
	var y = b.version;
	return ((x < y) ? sortOrderVersion : ((x > y) ? sortOrderVersion2 : sortByServer(a, b)));
  } // function sortByVersion(a, b)

function resetSortingVariables(sortby)
	{
		if(sortby != "type") {sortOrderType = 0}
		if(sortby != "method") {sortOrderMethod = 0}
		if(sortby != "category") {sortOrderCategory = 0}
		if(sortby != "server") {sortOrderServer = 0}
		if(sortby != "version") {sortOrderVersion = 0}
	}

//-----------------------------------------------------
// Get url parameters
//-----------------------------------------------------
// FROM: http://www.11tmr.com/11tmr.nsf/d6plinks/MWHE-695L9Z
// Modified by Rafael Jimenez to get 2 formats

function getURLParam(strParamName)
{
  var strReturn = "";
  var strHref = document.location.href;
  if ( strHref.indexOf("?") > -1 )
  {
    var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
      
	if ( strHref.indexOf("&") > -1 )
  		{
			var aQueryString = strQueryString.split("&");	
		}
	else if ( strHref.indexOf(":") > -1 )
		{
			var aQueryString = strQueryString.split(":");	
		}

    for ( var iParam = 0; iParam < aQueryString.length; iParam++ )
	{
      if (
aQueryString[iParam].indexOf(strParamName + "=") > -1 )
	  {
        var aParam = aQueryString[iParam].split("=");
        strReturn = aParam[1];
        break;
      }
    }
  }
  return strReturn;
}


//-----------------------------------------------------
// Get the 3 posible different url parameters for Dasty
//-----------------------------------------------------
function getDastyURLParam(param01, param02, param03)
{
	var param = "";
	var url_param01 = getURLParam(param01); // Dasty2
	var url_param02 = getURLParam(param02); // Dasty1 by Biosapiens
	var url_param03 = getURLParam(param03); // Dasty1 by Dasty1
	
	if(url_param01 == null || url_param01 == "")
		{
			if(url_param02 == null || url_param02 == "")
				{
					if(url_param03 == null || url_param03 == "")
						{
							param = null;
						}
					else
						{
							param = url_param03.toUpperCase();
						}
				}
			else
				{
					param = url_param02.toUpperCase();
				}
		}
	else
		{
			param = url_param01.toUpperCase();
		}
	return param;
}


//-----------------------------------------------------
// If the URL is not right create a right one and
// start Dasty2
//-----------------------------------------------------

function setDastyURLParam(redirection) 
	{
		var count_null = 0;
		
		//var query_id_null_temp = query_id_null;
		if(typeof(query_id_null) == "undefined")
			{
				query_id_null = 0;
			}

			
		
		// label
		var url_label = getDastyURLParam("label", "display", "dis");
		if(url_label == null || url_label == "")
			{
				filterLabel = default_filterLabel;
				count_null++;
			}
		else
			{
				filterLabel = url_label;
			}
			
		// id
		var url_id = getDastyURLParam("q", "id", "ID");
		if( url_id == null || url_id == "")
			{
				query_id = default_query_id;
				if( default_query_id == null || default_query_id == "")
					{	
						query_id_null = 1;
					}
				else
					{
						count_null++;
					}
			}
		else
			{
				query_id = url_id;
			}
			
		// timeout
		var url_timeout = getDastyURLParam("t", "t", "t");
		if(url_timeout == null || url_timeout == "")
			{
				timeout = default_timeout;
				count_null++;
			}
		else
			{
				timeout = url_timeout;
			}
			
		if(query_id_null == 0 || redirection == "redirection")	
			{
				// Correct URL if it is not complete otherwise start Dasty2.
				if(count_null > 0 || redirection == "redirection")
					{
						//alert(createDastyURL() + " / " + count_null);
						document.location.href = createDastyURL()
					}
				else
					{
						start_globals();
					}
			}
		else
			{
				start_globals();
			}
	}


//-----------------------------------------------------
// Create Dasty URL
//-----------------------------------------------------

function createDastyURL(newId)
	{
		if(newId)
			{
				query_id = newId;
			}
		var new_url = dasty_mainpage_name + "?q=" + query_id + "&label=" + filterLabel + "&t=" + timeout;
		return new_url;
	}
	

//-----------------------------------------------------
// Create Dasty URL
//-----------------------------------------------------

function createDastyURLNewID(newId)
	{
			if (dasty_url_control == 0)
				{
					query_id = newId;
					
					var display_query = document.getElementById("display_query");
					display_query.innerHTML = "";
					var display_seque = document.getElementById("display_seque");
					display_seque.innerHTML = "";
					var display_server_checking = document.getElementById("display_server_checking");
					display_server_checking.innerHTML = "";
					var display_feature_details = document.getElementById("display_feature_details");
					display_feature_details.innerHTML = "";
					var display_graphic = document.getElementById("display_graphic");
					display_graphic.innerHTML = "";
					var display_nonpositional = document.getElementById("display_nonpositional");
					display_nonpositional.innerHTML = "";
					
					var display_test = document.getElementById("display_test");
					display_test.innerHTML = "";
					
					start_globals();
				}
			else
				{
					document.location.href = createDastyURL(newId);
				}
	}
	

//-----------------------------------------------------
// Redirect pages with other names to index.html
//-----------------------------------------------------

function DastyRedirector()
	{
		//configuration();
		//default_query_parameters()
		//dasty_mainpage_name = "display.html";
		
		//query_id = getURLParam("ID");
		//filterLabel = getURLParam("dis");
		//timeout = getURLParam("t");
		
		//query_id = "";
		//filterLabel = "";
		//timeout = 3;
		
		//default_filterLabel = "BioSapiens";
		//default_query_id = "P05067";
		//default_timeout = 3;
		
		setDastyURLParam("redirection");
		
		//if(query_id == null || query_id == "") {query_id = default_query_id;}
		//if(filterLabel == null || filterLabel == "") {filterLabel = default_filterLabel;}
		//if(timeout == null || timeout == "") {timeout = default_timeout;}
		
		//document.location.href = createDastyURL();
	}
	
	
function findDastyHtmlPageName(option)
	{
		var strHref = document.location.href;
		var protocol = document.location.protocol;
		var strHref_http = strHref.split(protocol + "//");
		var url_dir = strHref_http[1].split("/");
		var url_dir_count = url_dir.length;
		var url_page = url_dir[url_dir_count - 1];
		var url_page_name = url_page.split(".");
		var dasty_page_name = url_page_name[0];
		
		if(url_page_name.indexOf("?") > -1)
			{
				var url_page_ext = url_page_name[1].split("?");
				var dasty_ext_name = url_page_ext[0];
			}
		else if(url_page_name.indexOf("&") > -1)
			{
				var url_page_ext = url_page_name[1].split("&");
				var dasty_ext_name = url_page_ext[0];
			}
		else if(url_page_name.indexOf("#") > -1)
			{
				var url_page_ext = url_page_name[1].split("#");	
				var dasty_ext_name = url_page_ext[0];
			}
		else
			{
				var dasty_ext_name = url_page_name[1]
			}
		
		if(option == 'ext_name')
			{
				return dasty_ext_name;
			}
		else if(option == 'page_name')
			{
				return dasty_page_name;
			}
		else
			{
				return dasty_page_name;
			}
	}
	
	
//-----------------------------------------------------
// Old function createDastyURL()
//-----------------------------------------------------
/*
function createDastyURL()
	{
		var strHref = document.location.href;
		var strQueryString = strHref.split("?");
    	var url = strQueryString[0];
		if(url[url.length -1] == "/")
			{
				var url_options = dasty_mainpage_name + "?q=" + query_id + "&label=" + filterLabel + "&t=" + timeout;
			}
		else
			{
				var url_options = "?q=" + query_id + "&label=" + filterLabel + "&t=" + timeout;
			}
		var new_url = url + url_options;
		return new_url;
	}
*/
//-----------------------------------------------------


//-----------------------------------------------------
// Old function DastyRedirector(file)
//-----------------------------------------------------
/**
 * Dasty 1.0 redirector.
 *
 * Requires:
 * - DastyConfig.js
 *
 * @author  Antony Quinn
 * @version $Id$
 * Modified by Rafel Jimenez
 * The modified version don't require DastyConfig.js
 */

/**
 * Redirects URLs of the form:
 * content?ID=<id>:dis=<label>
 * to:
 * <file>?q=<id>&label=<label>
 *
 * @param file File to redirect to, eg. index.html
 */
 
 /*
function DastyRedirector(file) {
    var id = "", label = "";
    var query = document.location.search.substring(1);
	alert(query);
    var params = query.split(":");
    if (params.length > 0)  {
        id = params[0].split("=")[1];
    }
    if (params.length > 1)  {
        label = params[1].split("=")[1];
    }
    //var url = file + "?" + QueryParamKeys.id + "=" + id;
	var url = file + "?" + "q" + "=" + id; // Rafael modification
    if (label.length > 0)   {
        //url += "&" + QueryParamKeys.registryLabel + "=" + label;
		url += "&" + "label" + "=" + label; // Rafael modification
    }
    //alert(url);
    document.location.href = url;
}
*/
//-----------------------------------------------------
// JavaScript Document
//------------------------------------------------------------------------------------------	
// ZOOM
//------------------------------------------------------------------------------------------			
function zoom(startId, endId)
	{
		document.getElementById("system_information").innerHTML = "";
		document.getElementById("system_information").innerHTML = "Dasty2 is zooming the graphic ...";
		zoom_start = parseInt(document.getElementById(startId).value - 1);
		zoom_end = parseInt(document.getElementById(endId).value);
		//alert("zoom beggining");
		
		if (isNaN(zoom_start) == true || isNaN(zoom_end) == true)
		  {
			  document.getElementById("system_information").innerHTML = "<span style=\"color:#CC0000\">One of the zoom values is not a number. </span><br />... Please correct it and try again.";
		  }
		else
		  {
			//alert(zoom_start + "/" + zoom_end);
			
			var seq_start = parseInt(sequence_info.sequence_start -1);
			var seq_stop = parseInt(sequence_info.sequence_stop);
			
			var temp_zoom_end = zoom_end;
			var temp_zoom_start = zoom_start;
			
			var zoom_message = "";
			var zoom_message2 = "";
			var zoom_error = 0;
			//if(temp_zoom_start > temp_zoom_end){zoom_start = seq_start; zoom_end = seq_stop;}
			//var temp_zoom_end = zoom_end;
			//var temp_zoom_start = zoom_start;
			//if(temp_zoom_start < seq_start){zoom_start = seq_start;}
			//if(temp_zoom_end > seq_stop){zoom_end = seq_stop;}
			
							if(temp_zoom_start < 0 && temp_zoom_end < 0)
							  {
								  zoom_message = "Zoom error! ... The start and end zoom value can not be negative."; 
								  zoom_message2 = "... Please correct it and try again."
								  zoom_start = seq_start;
								  zoom_end = seq_stop;
								  zoom_error = 1;
							  }
							else if(temp_zoom_start < 0 && temp_zoom_end > 0)
							  {
								  if(temp_zoom_end > seq_stop)
									{
										zoom_message = "Zoom error! ... The start zoom value can not be negative and the end zoom value can not be greater than the lenght of the sequence.";  
										zoom_message2 = "... Please correct it and try again."
										zoom_end = seq_stop;
										zoom_start = seq_start;
										zoom_error = 1;
									}
								  else
									{
										zoom_message = "Zoom error! ... The start zoom value can not be negative.";
										zoom_message2 = "... Dasty2 finished to zoom the graphic setting the start zoom value to " + (seq_start + 1)
										zoom_start = seq_start;
										zoom_error = 2;
									}
							  }
							else if(temp_zoom_start > 0 && temp_zoom_end < 0)
							  {
								  if(temp_zoom_start > seq_stop)
									{
										zoom_message = "Zoom error! ... The end value can not be negative and the start value can not be greater than the lenght of the sequence."; 
										zoom_message2 = "... Please correct it and try again."
										zoom_end = seq_stop;
										zoom_start = seq_start;
										zoom_error = 1;
									}
								  else
									{
										zoom_message = "Zoom error! ... The end zoom value can not be negative."; 
										zoom_message2 = "... Dasty2 finished to zoom the graphic setting the end zoom value to " + seq_stop
										
										zoom_end = seq_stop;
										zoom_error = 2;
									}
								  
							  }
							else if(temp_zoom_start > seq_stop && temp_zoom_end > seq_stop)
							  {
								  zoom_message = "Zoom error! ... The start and end zoom value can not be greater than the lenght of the sequence.";
								  zoom_message2 = "... Please correct it and try again."
								  
								  zoom_start = seq_start;
								  zoom_end = seq_stop;
								  zoom_error = 1;
							  }		
							 
							 
							var temp_zoom_end = zoom_end;
							var temp_zoom_start = zoom_start;
							
							if(temp_zoom_start > temp_zoom_end && zoom_error == 0)
								{
									zoom_message = "Zoom error! ... The start zoom value can not be greater than end zoom value.";
									zoom_message2 = "... Please correct it and try again."
									
									zoom_start = seq_start;
									zoom_end = seq_stop;
									zoom_error = 1;
								}
			
			
			//alert(zoom_start + "/" + zoom_end + "/" + temp_zoom_end + "/" + seq_stop);
			if(zoom_error == 0)
				{
					sorting();
					document.getElementById("system_information").innerHTML = "<span style=\"color:#999999\">... Dasty2 finished to zoom the graphic.</span>";
				}
			else if(zoom_error == 1)
				{
					// Display warning message
				}
			else if(zoom_error == 2)
				{
					// Execute sort() and display warning message
					sorting();
				}
				
			if(zoom_error == 1 || zoom_error == 2)
				{
					document.getElementById("system_information").innerHTML = "<span style=\"color:#CC0000\">" + zoom_message + "</span><br><span style=\"color:#999999\">" + zoom_message2; + "</span>"
				}
			
	  } // if (isNaN(zoom_start) == true || isNaN(zoom_end) == true)
	}
	
function resetZoom(startId, endId)
	{
		zoom_start = parseInt(sequence_info.sequence_start) - 1;
		zoom_end = parseInt(sequence_info.sequence_stop);
		//alert(zoom_start + "/" + zoom_end);
		document.getElementById(startId).value = zoom_start + 1;
		document.getElementById(endId).value = zoom_end;
		
		document.getElementById("system_information").innerHTML = "Dasty2 is resetting the graphic zoom to the default values ...";
		sorting();
		document.getElementById("system_information").innerHTML = "<span style=\"color:#999999\">... Dasty2 finished to reset the zoom values for the graphic.</span>";
	}
