function hide_node(id) {
var node=document.getElementById(id);
node.style.display = "none";
};

function show_node(id) {
var node=document.getElementById(id);
node.style.display = "";
};

function isblank(s)
{
    if(s == "http://") return true;
	for( var i = 0; i < s.length; i ++ )
	{
		var	c = s.charAt(i);
		if( (c != ' ') && (c != '\n') && (c != '') && (c != '\t') )
			return false;
	}
	return true;
}

var newRowsChromo = 0;

function drawZebra () {
  var elements = cssQuery(".chromos_zebra tbody tr");
  for (var i = 1; i < elements.length; i++)
     { 
	 var cellnumber = document.createTextNode(i);
 	 elements[i].getElementsByTagName("td").item(0).innerHTML = i;
	  if (i % 2) { 
			removeClass(elements[i], "altrow");  		
		} else {
			addClass(elements[i], "altrow");
		 	}
	 }
  if ( newRowsChromo > 0 ) { 
  	document.getElementById("chromos_table").style.display = "block";
// 	document.getElementById("add_another_chrom").style.display = "block"; 
//	document.getElementById("chromsize").disabled = true;
  } else {
	document.getElementById("chromos_table").style.display = "none";
//	document.getElementById("add_another_chrom").style.display = "none"; 
//	document.getElementById("chromsize").disabled = false;
  }
  //document.MPFORM.chromsize.value = newRowsChromo;
}

function deletetablerows() {
	  var elements = cssQuery(".chromos_zebra tbody tr");
  	  for (var i = 1; i < elements.length; i++)
      {
	  	var trparent = elements[i].parentNode;
		trparent.removeChild(elements[i]);
	  } 
	  newRowsChromo = 0;
	  newRowsCounter = 0;
}

function addtable(tab, lable, size) {
    var elements = cssQuery(".chromos_zebra tbody tr input.text_sm2");
	if (elements.length > 0) {
		for (var i = 0; i < elements.length; i++)
     	{ 
		if (elements[i].value != "") {	
			agree=confirm("Your current Chromosomes table is NOT empty !\n Do you want to delete old table and create NEW one?"); 
			if (!agree) { return; }
			break;
			}
		}
	}
//	rc != -1? rc : null;
//	var rows = size?size:document.MPFORM.chromsize.value;
	//if (size > 0) { var rows = size; } else { var rows = document.MPFORM.chromsize.value;}
	if (size > 2) { var rows = size; } else { var rows = 2;}
	if (rows <= 0) return;
	deletetablerows();
	for (var i=0; i < rows; i++) {
 	addrow(tab, lable);
  }
 drawZebra();
}

function addrow(tab, lable) {
	newRowsCounter++;
	if (lable == "Chromo") { newRowsChromo++; newRowsCounter = newRowsChromo; }
	if (lable == "Contact") { newRowsContact++; newRowsCounter = newRowsContact; }
	
	var src  = document.getElementById(tab).getElementsByTagName("tfoot")[0].getElementsByTagName("tr")[0];
	var dest = document.getElementById(tab).getElementsByTagName("tbody")[0];

	var srcopy = src.cloneNode(true);
	retainNames (srcopy.getElementsByTagName("input"));
	retainNames (srcopy.getElementsByTagName("select"));
	dest.appendChild(srcopy);
	
	// Assume the "remove" tag is the first and only link in the <tr></tr>
	var alink = srcopy.getElementsByTagName("img");
	if (alink) {
	   alink = alink.item(0);
	   alink.myrow = srcopy;
	   alink.lable = lable;
	   alink.onclick = remrow;
	}
}
function remrow(event)		// if presents row will not removed but hided with display:none
{
	var target;
            if (event) {  // mozilla et al
                target = event.target;
            } else {  // IE
                event = window.event;
				target = event.srcElement;
			}
	if (target.myrow) {
		remcheck(target.myrow);
		var trparent = target.myrow.parentNode;
		if (!rowcanDel) {
			agree=confirm("This row is NOT empty !\n Are you sure you want to Delete it?"); 
			if (!agree) { return false; }
		}
		trparent.removeChild(target.myrow);
		//if (target.lable == "Chromo") newRowsChromo--; 
		//if (target.lable == "Contact") newRowsContact--; 
		
	}
 drawZebra();
return false;
}

var rowcanDel = true;

