//	Function is called when the page is loaded
function pageIsReady() {
  //checkTraceProgress("1nvtA19366")();
  
 // Variables storing state of User Interface
  pdbid_uic = new user_interface_component("mypdbid", true, false);
  traceimage_uic = new user_interface_component("imageContainer", false, true);
  displaymotifs_uic = new user_interface_component("displayMotifs", false, true);
  selectlabels_uic = new user_interface_component("selectLabels", false, true);
  submittemplate_uic = new user_interface_component("submitTemplates", false, true);

  reset();
  
  // Add listeners to the toggleable User Interface Components
  $("#displayMotifs").hide();
  $("#displayMotifsButton").click(function() { displaymotifs_uic.toggle() });
  $("#displayPDBIDFormButton").click(function() { pdbid_uic.toggle() });
  $("#displayTraceImageButton").click(function() { traceimage_uic.toggle() });
  $("#displaySelectLabelsButton").click(function() { selectlabels_uic.toggle() });  
  $("#displayPDBIDHelpButton").click(showPDBIDHelp);
  $("#uploadForm").submit(uploadSubmit);
  $("#displayUploadHelpButton").click(showUploadHelp);
  $("#displayTemplateHelpButton").click(showTemplateHelp);
  $("#displayCustomLabelHelpButton").click(showCustomLabelHelp);
  $("#displayFindMatchHelpButton").click(showFindMatchHelp);
  $("#helpLink").click(openHelpDoc);
  $("#submit_pdbid").click(submitForm(1, 0, ""));			      // Add a function that will be called  when the form is submitted
  $("div#displayMotifs input[@type='checkbox']").val("");	      // clear out the default value 
  $("div#displayMotifs input[@type='checkbox']").click(submitForm(0, 0, "")); 
  $("#submitTemplates").click(submitTemplates);
  $("div#selectLabels #matchTemplates").click(matchTemplates);
  $("div#selectLabels #addUserLabel").click(addUserLabel);
  $("div#displayUserMotifs input[@type='text']").delayedObserver(.01, setCheckedStatus);
  
  // (function(value, object) { alert(object.attr("id")); } ));
} 

var firstTime = "Y";
function reset() {

  $("span#invalidPDBCode").hide();				      // Hide the error span and the loading span
  $("span#loading").hide();
  $("span#uploadingLoading").hide();
  $("span#uploading").hide();
  $("span#tracing").hide();
  $("#imageContainer").hide();
  $("div#selectLabels").hide();
  $("#submitTemplates").hide();
  $("div#templateMatchResults").hide();
  $("div#mystatus").hide();
  pdbid_uic.show();
  traceimage_uic.hide();
  displaymotifs_uic.hide();
  selectlabels_uic.hide();
  submittemplate_uic.hide();
 
  hideAll();
  
  $("span#userpdbid").empty();
  resetLabels();
  firstTime = "Y";
  $("#traceImage").css("background-image", "");
  $("#displayUserMotifs input[@type='checkbox']").attr("checked", "")
  $("#displayUserMotifs input[@type='text']").attr("value", "")
  $("#exactlySixLabel").hide();
  
  setCheckedStatus(null, null);
  isCustom = 0;
  customDirectory = "";
  submittedSearch = false;  
}

var isCustom = 0;
var customDirectory = "";

function submitForm(isFirstRun,pIsCustom,pCustomDirectory) {    
  isCustom = pIsCustom; 
  customDirectory = pCustomDirectory;

  return function() {
    hideAll();     
    if($("#pdbid").val().match(/^\d\w{3}\w?$/)) {             // Make sure that the pdbCode is in a valid format
      $("span#invalidPDBCode").hide();
    } else {
      $("span#invalidPDBCode").show();
      return false;
    }

    if(isFirstRun) {
	  //traceimage_uic.show();
      $("#pdbid").val(formatPDBID($("#pdbid").val()));
    } else {
      validateAndShowSubmitTemplateButton();
    }

    if (isCustom == 0) {
        $("span#loading").show();
    }

    var currentpdbid = $("#pdbid").val();
    //alert(currentpdbid);
    var selectedResidues = getSelectedResidues();
    //alert(motifstring);

       $.post( "/cgi-bin/eta/createImage.cgi",   // Post the form to the cgi page.  Pass the pdb code and a function
      { pdbid: currentpdbid,				// that will be called when the CGI is finished.
	    residues: selectedResidues, 
	    firstRun: isFirstRun,
        custom: isCustom,
        customDir: customDirectory
      },	
      handleData
    );
    return isFirstRun != 1;
  }; 
}

