
/***   Sequence manipulation     ***/
function ReverseComplement(seq){
    return Reverse(Complement(seq));
}

function Reverse(str){
    if (!str){
        return '';
    }else{
        var revstr='';
        for (i = str.length-1; i>=0; i--){
            revstr+=str.charAt(i);
        }
        return revstr;
    }
}

function Complement(str){
    var comStr="";
    var origString ="AaCcGgTtMmKkRrYyWwSsBbVvDdHhNn[]{}()/";
    var replString ="TtGgCcAaKkMmYyRrWwSsVvBbHhDdNn][}{)(/";
    for(var i=0;i<str.length;i++) {
        var c = str.charAt(i);
        for(var j=0;j<origString.length;j++) {
            var origChar = origString.charAt(j);
            if(origChar==c) {
                var replChar = replString.charAt(j);
                comStr+=replChar;
            }
        }
    }
    return comStr;
}

function CheckNucleotide(str){
    var nucs = /[AaCcGgTt-]/g;
    var matches =str.match(nucs);

    if(matches !=null && matches.length == str.length){
        return true;
    }else{
        return false;
    }
}

/***      SVG checking      ***/

function ReportVersion(v){

    if(v) version = v;    
    if(typeof(browserSupported) != 'undefined'){
        if(!versionSet && browserSupported){
            var notice = document.getElementById('notice');
//alert(browser+" "+version);
            if ((browser == 'Win Firefox' || browser == 'Win Mozilla' ) && version < 6){
               notice.innerHTML +="<img src=\"images/ex.jpg\" > You are using a supported browser "+
                    "("+browser+"), but you do NOT have (or you are NOT using) the correct Adobe SVG viewer.<br>"+
                    "<ul>You must download the  <a href=\"http://www.adobe.com/svg/viewer/install/beta.html\">Adobe SVG Viewer 6.0</a><font style=\"color:red;font-size:18\">*</font>"+
                    " and install it before using genewindow.</ul>"+
                    "<ul><font style=\"color:red;font-size:18\">*</font>Installation is not standard for Mozilla and Firefox"+
                    " browsers on Windows and requires a"+
                    " <a href=\"http://www.jarra.nl/wp-trackback.php/59\" target=\"_blank\"> manual procedure</a>. "+
                       "Additional instructions are also <a href=\"http://plugindoc.mozdev.org/windows-all.html#AdobeSVG\" target=\"_blank\">here</a>."+
                       "Firefox 1.5 users will also need to follow these <a href=\"/docs/firefox15.html\" target=\"_blank\">instructions</a>.";

            }else if (version < 3){
               notice.innerHTML +="<img src=\"images/ex.jpg\" ><b> You are using a supported browser ("+browser+"), but you do NOT have (or you are NOT using) the correct Adobe SVG viewer.</b><br>"+
                                  "Installation is not standard for Mozilla and Firefox browsers on Windows and requires a"+
                                    " <a href=\"http://www.jarra.nl/wp-trackback.php/59\" target=\"_blank\"> manual procedure</a>. "+
                                    "Additional instructions are also <a href=\"http://plugindoc.mozdev.org/windows-all.html#AdobeSVG\" target=\"_blank\">here</a>."+
                                    "Firefox 1.5 users will also need to follow these <a href=\"/docs/firefox15.html\" target=\"_blank\">instructions</a>."+
                                "<ul>You must download the  <a href=\"http://www.adobe.com/svg/viewer/install/main.html\">Adobe SVG Viewer</a> and install it before using genewindow.</ul>";
            }else{

               notice.innerHTML +="<img src=\"images/check.jpg\" >You are using a supported "+
                    "browser ("+browser+") and the correct Adobe SVG viewer.<br/><br/>";

                if(browser.indexOf('Firefox')>-1){
                   notice.innerHTML +="<img src=\"/images/firefox-logo-32x32.png\" /> Firefox 1.5 users see addition instructions "+
                                      "<a href=\"/docs/firefox15.html\" target=\"_blank\">here</a> if you are having problems viewing"+
                                      " Genewindow or if your being asked to download (svg_check.svg).<br/><br/>";
                }

                notice.innerHTML +="To begin, view an example gene (<a href=\"/IntervalRequest?q=brca1\">BRCA1</a>)"+
                    " or enter your own query in the 'SEEK' box at"+
                    " the top. To see valid search terms click on the 'how?'"+
                    " link next to 'SEEK'. Please see the <a href=\"about.jsp\">about</a>"+
                    " page for more information.<ul><b>Thank you for using Genewindow!</b></ul>";

                document.getElementById('plugin-note').innerHTML='plugin installed';
                //if (newbie) document.getElementById('seek').setAttribute('color', 'green');
            }

            versionSet=true;
            // remove the checker once check is complete.
            var checker = document.getElementById('SVGCheck');
            checker.parentNode.removeChild(checker);
        }
    }else{
        ReportVersionInDisplay(version);
    }
}