function remcheck(rowelements, second) {
		
		if (!second) rowcanDel = true;
		var crow = rowelements;
		if (crow.getElementsByTagName("input").length > 0) {
		var crowarray = crow.getElementsByTagName("input");
		for (var i = 0; i < crowarray.length; i++)
     	{ 
		if (crowarray[i].tagName !='INPUT') { break; }
		if (crowarray[i].value != "" && crowarray[i].value != "http://") {	
  			rowcanDel = false;
			break;
			}
		  }
		}
}

function rem2rows(event)		// if presents row will not removed but hided with display:none
{
	var target;
            if (event) {  // mozilla et al
                target = event.target;
            } else {  // IE
                event = window.event;
				target = event.srcElement;
			}
	if (target.myrow) {
		remcheck(target.myrow);
		remcheck(target.myrow2, 1);
		if (!rowcanDel) {
			agree=confirm("This row is NOT empty !\n Are you sure you want to Delete it?"); 
			if (!agree) { return false; }
		}
		var trparent = target.myrow.parentNode;
		trparent.removeChild(target.myrow);
		trparent.removeChild(target.myrow2);
		//if (target.lable == "Chromo") newRowsChromo--; 
	}
return false;
}

var newRowsOrgan = 0;
var newRowsCenter = 0;
var newRowsContact = 0;
var newRowsCounter = 0;

function add2rows(tab, lable) {
	newRowsCounter++;
	if (lable == "Organ") { newRowsOrgan++; newRowsCounter = newRowsOrgan; }
	if (lable == "Center") { newRowsCenter++; newRowsCounter = newRowsCenter; }
	
	var src  = document.getElementById(tab).getElementsByTagName("tfoot")[0].getElementsByTagName("tr")[0];
	var src2  = document.getElementById(tab).getElementsByTagName("tfoot")[0].getElementsByTagName("tr")[1];
	var dest = document.getElementById(tab).getElementsByTagName("tbody")[0];
	var srcopy = src.cloneNode(true);
	var srcopy2 = src2.cloneNode(true);
	dest.appendChild(srcopy);
	dest.appendChild(srcopy2);
	retainNames (srcopy.getElementsByTagName("input"));
	retainNames (srcopy2.getElementsByTagName("input"));
	retainNames (srcopy.getElementsByTagName("select"));
	retainNames (srcopy2.getElementsByTagName("select"));
	
	// Assume the "remove" tag is the first and only link in the <tr></tr>
	var alink = srcopy.getElementsByTagName("img");
	
	if (alink) {
	   alink = alink.item(0);
	   alink.myrow = srcopy;
   	   alink.myrow2 = srcopy2;
	   alink.lable = lable;
	   alink.onclick = rem2rows;
	}
    
//	if (typeof suggest == "object") suggest.load();
    
//return false;
}

function retainNames (rowcopyFields) {
	for (var i=0; i < rowcopyFields.length; i++) {
        //rowcopyFields[i].form = document.MPFORM;
		var theName = rowcopyFields[i].name; 
		//if (theName) {
			if (rowcopyFields[i].type == "radio") {
				rowcopyFields[i].value = theName + newRowsCounter;
			} else {
				rowcopyFields[i].name = theName + newRowsCounter;
				rowcopyFields[i].id = theName +  newRowsCounter;  // IE can't find just created elements by name, so it needs ID.
                if (rowcopyFields[i].tagName == "SELECT") {                	
                    var opts = rowcopyFields[i].getElementsByTagName("OPTION");
                    for (var j=0; j < opts.length; j++) {//IE 6 looses attributes
                        opts[j].defaultSelected = document.getElementById(theName).getElementsByTagName("OPTION")[j].defaultSelected;
                        opts[j].selected = document.getElementById(theName).getElementsByTagName("OPTION")[j].selected;
                        opts[j].value = document.getElementById(theName).getElementsByTagName("OPTION")[j].value;
                    }
                }else rowcopyFields[i].defaultValue = document.getElementById(theName).defaultValue //IE 6 looses defaultValue at cloning for text input
			}
		//}
	}
}

function ClearProjectType()
{
    singles();
}

function clearAll(nodeName) {

   var sMessage = "Are you sure you want to clear all data from the submission form?";
   if(nodeName == "clearblock2") sMessage = "Are you sure you want to clear all optional fields?";
   if(!confirm(sMessage)) return false;
   if (!document.getElementById) return false
   var node=document.getElementById(nodeName);

   if (node) {
      var cbs = node.getElementsByTagName("INPUT")
	  var cbsarea = node.getElementsByTagName("TEXTAREA")
      for (var i = 0; i < cbs.length; i++) {
         var cb = cbs[i]
         if (cb.getAttribute("TYPE").toUpperCase() == "CHECKBOX") {
            cb.checked = false;
         } else if(cb.id == "single_tag") {//special case
              ClearProjectType();
         } else {
            cb.value = cb.defaultValue; 
		 }
      }
      for (var i = 0; i < cbsarea.length; i++) {
		 cbsarea[i].value = cb.defaultValue; 
	  }
      //select
      var sels = node.getElementsByTagName("SELECT");
      for (var i = 0; i < sels.length; i++) {
        var opts = sels[i].getElementsByTagName("OPTION");
        for (var j = 0; j < opts.length; j++) {
            opts[j].selected = opts[j].defaultSelected;
        }
      }
   }
   return false;
}

