// global vars
var submitted=false; // has user attempted to submit?
var errors=false; // where there any errors during checking?
var warnings=false; // where there any warnings during checking?
var positionSet=false;
var polySet=false;
var allelesSet=false;
var geneSet=false;
var eNumSet=false;
var commentSet=false;
var egpIDSet=false;
var targetGene;


/**
/ for submitting variations
*/
function checkAction(){
    var s = document.submitPoly.action.value;

    if(s=='null'){
        Error('','you must select an action before submiting');
        return false;

    }else if (s=='abandon' && !checkComment()){
        Error('comment','*  you must comment why you are abandoning');
        return false;
    }else if ((s=='deactivate' || s=='remove') && !checkComment()){
            Error('comment','*  you must comment why you are '+s.substring(0, s.length-1)+"ing");
        return false;
    }else{
        return true;
    }

}


function checkAlleles(id, allStr, type, ref, len){
    if(allelesSet){
        if(allStr!=""){
            var alls=allStr.split("/");

            // for PositionCheck.jsp not passing refs. get refs in PositionCheck== to do list
            if(ref=="") ref = alls[0];

            // passing snp ids from positionCheck.jsp
            if(!id) id="";

            var pass= false;
            var msg="* malformed alleles";
            if(type=="SNP"){
                pass= checkSNP(alls, ref, len);
                msg="* alleles and/or position do not match SNP type";
            }else if(type=="INSERTION"){
                pass= checkInsertion(alls, ref, len);
                msg="* alleles and/or position do not match insertion type";
            }else if(type=="DELETION"){
                pass= checkDeletion(alls, ref, len);
                msg="* alleles and/or position do not match deletion type";
            }else if(type=="VNTR"){
                pass= checkVNTR(alls, ref, len);
                msg="* alleles and/or position do not match VNTR type";
            }

        //alert(pass+" "+id+" "+allStr+ " "+type+" "+ref+" "+len+ " "+checkSNP(alls, ref, len)+" "+checkInsertion(alls, ref, len)+" "+checkDeletion(alls, ref, len)+" "+checkVNTR(alls, ref, len));

            if(!pass){
                Error('id_'+id, msg);
                errors=true;
                return false;
            }else{
                RemoveError('id_'+id);
                errors=false;
                return true;
            }
        }else{
            return true;
        }
    }else{
        Error('id_'+id, '* to confirm your allele choice, you must click within the allele field');
        errors=true;
        return false;
    }
}

function checkVNTR(alls, ref, len){

    var vntrRef = getRefAllele(alls[0]);
    //alert(alls[0]+" "+vntrRef+" "+ref+" "+len);
    //alert(ref.indexOf(vntrRef)+" "+(ref.indexOf(vntrRef) !=-1)+" "+(len>=vntrRef.length)+" "+(alls[0].indexOf("(")==0)+" "+(alls[0].indexOf(":")!=-1)+" "+alls[0].indexOf(":"));
    if(ref.indexOf(vntrRef) !=-1 && len>=vntrRef.length && alls[0].indexOf("(")==0 && alls[0].indexOf(":")!=-1){
        return true;
    }else{
        return false;
    }
}

function checkSNP(alls, ref, len){
//alert(alls[0]+" "+ref+ ""+len+" "+(alls[0]==ref)+" "+(maxAlleleLength(alls)==1)+" "+(!doesArrayContain(alls, "-"))+" "+(areNucleotides(alls)));
    if(maxAlleleLength(alls)==1 && len==1 && !doesArrayContain(alls, "-") && areNucleotides(alls)){
        return true;
    }else{
        return false;
    }
}

function checkDeletion(alls, ref, len){
    //alert((alls[0].length==len)+" "+ (alls[0]==ref) +" "+ (alls[alls.length-1])=="-" +" "+ areNucleotides(alls));
    if(alls[0].length==len  && alls[alls.length-1]=="-" && areNucleotides(alls)){
        return true;
    }else{
        return false;
    }
}

function checkInsertion(alls, ref, len){
    //alert(alls+" "+ref+" "+len);
    //alert(len+" "+ alls[0]+" "+(len==2 )+" "+ (alls[0]=="-") +" "+ (alls[0]==ref) +" "+ areNucleotides(alls));
    if(len==2 && alls[0]=="-" && areNucleotides(alls)){
        return true;
    }else{
        return false;
    }
}

