/*
 * file: blastsearch.js
 * 
 * purpose: javascript used solely by BLAST UI page.
 * 
 * history
 *    11/13/09  eksc  created
 */
var targets = new Array();
var selected_source;

function addDataset() {
   var datasets_el = document.getElementById('datasets');
   var index = datasets_el.selectedIndex;

   var dataset_str = datasets_el.options[index].value;

   if (dataset_str == '') {
      return;
   }
   var dataset_str_ret = dataset_str.split('|');
   var blastDB_source = dataset_str_ret[0];
   var blastDB_db = dataset_str_ret[1];
   var blastDB_name = dataset_str_ret[2];
   var blast_info = dataset_str_ret[3];
   var db_index = dataset_str_ret[4];

   var selected_datasets_el = document.getElementById('selected_datasets');

   var datasets = new Array();
   if (selected_datasets_el.value != "") {
      datasets = selected_datasets_el.value.split('|');
   }

   datasets.push(blastDB_source + '--' + blastDB_db + '--' + blastDB_name
         + '--' + db_index);
   datasets.sort();
   datasets = uniq(datasets);
   selected_datasets_el.value = datasets.join('|');

   var html_str = createDatasetHTML(datasets, index);
   var datasetdiv_el = document.getElementById('datasetdiv');
   datasetdiv_el.innerHTML = html_str;

   if ((datasets.length > $('#MAX_DATASET_TARGETS').val())
         && ($('#email').val() == '')) {

      alert("You have selected a large number of datasets which may take "
            + "several minutes to process. Please consider providing an "
            + "email address to receive confirmation of your results.");
   }
}//addDataset


function addExample() {

   if (document.blastform.sequence.value == "") {

      var example_sequence = ">gi|162463221|ref|NM_001112073.1| Zea mays liguleless1 (lg1), mRNA\n";
      example_sequence += "CGATCGATCGAGATATCGTGTCAACGTGCCGGCCGGGGCGTGGGAAGATGATGAACCTATCGGCTGCCGC\n";
      example_sequence += "CAACGGCCGCGACGAGTTCCCCCCCTACGTCGTGCCGTCCAACGCGGCCGCTCCGCCCCCTTCCCTGCTC\n";
      example_sequence += "CCAACCATGGAGCAGCAGCAGGAGAGCAGCATCCACAGGGAGCATCATCAGCTGCTGGGCTACAACCTCG\n";
      example_sequence += "AGGCCAACTCGCTGGCCCTCCTGCCCCCGTCCAACGCCGCCGCCGCCCACCACCACACCACCTTCGCCGG\n";
      example_sequence += "CGGCCACAGCCCCCACGACATCCTCCACTTCTACACACCTCCTCCTTCCGCCGCCTCGCACTACCTCGCC\n";
      example_sequence += "GCCGCCGCCGGCAACCCCTACAGCCACTTAGTCTCCGCGCCCGGGACCACCTTCCACCAGACCTCGTCGT\n";
      example_sequence += "CCTACTACCCGCCCGCGGCGGCGGCGCAGGCCGCGCCCGAGTACTACTTCCCCACCCTCGTCAGCTCCGC\n";
      example_sequence += "CGAGGAGAACATGGCCAGCTTCGCCGCCACGCAGCTCGGCCTCAACCTCGGCTACCGCACCTACTTCCCG\n";
      example_sequence += "CCCAGAGGAGGCTACACGTACGGCCACCACCCGCCGCGCTGCCAGGCCGAGGGCTGCAAGGCCGACCTCT\n";
      example_sequence += "CCAGCGCCAAGCGATACCACCGTCGCCACAAGGTGTGCGAGCACCACTCCAAGGCGCCCGTCGTCGTCAC\n";
      example_sequence += "CGCCGGTGGACTGCATCAGAGGTTCTGCCAGCAGTGCAGCAGATTCCATCTGCTGGATGAGTTCGACGAT\n";
      example_sequence += "GCTAAGAAGAGCTGCAGGAAACGCCTAGCGGACCACAACCGCCGCCGCCGGAAGTCAAAGCCATCGGATG\n";
      example_sequence += "CTGATGCCGGAGACAAGAAAAGGGCACATGCGAACAAAGCAGCTGCAGCTAAAGACAAAGCAGAGAGTAG\n";
      example_sequence += "CAGCAAGAACATGGATATCGGAGATGGGTTAGGCGCACAGATACTGGGAAGTGCACTCTTGTCCAAGGAA\n";
      example_sequence += "CAAGATCAAACCATGGATCTTGGAGAGGTGGTGAAAGAAGCAGTGGATCCCAAGGGGAAGGCATCAATGC\n";
      example_sequence += "AACAGCATTACGGCTTCCCCTTCCATTCGTCGTCAGCAGGATCTTGCTTCCCCCAGACCCAAGCCGTCTC\n";
      example_sequence += "CAGTGATACCACATCCAATATAGGTCAAGTGCAAGAGCCAAGCTTAGGGTTCCACCATCAGCACCACCAA\n";
      example_sequence += "CACAGCAACATCTTGCAGCTCGGCCAGGCTATGTTTGATCTCGACTTCGATCACTAGTCAATATGTGATG\n";
      example_sequence += "CACATGCACCCTCTCTTTCTCACCCCACCCCACCCCTCCCCTCCCCTCTATCTTGTTTGTGCGCGTAATC\n";
      example_sequence += "CGAATATTTTTCCTTTTTAAATTATCTGTGTTAATTACTGTAACGTGGACATAATAATGATAGTCTATGC\n";
      example_sequence += "TTGCCATGCAA\n";

      document.blastform.sequence.value = example_sequence;

   }
}//addExample


