
// handle upload of new pdbs
  $(document).ready(function() {
    $('#uploadForm').submit(function() {

      if(files.length === 1) {
        alert("Please upload at least two PDB files for comparison.");
        return false;
      } else {
        // displayMessage("Computing alignment on: " + getNewProteinNames());
        displayInfo("Computing alignment on: " + getNewProteinNames());
            $(this).ajaxSubmit({
                error: function(xhr) {
                  status('Error: ' + xhr.status);
                },
                success: function(response) {
                  console.log(response);
                  if(response !== "Success"){
                    displayInfo("Alignment failure")
                    alert(response);
                  } else {
                    redrawAll();
                    // displayMessage("Computing comparative visualization for: " + getProteinNames());
                    displayInfo("Computing comparative visualization for: " + getProteinNames());
                  }
                }
        });
        return false;
      }
    });    
  });

//handle wannabePDBs
  $(document).ready(function () {
    $('#wannabepdbs').on('submit', function(e) {
        e.preventDefault();
        
        // console.log(document.getElementById('wannabepdbs_input').value);
        // displayMessage("Downloading: " + document.getElementById('wannabepdbs_input').value);
        displayInfo("Downloading: " + document.getElementById('wannabepdbs_input').value);
        $(this).ajaxSubmit({
            error: function(xhr) {
              alert('Error: ' + xhr.status);
            },
            success: function(response) {
              console.log(response);
              if(response !== "Success"){
                displayInfo("Download failure")
                alert(response);
              } else {
                getDownloadedData(document.getElementById('wannabepdbs_input').value.replace(/\s/g, '').split(','));
                redrawAll();
                // displayMessage("Computing comparative visualization for: " + getProteinNames());
                displayInfo("Computing comparative visualization for: " + getProteinNames());
              }
            }
        });
    });
  });

window.onresize = function(event) {
    redrawAll();
};

function displayMessage(s){
  $("#toBeAligned").val(s);
  document.getElementById("info_msg").innerHTML = s;
  displayedMessage = s;
}

function displayInfo(s){
  if (s === "done"){document.getElementById('info').style.display = "none"; return}
  else if(document.getElementById('info').style.display === "none") {document.getElementById('info').style.display = "";}
  document.getElementById("info_msg").innerHTML = s;
  // displayedMessage = s;
}

function resetDefault(){
  window.location.reload();
}

function disableSelection(target){
    if (typeof target.onselectstart!="undefined") //IE route
      target.onselectstart=function(){return false}
    else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
      target.style.MozUserSelect="none"
    else //All other route (ie: Opera)
      target.onmousedown=function(){return false}
    target.style.cursor = "default"
}

// gets info about new uploaded data from input file field
function getFileData(myArray){
  files = [];
  pdbFiles = [];
  newProteins = [];
  var f = "";
  for (var i = 0; i < myArray.length; i++) {
    var prot = myArray[i].name.substr(0,myArray[i].name.indexOf('.'));
    files.push(prot);
    newProteins.push(prot);
    f += prot;
  }

  //$("#toBeAligned").val("Proteins to be aligned: " + getProteinNames());
  //displayedMessage = "Proteins to be aligned: " + getProteinNames();
  displayMessage("Proteins to be aligned: " + getNewProteinNames());
  if(myArray.length === 2) {
    fastaFile = "./public/uploads/"+f+"/"+f+".fasta"; 
  } else {
    fastaFile = "./public/uploads/"+f+"/"+f+".ali";
  }
  for (var i = 0; i < myArray.length; i++) {
    pdbFiles[i] = f+"/"+myArray[i].name;
  }
  $("#submit_btn").removeAttr("disabled");
}