// className functions

function changeClass(id, newClass) {
cId=document.getElementById(id);
cId.className=newClass;
}

function addClass(element, className) {
if (!hasClass(element, className)) {
if (element.className) element.className += " " + className;
else element.className = className;
}
};

function removeClass(element, className) {
var regexp = new RegExp("(^|\\s)" + className + "(\\s|$)");
element.className = element.className.replace(regexp, "$2");
};

function hasClass(element, className) {
var regexp = new RegExp("(^|\\s)" + className + "(\\s|$)");
return regexp.test(element.className);
};

function metagenomic() {
hide_node("orgname_strain_div");
show_node("project_name_div");
onLinkOver("datadescr_label", lbl_datadescr_met);
hide_node("chromo_block");
document.getElementById("metagenomic_tag").checked = true;
};

function set_private() {
document.getElementById("is_private").checked = true;
};

function singles() {
show_node("orgname_strain_div");
hide_node("project_name_div");
onLinkOver("datadescr_label", lbl_datadescr_org);
show_node("chromo_block");
document.getElementById("single_tag").checked = true;
};

function SetValue(id, value) {
var node = document.getElementById(id);
if(isblank(value)) node.value = '';//node.defaultValue;
else node.value = value;
};

function SetSelectOption(id, option) {
  var opts = document.getElementById(id).getElementsByTagName("option");
  for (var i = 0; i < opts.length; i++) {
    if(opts[i].value == option) {
      opts[i].selected = true;
      return;
    }
  }
}

function TestCheck() {
    document.MPFORM.submit();
}

function FillLastCenter(parent_node_id, name, url) {
    var textinp = document.getElementById(parent_node_id).getElementsByTagName("input");
    textinp[textinp.length - 1].value = url;
    textinp[textinp.length - 2].value = name;
}

var FilledOrgans = 0;
var FilledCenters = 0;

//	for initial (on load) fill up (from CGI) only.
//	works only until Center is added or deleted.
function AddCenter(lable, name, url) 
{
    if(lable == "Organ") {
        if(newRowsOrgan < FilledOrgans) add2rows("organ_dd", "Organ");
        FillLastCenter("organ_dd", name, url);
        FilledOrgans++;
    } else if(lable == "Center") {
        if(newRowsCenter < FilledCenters) add2rows("center_dd", "Center");
        FillLastCenter("center_dd", name, url);
        FilledCenters++;
    } else if(lable == "Consor") {
        FillLastCenter("consor_dd", name, url);
    }    
}

var FilledContacts = 0;

//	for initial (on load) fill up (from CGI) only.
//	works only until Contact is added or deleted.
function AddContact(fname, lname, url) 
{
    if(newRowsContact < FilledContacts) addrow("contact_dd", "Contact");
    ++FilledContacts;
    var textinp = document.getElementById("contact_dd").getElementsByTagName("input");
    textinp[textinp.length - 1].value = url;
    textinp[textinp.length - 2].value = lname;
    textinp[textinp.length - 3].value = fname;
}

var FilledChromo = 0;

//	for initial (on load) fill up (from CGI) only.
//	works only until Chromo is added or deleted.
function AddChromo(name, size, type) 
{
    if(newRowsChromo <= FilledChromo) {
        addrow('chromos_dd', 'Chromo');
        drawZebra();
    }
    ++FilledChromo;
    document.getElementById("chr_name" + FilledChromo).value = name;
    document.getElementById("chr_size" + FilledChromo).value = size;
    SetSelectOption("chr_type" + FilledChromo, type);
}