function closeEl(el_id) {
   var el = document.getElementById(el_id);
   el.style.display = "none";
}


function createDatasetHTML(datasets, index) {

   var html_str;
   if (datasets.length == 0) {
      html_str = '<b>-- no datasets selected --</b>';
   } else {
      html_str = '<table class="smalltext">';
      for (i in datasets) {
         html_str += createDatasetRow(i, datasets[i], index);
      }
      html_str += "</table>";

      var datasetdiv_el = document.getElementById('datasetdiv');
   }

   return html_str;
}//createDatasetHTML


function createDatasetRow(i, dataset_str, index) {

   var dataset_str_ret = dataset_str.split('--');
   var blastDB_source = dataset_str_ret[0];
   var blastDB_db = dataset_str_ret[1];
   var blastDB_name = dataset_str_ret[2];
   var row_index = dataset_str_ret[3];

   var html_str = '<tr>';
   html_str += '<td>' + blastDB_name + '</td>';
   html_str += '<td>';
   html_str += '<input type="button" value="Remove" ';
   html_str += 'onclick="removeDataset(' + i + ')">';
   html_str += '<a href="javascript:openDescribe(' + "'describediv',"
         + row_index + ')">describe</a>'
   html_str += '</td>';
   html_str += '</tr>';
   html_str += '<input type="hidden" value="' + blastDB_source + '|'
         + blastDB_db + '" class="targets" name="targets[]">';
   return html_str;
}//createDatasetRow


function createTree() {
   var loc = window.location.href;
   var base_url = loc.substring(0, loc.indexOf('/search/'));

   //creating the list elements for the tree and appending it to the page
   // (ul element created in template)
   var html = "";
   $
         .each(
               targets,
               function(ind, val) {
                  mod_name = ind.replace('.', '_'); // because jquery can't handle .'s in ids
                  html += '<li><input type="checkbox" ' + 'value="' + ind
                        + '" ' + 'id="checkbox_' + ind
                        + '" disabled="disabled"/>'
                        //             + 'id="checkbox_' + ind + '""/>' 
                        + '<label id="label_' + ind + '">' + ind
                        + '</label>'
                        + ' <span class="url_status" id="status_'
                        + mod_name + '">' + 'verifying...</span>';
                  var dbs = val.databases;

                  $
                        .each(
                              dbs,
                              function(dbind, dbval) {
                                 html += '<ul><li><input type="checkbox" value="'
                                       + ind
                                       + '|'
                                       + dbind
                                       + '" class="tree_target" />'
                                       + '<label>'
                                       + dbval.name
                                       + '</label>'
                                       + '<a style="margin-left:10px" href="javascript:showTargetInfo(\''
                                       + ind
                                       + '\',\''
                                       + dbind
                                       + '\')"><img src="'
                                       + base_url
                                       + '/images/help.png" border="0"></a>'
                                       + '</li></ul>';
                              });

                  html += '</li>';
               });
   $('.custom_target_tree').append(html);

   //calling the checkbox tree
   $(".custom_target_tree").checkboxTree({
      /*0.4.2
       collapseImage: base_url+"/images/row-contract1.gif",
       expandImage: base_url+"/images/row-expand1.gif",
       leafImage: base_url+"/images/img-arrow-blank.gif",
       */
      collapsedarrow : base_url + "/images/row-expand1.gif",
      expandedarrow : base_url + "/images/row-contract1.gif",
      blankarrow : base_url + "/images/img-arrow-blank.gif",
      checkchildren : true
   });

   //adding sliding animations to the tree
   $("input[name='target_select']").change(function() {
      var t = $("input[name='target_select']:checked").val();
      if ($("input[name='target_select']:checked").val() == 'all_targets')
         $(".custom_target_tree").hide("fast");
      else
         $(".custom_target_tree").slideDown("fast");
      //$(".custom_target_tree").dialog();
   });

   var t = $(".checkboxtreeactive");

}//createTree