function getRefAllele(allsStr){
    var alls=allsStr.split("/");
    var ref =alls[0];
    if(ref.indexOf(")") !=-1){
        ref= ref.substring(1, ref.indexOf(")"))
    }
    return ref;
}

function areNucleotides(a){
    var pass=true;
    for(i=0; i<a.length; i++){
        if(!CheckNucleotide(a[i])){
            pass=false;
        }
    }
    return pass;
}

function doesArrayContain(a, s){
    var pass=false;
    for(i=0; i<a.length; i++){
        if(a[i]==s){
            pass=true;
        }
    }
    return pass;
}

function maxAlleleLength(a){
    var l=0;
    for(i=0; i<a.length; i++){
        if(a[i].length > l){
            l= a[i].length;
        }
    }
    return l;
}


function RemoveUnSetFields(){
    if(!positionSet){
        var n = document.getElementById('pos'+varID);
        var d = selectTopDiv(n);
        RemoveChildernFrom(d);
    }
    if(!polySet){
        var n = document.getElementById('type'+varID);
        var d = selectTopDiv(n);
        RemoveChildernFrom(d);

        var n = document.getElementById('id_alleles'+varID);
        var d = selectTopDiv(n);
        RemoveChildernFrom(d);

    }else{
        if(!allelesSet){
            var n = document.getElementById('alleles'+varID);
            var d = selectTopDiv(n);
            RemoveChildernFrom(d);
        }
    }

    if(!eNumSet){
        var n = document.getElementById('enumber');
        var d = selectTopDiv(n);
        RemoveChildernFrom(d);
    }

    if(!commentSet){
        var n = document.getElementById('comment');
        var d = selectTopDiv(n);
        RemoveChildernFrom(d);
    }

}

function RemoveHiddenFields(){
    var divs = document.getElementsByTagName('div');
    for(var i=0; i<divs.length; i++){
        var d =divs[i];
        if(d.style.display=='none'){
            var p=d.parentNode;
            p.removeChild(d);
        }
    }
}

/**
/ submits poly
*/
    // dont send hidden fields
function SubmitPoly(){
    if(action!='null' && checkAction()){
        var anythingupdated = checkFields();   // check all fields for changes before submitting
//alert(action+" "+anythingupdated+" "+(!warnings)+" "+(submitted)+" "+(!errors));

        // make sure they updated something
        if(action=='update' && !anythingupdated){
            if(!errors) errors=true; // only set errors if there are not already errors
            Error('','you need to change a least one field before updating');
        }


        if((!warnings || submitted) && !errors){
            RemoveHiddenFields();
            RemoveUnSetFields();
            RemoveWarning('warning_msg');

           document.submitPoly.submit();
           //alert('submitting turned off');
        }else if(!errors){
            submitted=true;
            Warning('* optional fields not changed, to continue click submit again.');
            var butt = document.getElementById('submit_button');
            butt.style.color='#FFCC00';
        }
    //}else{
        //Error('','you must select an action before submitting');
        //return false;
    }
    resizeWinTo('myBody');
}


function checkProteinSys(){
    // validate proteomic info

    if (document.submitPoly.proteomic != null){
        var prot = document.submitPoly.proteomic.value;
        if(prot.substring(0,4) == "Ex. "){
            document.submitPoly.proteomic.value="";
        }
    }
}

var pin =true;
function AddProtSys(){
    alert("this isnt working. yell at brian, but remember to tell him EXACTLY what is is you were trying to do.");
    /*
    var prothtml ='<input name="proteomic" id="proteomic" style="font-size:10px" type="text" value="Ex. P106P" size="8" onfocus="if(pin) this.value = \'\'" onblur="pin=false" >';
    var prot = document.getElementById("protSys");
    prot.innerHTML = prothtml;
*/
}
function ChangeCGFPos(nt, posit){
    alert("this isnt working. yell at brian, but remember to tell him EXACTLY what is is you were trying to do.");
    /*
    var poshtml ='<input name="pos'+varID+'" id="pos'+varID+'" style="font-size:10px" type="text" value="'+posit+'" size="18" onmouseout="return nd();">';
    var pos = document.getElementById("id_pos"+varID);
    pos.innerHTML = nt+' '+poshtml;
    var chrpos = document.getElementById("cgf_chr_pos");
    chrpos.innerHTML += ' <font style="font-size:9px;">(auto corrected)</font>';
*/
}