function Authenticate(a){
    //alert("Login tasks are disabled until further notice.  :-(");
    //alert(document.authentication.action);
    document.authentication.actiontype.value=a;
    document.authentication.submit();
}

function WindowOpener(page, w, h){
    var winl = (screen.width - w) / 2;
    var wint = (screen.height - h) / 2;
    winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+'resizable=no,scrollbars=no,status=no';
    window.open(page,"",winprops);
}

function BigWindowOpener(page, w, h){
    var winl = (screen.width - w) / 2;
    var wint = (screen.height - h) / 2;
    winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+'resizable=yes,scrollbars=yes';
    window.open(page,"",winprops);
}

/******  for display of data  *******/

// set the page height after the svg calculates its height
function SetHTMLAttributes(ph, h){
    pageHeight=ph; //+500   // height of the header
    hits=h;    
    document.getElementById('display').setAttribute("height", pageHeight);
}


function ReportVersionInDisplay(v){
    if(!versionSet){
        var content = document.getElementById('content');
        if(v) version = v;

        if ((browser == 'Win Firefox' || browser == 'Win Mozilla') && version < 6){
            content.innerHTML +="<img src=\"images/ex.jpg\" ><b> You do NOT have or you are NOT using the correct Adobe SVG viewer.</b><br>"+
                "<ul>You must download the  <a href=\"http://www.adobe.com/svg/viewer/install/beta.html\">Adobe SVG Viewer</a> and install it before using Genewindow.</ul>";
            while(content.hasChildNodes()){
                content.removeChild(content.firstChild);
            }

        }else if(version < 3){

            while(content.hasChildNodes()){
                content.removeChild(content.firstChild);
            }
            if(browser == 'unsupported'){
                content.innerHTML +="<img src=\"images/ex.jpg\" ><b> You do NOT have or you are NOT using the correct Adobe SVG viewer.</b><br>"+
                    "<ul>You must download the  <a href=\"http://www.adobe.com/svg/viewer/install/main.html\">Adobe SVG Viewer</a>"+
                    " and install it before using Genewindow. Also consult the <a href=\"javascript:WindowOpener('BrowserMatrixWindow.jsp', 450, 250);\" style=\"font-size:10\">matrix of browsers</a> supported.</ul>";
            }else{
                content.innerHTML +="<img src=\"images/ex.jpg\" ><b> You do NOT have or you are NOT using the correct Adobe SVG viewer.</b><br>"+
                    "<ul>You must download the  <a href=\"http://www.adobe.com/svg/viewer/install/main.html\">Adobe SVG Viewer</a> and install it before using Genewindow.</ul>";
            }
        }

        versionSet=true;
        // remove the checker once check is complete.
        var checker = document.getElementById('SVGCheck');
        checker.parentNode.removeChild(checker);
    }
}

/**
function ShowSearchOptions(){

    var so = document.getElementById('searchOptions');
    // remove options button
    so.removeChild(so.childNodes[0]);

    var sel = document.createElement('select');
    sel.name='format';
    sel.id='format';
    sel.style.fontSize='9px';

    var op1 = document.createElement('option');
    op1.text='normal view';
    op1.value='null';
    op1.selected;
    var op2 = document.createElement('option');
    op2.text='fasta sequence (annotated)';
    op2.value='fasta';
    var op3 = document.createElement('option');
    op3.text='polymorphism details only';
    op3.value='detail';

    sel.add(op1);
    sel.add(op2);
    sel.add(op3);

    so.appendChild(sel);
}
*/

/**
/ appends a star to the node indicating an error a the node
*/

function Error(n, msg){
    var hasStar=false;
    var parent=document.getElementById(n);

    var note ="* required";
    if(typeof msg != 'undefined'){
        note =msg;
    }

//alert(parent+" "+parent.parentNode);

    if(parent != null && parent.innerHTML.indexOf("*") == -1){
        var star = document.createElement('font');
        star.style.color='red';
        star.style.fontSize='18px';
        star.style.fontWeight='bolder';
        star.id='star';
        star.innerHTML=" *";
        parent.appendChild(star);
    }

    var msg=document.getElementById('error_msg');
    //alert(note+" "+(msg.childNodes.length < 1));
    //if(msg.childNodes.length < 1){
        var m = document.createElement('font');
        m.style.color='red';
        m.style.fontSize='16px';
        m.style.fontWeight='bolder';
        //if(m.innerHTML == ''){

            //m.innerHTML=note;
        //}

        m.appendChild(document.createTextNode(note));
        if(msg.childNodes[0] != null){
            msg.removeChild(msg.childNodes[0]);
        }
        msg.appendChild(m);
   //alert(msg+" "+msg.innerHTML); 
    //}
   // resizeWinTo('myBody');
}