function validateUpload() {
  return $("#nameOfFile").val().length > 0;
}

function uploadSubmit() {
  if($("#nameOfFile").val().length <= 0) {
    alert("Please select a .zip file containing trace data to upload."); 
    return false;
  }

  var params = {}; 
  isCustom = 1;
  params["custom"] = isCustom;
  $("form#uploadForm").find("#nameOfFile").each(function() { params[this.id] = this.value; }); 
  $.post("/cgi-bin/eta/handleZipFile.cgi", params, handleUploadedFormData(1)); 
  $("span#uploading").show();
  return true; // return true so that the submit event happens
}

function handleUploadedFormData(pIsCustom) {
  return function(data) {
    //alert("handleUploadFormData:\n" + data);
    $("span#uploading").hide();
    customDirectory = "";
    var arguementHash = parseArguements(data);
    for (key in arguementHash) {
      if(key == "Directory") {
        customDirectory = arguementHash[key]; 
      } else if (key == "Error") {
        alert(arguementHash[key]); 
        return false;
      } else if (key == "PDB") {
        $("#pdbid").val(arguementHash[key]);
      }
    }
    $("span#uploadingLoading").show();
    submitForm(1, pIsCustom,  customDirectory)();
  }   
}

function resetToLabelSelection() {
  traceimage_uic.hide();
  displaymotifs_uic.hide();
  selectlabels_uic.show();
  submittemplate_uic.hide();
}

function resetToResidueSelection() {
  traceimage_uic.show();
  displaymotifs_uic.show();
  selectlabels_uic.hide();
  //submittemplate_uic.hide();
  $("div#labelControls").hide();
  submittemplate_uic.show();
  resetLabels();
}

function resetLabels() {

  $('div#labels').empty();
  $('table#userLabelTable').empty();
}

function validateAndShowSubmitTemplateButton() {
   	if(requiredResiduesSelected()) {
		submittemplate_uic.show();
        $("#exactlySixLabel").hide();
        return true;
	} else {
		submittemplate_uic.hide();
        $("#exactlySixLabel").show();
        return false;
	}
}

function toggle(feature, visible){
	if (!visible){
		$("#" + feature).slideDown();
	} else {
		$("#" + feature).slideUp();
	}
}

function formatPDBID(pdbID) {
    //if(pdbID.slice(-1) == "_") {
     // pdbID = pdbID.slice(0, -1);
    //}

    if(pdbID.length == 4) {
      pdbID = (pdbID + "_").toLowerCase();
    } else if (pdbID.length == 5){
      pdbID = pdbID.slice(0,4).toLowerCase() + pdbID.slice(4).toUpperCase();
    }
    
    return pdbID
}

function handleData(data){
  //alert("Error in handleData: " + data);
  $("span#loading").hide();
  $("span#uploadingLoading").hide();
  
  var arguementHash = parseArguements(data);
  //$("#sessionFile").attr("href", "images/templates/" + arguementHash["PyMolSession"]);
  //$("#traceImage").attr("href", "images/templates/" + arguementHash["PyMolSession"]);
  for (key in arguementHash) {
    if (key == "CreatedImage") {
      if(isCustom == 1) {
        var fileName = arguementHash[key];     
        $("#sessionFile").attr("href", "output/" + customDirectory + "/" + arguementHash["PyMolSession"]);
        $("#sessionFileLink").attr("href", "output/" + customDirectory + "/" + arguementHash["PyMolSession"]);
        $("#traceImage").css("background-image", "url(\"output/" + customDirectory + "/" + fileName + "?" + (new Date()).getTime() + "\")");
        $("#traceImage").attr("href", "output/" + customDirectory + "/" + arguementHash["PyMolSession"]);
      } else {
        var fileName = arguementHash[key];     
        $("#sessionFile").attr("href", "images/templates/" + arguementHash["PyMolSession"]);
        $("#sessionFileLink").attr("href", "images/templates/" + arguementHash["PyMolSession"]);
        $("#traceImage").css("background-image", "url(\"images/templates/" + fileName + "?" + (new Date()).getTime() + "\")");
        $("#traceImage").attr("href", "images/templates/" + arguementHash["PyMolSession"]);
      }
    } else if (key == "Residues" && arguementHash["FirstRun"] == "True") {
      setETMotifs(arguementHash[key].split(","));
    } else if (key == "Error") {
      alert(arguementHash[key]);
      if(arguementHash["FirstRun"] == "True") {
        traceimage_uic.hide();
        return false;
      }
    } else if (key == "NoTrace") {
      if (arguementHash[key] == "True") {
        //alert("Unable to find ET data, running trace.");
        runTrace();
        return false;
      }
    }
  }

  if(arguementHash["FirstRun"] == "True") {
    $("div#selectLabels").show(); 
    $("div#labelControls").hide();
	// Adjust User Interface for Trace Viewing and Residue Selection
	traceimage_uic.show();
	pdbid_uic.hide();
	$("span#userpdbid").empty().append(": " + $("#pdbid").val());
	displaymotifs_uic.show();
	validateAndShowSubmitTemplateButton();
  }
}