function findElementPosition(el) {
   var curleft = curtop = 0;
   if (el.offsetParent) {
      var obj = el;
      do {
         curleft += obj.offsetLeft;
         curtop += obj.offsetTop;
      } while (obj = obj.offsetParent);
      return curleft;
   } else {
      return 0;
   }
}


function hideHelp(helpdiv) {
   helpdiv_el = document.getElementById(helpdiv);
   helpdiv_el.style.display = 'none';
}


function largeBLASTrequest() {
   // All targets is "large"
   var is_large = ($(".target_select:checked").val() == 'all_targets');

   if (!is_large) {
      is_large = ($(".tree_target:checked").length > 15);
   }

   return is_large;
}//largeBLASTrequest


function openDescribe(el_id, index) {

   var datasets_el = document.getElementById('datasets');

   var dataset_str = datasets_el.options[index].value;

   if (dataset_str == '') {
      return;
   }

   if (index != 0) {
      //var dataset_str = datasets_el.options[index].value;

      var display_info = dataset_str.split('|');

      var el = document.getElementById(el_id);
      
      // rough guess of div height based on text length
      var divheight = 20 * (display_info[3].length / 30);

      // jQuery selectors
      $("#describediv").height(divheight + 25);
      $("#descriptiondiv").height(divheight);
      $("#descriptiondiv").html(display_info[3]);
      $("#describediv").show();
   }
}//openDescribe


function openEl(el_id) {
   var el = document.getElementById(el_id);
   el.style.display = "block";
}//openEl


function removeDataset(index) {
   var selected_datasets_el = document.getElementById('selected_datasets');
   var datasets = selected_datasets_el.value.split('|');
   datasets.splice(index, 1);
   selected_datasets_el.value = datasets.join('|');

   var datasetdiv_el = document.getElementById('datasetdiv');
   var html_str = createDatasetHTML(datasets);
   datasetdiv_el.innerHTML = html_str;
}//removeDataset


function setAmiWordSizes() {

   document.blastform.word_size.options.length = 0;

   document.blastform.word_size.options[0] = new Option(2, 2, false, false);
   document.blastform.word_size.options[1] = new Option(3, 3, true, true);

}


function setNucWordSizes() {

   document.blastform.word_size.options.length = 0;

   document.blastform.word_size.options[0] = new Option(7, 7, false, false);
   document.blastform.word_size.options[1] = new Option(11, 11, true, true);
   document.blastform.word_size.options[2] = new Option(15, 15, false, false);

}

function setParams(variables, values) {

   var len = variables.length;

   for (i = 0; i < len; i++) {

      document.getElementById(variables[i]).value = values[i];

   }
}

function setTargetArray() {
   selected_source = '';
   $.get("taskcontroller.php?a=GET_BLAST_TARGETS", {}, function(data) {
      targets = data; //passed back from PHP function getBLASTtargets()
      createTree();
      //initSources();
      //setDBs();
      verifyURLs();
   }, 'json');//.get

}//setTargetArray