// gets info about new downloaded data from rcsb.com
function getDownloadedData(myArray){
  files = [];
  pdbFiles = [];
  newProteins = [];
  var f = "";
  for (var i = 0; i < myArray.length; i++) {
    var prot = myArray[i];
    console.log(prot);
    files.push(prot);
    newProteins.push(prot);
    f += prot;
  }

  //$("#toBeAligned").val("Proteins to be aligned: " + getProteinNames());
  //displayedMessage = "Proteins to be aligned: " + getProteinNames();
  displayMessage("Proteins to be aligned: " + getNewProteinNames());
  if(myArray.length === 2) {
    fastaFile = "./public/uploads/"+f+"/"+f+".fasta"; 
  } else {
    fastaFile = "./public/uploads/"+f+"/"+f+".ali";
  }
  for (var i = 0; i < myArray.length; i++) {
    pdbFiles[i] = f+"/"+myArray[i] + ".pdb";
  }
}

function downloadFiles(){
  $.get(
    "/download",
    {proteins : getProteinNames()},
    function(data) {
       window.location = data;
  });
}

function showUploadPDBs(){
  if(document.getElementById('uploadForm').style.display === "none") {document.getElementById('uploadForm').style.display = "block";}
  else {document.getElementById('uploadForm').style.display = "none";}
  document.getElementById('wannabepdbs').style.display = "none";
}

function showWannabePDBs(){
  document.getElementById('uploadForm').style.display = "none";
  if(document.getElementById('wannabepdbs').style.display === "none") {
    document.getElementById('wannabepdbs').style.display = "block";
    document.getElementById('wannabepdbs_input').focus();
  } else {
    document.getElementById('wannabepdbs').style.display = "none";
  }
}

function showDynamics(){
  alert("We are working on this ;-)");
}

  function getProteinNames(){
    var s = "";
    for (var i = 0; i < proteins.length-1; i++) { s += proteins[i] + ", ";}
    return s + proteins[proteins.length-1];
  }

  function getNewProteinNames(){
    var s = "";
    for (var i = 0; i < newProteins.length-1; i++) { s += newProteins[i] + ", ";}
    return s + newProteins[newProteins.length-1];
  }

//reads fasta file from server memory
  function readTextFile(file) {
      var rawFile = new XMLHttpRequest();
      rawFile.open("GET", file, false);
      rawFile.onreadystatechange = function () {
          if (rawFile.readyState === 4) {
              if (rawFile.status === 200 || rawFile.status == 0) {
                  fasta = rawFile.responseText;
              }
          } else {
              console.log("File not supported!");
          }
      }
      rawFile.send(null);
  }

//creates 
  function createDoubles(){

    alignedSS = alignedResidues.slice();

    for(var i = 0; i < proteins.length; i++){
      var indexAl = 0;
      var indexNotAl = 0;

      alignToNotAlign[i] = [];
      notAlignToAlign[i] = [];
    
      for (var j = 0; j < alignedSS[i].length-1; j++) {
        if(alignedSS[i].charAt(j) === '-'){
        } else {
          if(indexAl < ss[i].length){
            //console.log(alignedSS[i])
              alignedSS[i] = alignedSS[i].replaceAt(j, ss[i][indexAl]);
              notAlignToAlign[i][indexAl] = j;
              alignToNotAlign[i][j] = indexAl;
              indexAl++;
          }
        }
      }
    }
  }

  String.prototype.replaceAt=function(index, replacement) {
      return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
  }

//Browse button shit
$(function() {
  // We can attach the `fileselect` event to all file inputs on the page
  $(document).on('change', ':file', function() {
    var input = $(this),
        numFiles = input.get(0).files ? input.get(0).files.length : 1,
        label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
    input.trigger('fileselect', [numFiles, label]);
  });

  // We can watch for our custom `fileselect` event like this
  $(document).ready( function() {
      $(':file').on('fileselect', function(event, numFiles, label) {

          var input = $(this).parents('.input-group').find(':text'),
              log = numFiles > 1 ? numFiles + ' files selected' : label;

          if( input.length ) {
              input.val(log);
          } else {
              if( log ) alert(log);
          }

      });
  });
  
});