function runTrace() {
  //$("#pdbid").val("1jrkA");
  var currentpdbid = noUnderscores($("#pdbid").val());
  var traceID = (new Date()).getDate();
  $("span#tracing").show();
  $.post( "/cgi-bin/runET/runET2.cgi",
  { txtPDB_ID: currentpdbid,
    redFLAG: "ON",
    txtTraceID: traceID,
    txtE_CUTOFF: "0.05",
    txtNUM_PROT: "500",
    txtMAX_BLAST_RETURN: "500",
    txtMIN_BLAST_EVAL: "1e-250",
    txtMAX_BLAST_EVAL: "0.05",
    txtMIN_BLAST_IDENT: "20",
    txtMAX_BLAST_IDENT: "95",
    txtMIN_BLAST_FRAC: "0.5",
    txtFRAG_LENGTH: "0.9", 
    txtSHORT_LENGTH: "0.8",
    txtREAL_VAL: "ON",
    txtSIM_MATRIX: "blosum62"
  },	
  handleTraceProgressData(traceID)
  );
}

function checkTraceProgress(traceID) {
  return function() {
    var pdbID = noUnderscores($("#pdbid").val());
    $.post( "/cgi-bin/runET/runET2.cgi",
    { TraceID: pdbID + traceID
    },
    handleTraceProgressData(traceID)
    );
  }
}

function handleTraceProgressData(pTraceID) {
  return function(data) {
    //alert(data);
    var finished = data.toUpperCase().indexOf("TRACE COMPLETE") >= 0;
    var error = data.toUpperCase().indexOf("ERROR") >= 0;
    if(error) {
      //alert(data);
      //var errIndex = data.toUpperCase().indexOf("ERROR");
      //var errorMessage = data.slice(errIndex, data.indexOf("\n", errIndex))
      alert("There was an error running the trace.  Please try running the trace with the Evolutionary Trace Viewer first and then uploading the trace to the ETA server.");
      $("span#tracing").hide();
    } else if (finished) {
      //alert(data);
      $("span#tracing").hide();
      var currentpdbid = noUnderscores($("#pdbid").val());
      $.post("/cgi-bin/eta/handleZipFile.cgi", 
            { nameOfFile: "/var/www/html/download/" + currentpdbid + pTraceID + ".zip",
              custom: 0
            },
         handleUploadedFormData(0)); 
    } else {
      $("span#tracing").empty().append(getStatusMessage(data));
      setTimeout(checkTraceProgress(pTraceID),2500);
    }
  }
}

len = 0;
function getStatusMessage(data) {
  result = "Running Evolutionary Trace"; 
  var strings = ["Running Evolutionary Trace",
    "Downloading PDB file",
    "Extracting chain/sequence from PDB file",
    "BLAST search",
    "Selecting and retrieving homologs",
    "Removing identical sequences",
    "Generating the alignment",
    "Aligning"
    ];
  for(var i = 0; i < strings.length; i++) {
    if(data.indexOf(strings[i]) >= 0) {
      result = strings[i];
      if(i >= 1) {
        s = ". . . ";
        for(j = 0; j < len; j++) {
          s += ". ";
        }
        result = "Running Evolutionary Trace: " + result + s;
      }
    }
  }
  len = (len + 1) % 7
  return result;
}