/**
*
*       VALIDATION
*
*/
function checkGene(){
    // its a list
    if(document.submitPoly.targetgene.type != 'hidden' && document.submitPoly.targetgene[0].value == 'NULL'){
   //alert(document.submitPoly.targetgene[0].selected);//+" "+document.submitPoly.targetgene.options[0].selected+" "+(typeof document.submitPoly.targetgene == 'undefined')+" "+(document.submitPoly.targetgene.value != 'NULL'));
        if(!document.submitPoly.targetgene[0].selected){
            RemoveError('target_gene');
            return true;
        }else{
            Error('target_gene')
            return false;
        }
    }else{
        return true;
    }
}

/**
/ check old cgf identifier (Enumber, or assay number)
*/
function checkENumber(){
    var eNumb = document.submitPoly.enumber;
    if(!isHidden(eNumb)){
        if(eNumb && eNumb.value != 'Ex. E1356_101'){
            return true;
        }else if(eNumb){
            return false;
        }
    }else{
        return true;
    }
}

function checkComment(){
     //alert('checking comment');
    // validate comment, put null string if no comment
    var comm = document.submitPoly.comment.value;
    if (comm == 'insert comment'){
        //document.submitPoly.comment.value = "";
        return false;
    }else if (comm != com && document.submitPoly.comment.value != ""){
        document.submitPoly.comment.value = comm;
        return true;
    }else{
        return false;
    }
}

function checkEGPID(){
    var egp = document.submitPoly.external_id;
    if(!isHidden(egp)){
        if(egp.value == '' ||  egp.value == 'gs######'){
            Error('external_id');
            return false;
        }else{
            RemoveError('external_id');
            return true;
        }
    }else{
        return true;
    }
}

function checkPosition(){
    var pass=false;
    var pos = document.getElementById('pos'+varID);
    if(!isHidden(pos)){
        if(typeof pos != 'undefined' && positionSet){
            var posArray = pos.value.split('-');
    //alert(pos+" "+positionSet+" "+posArray.length+" "+posArray[0]+" "+posArray[1])
            if(posArray.length == 1){
                pos.value=posArray[0]+'-'+posArray[0];
                posArray[1]=posArray[0];
                pass= true;
            }else if(posArray.length == 2){ // || posArray[0].length != parseInt(posArray[0]).toString().length ||
                //posArray[1].length != parseInt(posArray[1]).toString().length){
                pass= true;
                //Error('id_pos'+varID);
                //Warning('*','id_pos'+varID);
            }
            // store the new length for checkAlleles
            if(len != 'undefined' && posArray.length==2){
                 len = (parseInt(posArray[1]) - parseInt(posArray[0]))+1;
            }
        }
    }else{
        pass=true;
    }
    return pass;
}

function checkPolyType(){
    var t =document.getElementById("type"+varID);
    if(!isHidden(t) && !polySet){
        return false;
    }else{
        return true;
    }
}


function checkFields(){

    // required fields
    if(!checkGene() || !checkEGPID()){
        errors=true;
    }else{
        errors=false;
    }

    if(!errors){
        if(!checkENumber()){
            Warning('*','id_enumber');
            warnings=true;
        }
        if(!checkPosition()){
            Warning('*','id_pos'+varID);
            warnings=true;
        }
        if(!checkPolyType()){
            Warning('*','id_type'+varID);
            warnings=true;
        }
        if(!checkComment()){
            Warning('*','comment');
            warnings=true;
        }
    }

    if(!checkENumber() && !checkPosition() && !checkPolyType() && !checkComment()){
        return false;
    }else{
        return true;
    }

}



//
// action options
//

function selectTopDiv(e){
    if(e){
        var p = e.parentNode;
        if(p.tagName== 'DIV'){
            return p;
        }else{
            return selectTopDiv(p);
        }
    }
}

function ShowTargetGene(){
    var g = document.getElementById('target_gene');
    if(isHidden(g)){
        var d = selectTopDiv(g);
        d.style.display="";
    }
}