function showBLASTInputHelp(helpdiv, which, targ) {

   var targ_el = document.getElementById(targ);
   var left = findElementPosition(targ_el);

   helpdiv_el = document.getElementById(helpdiv);
   helpdiv_el.style.left = left;

   var html_str = '';

   if (which == 'short_sequence') {
      html_str + '<i>';
      html_str += 'Complete, nearly identical matches for sequences which are ';
      html_str += 'approximately 50 or fewer bases each.';
      html_str += '</i>';
   } else if (which == 'max_target') {
      html_str = '<i>';
      html_str += "Maximum number of aligned sequences to display, that is,";
      html_str += "target sequences that the query aligns to. If the target is ";
      html_str += "an assembly, this will indicate the maximum number of ";
      html_str += "chromosomes to report alignments for.";
      html_str += '</i>';
      helpdiv_el.style.left = left + 250;
   } else if (which == 'mismatch') {
      html_str = '<i>';
      html_str += "Set a reward for a match and a penalty for a mismatch. The ";
      html_str += "reward/penalty ratio should be increased as sequences become";
      html_str += " more divergent. A ratio of 0.33 (1/-3) is appropriate for ";
      html_str += "sequences that are about 99% conserved; a ratio of 0.5 (1/-2) ";
      html_str += "is best for sequences that are 95% conserved; a ratio of ";
      html_str += "about one (1/-1) is best for sequences that are 75% conserved.";
      html_str += '</i>';
      helpdiv_el.style.left = left + 250;
   } else if (which == 'wordSize') {
      html_str = '<i>';
      html_str += "The length of the seed that initiates an alignment. For a ";
      html_str += "nucleotide-nucleotide search an exact match of the entire ";
      html_str += "word is repquired before an extension ininitiated, so speed ";
      html_str += "and sensitivity of the search is affected by incresasing or ";
      html_str += "decreasing the word size. For other search, one would ";
      html_str += "normally use word sizes of 2 or 3.";
      html_str += '</i>';
      helpdiv_el.style.left = left + 250;
   } else if (which == 'max_evalue') {
      html_str = '<i>';
      html_str += "The e-value specifies the statistical significance threshold ";
      html_str += "for reporting matches against database sequences. For example,";
      html_str += "an e-value of 10 means that 10 such matches are expected to be ";
      html_str += "found merely by chance. If the statistical significance ";
      html_str += "ascribed to a match is greater than the e-value threshold, the ";
      html_str += "match will not be reported. Lower e-value thresholds are more ";
      html_str += "stringent, leading to fewer chance matches being reported.";
      html_str += '</i>';
      helpdiv_el.style.left = left + 250;
   } else if (which == 'high_similarity') {
      html_str = '<i>';
      html_str += "Use tight constraints on quality of hits. Useful for finding near-exact";
      html_str += "matches or orthologous maize sequence for a maize sequence query.";
      html_str += '</i>';
   } else if (which == 'low_similarity') {
      html_str = '<i>';
      html_str += "Use more relaxed constraints on quality of hits. Useful for searching ";
      html_str += "maize sequence with non-maize queries.";
      html_str += '</i>';
   } else if (which == 'BLAST_text') {
      html_str = '<i>';
      html_str += 'Standard BLAST text output';
      html_str += '</i>';
   } else if (which == 'BLAST_table') {
      html_str = '<i>';
      html_str += 'BLAST table output, corresponding to the -m 8 parameter to blastall.';
      html_str += '</i>';
   } else if (which == 'enhanced') {
      html_str = '<i>';
      html_str += 'MaizeGDB-generated output which includes visualizations of ';
      html_str += 'queries and hits, genome alignment (where applicable), ';
      html_str += 'et cetera.';
      html_str += '</i>';
   } else if (which == 'name_sequence') {

      html_str = '<i>';
      html_str += '(Optional) Provide a name to identify your sequence,';
      html_str += 'otherwise the defline will be used if the input is in FASTA.';
      html_str += '</i>';

   } else if (which == 'email') {

      html_str = '<i>';
      html_str += '(Optional) If you would like results to be mailed to you, enter your e-mail here.';
      html_str += '</i>';

   }

   helpdiv_el.innerHTML = html_str;
   helpdiv_el.style.display = 'block';
}//showBLASTInputHelp


function showTargetInfo(source, db) {
   window
         .open("showmore.php?source=" + source + "&db=" + db, '',
               "location=0,menubar=0,status=0,titlebar=0,scrollbars=1,height=300,width=600");
}//showTargetInfo