function noUnderscores(s) {
  return s.replace(/_/, "");
}

function requiredResiduesSelected() {

  var selectedResidues = getSelectedResidues(); 
  if(selectedResidues.length == 0) {
    return false;
  }
  $("span#traceimage").empty().append(": " + selectedResidues);
  var motifs = selectedResidues.split(","); 
  var uniqCount = 0;
  var uniq = [];
  var shouldReturn = false;
  jQuery.each(motifs, function(i, residue) {
    uniq[residue] = "Y";
    if(!residue.match(/^\d+$/)) {
      alert("\"" + residue + "\" is not a valid residue number.");
      shouldReturn = true;
    } 
  });

  if(shouldReturn) {
    return false;
  }

  jQuery.each(uniq, function(i, val) {
    if(val == "Y") {
      uniqCount++;
    }
  });

  var REQUIRED_RESIDUES = 6;
  if(uniqCount != motifs.length) {
    alert("All six residues must be unique.");
  }
  return (REQUIRED_RESIDUES == motifs.length) && (REQUIRED_RESIDUES == uniqCount);
}

function getSelectedCheckBoxes(divID) {
  return $("div#" + divID + " input[@type=checkbox]:checked");
}

function submitTemplates() {
  hideAll();

  if(!requiredResiduesSelected()) {
    alert("Please select six residues.");
    return false;
  } 

  $.post("/cgi-bin/eta/createLabels.cgi", 
    { pdbid: $("#pdbid").val(),
      residues: getSelectedResidues(),
      custom: isCustom,
      customDir: customDirectory
    },
    handleLabelData
  );

  $("span#loading").show();
  return false;
}

function handleLabelData(data) {
  //alert("create Labels: " + data);
  var arguementHash = parseArguements(data);
  $("span#loading").hide();

  for (key in arguementHash) {
    if (key == "Error") {
      alert(arguementHash[key]);
      return;
    } else if (key == "Output") {
      $("div#labels").empty().append(arguementHash[key]);
      //$("div#labels td").attr("align", "center");
      $("div#labels tr").each( function(i) {
            if(i % 2 == 1){
            $(this).attr("bgcolor", "#cccccc");
        } else {
            $(this).attr("bgcolor", "#e2e2e2");
        }
      })

      $("div#labelControls").show();
      selectlabels_uic.show();
      traceimage_uic.hide(); 
      displaymotifs_uic.hide();
    }
  }
}

// build a comma seperated string of the motif numbers that have been selected by the user
/*function getSelectedMotifs() {
  var checkBoxes = getSelectedCheckBoxes("displayMotifs");
  var result = "";
  for(i = 0; i < checkBoxes.length; i++) {
    if(result.length > 0) {
      result += ",";
    }
    checkBox = checkBoxes[i];
    result += checkBox.value;
  }
  return result;
}
*/

function validateUserTemplates(userTemplates) {
  if(userTemplates.length <= 0) {
    return true;
  }
  var result = true;
  var aas = new Array("G", "P", "A", "V", "L", "I", "M", "C", "F", "Y", "W", "H", "K", "R", "Q", "N", "E", "D", "S", "T");
  jQuery.each(userTemplates.split("|"), function(i, template) {
    labels = template.split(" ");
    for(var j = 2; j < labels.length; j+=2) {
      aa = labels[j];
      if(jQuery.inArray(aa.trim().toUpperCase(), aas) < 0) {
        alert(aa + " is not a valid amino acid label.");
        result = false;
        break;
      }
    }
    if(!result) {
      return result;
    }
  });
  return result;
}

// The default template will have the default residues selected and the default labels
function isDefaultTemplate() {
  return areDefaultResidues() && areDefaultLabels();
}

function areDefaultResidues() {
  return $("div#displayETMotifs input[@type=checkbox]:checked").length == 6;
}

function areDefaultLabels() {
  var result = true;
  $("div#labels input[@type=checkbox]").each ( function() {
    if($(this).attr("isDefault") == "True" && !$(this).attr("checked")) {
      result = false;
    } else if ($(this).attr("isDefault") == "False" && $(this).attr("checked")) {
      result = false;
    }
  });
  return result;
}