//server messages
var empty_msg = "";
var correct_error_msg = 'Please correct the following problem:<br>';
var double_project_msg = '';
var prefix_is_taken_msg = 'Sorry, this locus tag prefix was taken. Please choose another one.<br>Locus tag prefix availability could be checked <a target="_blank" href="http://www.ncbi.nlm.nih.gov/genomes/lltp.cgi">here</a>.';
var wrong_prefix_format_msg = 'Locus tag prefix format is wrong. Please refer to <a target="_blank" href="http://www.ncbi.nlm.nih.gov/genomes/locustag/Proposal.pdf">Prefix Format Help</a>.<br>';
var server_down_message = 'Server is temporary down for maintenance. Please try again later or contact&nbsp;&nbsp;<a href="mailto:genomes@ncbi.nlm.nih.gov">genomes@ncbi.nlm.nih.gov</a><br>';

// tip messages

var tip_default_msg = 'Brief help messages are available for every field. If you have further questions, please examine the help document available on the left side menu, or send a message to:<a href="mailto:genomes@ncbi.nlm.nih.gov">genomes@ncbi.nlm.nih.gov</a>';
var tip_metagenomic_msg = "If you are submitting the combined genomic sequences of all organisms from a given environment (ex. Sargasso Sea project) then select this category.";
var tip_single_species_msg = "Default sequencing projects consist of the genome sequence of a single organism.";
var tip_organism_msg = "Add the correct taxonomic name of the organism for which you are sequencing the genome (Ex: Escherichia coli).";
var tip_project_msg = "Add the project name.";
var tip_strain_msg = "Add a strain, breed, or isolate name that will distinguish this organism from those that are closely related."
var tip_fname_msg = "Enter the first name of the person who can be contacted by database staff regarding their Genome Project submission."
var tip_lname_msg = "Enter the lastname of the person who can be contacted by database staff regarding their Genome Project submission."
var tip_email_msg = "Enter the full email address of the person who can be contacted by database staff regarding his/her Genome Project submission. (Ex: jsmith@university.edu)"
var tip_dnasource_msg = "Enter the location (academic laboratory, ATCC, etc.) or person (principal investigator, laboratory name) where the DNA that was used in this sequencing project can be obtained by interested third parties."
var tip_suborgan_msg = 'Enter the complete name of the organization that is submitting this Genome Project (Ex: TIGR). If there is more than one submitter, click on the "Add Another Organization" link for additional fields.'
var tip_suburl_msg = "Enter the submitter's web address for the submitting organization (if any)."
var tip_seqcenter_msg = 'Enter the complete name of the Center where the DNA was sequenced if it is different than the submitter. If there is more than one Sequencing Center, click on the "Add Another Center" link for more fields.'
var tip_sequrl_msg = "Enter the web address for the Sequencing Center (if any)."
var tip_consname_msg = "Enter the complete name of the Consortium that is submitting this Genome Project (Ex: International Human Genome Sequencing Consortium)."
var tip_consurl_msg = "Enter the web address for the Consortium (if any)."
var tip_seqmethod_msg = "Enter the method by which the Genome Sequence was obtained (Ex: whole genome shotgun sequencing, clone-based sequencing, etc.)."
var tip_seqtechno_txt_msg = "Enter other technology which was used for sequencing."
var tip_seqtechno_msg = "Check appropriate technologies which were used for sequencing (Ex: ABI-style traces, 454/Solexa-style reads, etc.)."
var tip_seqdepth_msg = "Enter the average sequencing depth or coverage for the genomic data (Ex: 8X)."
var tip_tag_auto_msg = "Allow database staff to automatically assign a locus tag prefix for this genome."
var tip_tag_manual_msg = 'Manually enter your own locus tag prefix for this genome. If you leave it blank, the prefix will be assigned automatically.'
var tip_chromnumber_msg = 'Enter the total number of chromosomes that will be sequenced for this particular Genome Sequencing Project (if known) and click "Update Table" button to show input fields, click "Add Chromosome" to add one name.'
var tip_chrns_msg = "Enter the individual replicon name, size (in megabases), and type."
var tip_chromsize_msg = "Enter the total size of the genome (in megabases) for this particular organism (if known)."
var tip_projecturl_msg = "Enter the submitter's web address for this specific Genome Sequencing Project (if any)."
var tip_dataurl_msg = "Enter the submitter's web address for data access for this specific Genome Sequencing Project if different than above (if any)."
var tip_datadescr_msg = "Enter a brief description of why the genome sequence of this organism (especially the breed, strain, or isolate) is important to the scientific community. If you are submitting a metagenomic project then explain the environment that is being studied."
var tip_chromsizes_msg = "Enter the total size of the genome (in megabases) for this particular organism (if known)."
var tip_indivchromos_msg = "Enter the chromosome names/numbers for this particular oragnism and separate each one with a comma (Ex: I, II, III, IV)."
var tip_is_private_msg = 'Check the check box if you want the submission to be confidential.'
var tip_metatype_msg = 'Select metagenomic type.'
var tip_comment_msg = 'Comment to database staff. This text does not appear in any public view.'
//label texts