function startBLAST(frm) {
   //if (verifyBLASTInput()) {
   ret = $.post('taskcontroller.php', {
      a : 'CLEAR_CACHE'
   });

   // stupid, clunky, possible fix for Safari 4 problem (the $.post()  
   //   statment above doesn't reliably happen).
   pause(100);

   //create hidden fields depending what targets are selected by the user
   var html = "";
   //         if ($(".target_select:checked").val() == 'custom_set')
   //         {
   //           var sel_targs = $('.tree_target:checked');
   //           $.each(sel_targs,function(ind,val){
   //             html += '<input type="hidden" value="' 
   //                    + $(val).attr('value') 
   //                    + '" class="targets" name="targets[]">';
   //           });    
   //         }
   //         else
   //         {
   //           var sel_targs = $('.tree_target');
   //           $.each(sel_targs,function(ind,val){
   //             html += '<input type="hidden" value="' 
   //                    + $(val).attr('value') 
   //                    + '" class="targets" name="targets[]">';
   //           });
   //         }
   if (verifyBLASTInput()) {
      $('.custom_target_tree').after(html);
      $("#process_indicator").show();

      frm.submit();
   }
   //}
}//startBLAST


function toggle_withImage(tog_id, el_id, image_url) {

   var tog = document.getElementById(tog_id);
   var el = document.getElementById(el_id);

   if (el.style.display == "block") {
      el.style.display = "none";
      tog.innerHTML = "<img src='" + image_url
            + "/expand.png' border=0 alt='expand image' />";
   } else {
      el.style.display = "block";
      tog.innerHTML = "<img src='" + image_url
            + "/collapse.png' border=0 alt='collapse image' />";
   }
}


function verifySequence(MAX_QUERIES, sequence, MAX_SEQUENCE_LENGTH) {

   // Definition(s) lines found
   if (sequence.indexOf(">") != -1) {

      var sequences = sequence.split(">");
      sequences.shift();

      // Check for max number of sequences
      if (sequences.length > MAX_QUERIES) {
         alert("Maximum number of input sequences allowed is " + MAX_QUERIES);

         return false;
      }

      for ( var i in sequences) {

         var seq = sequences[i];

         var non_def = seq.replace(/^.+\n/, "");

         if (non_def.length > MAX_SEQUENCE_LENGTH) {

            alert("You have entered too many sequences or your total query sequence length is too long."
                  + "You can enter up to "
                  + MAX_QUERIES
                  + " sequences with a total length of no more than "
                  + MAX_SEQUENCE_LENGTH
                  + ". If you wish to BLAST a large query, please follow the link at the  top of the "
                  + "page to ZeAlign.")

            //alert("Sequence number " + i + " is longer than the allowed length of " + MAX_SEQUENCE_LENGTH);

            return false;

         } else if (non_def.length == 0) {

            alert("Sequence number " + i
                  + " does not contain any characters.");

            return false;

         }
      }
   }

   else if (sequence.match(/^\s*\d+\s+\w+/)
            || sequence.match(/\w+\s+\d+/)) {
      // Old style of fasta with indices on rows
      sequence = sequence.replace(/\s/g, '');
      sequence = sequence.replace(/\d+/g, '');
      if (sequence.length > MAX_SEQUENCE_LENGTH) {
         alert("You have entered too many sequences or your total query "
               + "sequence length is too long. You can enter up to "
               + MAX_QUERIES
               + " sequences with a total length of no more than "
               + MAX_SEQUENCE_LENGTH
               + ". If you wish to BLAST a large query, please follow the link"
               + " at the  top of the page to ZeAlign.");
         return false;
      }
   }
   
   // Non-sequence input expected if a numeric character is found without
   // the existence of a definition line.
   else if (sequence.match(/[0-9]/)) {

      sequence = sequence.replace(/,\s*/gm, ",");
      sequence = sequence.replace(/\s+/gm, ",");
      sequence = sequence.replace(/\;\s*/gm, ",");
      sequence = sequence.replace(/,+/gm, ",");
      sequence = sequence.replace(/^,/gm, "");
//alert("check sequence: " + sequence);
      var GIs = sequence.split(/,|\n/);

      if (GIs.length > MAX_QUERIES) {

         alert("You have entered too many sequences or your total query sequence length is too long."
               + "  You can enter up to "
               + MAX_QUERIES
               + " sequences with a total length of no more than "
               + MAX_SEQUENCE_LENGTH
               + ". If you wish to BLAST a large query, please follow the link at the  top of the "
               + "page to ZeAlign.")

         return false;
      }
   }

   // Raw sequence
   else if (sequence.length > MAX_SEQUENCE_LENGTH) {

      alert("You have entered too many sequences or your total query sequence length is too long."
            + "You can enter up to "
            + MAX_QUERIES
            + " sequences with a total length of no more than "
            + MAX_SEQUENCE_LENGTH
            + ". If you wish to BLAST a large query, please follow the link at the  top of the "
            + "page to ZeAlign.")

      return false;

   }

   return true;
}//verifySequence