function ShowComment(){
    var g = document.getElementById('comment');
    if(isHidden(g)){
        var d = selectTopDiv(g);
        d.style.display="";
    }
}

function ShowEnum(){
    var g = document.getElementById('id_enumber');
    if(isHidden(g)){
        var d = selectTopDiv(g);
        d.style.display="";
    }
}

function AddOrderIDOption(){
    var p = document.getElementById('id_orderid');
    if(isHidden(p)){
        var d = selectTopDiv(p);
        d.style.display="";
    }

    var a = document.createElement('a');
    a.href='javascript:AddOrderID();';
    a.innerHTML='add order id';
    p.appendChild(a);
}

function AddOrderID(){
    var p = document.getElementById('id_orderid');
    var o = document.createElement('input');
    o.type='text';
    o.name='orderid';
    o.id = 'orderid';
    o.value='order id';
    o.style.fontSize="10px";
    o.style.color="#A1A1A1";
    o.onfocus=ClearInput;
    if(p.childNodes[0]) p.removeChild(p.childNodes[0]);
    p.appendChild(o);
}

function ShowBioseqOption(){
    var g = document.getElementById('bioseq');
    var d = selectTopDiv(g);
    d.style.display="";
}

function ShowExternalOption(){
    var g = document.getElementById('external_id');
    var d = selectTopDiv(g);
    d.style.display="";
}

function ShowSubmissionInfo(){
    var s = document.getElementById('sub_info');
    if(isHidden(s)){
        var d = selectTopDiv(s);
        d.style.display="";
        var hr = document.getElementById('sub_hr');
        hr.style.display="";
    }
}

function SetEditableFields(){

    var p = document.getElementById('id_pos'+varID);

    var d = selectTopDiv(p);
    d.style.display="";

    var t = document.getElementById('id_type'+varID);

    var td = selectTopDiv(t);
    td.style.display="";

    var a = document.getElementById('id_alleles'+varID);

    var ad = selectTopDiv(a);
    ad.style.display="";


}

var action='null';
function SetActionOptions(e){
    action = e.options[e.selectedIndex].value;

    HideAllEntryFields();

    if(action!='null'){

        ShowSubmissionInfo();

        if(action=='sequencing'){
            ShowBioseqOption();
        }else if(action=='egp'){
            ShowExternalOption();            
            ShowBioseqOption();
        }else if(action=='update'){
            ShowEnum();
            SetEditableFields();

            var vartochange = CreateHiddenField('vars_to_change', varID);
            document.submitPoly.appendChild(vartochange);

        }else if(action=='cgfalias'){
            ShowEnum();
        }else if (action=='assay'){
            AddOrderIDOption();
            ShowBioseqOption();
        }

        ShowTargetGene();
        ShowComment();

        RemoveError('');

        resizeWinTo('myBody');
    }
}

function HideAllEntryFields(){
    var d = document.getElementById('entrydata');
    if(d){
        var divs = d.getElementsByTagName("div");
        for(var i=0; i<divs.length; i++){
            divs[i].style.display="none";
        }
    }
}

function isHidden(e){
    if(e){
        var d = selectTopDiv(e);
        if(d.style.display=='none'){
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

function GetAllelesFromPolyType(v, ref){

    var a=ref;
    if(v!='null' && v=='SNP'){
        a=ref+'/';
    }else if(v!='null' && v=='INSERTION'){
        a='-/';
    }else if(v!='null' && v=='DELETION'){
        a=ref+'/-';
    }else if(v!='null' && v=='VNTR'){
       a='('+ref+')';
    }
    return a;
}

function ChangeAlleles(t, ref){
    var type = t.options[t.selectedIndex].value;
    var a = GetAllelesFromPolyType(type, ref);

    var p = document.getElementById('id_alleles'+varID);
    RemoveChildernFrom(p);

    AddAlleles('alleles'+varID, a, type);

    var input;
    if(type && (type=="VNTR" || type=="INSERTION" || type=="DELETION")){
        input = p.getElementsByTagName('textarea');
    }else{
        input = p.getElementsByTagName('input');
    }
    input[0].onfocus= ClearStyle;
    input[0].onblur= SetAllelesTrue;
    polySet=true;
    resizeWinTo('myBody');
}


function SetAllelesTrue(){
    allelesSet=true;
    RemoveMessages('id_alleles'+varID);
}