function Warning(note,nodeid){

    if(typeof note == 'undefined'){
        note ="*";
    }

    if(typeof nodeid == 'undefined'){
        nodeid='warning_msg';
    }

    var war_node=document.getElementById(nodeid);
//alert(note+" "+nodeid);
    if(war_node){
        if(war_node.innerHTML.indexOf(note) == -1){
            var m = document.createElement('font');
            m.id=nodeid+"_warning";
            m.style.color='#FFCC00';
            m.style.fontSize='16px';
            m.style.fontWeight='bolder';
            m.appendChild(document.createTextNode(note));
        /*
            if(war_node.childNodes[0] != null){
                war_node.removeChild(war_node.childNodes[0]);
            }
        */
            war_node.appendChild(m);
        }

    }
}

function RemoveMessages(id){
    RemoveError(id);
    RemoveWarning(id);
}

/**
/ removes a star to the node indicating the error is fixed
*/
function RemoveError(n){

    var parent = document.getElementById(n);
    if(parent){
        var nodes = parent.childNodes;

        for(var i=0; i< nodes.length; i++){
            var node = nodes[i];
            if(node.innerHTML == ' *' || node.id=='star'){
                parent.removeChild(node);
            }
        }
    }
    var msg=document.getElementById('error_msg');
    msg.innerHTML='';

}

function RemoveWarning(id){
    var node = document.getElementById(id+'_warning');
    if(node){
        node.parentNode.removeChild(node);
    }
}

function NeedTargetGene(){
    alert('You must expand your view to include a gene before you can make a submission.');
}



/**
/ checks to make sure user is not submitting a var for sequencing without flanks
*/
/*
function checkFlanks(){
    var f = document.submitPoly.flanks.value;
    var s = document.submitPoly.action.value;
    if(s=='sequencing' && f == 0){
        Error('flanks', '*&nbsp;you must choose flanks before submitting to sequencing');
        return false;
    }else{
        RemoveError('flanks');
        return true;
    }
}
*/
/**
/ users are not allowed to submit a var without a target gene
*/

/**
/ keeps track of the users input by filling in the header
*/
function SetHeaderForm(q){
   if(document.searchform.q){
    document.searchform.q.value=q;
    document.searchform.q.style.color='';
   }

/**
   if(document.seek.format){
       for (var i=1; i< document.seek.format.options.length; i++){
           var op = document.seek.format.options.item(i);
           if(op.value==l){
               op.selected=true;
           }
       }
    }
*/
}

/**
/ generic function for clearing the value in an input field
*/
function ClearInput(t){        
    if(t && t.style && t.value){
        t.value='';
        t.style.color='';
    }else{
        this.value='';
        this.style.color='';
    }
}

function ClearValue(){
    this.value='';
}

function ClearStyle(){
    this.style.color='';
}




function AddAlleles(aid, alleles, type){
//alert(type+' '+alleles+' '+aid);
    var h=null;
    if(type && (type=="VNTR" || type=="INSERTION" || type=="DELETION")){
        h = document.createElement("textarea");

        h.rows='4';
        h.cols='50';
        h.wrap="soft";
    }else{
        h = document.createElement("input");
        h.size='5';
        h.type = "text";
    }

    h.name = aid;
    h.id=aid;

    var al="ref/allele1/etc";
    if(alleles != null) al=alleles;

    h.value = al;
    h.style.fontSize="10px";
    h.style.color="#A1A1A1";

    h.onfocus=ClearInput;

    var p = document.getElementById("id_"+aid);
    //var p = a.parentNode;
    if(p.childNodes[0]) p.removeChild(p.childNodes[0]);
    p.appendChild(h);    
}