function verifyBLASTInput() {

   if (!verifySequence($('#MAX_QUERIES').val(), $('#sequence').val(), $(
         '#MAX_SEQUENCE_LENGTH').val())) {

      return false;

   }

   if (jQuery.trim($("#sequence").val()) == ''
         && trim($('#sequence_file').val()) == '') {
      alert("You haven't entered any sequence.");
      return false;
   }
   if (!verifyEmail($("#email").val())) {
      return false;
   }
   if ($('#max_evalue').val() == ''
         || isNaN(parseFloat($('#max_evalue').val()))) {
      alert("You haven't provided a valid e-value cutoff");
      return false;
   }
   if ($('#max_evalue').val().valueOf() < 1.0e-295) {
      alert("Your e-value cut-off must be 0 or a number greater than 1e-295");
      return false;
   }
   var seq_type = $('.seq_type:checked').val();
   if (seq_type != 'nucleotide' && seq_type != 'aminoacid') {
      alert("you haven't indicated whether your query consists of nucleotides or amino acids");
      return false;
   }
   if (!verifySequenceType()) {
      alert("Your query sequence is invalid. Check the sequence type setting.");
      return false;
   }
   if ($('#selected_datasets').val() == '') {

      alert("you haven't selected any target datasets.");
      return false;
   }
   return true;
   
   ////////////////////////////////////////////////////////////
   var email_addr = $.trim($('#email').val());
   var email_entered = (email_addr.length > 0);

   // Warn user if lots of targets selected
   if (!email_entered && largeBLASTrequest()) {
      var msg = "This request may take several minutes. You may instead ";
      msg += "cancel this request and enter your e-mail and have the ";
      msg += "results sent to you, or click 'OK' to wait for the results ";
      msg += "to display in your browser.";
      if (!confirm(msg)) {
         return false;
      }
   }
   if ($(".target_select:checked").val() == 'custom_set'
         && $(".tree_target:checked").length == 0) {
      alert("You haven't selected any BLAST targets.");
      return false;
   }
   if ($('#max_evalue').val() == ''
         || isNaN(parseFloat($('#max_evalue').val()))) {
      alert("You haven't provided a valid e-value cutoff");
      return false;
   }
   if ($('#max_evalue').val().valueOf() < 1.0e-295) {
      alert("Your e-value cut-off must be 0 or a number greater than 1e-295");
      return false;
   }
   var seq_type = $('.seq_type:checked').val();
   if (seq_type != 'nucleotide' && seq_type != 'aminoacid') {
      alert("you haven't indicated whether your query consists of nucleotides or amino acids");
      return false;
   }
   if (!verifySequenceType()) {
      alert("Your query sequence is invalid. Check the sequence type setting.");
      return false;
   }
   if ($(".out_seq_type:checked").length == 0) {
      alert("You need to select at least one of the output sequence types (nucleotide/amino acid)");
      return false;
   }
   // Limit max hits if combined output requested
   var t = $('#out_format_type:checked');
   if ($('#out_format_type:checked').val() == 'com_all') {
      var el = $('#max_hits');
      $('#max_hits').val(10);
   }

   if (!verifyEmail($("#email").val())) {
      return false;
   }

   return true;
}//verifyBLASTInput


function verifyURLs() {
   $.each(targets, function(ind, val) {
      var url = val.url;
      var name = val.source;
      var t = $('#checkbox_' + name);
      //         $('#checkbox_'+name).attr('disabled', 'disabled');

      $.get("taskcontroller.php?a=CHECK_URL", {
         url : url,
         name : name
      }, function(data) {
         var name = data.name;
         name = name.replace('.', '_');
         $('#status_' + name).text(data.msg);
         if (data.status == '200') {
            var t = $('#checkbox_' + name);
            //                  $('#checkbox_'+name).removeAttr('disabled');
            //                 $('#checkbox_'+name).attr('disabled', 'disabled');
         } else {
            $('#status_' + name).css('color', 'red');
            $('#label_' + name).css('color', 'gray');
            //                 $('#checkbox_'+name).attr('disabled', 'disabled');
            //eksc- doesn't work?
            //                 $('#checkbox_'+name).hide();
         }
      }, 'json');//.get
   });
}//verifyURLs