// build a string and post it back to the cgi pages
function matchTemplates() {
  var checkBoxes = getSelectedCheckBoxes("labels");
 
  var result = "";
 
  for(i = 0; i < checkBoxes.length; i++) {
  //  result += checkBoxes[i].value + "\n";
    result += checkBoxes[i].value + "|";
  }
  userTemplates = userEnteredTemplates();
  if(userTemplates == "Error") {
    return false;
  }
  if(!validateUserTemplates(userTemplates)) {
    return false;
  } 
  selectlabels_uic.hide();
  result += userTemplates;
  $.post( "/cgi-bin/eta/makeTemplateFile.cgi",
    {argumentString: result, 
    isDefaultTemplate: isDefaultTemplate(),
    custom: isCustom, 
    customDir: customDirectory
    },
    handleTemplateMatchData
  );
    $("span#loading").show();
  return false;
}

function userEnteredTemplates() {
  var result = "";
  var selectedCheckBoxes = getSelectedCheckBoxes("userLabels");
  
  for(i = 0; i < selectedCheckBoxes.length; i++) {
    var substituteString = selectedCheckBoxes[i].value;
    //alert(substituteString);
    var tableRow = getTableRowOfCheckBox(selectedCheckBoxes[i]);
    var textBoxes = $(tableRow).children().find("input[@type='text']");
    var shouldAdd = true;
    for(j = 0; j < textBoxes.length; j++) {
      if(textBoxes[j].value.trim().length > 0) {
	    // only replace the next pound sign with the value as we fill in the string
	    substituteString = substituteString.replace(/#/, textBoxes[j].value.trim());
      } else {
        // Don't add the values if one of the text boxes is not filled in
        shouldAdd = false;
        alert("Please fill in labels for all of the residues.");
        return "Error";
      }
    }
    if(shouldAdd) {
      result += substituteString + "|";
    }
  } 
  return result;
}

function getTableRowOfCheckBox(checkBox) {
  return checkBox.parentNode.parentNode;
}

var intervalID = -1;

function handleTemplateMatchData(data) {
  $("span#loading").hide();
  //$("div#templateMatchResults").show();
  //$('div#templateMatchResults').empty().append(data);
  var arguementHash = parseArguements(data);
  var currentpdbid = $("#pdbid").val();
  for (key in arguementHash) {
    if (key == "Error") {
      return false;
    }else if (key == "MD5Sum"){
      var MD5Sum = arguementHash[key];
      $("div#mystatus").show(); 

      $.post( "/cgi-bin/eta/runTemplateSearch.cgi",   // Post the form to the cgi page.  Pass the pdb code and a function
      { PDBID: currentpdbid,                            // that will be called when the CGI is finished.
        MD5SumValue: MD5Sum,
        custom: isCustom 
      },
      handleCallOutput
      );
      submittedSearch = true;
      intervalID = setInterval(checkIsDone(data), 3000);  
      // load the status of runTemplateSearch into the frame under the status section
      window.frames['StatusOutput'].location="statusOutput.html";
    }  
  }
}

function checkIsDone(data) //This function will check to see if runTemplateSearch is completed. If so, it will redirect the page
{   
   return function() 
   {
      var arguementHash = parseArguements(data);

      for (key in arguementHash)
      {
        
      if(key == "MD5Sum")
        {
           var MD5Sum = arguementHash[key];
           var currentpdbid = $("#pdbid").val();
        }
      }

      $.post( "/cgi-bin/eta/iCanHazResultz.cgi",
        { PDBID: currentpdbid,
          MD5SumValue: MD5Sum
        },
        handleIsDoneResponse
      );
   }
}

function handleIsDoneResponse(data)
{
  //alert(data);
  var arguementHash = parseArguements(data);
  var MD5Sum = "";
  var currentpdbid = $("#pdbid").val();
  var isComplete = "";
  for (key in arguementHash) {
    if(key == "Done") {
      isComplete = arguementHash[key];
    } else if(key == "MD5Sum") {
       MD5Sum = arguementHash[key];
    } else if (key == "Error") {
      alert(argumentHash[key]);
      clearInterval(intervalID);
      reset();
      return;
    }
  }

  if(isComplete == "T") {
     window.location="output.php?load=" +MD5Sum+ "/" +currentpdbid+ ".html";
     submittedSearch = false;
  } else if(isComplete == "N") {
     window.frames['StatusOutput'].location="statusOutput.html";
  } else if(isComplete == "E") {
      submittedSearch = false;
      clearInterval(intervalID);
      alert("There was a fatal error in the ETA pipeline.");
      reset();
  } else {
      window.frames['StatusOutput'].location="output/" +MD5Sum+ "/" +currentpdbid+ "_status.html";  
      // window.frames['StatusOutput'].location.reload();
  }
}


function handleCallOutput(data)
{

// :-)  Does nothing... This is a dummy function that should not do anything
//   window.location="http://mammoth.bcm.tmc.edu/eta/output.php?load=" +MD5Sum+ "/" +currentpdbid+ ".html";
}



function addUserLabel() {
  var residues = getSelectedResidues();
  var selectedResidues = residues.split(",");
  var checkBoxes = getSelectedCheckBoxes("labels");
  var userLabelRow =
    "<tr><td width=20px><input type='checkbox' checked value='" + toSubstitutionValue(checkBoxes[0].value) + "'></input>" + 
      "<td><input type='text' maxlength='1' class='userLabelInput'></input></td>" + 
      "<td><input type='text' maxlength='1' class='userLabelInput'></input></td>" + 
      "<td><input type='text' maxlength='1' class='userLabelInput'></input></td>" + 
      "<td><input type='text' maxlength='1' class='userLabelInput'></input></td>" + 
      "<td><input type='text' maxlength='1' class='userLabelInput'></input></td>" + 
      "<td><input type='text' maxlength='1' class='userLabelInput'></input></td></tr>";
  var userLabelHeading = "<tr><th colspan='7'><center><font color='white'> Custom Amino Acid Combinations</font></center></th></tr>";
  var tableHeading = "<tr><th></th>" + 
      "<th>" + selectedResidues[0] + "</th>" + 
      "<th>" + selectedResidues[1] + "</th>" +
      "<th>" + selectedResidues[2] + "</th>" +
      "<th>" + selectedResidues[3] + "</th>" +
      "<th>" + selectedResidues[4] + "</th>" +
      "<th>" + selectedResidues[5] + "</th>";
  if(firstTime == "Y")
  {
    $("#userLabelTable").append(userLabelHeading);
    $("#userLabelTable").append(tableHeading);
    $("#userLabelTable").append(userLabelRow);
    firstTime = "N";
  }
  else
  {
    $("#userLabelTable").append(userLabelRow);
  }

}
// Put placeholders in for amino acid types in template string. 
// This lets us substitute user labels into the template. 
function toSubstitutionValue(str) {
  return str.replace(/\s[a-zA-Z]/g, " #");
}

function getSelectedResidues() {
  var checkboxes = $("#displayETMotifs input[@type='checkbox']:checked");
  var result = "";
  checkboxes.each( function() {
      result += $(this).val() + ",";
  });

  var userCheckBoxes = $("#displayUserMotifs input[@type='checkbox']:checked");
  userCheckBoxes.each( function() {
  	result += $("#userMotif" + $(this).attr("i")).val() + ",";
  });
  
  return result.replace(/,$/, '');
}

function setETMotifs(motifList) {
	var residueLabels = $("#displayETMotifs span");
	residueLabels.each( function(i) {
    	$(this).empty().append(motifList[i]);	// set the text in the span to be the residue number.
	});

	var checkboxes = $("#displayETMotifs input[@type='checkbox']");
	checkboxes.each( function(i) {
	    $(this).val(motifList[i]);
	    $(this).attr("checked", "checked");
	});
    $("#displayETMotifs").show();
}

function parseArguements(data) {					// hash the arguements recieved from the cgi page  
var arguementHash = {};						// The key will be the name of the arguement, the value will the the value of the arguement
  var lines = data.split('\n'); 
  for (i=0; i<lines.length; i++) {
    var line = lines[i];
    if(line.length == 0 || seperatorIndex(line) < 0) {
      continue;
    }
    var key = line.substring(0, seperatorIndex(line));
    var value = line.substring(seperatorIndex(line) + 1);
    arguementHash[key] = value;
  }
  return arguementHash;
}

function seperatorIndex(line) {						// return the index of the seperator in the current line
  return line.indexOf(":");
}

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };

// Template for the user_interface_component objects used later
//	These objects essentially store the status of components of the input page, allowing features to be toggled open and closed, as well as locked
function user_interface_component(identifier, visibility, locked){
	this.id = identifier;
	this.locked = locked;
	this.visible = visibility;
	this.toggle = toggle_visibility;
	this.lock = lock;
	this.unlock = unlock;
	this.show = make_visible;
	this.hide = make_hidden;
	this.lockedText = $("#"+identifier).attr("lockedText") 
}

//	Changes the visibility of a uic
var submittedSearch = false 

function toggle_visibility() {
  if(!this.locked) {
      toggle(this.id, this.visible);
      this.visible = !this.visible;
  } else {
    if (this.id == "mypdbid") {
      if(confirm("Are you sure you would like to start over?")) {
        reset();
      }
    } else if (this.id == "imageContainer" && (selectlabels_uic.locked == false || submittedSearch)) {
      if(confirm("Are you sure you would like to return to the residue selection?")) {
        resetToResidueSelection();
        if(submittedSearch) {
          stopSearch();
        }
      }
    } else if (this.id == "selectLabels" && (displaymotifs_uic.locked == false || submittedSearch)) {
      if(submittedSearch) {
        if(confirm("Are you sure you would like to return to the label selection?")) {
          resetToLabelSelection();
          stopSearch();
        }
      } else {
        alert("Please select a set of 6 residues.");
      }
    } else {
        alert(this.lockedText);
    }
  }
}

