// nupack UI js
var nupack;

if (!nupack) nupack = {};

nupack.create_sequence_input = function(root, index)
{
    // structural divs
    var node_div = nupack.utility.tag_with_class('div', 'species');
    var node_sequence_div = nupack.utility.tag_with_class('div', 'sequence form_row');
    var node_conc_div = nupack.utility.tag_with_class('div', 'concentration form_row');
    var node_na_type_div = nupack.utility.tag_with_class('div', 'na_type form_row');
    var node_seq_name_div = nupack.utility.tag_with_class('div', 'form_row');

    // spans for form layout
    var node_sequence_label = nupack.utility.tag_with_class('div', 'label');
    var node_sequence_input = nupack.utility.tag_with_class('div', 'item');

    var node_conc_label = nupack.utility.tag_with_class('div', 'label');
    var node_conc_input = nupack.utility.tag_with_class('div', 'item');

    var node_na_type_label = nupack.utility.tag_with_class('div', 'label');
    var node_na_type_input = nupack.utility.tag_with_class('div', 'input');

    var node_seq_name_label = nupack.utility.tag_with_class('div', 'label');
    var node_seq_name_input = nupack.utility.tag_with_class('div', 'input');

    // sequence fields
    var node_sequence = document.createElement('textarea');
    node_sequence.setAttribute("cols", 45);
    node_sequence.setAttribute("rows", 2);
    var node_sequence_descr = document.createTextNode('Sequence ' + (index + 1) + ':');


    // concentration fields
    var node_concentration = document.createElement('input');
    var node_conc_scale = document.createElement('select');
    var node_conc_descr = document.createTextNode('Concentration:');

    // na_type fields
    var node_na_type = document.createElement('select');
    var node_na_type_descr = document.createTextNode('Type:');

    // name fields
    var node_seq_name = document.createElement('input');
    var node_seq_name_descr = document.createTextNode('Name:');

    // set the rails keywords
    var name_prefix = "partition_sequence["
    var id_prefix = "partition_sequence_"

    // sequence input tag
    node_sequence.setAttribute("name", name_prefix + index + "][contents]");
    node_sequence.setAttribute("id", id_prefix + index + "_contents");
    node_sequence.setAttribute("type", "text");

    // concentration input tag
    node_concentration.setAttribute("name", name_prefix + index + "][concentration]");
    node_concentration.setAttribute("id", id_prefix + index + "_concentration");
    node_concentration.setAttribute("type", "text");
    node_concentration.setAttribute("class", "short_numeric");

    // concentration scale input tag
    node_conc_scale.setAttribute("name", name_prefix + index + "][scale]");
    node_conc_scale.setAttribute("id", id_prefix + index + "_scale");

    // nucleic acid type tag
    node_na_type.setAttribute("name", name_prefix + index + "][na_type]");
    node_na_type.setAttribute("id", id_prefix + index + "_na_type");

    //name
    node_seq_name.setAttribute("name", name_prefix + index + "][name]");
    node_seq_name.setAttribute("id", id_prefix + index + "_name");
    node_seq_name.setAttribute("maxlength", "10");
    node_seq_name.setAttribute("size", "10");


    // set up the unit-picking select
    var unit = "M" // molar
    var num_prefixes = 4 // milli, micro, nano, pico

    var opts = Array(num_prefixes);
    var opt_values = ["-3", "-6", "-9", "-12"]
    var opt_names = ["m", "μ", "n", "p"]

    for(var i = 0; i < num_prefixes; i++)
    {
        opts[i] = document.createElement('option')
        opts[i].setAttribute("value", opt_values[i]);
        if(opt_values[i] == "-6") // default to micro-molar being selected
        {
            opts[i].setAttribute("selected", "selected");
        }
        var text = document.createTextNode(opt_names[i] + unit)
        opts[i].appendChild(text)
        node_conc_scale.appendChild(opts[i]);
    }

    // set up the nucleic acid type select

    var num_na_types = 2;

    opts = Array(num_na_types);
    opt_values = ["DNA", "RNA"]
    opt_names = opt_values

    for(var i = 0; i < num_na_types; i++)
    {
        opts[i] = document.createElement('option');
        opts[i].setAttribute("value", opt_values[i]);
        var text = document.createTextNode(opt_names[i]);
        opts[i].appendChild(text)
        node_na_type.appendChild(opts[i])
    }

    // tie together the structure

    //sequence name
    node_seq_name_label.appendChild(node_seq_name_descr);
    node_seq_name_input.appendChild(node_seq_name);


    // conc spans
    node_conc_label.appendChild(node_conc_descr);
    node_conc_input.appendChild(node_concentration);
    node_conc_input.appendChild(node_conc_scale);

    // conc spans in the conc div
    node_conc_div.appendChild(node_conc_label);
    node_conc_div.appendChild(node_conc_input);

    // contents spans
    node_sequence_label.appendChild(node_sequence_descr);
    node_sequence_input.appendChild(node_sequence);

    // contents spans in the contents div
    node_sequence_div.appendChild(node_sequence_label);
    node_sequence_div.appendChild(node_sequence_input);

    // na_type span contents
    node_na_type_label.appendChild(node_na_type_descr);
    node_na_type_input.appendChild(node_na_type);

    // na_type spans in na_type div
    node_na_type_div.appendChild(node_na_type_label);
    node_na_type_div.appendChild(node_na_type_input);

    //seq name divs
    node_seq_name_div.appendChild(node_seq_name_label);
    node_seq_name_div.appendChild(node_seq_name_input);

    node_div.appendChild(node_sequence_div);
    node_div.appendChild(node_conc_div);
    node_div.appendChild(node_seq_name_div);
    // XXX do not append; right now all the strands have to be the same time so this choice is made
    // per-job, not per-sequence
    //node_div.appendChild(node_na_type_div);

    // make the node hidden, so we can then Appear it -- required for Appear to work!
    Element.hide(node_div);
    root.appendChild(node_div);
    // hehe. So egregious!
    new Effect.Appear(node_div);
}