function ChangePolyType(id, v){

    var sel = document.createElement('select');
    sel.name=id;
    sel.id=id;
    sel.style.fontSize='10px';

    var op1 = document.createElement('option');
    op1.text='SNP';
    op1.value='SNP';
    var op2 = document.createElement('option');
    op2.text='VNTR';
    op2.value='VNTR';
    var op3 = document.createElement('option');
    op3.text='insertion';
    op3.value='INSERTION';
    var op4 = document.createElement('option');
    op4.text='deletion';
    op4.value='DELETION';


    // firefox needs an additional argument
    if(sel.add.length==2){
        sel.add(op1, null);
        sel.add(op2, null);
        sel.add(op3, null);
        sel.add(op4, null);
    }else{
        sel.add(op1);
        sel.add(op2);
        sel.add(op3);
        sel.add(op4);
    }


    var polytype = document.getElementById("id_"+id);
    polytype.removeChild(polytype.childNodes[0]);
    if(polytype.childNodes[0]) polytype.removeChild(polytype.childNodes[0]);
    polytype.appendChild(sel);

    SelectOption(sel, v);

    // remove the star if present
    var star = polytype.getElementsByTagName("font");
    if(star.length >0) polytype.removeChild(star[0]);

}


/**
/ Expand and Shrink the space under the ehader to allow for LiveSearch results.
/ Currently only used for firefox
*/
var grad = new Array();
function Expand(target, value){
    var t = document.getElementById(target);
    if(t){

        if(!grad[target]) grad[target] = 0;
        grad[target] = grad[target] + 3;

        if(grad[target] < value) {
            t.style.height = (grad[target]) + "px";
            setTimeout("Expand('" + target + "'," + value + ")",1);
        } else {
            t.style.height = (value) + "px";
        }
    }
}

function Shrink(target, value){
    var t = document.getElementById(target);
    if(t){
    	if(!grad[target]) grad[target] = 0;

        grad[target] = grad[target] - 6;

        if(grad[target] > 0) {
            t.style.height = (grad[target]) + "px";
            setTimeout("Shrink('" + target + "'," + value + ")",1);
        } else {
            t.style.height = "0px";
        }
    }
}

function CreateHiddenField(n, v){
    var h = document.createElement("input");
    h.type = "hidden";
    h.name = n;
    h.id = n;
    h.value = v;
    return h
}


/*
/ for the admin tools section
*/

var toolsmenu='<a href="javascript:topMenu();" style="font-size:20px;">tools</a>:';
var batchmenu='<a href="javascript:BatchMenu();" style="font-size:20px;">batch</a>:'
var limsexport='<a href="javascript:LIMSExport();" style="font-size:20px;">lims</a>:';
var illuminaexport='<a href="javascript:IlluminaExport();" style="font-size:20px;">illumina</a>:';
function BatchSubmissionForm(order){

    if(!order){
        RemoveChildernFrom(document.getElementById('id_orderid'));
    }

    var bs = document.getElementById("batchSubmit");
    bs.style.display='';

    var bm = document.getElementById("batchMenu");
    bm.style.display='none';

}

function topMenu(){
    var tm = document.getElementById("topMenu");
    tm.style.display='';

    var bs = document.getElementById("batchSubmit");
    bs.style.display='none';

    var bo = document.getElementById("batchMenu");
    bo.style.display='none';

    var tn = document.getElementById("toolsNav");
    tn.innerHTML =toolsmenu;

}


function BatchMenu(){
    var t = document.getElementById("tools");
    var tn = document.getElementById("toolsNav");
    tn.innerHTML =toolsmenu+batchmenu;

    document.batchSubmitList.reset();

    var tm = document.getElementById("topMenu");
    tm.style.display='none';

    var bm = document.getElementById("batchMenu");
    bm.style.display='';

    //var bs = document.getElementById("batchSubmit");
    //bs.style.display='';
    var bs = document.getElementById("batchSubmit");
    bs.style.display='none';

}

function LIMSExport(order){
    var t = document.getElementById("tools");
    var tn = document.getElementById("toolsNav");
    tn.innerHTML =toolsmenu+batchmenu+limsexport;

    var le = document.getElementById("limsexport");
    le.style.display='';

    var bm = document.getElementById("batchMenu");
    bm.style.display='none';

    //document.batchSubmitList.batchaction.value="lims";

    //BatchSubmissionForm(order);
}

function ExportAction(e){
    action = e.options[e.selectedIndex].value;
    if(action!='null'){
        document.batchSubmitList.batchaction.value=action;

        if(action=='egp'){
            var bm = document.getElementById("egpentry");
            bm.style.display='';
            var bm = document.getElementById("limsexport");
            bm.style.display='none';

        }else{
            var bm = document.getElementById("batchSubmit");
            bm.style.display='';
            var bm = document.getElementById("limsexport");
            bm.style.display='none';
        }

        //BatchSubmissionForm(false);
    }
}