function stopSearch() {
  clearInterval(intervalID);
  submittedSearch = false;
  $("div#mystatus").hide();
}

function testCalling() {
  alert("called");
}

//	Forces a uic to be visible
function make_visible(){
	this.unlock();
	if(!this.visible){ this.toggle(); }
}

//	Forces a uic to be hidden
function make_hidden(){
	if(this.visible){ this.toggle(); }
	this.lock();
}

// Lock a uic
function lock(){
	this.locked = true;
}
// Unlock a uic
function unlock(){
	this.locked = false;
}


function openHelpDoc()
{
   window.open( "helpDoc.html", "HelpWindow", "width=500, height=500");
}

function showPDBIDHelp()
{
   $("div#uploadHelpLayer").hide();    
   $("div#templateHelpLayer").hide();
   $("div#customLabelHelpLayer").hide();
   $("div#findMatchHelpLayer").hide();
   $("div#pdbidHelpLayer").slideToggle(500);
}

function showUploadHelp()
{
   $("div#pdbidHelpLayer").hide();
   $("div#uploadHelpLayer").slideToggle(500);
   $("div#templateHelpLayer").hide();
   $("div#customLabelHelpLayer").hide();
   $("div#findMatchHelpLayer").hide();
}

function showTemplateHelp()
{
   $("div#pdbidHelpLayer").hide();
   $("div#uploadHelpLayer").hide();
   $("div#templateHelpLayer").slideToggle(500);
   $("div#customLabelHelpLayer").hide();
   $("div#findMatchHelpLayer").hide();
}

function hideAll()
{
   $("div#pdbidHelpLayer").hide();
   $("div#uploadHelpLayer").hide();
   $("div#templateHelpLayer").hide();
   $("div#customLabelHelpLayer").hide();
   $("div#findMatchHelpLayer").hide();   
}

function showCustomLabelHelp()
{
   $("div#pdbidHelpLayer").hide();
   $("div#uploadHelpLayer").hide();
   $("div#templateHelpLayer").hide();
   $("div#customLabelHelpLayer").slideToggle(500);
   $("div#findMatchHelpLayer").hide();

}

function showFindMatchHelp()
{
   $("div#pdbidHelpLayer").hide();
   $("div#uploadHelpLayer").hide();
   $("div#templateHelpLayer").hide();
   $("div#customLabelHelpLayer").hide();
   $("div#findMatchHelpLayer").slideToggle();
}

function setCheckedStatus(value, object) {
  needToCheckSubmitButtonStatus = false;
  jQuery.each($("div#displayUserMotifs input[@type='text']"), function(i, textBox) {
    checkbox = $("div#displayUserMotifs #" + textBox.getAttribute("id") + "checkbox");
    checkbox.attr("disabled", (textBox.value.length > 0 ? "" : "true"));
    if(textBox.value.length <= 0) {
      checkbox.attr("checked", "");
      needToCheckSubmitButtonStatus = true;
    }
  });

  if(needToCheckSubmitButtonStatus && object != null) {
     validateAndShowSubmitTemplateButton();
  }
}