nupack.change_sequence_inputs = function()
{
    //alert("changed " + $F("job_num_sequences"));
    var user_sel = $F("partition_job_num_sequences");
    var pseudoknots = $F("partition_job_pseudoknots");
    var max_complex_size = $F("partition_job_max_complex_size");

    var root = $("partition_species_inputs");

    // user entered a non-integer
    if (!user_sel.match(/^\d+$/))
    {
      //alert ("Reset!");

      // looks at all descendants
      // var inputs = root.getElementsByTagName('input');
      // for( var i=0; i < inputs.length; i++ )
        // inputs[i].parentNode.removeChild(inputs[i]);

      nupack.utility.delete_child_tags(root, 'tr');

      //Element.hide(root);
    }
    // user entered an integer
    else
    {
        if (pseudoknots == undefined) {
          pseudoknots = 0;
        }
        //alert("HERE "+pseudoknots);
        var hide_conc = 0;

        if (pseudoknots == 1 || max_complex_size == 1 || user_sel == 1) {
          hide_conc = 1;
        }

        Element.show(root);

        var have_already = nupack.utility.count_child_tags(root, 'tr', 1);
        var num_needed = user_sel - have_already;
        // alert("user_sel: " + user_sel+", have: " + have_already+", need: " + num_needed);

        // if we need n inputs and we have k <= n already:
        // go through every input we have and unhide it if we have not unhidden up to user_sel,
        // and hide it if we have.
        // If we still need more, add more inputs.

        var inputs_seen = 0;
        // if we have found more inputs than asked for, hide them. If we haven't found enough,
        // unhide them.
        child_elems=nupack.utility.get_child_nodes(root, 'tr', 1)

        var show_conc=undefined;
        for(var i = 0; i < child_elems.length; i++)
        {
            el = $(child_elems[i])
            // only check if it's a tag -- 1 means element, 3 means text node, etc
            if(el.nodeType == 1 && el.tagName.toLowerCase() == 'tr')
            {
                if (inputs_seen >= user_sel)
                {
                    Element.hide(el);
                    //new Effect.Fade(el);
                }
                else
                {
                    // remember to change effect in create_sequence_input
                    //new Effect.Appear(el);
                    if (child_elems[i].search("part_")==0)
                      Element.show(el);
                    if (child_elems[i].search("conc")==0){
                      console.log("Got "+child_elems[i]);
                      if (show_conc==undefined)
                        show_conc=el.style.display;
                      else
                        el.style.display=show_conc;
                      console.log("display="+show_conc);
                    }
                }
                inputs_seen += 1;
            }
        }

        //delete_child_tags(root, 'input');
        // we need more than we have already
        if (show_conc=="") hide_conc=0;
        if(num_needed >= 0)
        {
            // stolen from from rails-generated stuff
            new Ajax.Request('/partition/change_sequence_inputs',
                              { asynchronous:true,
                                evalScripts:true,
                                parameters:'existing_inputs=' + have_already +
                                '&number_to_insert=' + num_needed + '&hide_conc=' + hide_conc
                              }
                            )


            // We no longer need the hideous function above -- the ajax call above will slip in the
            // necessary DOM elements in without all that child-node linking nightmare

            // need to continue the chain of indices properly, so tweak the loop var
            //for (var i = have_already; i < user_sel; i++)
            //{
                //nupack.create_sequence_input(root, i);
            //}
        }

    }
}