var lbl_datadescr_org = 'Brief description of the importance of this organism to the scientific world:'
var lbl_datadescr_met = 'Brief description of the importance of this project to the scientific world:'

function CheckBlank(descr, id)
{
    var el = document.getElementById(id);
    if(isblank(el.value)) {
        alert("Please provide\n" + descr);
        el.focus();
        el.onfocus();
        return true;
    }
    return false;
}

function CheckLocusTag()
{
    var lt = document.getElementById('enter_tag_input');
    if(isblank(lt.value)) {
        if(confirm('You have not provided a locus tag prefix. Do you want one to be assigned for you?')) return false;
        else {
            lt.onfocus();
            lt.focus();
            return true;
        }
    }
    return false;
}

function CheckSubmit()
{
    if(CheckBlank("Contact's First Name", "fname0")) return;
    if(CheckBlank("Contact's Last Name", "lname0")) return;
    if(CheckEmail(document.getElementById("email0"))) return;
    if(CheckBlank("Submitting Organization", "suborgan0")) return;
    if(document.getElementById('single_tag').checked) {//single project
        if(CheckBlank("Organism Name", "organism")) return;
        if(CheckBlank("Strain/isolate/breed", "strain")) return;
    } else {
        if(CheckBlank("Project Name", "project_name")) return;
    }
    if(CheckLocusTag()) return;
    document.MPFORM.max_center_num.value = newRowsCenter + 1;
    document.MPFORM.max_organ_num.value = newRowsOrgan + 1;
    document.MPFORM.max_contact_num.value = newRowsContact + 1;
    document.MPFORM.max_chromo_num.value = newRowsChromo + 1;
    //!YG	remove alert prior submission
    //alert('Submission processing will take few seconds. Please wait for conformation page. Do not click on "submit project" again, it will cause extra submission!');
    //alert('Submitting...');
    document.MPFORM.submit();
}
function writecookie()
{
	if( document.MPFORM.ContactName.value == "" && document.MPFORM.ContactEMAIL.value == "" )
		return;

	var d = new Date();
		d.setFullYear(2100);
	var c = escape( document.MPFORM.ContactName.value + "|" +  document.MPFORM.ContactEMAIL.value );
		document.cookie = "submitterContactInfo=" + c + "; expires=" + d.toGMTString();
}
function readcookie()
{
	var	c = document.cookie;
	var	s = c.indexOf("submitterContactInfo=");
		if( s == -1 )
			return;
		s = s + 21;
	var	e = c.indexOf(";", s);
		if( e == -1 ) e = c.length;
	var	v = unescape(c.substr( s, e ));
	var	contact = v.split( '|' ); 
		document.MPFORM.ContactName.value = contact[0];
		e = contact[1].indexOf(";", 0);
		if( e == -1 ) e = contact[1].length;
		document.MPFORM.ContactEMAIL.value = contact[1].substr(0,e);
}
function CheckEmail(e)
{
	var p = /^((\w|\d|-|_)([-_.\w\d]*)@([-_.\w\d]+)(-|_\w|\d|(\s*))(,*))+/;
	var r = e.value.match( p );
	if( r != null )
		return false;
	else
	{
	var msg = 'Wrong email adress' + '\n' + e.value;
		alert( msg );
		e.focus();
		e.onfocus();
	}
	return true;
}

function checkSeqTechno(e)
{
var r = document.getElementById('seqtechno');
	if( e.checked == true )
		r.value = parseInt(r.value) + parseInt(e.value); 
	else 
		r.value = parseInt(r.value) - parseInt(e.value); 
}

function setSeqTechnoCheck( value, id )
{
var e = document.getElementById( id );
	if( e )
	{
		if( (parseInt(e.value) & parseInt(value)) == parseInt(e.value) )
		{
			e.checked = true ;
		}
	}
}

function setSeqTechno()
{
var e = document.getElementById('seqtechno');
var a = ['Other','Sanger','ABI','454','Solexa'];	

	if( e && e.value > 0 )
	{
		for( var i = 0; i < a.length; i ++ ) setSeqTechnoCheck( e.value, 'seqtechno' + a[ i ] );
	}
}

//!YG ------------------ email-specific code ------

function alertEmail( isok, text )
{
	//var msg = isok ? "E-mail notification has been sent\n" : "E-mail notification has not been sent\n";
	
	alert( text );
}