function uniq(arr) {
   var o = {}, i, l = arr.length, r = [];
   for (i = 0; i < l; i += 1) {
      o[arr[i]] = arr[i];
   }
   for (i in o) {
      r.push(o[i]);
   }
   return r;
}

/*unused
 function blastAll(frm) {
 //add all targets
 addAllTargets();
 //check combined blast
 $('input[name=comall]').attr('checked', true);
 //call startBLAST
 startBLAST(frm);
 }
 */
/*unused
 function selectTarget() {
 var selected_div;
 if ($(this).is('.dbs')) {
 selected_div = $(this);
 }
 else {
 return;
 }
 var selected_target = selected_div.text();
 dbs = targets[selected_source].databases;
 $.each(dbs,
 function(db, desc) {
 var name = desc.name;
 if (name == selected_target) {
 $('#target_description').html(desc.citation);
 }
 });
 }
 */
/*unused   
 function initSources() {
 $.each(targets, 
 function(targ, dbs) {
 var newdiv = makeItem(targ, targ, 'sources');
 newdiv.click(setDBs);
 $('#sourcediv').append(newdiv);
 });
 }//initSources
 */
/*unused
 function setDBs() {
 var selected_div;
 if ($(this).is('.sources')) {
 selected_div = $(this);
 }
 else {
 selected_div = $('.sources').eq(0);
 }
 selected_source = selected_div.text();
 selectItem(selected_div);
 $('#target_description').html('');

 $('#dbdiv').children().remove();
 dbs = targets[selected_source].databases;
 $.each(dbs, 
 function(db, desc) {
 var newdiv = makeItem(desc.name, db, 'dbs');
 newdiv.click(selectTarget);
 $('#dbdiv').append(newdiv);
 });
 }//setDBs
 */
/*unused
 function addTarget() {
 var selected_source = $('.sources.active');
 if (selected_source.length == 0) {
 alert("You haven't selected a source.");
 return;
 }
 var selected_db = $('.dbs.active');
 if (selected_db.length == 0) {
 alert("You haven't selected a target database.");
 return;
 }
 $('#targetdiv').children('#instdiv').remove();
 new_val = selected_source.text() + "|" + selected_db.data('value');
 new_text = selected_source.text() + " - " + selected_db.text();
 $('#targetdiv').append(makeItem(new_text, new_val, 'target_names'));
 $('#targetdiv').append($('<input type="hidden" name="targets[]" class="targets" value="' + new_val + '">'));
 setTargetBackground();
 }//addTarget
 */
/*unused
 function addAllTargets() {
 var sources = $('.sources');
 $('#targetdiv').children().remove();
 $.each(sources,function(){
 var src_text = $(this).text();
 var dbs = targets[src_text].databases;
 $.each(dbs,function(db,desc){
 new_val = src_text + "|" + db;
 new_text = src_text + " - " + $(this).attr('name');
 $('#targetdiv').append(makeItem(new_text, new_val, 'target_names'));
 $('#targetdiv').append($('<input type="hidden" name="targets[]" class="targets" value="' + new_val + '">'));
 setTargetBackground();
 });
 });
 }//adds all Targets
 */
/*unused   
 function removeAllTargets() {
 var target_arr = $('.target_names');
 if (target_arr.length == 0) {
 alert("There is nothing to remove.");
 return;
 }
 $.each(target_arr,function(){
 var value = $(this).data('value');
 $("input.targets[value='"+value+"']").remove();
 $(this).remove();
 });
 setTargetBackground();
 }//remove all Targets
 */
/*unused
 function removeTarget() {
 var selected_target = $('.target_names.active');
 if (selected_target.length == 0) {
 alert("You haven't selected anything to remove.");
 return;
 }
 var value = selected_target.data('value');
 $("input.targets[value='"+value+"']").remove();
 selected_target.remove();
 setTargetBackground();
 }//removeTarget
 */
/*unused
 function setTargetBackground() {
 if ($('.target_names').length > 0) {
 $('#targetdiv').css('background-color', '#ffffff');
 }
 else {
 $('#targetdiv').css('background-color', '#f0f0f0');
 }
 }
 */