function IlluminaExport(){
    var t = document.getElementById("tools");
    var tn = document.getElementById("toolsNav");
    tn.innerHTML =toolsmenu+batchmenu+illuminaexport;

    var bm = document.getElementById("batchMenu");
    bm.style.display='none';
    document.batchSubmitList.batchaction.value='illumina';

    BatchSubmissionForm(false);
}
function IlluminaLIMSExport(){
    AddOrderID();
    LIMSExport(true);
}

var oin=false;
function SubmitEGPBatch(){

    var f = document.getElementById("RSIFrame");
    f.src="admin/submitting.html";

    var gs = document.getElementById("genesymbol");
    var g =document.batchSubmitList.hugoid;
    g.value= gs.value

    if(g && (g.value=="gene symbol" || g.value=="")){
        Error("id_hugoid");
    }else{
        RemoveError('id_hugoid');
        f.style.width="550px";
        f.style.height="200px";
        
        document.batchSubmitList.submit();
    }
}


//var hin=false;
function SubmitBatch(){
    var fpass=true;
    var opass=true;


/*
    var h = document.getElementById("hugoid");
    if(h.value=="gene (auto)"){
        h.value="";
        Warning('*','id_hugoid');
        Warning('* optional fields not changed, to continue click submit again.');
    }
*/

    var o = document.getElementById("orderid");
    if(o && o.value=="order id"){
        opass=false;
    }else{
        RemoveError('id_orderid');
    }

    if(document.batchSubmitList.uploadedfile.value==""){
        fpass=false;
    }else{
        RemoveError('id_uploadedfile');
    }

    if(fpass && opass){
        RemoveWarning('warning_msg');
//        RemoveWarning('id_hugoid');

        var f = document.getElementById("RSIFrame");
        f.style.width="550px";
        f.style.height="200px";

        document.batchSubmitList.submit();
    }else{
        if(!opass) Error('id_orderid', "* you must provide an order id");
        if(!fpass) Error('id_uploadedfile', "* you must upload a file");
    }



}



/*
/ messaging system that will soon replace the Error functions
*/
function ShowMessage(target, classStyle, msg){
    var t = document.getElementById(target);
    t.className=classStyle;
    t.innerHTML=msg;
    resizeWinTo('myBody');
}

var size = new Array();
function ExpandHeight(target, value){
    // for svg embed
    var t = document.getElementById(target);
    t.height=parseInt(t.height)+value;
}


/*
/ Need to refresh the page's CSS in Safari after resizing
*/
function RedrawStyles(){
    if (navigator.userAgent.indexOf("Safari") > 0) {
        document.body.style.display="none";
        setTimeout('document.body.style.display=""', 0);
    }
}

/*
/ Resizes the window based on the content
*/

var noresize=false;
function resizeWinTo( idOfDiv ) {
                       
    if(!noresize){
        var oH = getRefToDivMod( idOfDiv ); if( !oH ) { return false; }
        var oW = oH.clip ? oH.clip.width : oH.offsetWidth;
        var oH = oH.clip ? oH.clip.height : oH.offsetHeight; if( !oH ) { return false; }
        var x = window; x.resizeTo( oW + 0, oH + 200 );
        var myW = 0, myH = 0, d = x.document.documentElement, b = x.document.body;
        if( x.innerWidth ) { myW = x.innerWidth; myH = x.innerHeight; }
        else if( d && d.clientWidth ) { myW = d.clientWidth; myH = d.clientHeight; }
        else if( b && b.clientWidth ) { myW = b.clientWidth; myH = b.clientHeight; }
        if( window.opera && !document.childNodes ) { myW += 16; }
        x.resizeTo( oW + ( ( oW + 0 ) - myW ), oH + ( (oH + 200 ) - myH ) );

        RedrawStyles();
    }
}

function getRefToDivMod( divID, oDoc ) {
        if( !oDoc ) { oDoc = document; }
        if( document.layers ) {
                if( oDoc.layers[divID] ) { return oDoc.layers[divID]; } else {
                        for( var x = 0, y; !y && x < oDoc.layers.length; x++ ) {
                                y = getRefToDivNest(divID,oDoc.layers[x].document); }
                        return y; } }
        if( document.getElementById ) { return oDoc.getElementById(divID); }
        if( document.all ) { return oDoc.all[divID]; }
        return document[divID];
}

function RemoveChildernFrom(n){
    var array = new Array();
    var i=0;

    if(typeof n != 'undefined'){
        while(n.childNodes.length!=0){
            array[i]=n.childNodes[0];
            n.removeChild(n.childNodes[0]);
            i++;
        }
    }
    return array;
}
