<commit_before>/**ADMIN TABS**/
var tabs = $("#tab-container");
$("#tab-container").easytabs({
  animationSpeed: "fast",
  //updateHash: false,
});

tabs.easytabs({ animate: false });
tabs.bind("easytabs:before", function (e, clicked) {
  // $("#main_editor").val(editor_content);
  if (clicked.parent().hasClass("disabled")) {
    return false;
  }
});
$(".prevent-default").click(function (e) {
  e.preventDefault();
  return false;
});

function enable_all() {
  $("#clone_div").show();
  var tabs = $("#tab-container");
  disable_easytabs(tabs, []);
  disable_easytabs(tabs, [4,5]);
}

disable_easytabs(tabs, [4,5]);
//Disable tabs on_disable_b_and_c_clicked();
function on_disable_b_and_c_clicked() {
  $("#clone_div").hide();
  var tabs = $("#tab-container");
  disable_easytabs(tabs, [3, 4, 5]);
  return false;
}

function disable_easytabs(tabs, indexes) {
  var lis = tabs.children("ul").children();
  var index = 0;
  lis.each(function () {
    var li = $(this);
    var a = li.children("a");
    var disabled = $.inArray(index, indexes) != -1;
    if (disabled) {
      li.addClass("disabled");
    } else {
      li.removeClass("disabled");
    }
    index++;
  });
}

tabs.bind('easytabs:after', function(e, clicked, targetPanel, data) {
  tab_opration(clicked[0].outerText)
});

// Realoading admin page will fire this function
tab_opration($("#tab-container .tab.active")[0].innerText);

// Tab change operation
function tab_opration(str){
    switch(str) {
      case "Edit page":
       fill_input_text();
        break;
      case "Site settings":
        // code block
        break;
      case "Database settings":
        db_operation("db_name", "check");
        break;
      case "Annotation":
       // db_operation("db_name", "check");
        check_files();

        break;
      case "Expression":
        check_expression_files();
      // code block
        break;
      case "Summary":
      // code block
        break;
      default:
      // code block
    }
}

/** DATABASE **/
$("#create_db").click(function () {
    db_operation("create_database", "dump");
});
$("#create_db_arabidopsis").click(function () {
    db_operation("create_database", "artha");
    download_indices("create_database", "dump");
});
$("#drop_db").click(function () {
    db_operation("drop_database", "drop");
});

// Cloning
function clone_genome(t) {
  //alert("This button will allow you to clone the existing "+t.id+" database in the future","clone download")
  if( t.id=="artha"){
    db_operation("clone_database", t.id);
  }else{
    alert("This button will allow you to clone the existing "+t.id+" database in the future","clone download");
  }

 };

 $("#myadmin_links").click(function () {
     window.open("http://" + $('#mhost').val() + "/phpmyadmin/db_structure.php?db=" + $('#mdbname').val(), '_blank');
 });
 $("#myadmin_links_annotation").click(function () {
  window.open("http://" + $('#mhost').val() + "/phpmyadmin/db_structure.php?db=" + $('#mdbname').val(), '_blank');
});
$("#myadmin_links_expression").click(function () {
  window.open("http://" + $('#mhost').val() + "/phpmyadmin/db_structure.php?db=" + $('#mdbname').val(), '_blank');
});

 //Check database
 function db_operation(action, name) {
   if(action!="clone_database"){on_disable_b_and_c_clicked();}
   $(".loader-wrap").show();
     mhost = $('#mhost').val();
     musername = $('#musername').val();
     mpasswd = $('#mpassword').val();
     mdbname = $('#mdbname').val();
     var finalvarx = "host=" + mhost + "&username=" + musername + "&password=" + mpasswd + "&database=" + mdbname + "&action=" + action + "&name=" + name;
     $.ajax({
         type: "POST",
         url: "plugins/home/service/db_settings.php",
         data: (finalvarx),
         dataType: 'json',
         success: function (data) {
          $(".loader-wrap").hide();
//            toastr.options = { "closeButton": false, "debug": false, "positionClass": "toast-top-right", "onclick": null, "showDuration": "10000", "hideDuration": "1000", "timeOut": "40000", "extendedTimeOut": "0", "showEasing": "linear", "hideEasing": "linear", "showMethod": "fadeIn", "hideMethod": "fadeOut" }
             if (data.status == "success") {
                 toastr.success(data.message, "Success");
                 if(data.name!=""){
                 enable_all();
                 if(name=="check" && $("#tab-container .tab.active")[0].innerText =="Annotation"){$("#database_checkbox").prop("checked", true);}
                }
             } else {
                 toastr.error(data.message, "Failure");
                 on_disable_b_and_c_clicked();
                 $("#database_checkbox").prop("checked", false)
             }
             if (action == "db_name") {
                 $("#mdbname").val(data.name);
             }
         },
         error: function (data) {
            if(data.status!=""){
             on_disable_b_and_c_clicked();}
         }
     });
 }

//Download indices
function download_indices(action, name) {
    mhost = $('#mhost').val();
    musername = $('#musername').val();
    mpasswd = $('#mpassword').val();
    mdbname = $('#mdbname').val();
    var finalvarx = "host=" + mhost + "&username=" + musername + "&password=" + mpasswd + "&database=" + mdbname + "&action=" + action + "&name=" + name;
    $.ajax({
        type: "POST",
        url: "plugins/home/service/download_indices.php",
        data: (finalvarx),
        dataType: 'json',
        success: function (data) {
            toastr.options = { "closeButton": false, "debug": false, "positionClass": "toast-top-right", "onclick": null, "showDuration": "10000", "hideDuration": "1000", "timeOut": "40000", "extendedTimeOut": "0", "showEasing": "linear", "hideEasing": "linear", "showMethod": "fadeIn", "hideMethod": "fadeOut" }
            console.log(data)
            if (data > 10) {
                toastr.success("download and indexed fasta files", "Success");
            } else {
                toastr.error("remote server failed", "Failure");
            }
        }
    });
}

/** ANNOTATION **/
// Check files are in the data folder
function check_files() {
  mhost = $('#mhost').val();
  musername = $('#musername').val();
  mpasswd = $('#mpassword').val();
  mdbname = $('#mdbname').val();
  var finalvarx = "host=" + mhost + "&username=" + musername + "&password=" + mpasswd + "&database=" + mdbname + "&action=check_files" ;
  $("#files_waiting").show();
  $.ajax({
      type: "POST",
      url: "plugins/home/service/annotation.php",
      data: (finalvarx),
      dataType: 'json',
      success: function (data) {
          toastr.options = { "closeButton": false, "debug": false, "positionClass": "toast-top-right", "onclick": null, "showDuration": "10000", "hideDuration": "1000", "timeOut": "40000", "extendedTimeOut": "0", "showEasing": "linear", "hideEasing": "linear", "showMethod": "fadeIn", "hideMethod": "fadeOut" }
          if(data.length==0){
            $("#check_files_span").html("Now you have all the required files in the data directory");
            if($("#tab-container .tab.active")[0].innerText =="Annotation"){$("#files_checkbox").prop("checked", true);
              $("#files_waiting").hide();
            }

          }else{
              console.log(data)
              $("#check_files_span").show();
             $("#missing_files").html(data.join(','));
              toastr.warning("There are some missing files, please upload them to data directory", "Missing files");
          }
      }
  });
}

// Generate suitable files in correct formats
function generate_files(){
  $("#prepare_waiting").show();
  mhost = $('#mhost').val();
  musername = $('#musername').val();
  mpasswd = $('#mpassword').val();
  mdbname = $('#mdbname').val();
  var finalvarx = "host=" + mhost + "&username=" + musername + "&password=" + mpasswd + "&database=" + mdbname + "&action=prepare_files" ;
  $.ajax({
      type: "POST",
      url: "plugins/home/service/annotation.php",
      data: (finalvarx),
      dataType: 'json',
      success: function (data) {
        $("#prepare_waiting").hide();
          if($("#tab-container .tab.active")[0].innerText =="Annotation"){$("#prepare_checkbox").prop("checked", true);}
      }
  });
  }

// Load files into the database
  function load_database(){
    $("#load_waiting").show();
    mhost = $('#mhost').val();
    musername = $('#musername').val();
    mpasswd = $('#mpassword').val();
    mdbname = $('#mdbname').val();
    var finalvarx = "host=" + mhost + "&username=" + musername + "&password=" + mpasswd + "&database=" + mdbname + "&action=load_files" ;
    $.ajax({
        type: "POST",
        url: "plugins/home/service/annotation.php",
        data: (finalvarx),
        dataType: 'json',
        success: function (data) {
          $("#load_waiting").hide();
            if($("#tab-container .tab.active")[0].innerText =="Annotation"){$("#load_checkbox").prop("checked", true);}
        },
        complete: function(xhr, textStatus) {

          $("#load_waiting").hide();
      }
    });
    }

// Refresh if there in no content added in home page
function fill_input_text(){
  if($("#tab-container .tab.active")[0].innerText =="Edit page"){
    if(CKEDITOR.instances.editor!=undefined){
    location.reload();
    }
  }
}

// Generate fatsa indices for BLAST
function generate_fasta_indices(){
  $("#fasta_waiting").show();
  var finalvarx = "action=generate_indices" ;
  $.ajax({
      type: "POST",
      url: "plugins/home/service/annotation.php",
      data: (finalvarx),
      dataType: 'json',
      success: function (data) {
        $("#fasta_waiting").hide();
      },
      complete: function(xhr, textStatus) {
        $("#fasta_waiting").hide();
    }
  });
  }

// Update gene i in transcript_info table
function annotation_update_gene_i(){
  $("#update_gene_i_waiting").show();
  mhost = $('#mhost').val();
  musername = $('#musername').val();
  mpasswd = $('#mpassword').val();
  mdbname = $('#mdbname').val();

  var finalvarx = "host=" + mhost + "&username=" + musername + "&password=" + mpasswd + "&database=" + mdbname + "&action=update_gene_i" ;
  $.ajax({
      type: "POST",
      url: "plugins/home/service/annotation.php",
      data: (finalvarx),
      dataType: 'json',
      success: function (data) {
        $("#update_gene_i_waiting").hide();
      },
      complete: function(xhr, textStatus) {
        $("#update_gene_i_waiting").hide();
    }
  });
}

// Update gene and transcript description
function annotation_update_description(){
  $("#update_description_waiting").show();
  mhost = $('#mhost').val();
  musername = $('#musername').val();
  mpasswd = $('#mpassword').val();
  mdbname = $('#mdbname').val();

  var finalvarx = "host=" + mhost + "&username=" + musername + "&password=" + mpasswd + "&database=" + mdbname + "&action=update_description" ;
  $.ajax({
      type: "POST",
      url: "plugins/home/service/annotation.php",
      data: (finalvarx),
      dataType: 'json',
      success: function (data) {
        $("#update_description_waiting").hide();
      },
      complete: function(xhr, textStatus) {
        $("#update_description_waiting").hide();
    }
  });
}

// Load extra annotation KEGG/Pfam/GO
function annotation_update_extra_annotation(){
  $("#update_extra_annotation_waiting").show();
  var finalvarx = "host=" + mhost + "&username=" + musername + "&password=" + mpasswd + "&database=" + mdbname + "&action=load_extra_annotations" ;
  $.ajax({
      type: "POST",
      url: "plugins/home/service/annotation.php",
      data: (finalvarx),
      dataType: 'json',
      success: function (data) {
        $("#update_extra_annotation_waiting").hide();
      },
      complete: function(xhr, textStatus) {
        $("#update_extra_annotation_waiting").hide();
    }
  });
}

// Load BLAST indices
function annotation_update_best_blast(){
  $("#update_best_blast_waiting").show();
  var finalvarx = "host=" + mhost + "&username=" + musername + "&password=" + mpasswd + "&database=" + mdbname + "&action=load_best_blast" ;
  $.ajax({
      type: "POST",
      url: "plugins/home/service/annotation.php",
      data: (finalvarx),
      dataType: 'json',
      success: function (data) {
        $("#update_best_blast_waiting").hide();
      },
      complete: function(xhr, textStatus) {
        $("#update_best_blast_waiting").hide();
    }
  });
}

/** EXPRESSION **/
// Check if the experiment and expression files are exist
function check_expression_files() {
  mhost = $('#mhost').val();
  musername = $('#musername').val();
  mpasswd = $('#mpassword').val();
  mdbname = $('#mdbname').val();
  var finalvarx = "host=" + mhost + "&username=" + musername + "&password=" + mpasswd + "&database=" + mdbname + "&action=check_files" ;
  $("#check_experiment_waiting").show();
  $.ajax({
      type: "POST",
      url: "plugins/home/service/expression.php",
      data: (finalvarx),
      dataType: 'json',
      success: function (data) {
          if(data.length==0){
            //$("#check_files_span").html("Now you have all the required files in the data directory");
            $("#expression_error").hide();
            if($("#tab-container .tab.active")[0].innerText =="Expression"){$("#check_experiment_checkbox").prop("checked", true);
              $("#check_experiment_waiting").hide();
            }
          }else{

              $("#expression_error").show();
             $("#expression_error").html("Warning! There are some missing files "+JSON.stringify(data)+ ". Please upload them into the data directory.");
             // toastr.warning("There are some missing files, please upload them to data directory", "Missing files");
          }
      }
  });
}

// Load files into the database
function load_expression_table(tmp_name){
  $("#expression_info").hide()
  $("#"+tmp_name+"_waiting").show();
  mhost = $('#mhost').val();
  musername = $('#musername').val();
  mpasswd = $('#mpassword').val();
  mdbname = $('#mdbname').val();
  var finalvarx = "host=" + mhost + "&username=" + musername + "&password=" + mpasswd + "&database=" + mdbname + "&action=load_files&name="+tmp_name ;
  $.ajax({
      type: "POST",
      url: "plugins/home/service/expression.php",
      data: (finalvarx),
      dataType: 'json',
      success: function (data) {
        $("#"+tmp_name+"_waiting").hide();
        if(tmp_name=="expression"){$("#expression_info").show();}
          if($("#tab-container .tab.active")[0].innerText =="Expression"){$("#load_"+tmp_name+"_checkbox").prop("checked", true); }
      },
      complete: function(xhr, textStatus) {
        if($("#tab-container .tab.active")[0].innerText =="Expression"){$("#load_"+tmp_name+"_checkbox").prop("checked", true); }
        if(tmp_name=="expression"){$("#expression_info").show();}
        $("#"+tmp_name+"_waiting").hide();
    }
  });
  }

// Help

function go_to_help(t){
  console.log(t)
}
<commit_msg>alert removed<commit_after>/**ADMIN TABS**/
var tabs = $("#tab-container");
$("#tab-container").easytabs({
  animationSpeed: "fast",
  //updateHash: false,
});

tabs.easytabs({ animate: false });
tabs.bind("easytabs:before", function (e, clicked) {
  // $("#main_editor").val(editor_content);
  if (clicked.parent().hasClass("disabled")) {
    return false;
  }
});
$(".prevent-default").click(function (e) {
  e.preventDefault();
  return false;
});

function enable_all() {
  $("#clone_div").show();
  var tabs = $("#tab-container");
  disable_easytabs(tabs, []);
  disable_easytabs(tabs, [4,5]);
}

disable_easytabs(tabs, [4,5]);
//Disable tabs on_disable_b_and_c_clicked();
function on_disable_b_and_c_clicked() {
  $("#clone_div").hide();
  var tabs = $("#tab-container");
  disable_easytabs(tabs, [3, 4, 5]);
  return false;
}

function disable_easytabs(tabs, indexes) {
  var lis = tabs.children("ul").children();
  var index = 0;
  lis.each(function () {
    var li = $(this);
    var a = li.children("a");
    var disabled = $.inArray(index, indexes) != -1;
    if (disabled) {
      li.addClass("disabled");
    } else {
      li.removeClass("disabled");
    }
    index++;
  });
}

tabs.bind('easytabs:after', function(e, clicked, targetPanel, data) {
  tab_opration(clicked[0].outerText)
});

// Realoading admin page will fire this function
tab_opration($("#tab-container .tab.active")[0].innerText);

// Tab change operation
function tab_opration(str){
    switch(str) {
      case "Edit page":
       fill_input_text();
        break;
      case "Site settings":
        // code block
        break;
      case "Database settings":
        db_operation("db_name", "check");
        break;
      case "Annotation":
       // db_operation("db_name", "check");
        check_files();

        break;
      case "Expression":
        check_expression_files();
      // code block
        break;
      case "Summary":
      // code block
        break;
      default:
      // code block
    }
}

/** DATABASE **/
$("#create_db").click(function () {
    db_operation("create_database", "dump");
});
$("#create_db_arabidopsis").click(function () {
    db_operation("create_database", "artha");
    download_indices("create_database", "dump");
});
$("#drop_db").click(function () {
    db_operation("drop_database", "drop");
});

// Cloning
function clone_genome(t) {
  if( t.id=="artha"){
    db_operation("clone_database", t.id);
  }else{
    alert("This button will allow you to clone the existing "+t.id+" database in the future","clone download");
  }

 };

 $("#myadmin_links").click(function () {
     window.open("http://" + $('#mhost').val() + "/phpmyadmin/db_structure.php?db=" + $('#mdbname').val(), '_blank');
 });
 $("#myadmin_links_annotation").click(function () {
  window.open("http://" + $('#mhost').val() + "/phpmyadmin/db_structure.php?db=" + $('#mdbname').val(), '_blank');
});
$("#myadmin_links_expression").click(function () {
  window.open("http://" + $('#mhost').val() + "/phpmyadmin/db_structure.php?db=" + $('#mdbname').val(), '_blank');
});

 //Check database
 function db_operation(action, name) {
   if(action!="clone_database"){on_disable_b_and_c_clicked();}
   $(".loader-wrap").show();
     mhost = $('#mhost').val();
     musername = $('#musername').val();
     mpasswd = $('#mpassword').val();
     mdbname = $('#mdbname').val();
     var finalvarx = "host=" + mhost + "&username=" + musername + "&password=" + mpasswd + "&database=" + mdbname + "&action=" + action + "&name=" + name;
     $.ajax({
         type: "POST",
         url: "plugins/home/service/db_settings.php",
         data: (finalvarx),
         dataType: 'json',
         success: function (data) {
          $(".loader-wrap").hide();
//            toastr.options = { "closeButton": false, "debug": false, "positionClass": "toast-top-right", "onclick": null, "showDuration": "10000", "hideDuration": "1000", "timeOut": "40000", "extendedTimeOut": "0", "showEasing": "linear", "hideEasing": "linear", "showMethod": "fadeIn", "hideMethod": "fadeOut" }
             if (data.status == "success") {
                 toastr.success(data.message, "Success");
                 if(data.name!=""){
                 enable_all();
                 if(name=="check" && $("#tab-container .tab.active")[0].innerText =="Annotation"){$("#database_checkbox").prop("checked", true);}
                }
             } else {
                 toastr.error(data.message, "Failure");
                 on_disable_b_and_c_clicked();
                 $("#database_checkbox").prop("checked", false)
             }
             if (action == "db_name") {
                 $("#mdbname").val(data.name);
             }
         },
         error: function (data) {
            if(data.status!=""){
             on_disable_b_and_c_clicked();}
         }
     });
 }

//Download indices
function download_indices(action, name) {
    mhost = $('#mhost').val();
    musername = $('#musername').val();
    mpasswd = $('#mpassword').val();
    mdbname = $('#mdbname').val();
    var finalvarx = "host=" + mhost + "&username=" + musername + "&password=" + mpasswd + "&database=" + mdbname + "&action=" + action + "&name=" + name;
    $.ajax({
        type: "POST",
        url: "plugins/home/service/download_indices.php",
        data: (finalvarx),
        dataType: 'json',
        success: function (data) {
            toastr.options = { "closeButton": false, "debug": false, "positionClass": "toast-top-right", "onclick": null, "showDuration": "10000", "hideDuration": "1000", "timeOut": "40000", "extendedTimeOut": "0", "showEasing": "linear", "hideEasing": "linear", "showMethod": "fadeIn", "hideMethod": "fadeOut" }
            console.log(data)
            if (data > 10) {
                toastr.success("download and indexed fasta files", "Success");
            } else {
                toastr.error("remote server failed", "Failure");
            }
        }
    });
}

/** ANNOTATION **/
// Check files are in the data folder
function check_files() {
  mhost = $('#mhost').val();
  musername = $('#musername').val();
  mpasswd = $('#mpassword').val();
  mdbname = $('#mdbname').val();
  var finalvarx = "host=" + mhost + "&username=" + musername + "&password=" + mpasswd + "&database=" + mdbname + "&action=check_files" ;
  $("#files_waiting").show();
  $.ajax({
      type: "POST",
      url: "plugins/home/service/annotation.php",
      data: (finalvarx),
      dataType: 'json',
      success: function (data) {
          toastr.options = { "closeButton": false, "debug": false, "positionClass": "toast-top-right", "onclick": null, "showDuration": "10000", "hideDuration": "1000", "timeOut": "40000", "extendedTimeOut": "0", "showEasing": "linear", "hideEasing": "linear", "showMethod": "fadeIn", "hideMethod": "fadeOut" }
          if(data.length==0){
            $("#check_files_span").html("Now you have all the required files in the data directory");
            if($("#tab-container .tab.active")[0].innerText =="Annotation"){$("#files_checkbox").prop("checked", true);
              $("#files_waiting").hide();
            }

          }else{
              console.log(data)
              $("#check_files_span").show();
             $("#missing_files").html(data.join(','));
              toastr.warning("There are some missing files, please upload them to data directory", "Missing files");
          }
      }
  });
}

// Generate suitable files in correct formats
function generate_files(){
  $("#prepare_waiting").show();
  mhost = $('#mhost').val();
  musername = $('#musername').val();
  mpasswd = $('#mpassword').val();
  mdbname = $('#mdbname').val();
  var finalvarx = "host=" + mhost + "&username=" + musername + "&password=" + mpasswd + "&database=" + mdbname + "&action=prepare_files" ;
  $.ajax({
      type: "POST",
      url: "plugins/home/service/annotation.php",
      data: (finalvarx),
      dataType: 'json',
      success: function (data) {
        $("#prepare_waiting").hide();
          if($("#tab-container .tab.active")[0].innerText =="Annotation"){$("#prepare_checkbox").prop("checked", true);}
      }
  });
  }

// Load files into the database
  function load_database(){
    $("#load_waiting").show();
    mhost = $('#mhost').val();
    musername = $('#musername').val();
    mpasswd = $('#mpassword').val();
    mdbname = $('#mdbname').val();
    var finalvarx = "host=" + mhost + "&username=" + musername + "&password=" + mpasswd + "&database=" + mdbname + "&action=load_files" ;
    $.ajax({
        type: "POST",
        url: "plugins/home/service/annotation.php",
        data: (finalvarx),
        dataType: 'json',
        success: function (data) {
          $("#load_waiting").hide();
            if($("#tab-container .tab.active")[0].innerText =="Annotation"){$("#load_checkbox").prop("checked", true);}
        },
        complete: function(xhr, textStatus) {

          $("#load_waiting").hide();
      }
    });
    }

// Refresh if there in no content added in home page
function fill_input_text(){
  if($("#tab-container .tab.active")[0].innerText =="Edit page"){
    if(CKEDITOR.instances.editor!=undefined){
    location.reload();
    }
  }
}

// Generate fatsa indices for BLAST
function generate_fasta_indices(){
  $("#fasta_waiting").show();
  var finalvarx = "action=generate_indices" ;
  $.ajax({
      type: "POST",
      url: "plugins/home/service/annotation.php",
      data: (finalvarx),
      dataType: 'json',
      success: function (data) {
        $("#fasta_waiting").hide();
      },
      complete: function(xhr, textStatus) {
        $("#fasta_waiting").hide();
    }
  });
  }

// Update gene i in transcript_info table
function annotation_update_gene_i(){
  $("#update_gene_i_waiting").show();
  mhost = $('#mhost').val();
  musername = $('#musername').val();
  mpasswd = $('#mpassword').val();
  mdbname = $('#mdbname').val();

  var finalvarx = "host=" + mhost + "&username=" + musername + "&password=" + mpasswd + "&database=" + mdbname + "&action=update_gene_i" ;
  $.ajax({
      type: "POST",
      url: "plugins/home/service/annotation.php",
      data: (finalvarx),
      dataType: 'json',
      success: function (data) {
        $("#update_gene_i_waiting").hide();
      },
      complete: function(xhr, textStatus) {
        $("#update_gene_i_waiting").hide();
    }
  });
}

// Update gene and transcript description
function annotation_update_description(){
  $("#update_description_waiting").show();
  mhost = $('#mhost').val();
  musername = $('#musername').val();
  mpasswd = $('#mpassword').val();
  mdbname = $('#mdbname').val();

  var finalvarx = "host=" + mhost + "&username=" + musername + "&password=" + mpasswd + "&database=" + mdbname + "&action=update_description" ;
  $.ajax({
      type: "POST",
      url: "plugins/home/service/annotation.php",
      data: (finalvarx),
      dataType: 'json',
      success: function (data) {
        $("#update_description_waiting").hide();
      },
      complete: function(xhr, textStatus) {
        $("#update_description_waiting").hide();
    }
  });
}

// Load extra annotation KEGG/Pfam/GO
function annotation_update_extra_annotation(){
  $("#update_extra_annotation_waiting").show();
  var finalvarx = "host=" + mhost + "&username=" + musername + "&password=" + mpasswd + "&database=" + mdbname + "&action=load_extra_annotations" ;
  $.ajax({
      type: "POST",
      url: "plugins/home/service/annotation.php",
      data: (finalvarx),
      dataType: 'json',
      success: function (data) {
        $("#update_extra_annotation_waiting").hide();
      },
      complete: function(xhr, textStatus) {
        $("#update_extra_annotation_waiting").hide();
    }
  });
}

// Load BLAST indices
function annotation_update_best_blast(){
  $("#update_best_blast_waiting").show();
  var finalvarx = "host=" + mhost + "&username=" + musername + "&password=" + mpasswd + "&database=" + mdbname + "&action=load_best_blast" ;
  $.ajax({
      type: "POST",
      url: "plugins/home/service/annotation.php",
      data: (finalvarx),
      dataType: 'json',
      success: function (data) {
        $("#update_best_blast_waiting").hide();
      },
      complete: function(xhr, textStatus) {
        $("#update_best_blast_waiting").hide();
    }
  });
}

/** EXPRESSION **/
// Check if the experiment and expression files are exist
function check_expression_files() {
  mhost = $('#mhost').val();
  musername = $('#musername').val();
  mpasswd = $('#mpassword').val();
  mdbname = $('#mdbname').val();
  var finalvarx = "host=" + mhost + "&username=" + musername + "&password=" + mpasswd + "&database=" + mdbname + "&action=check_files" ;
  $("#check_experiment_waiting").show();
  $.ajax({
      type: "POST",
      url: "plugins/home/service/expression.php",
      data: (finalvarx),
      dataType: 'json',
      success: function (data) {
          if(data.length==0){
            //$("#check_files_span").html("Now you have all the required files in the data directory");
            $("#expression_error").hide();
            if($("#tab-container .tab.active")[0].innerText =="Expression"){$("#check_experiment_checkbox").prop("checked", true);
              $("#check_experiment_waiting").hide();
            }
          }else{

              $("#expression_error").show();
             $("#expression_error").html("Warning! There are some missing files "+JSON.stringify(data)+ ". Please upload them into the data directory.");
             // toastr.warning("There are some missing files, please upload them to data directory", "Missing files");
          }
      }
  });
}

// Load files into the database
function load_expression_table(tmp_name){
  $("#expression_info").hide()
  $("#"+tmp_name+"_waiting").show();
  mhost = $('#mhost').val();
  musername = $('#musername').val();
  mpasswd = $('#mpassword').val();
  mdbname = $('#mdbname').val();
  var finalvarx = "host=" + mhost + "&username=" + musername + "&password=" + mpasswd + "&database=" + mdbname + "&action=load_files&name="+tmp_name ;
  $.ajax({
      type: "POST",
      url: "plugins/home/service/expression.php",
      data: (finalvarx),
      dataType: 'json',
      success: function (data) {
        $("#"+tmp_name+"_waiting").hide();
        if(tmp_name=="expression"){$("#expression_info").show();}
          if($("#tab-container .tab.active")[0].innerText =="Expression"){$("#load_"+tmp_name+"_checkbox").prop("checked", true); }
      },
      complete: function(xhr, textStatus) {
        if($("#tab-container .tab.active")[0].innerText =="Expression"){$("#load_"+tmp_name+"_checkbox").prop("checked", true); }
        if(tmp_name=="expression"){$("#expression_info").show();}
        $("#"+tmp_name+"_waiting").hide();
    }
  });
  }

// Help

function go_to_help(t){
  console.log(t)
}
<|endoftext|>


<commit_before>IonicModule
.controller('$ionicRefresher', [
  '$scope',
  '$attrs',
  '$element',
  '$ionicBind',
  '$timeout',
  function($scope, $attrs, $element, $ionicBind, $timeout) {
    var self = this,
        isDragging = false,
        isOverscrolling = false,
        dragOffset = 0,
        lastOverscroll = 0,
        ptrThreshold = 60,
        activated = false,
        scrollTime = 500,
        startY = null,
        deltaY = null,
        canOverscroll = true,
        scrollParent,
        scrollChild;

    if (!isDefined($attrs.pullingIcon)) {
      $attrs.$set('pullingIcon', 'ion-android-arrow-down');
    }

    $scope.showSpinner = !isDefined($attrs.refreshingIcon) && $attrs.spinner != 'none';

    $scope.showIcon = isDefined($attrs.refreshingIcon);

    $ionicBind($scope, $attrs, {
      pullingIcon: '@',
      pullingText: '@',
      refreshingIcon: '@',
      refreshingText: '@',
      spinner: '@',
      disablePullingRotation: '@',
      $onRefresh: '&onRefresh',
      $onPulling: '&onPulling'
    });

    function handleTouchend() {
      // if this wasn't an overscroll, get out immediately
      if (!canOverscroll && !isDragging) {
        return;
      }
      // reset Y
      startY = null;
      // the user has overscrolled but went back to native scrolling
      if (!isDragging) {
        dragOffset = 0;
        isOverscrolling = false;
        setScrollLock(false);
      } else {
        isDragging = false;
        dragOffset = 0;

        // the user has scroll far enough to trigger a refresh
        if (lastOverscroll > ptrThreshold) {
          start();
          scrollTo(ptrThreshold, scrollTime);

        // the user has overscrolled but not far enough to trigger a refresh
        } else {
          scrollTo(0, scrollTime, deactivate);
          isOverscrolling = false;
        }
      }
    }

    function handleTouchmove(e) {
      // if multitouch or regular scroll event, get out immediately
      if (!canOverscroll || e.touches.length > 1) {
        return;
      }
      //if this is a new drag, keep track of where we start
      if (startY === null) {
        startY = parseInt(e.touches[0].screenY, 10);
      }

      // kitkat fix for touchcancel events http://updates.html5rocks.com/2014/05/A-More-Compatible-Smoother-Touch
      if (ionic.Platform.isAndroid() && ionic.Platform.version() === 4.4 && scrollParent.scrollTop === 0) {
        isDragging = true;
        e.preventDefault();
      }

      // how far have we dragged so far?
      deltaY = parseInt(e.touches[0].screenY, 10) - startY;

      // if we've dragged up and back down in to native scroll territory
      if (deltaY - dragOffset <= 0 || scrollParent.scrollTop !== 0) {

        if (isOverscrolling) {
          isOverscrolling = false;
          setScrollLock(false);
        }

        if (isDragging) {
          nativescroll(scrollParent, parseInt(deltaY - dragOffset, 10) * -1);
        }

        // if we're not at overscroll 0 yet, 0 out
        if (lastOverscroll !== 0) {
          overscroll(0);
        }
        return;

      } else if (deltaY > 0 && scrollParent.scrollTop === 0 && !isOverscrolling) {
        // starting overscroll, but drag started below scrollTop 0, so we need to offset the position
        dragOffset = deltaY;
      }

      // prevent native scroll events while overscrolling
      e.preventDefault();

      // if not overscrolling yet, initiate overscrolling
      if (!isOverscrolling) {
        isOverscrolling = true;
        setScrollLock(true);
      }

      isDragging = true;
      // overscroll according to the user's drag so far
      overscroll(parseInt((deltaY - dragOffset) / 3, 10));

      // update the icon accordingly
      if (!activated && lastOverscroll > ptrThreshold) {
        activated = true;
        ionic.requestAnimationFrame(activate);

      } else if (activated && lastOverscroll < ptrThreshold) {
        activated = false;
        ionic.requestAnimationFrame(deactivate);
      }
    }

    function handleScroll(e) {
      // canOverscrol is used to greatly simplify the drag handler during normal scrolling
      canOverscroll = (e.target.scrollTop === 0) || isDragging;
    }

    function overscroll(val) {
      scrollChild.style[ionic.CSS.TRANSFORM] = 'translateY(' + val + 'px)';
      lastOverscroll = val;
    }

    function nativescroll(target, newScrollTop) {
      // creates a scroll event that bubbles, can be cancelled, and with its view
      // and detail property initialized to window and 1, respectively
      target.scrollTop = newScrollTop;
      var e = document.createEvent("UIEvents");
      e.initUIEvent("scroll", true, true, window, 1);
      target.dispatchEvent(e);
    }

    function setScrollLock(enabled) {
      // set the scrollbar to be position:fixed in preparation to overscroll
      // or remove it so the app can be natively scrolled
      if (enabled) {
        ionic.requestAnimationFrame(function() {
          scrollChild.classList.add('overscroll');
          show();
        });

      } else {
        ionic.requestAnimationFrame(function() {
          scrollChild.classList.remove('overscroll');
          hide();
          deactivate();
        });
      }
    }

    $scope.$on('scroll.refreshComplete', function() {
      // prevent the complete from firing before the scroll has started
      $timeout(function() {

        ionic.requestAnimationFrame(tail);

        // scroll back to home during tail animation
        scrollTo(0, scrollTime, deactivate);

        // return to native scrolling after tail animation has time to finish
        $timeout(function() {

          if (isOverscrolling) {
            isOverscrolling = false;
            setScrollLock(false);
          }

        }, scrollTime);

      }, scrollTime);
    });

    function scrollTo(Y, duration, callback) {
      // scroll animation loop w/ easing
      // credit https://gist.github.com/dezinezync/5487119
      var start = Date.now(),
          from = lastOverscroll;

      if (from === Y) {
        callback();
        return; /* Prevent scrolling to the Y point if already there */
      }

      // decelerating to zero velocity
      function easeOutCubic(t) {
        return (--t) * t * t + 1;
      }

      // scroll loop
      function scroll() {
        var currentTime = Date.now(),
          time = Math.min(1, ((currentTime - start) / duration)),
          // where .5 would be 50% of time on a linear scale easedT gives a
          // fraction based on the easing method
          easedT = easeOutCubic(time);

        overscroll(parseInt((easedT * (Y - from)) + from, 10));

        if (time < 1) {
          ionic.requestAnimationFrame(scroll);

        } else {

          if (Y < 5 && Y > -5) {
            isOverscrolling = false;
            setScrollLock(false);
          }

          callback && callback();
        }
      }

      // start scroll loop
      ionic.requestAnimationFrame(scroll);
    }

    self.init = function() {
      scrollParent = $element.parent().parent()[0];
      scrollChild = $element.parent()[0];

      if (!scrollParent || !scrollParent.classList.contains('ionic-scroll') ||
        !scrollChild || !scrollChild.classList.contains('scroll')) {
        throw new Error('Refresher must be immediate child of ion-content or ion-scroll');
      }

      ionic.on('touchmove', handleTouchmove, scrollChild);
      ionic.on('touchend', handleTouchend, scrollChild);
      ionic.on('scroll', handleScroll, scrollParent);

      // cleanup when done
      $scope.$on('$destroy', destroy);
    };

    function destroy() {
      ionic.off('touchmove', handleTouchmove, scrollChild);
      ionic.off('touchend', handleTouchend, scrollChild);
      ionic.off('scroll', handleScroll, scrollParent);
      scrollParent = null;
      scrollChild = null;
    }

    // DOM manipulation and broadcast methods shared by JS and Native Scrolling
    // getter used by JS Scrolling
    self.getRefresherDomMethods = function() {
      return {
        activate: activate,
        deactivate: deactivate,
        start: start,
        show: show,
        hide: hide,
        tail: tail
      };
    };

    function activate() {
      $element[0].classList.add('active');
      $scope.$onPulling();
    }

    function deactivate() {
      // give tail 150ms to finish
      $timeout(function() {
        // deactivateCallback
        $element.removeClass('active refreshing refreshing-tail');
        if (activated) activated = false;
      }, 150);
    }

    function start() {
      // startCallback
      $element[0].classList.add('refreshing');
      var q = $scope.$onRefresh();

      if (q && q.then) {
        q['finally'](function() {
          $scope.$broadcast('scroll.refreshComplete');
        });
      }
    }

    function show() {
      // showCallback
      $element[0].classList.remove('invisible');
    }

    function hide() {
      // showCallback
      $element[0].classList.add('invisible');
    }

    function tail() {
      // tailCallback
      $element[0].classList.add('refreshing-tail');
    }

    // for testing
    self.__handleTouchmove = handleTouchmove;
    self.__getScrollChild = function() { return scrollChild; };
    self.__getScrollParent = function() { return scrollParent; };
  }
]);
<commit_msg>fix(refresher): PTR in desktop. Fixes #4758<commit_after>IonicModule
.controller('$ionicRefresher', [
  '$scope',
  '$attrs',
  '$element',
  '$ionicBind',
  '$timeout',
  function($scope, $attrs, $element, $ionicBind, $timeout) {
    var self = this,
        isDragging = false,
        isOverscrolling = false,
        dragOffset = 0,
        lastOverscroll = 0,
        ptrThreshold = 60,
        activated = false,
        scrollTime = 500,
        startY = null,
        deltaY = null,
        canOverscroll = true,
        scrollParent,
        scrollChild;

    if (!isDefined($attrs.pullingIcon)) {
      $attrs.$set('pullingIcon', 'ion-android-arrow-down');
    }

    $scope.showSpinner = !isDefined($attrs.refreshingIcon) && $attrs.spinner != 'none';

    $scope.showIcon = isDefined($attrs.refreshingIcon);

    $ionicBind($scope, $attrs, {
      pullingIcon: '@',
      pullingText: '@',
      refreshingIcon: '@',
      refreshingText: '@',
      spinner: '@',
      disablePullingRotation: '@',
      $onRefresh: '&onRefresh',
      $onPulling: '&onPulling'
    });

    function handleMousedown(e) {
      e.touches = e.touches || [{
        screenX: e.screenX,
        screenY: e.screenY
      }];
      // Mouse needs this
      startY = parseInt(e.touches[0].screenY, 10);
    }

    function handleTouchend() {
      // if this wasn't an overscroll, get out immediately
      if (!canOverscroll && !isDragging) {
        return;
      }
      // reset Y
      startY = null;
      // the user has overscrolled but went back to native scrolling
      if (!isDragging) {
        dragOffset = 0;
        isOverscrolling = false;
        setScrollLock(false);
      } else {
        isDragging = false;
        dragOffset = 0;

        // the user has scroll far enough to trigger a refresh
        if (lastOverscroll > ptrThreshold) {
          start();
          scrollTo(ptrThreshold, scrollTime);

        // the user has overscrolled but not far enough to trigger a refresh
        } else {
          scrollTo(0, scrollTime, deactivate);
          isOverscrolling = false;
        }
      }
    }

    function handleTouchmove(e) {
      e.touches = e.touches || [{
        screenX: e.screenX,
        screenY: e.screenY
      }];

      // if multitouch or regular scroll event, get out immediately
      if (!canOverscroll || e.touches.length > 1) {
        return;
      }
      //if this is a new drag, keep track of where we start
      if (startY === null) {
        startY = parseInt(e.touches[0].screenY, 10);
      }

      // kitkat fix for touchcancel events http://updates.html5rocks.com/2014/05/A-More-Compatible-Smoother-Touch
      if (ionic.Platform.isAndroid() && ionic.Platform.version() === 4.4 && scrollParent.scrollTop === 0) {
        isDragging = true;
        e.preventDefault();
      }

      // how far have we dragged so far?
      deltaY = parseInt(e.touches[0].screenY, 10) - startY;

      // if we've dragged up and back down in to native scroll territory
      if (deltaY - dragOffset <= 0 || scrollParent.scrollTop !== 0) {

        if (isOverscrolling) {
          isOverscrolling = false;
          setScrollLock(false);
        }

        if (isDragging) {
          nativescroll(scrollParent, parseInt(deltaY - dragOffset, 10) * -1);
        }

        // if we're not at overscroll 0 yet, 0 out
        if (lastOverscroll !== 0) {
          overscroll(0);
        }
        return;

      } else if (deltaY > 0 && scrollParent.scrollTop === 0 && !isOverscrolling) {
        // starting overscroll, but drag started below scrollTop 0, so we need to offset the position
        dragOffset = deltaY;
      }

      // prevent native scroll events while overscrolling
      e.preventDefault();

      // if not overscrolling yet, initiate overscrolling
      if (!isOverscrolling) {
        isOverscrolling = true;
        setScrollLock(true);
      }

      isDragging = true;
      // overscroll according to the user's drag so far
      overscroll(parseInt((deltaY - dragOffset) / 3, 10));

      // update the icon accordingly
      if (!activated && lastOverscroll > ptrThreshold) {
        activated = true;
        ionic.requestAnimationFrame(activate);

      } else if (activated && lastOverscroll < ptrThreshold) {
        activated = false;
        ionic.requestAnimationFrame(deactivate);
      }
    }

    function handleScroll(e) {
      // canOverscrol is used to greatly simplify the drag handler during normal scrolling
      canOverscroll = (e.target.scrollTop === 0) || isDragging;
    }

    function overscroll(val) {
      scrollChild.style[ionic.CSS.TRANSFORM] = 'translateY(' + val + 'px)';
      lastOverscroll = val;
    }

    function nativescroll(target, newScrollTop) {
      // creates a scroll event that bubbles, can be cancelled, and with its view
      // and detail property initialized to window and 1, respectively
      target.scrollTop = newScrollTop;
      var e = document.createEvent("UIEvents");
      e.initUIEvent("scroll", true, true, window, 1);
      target.dispatchEvent(e);
    }

    function setScrollLock(enabled) {
      // set the scrollbar to be position:fixed in preparation to overscroll
      // or remove it so the app can be natively scrolled
      if (enabled) {
        ionic.requestAnimationFrame(function() {
          scrollChild.classList.add('overscroll');
          show();
        });

      } else {
        ionic.requestAnimationFrame(function() {
          scrollChild.classList.remove('overscroll');
          hide();
          deactivate();
        });
      }
    }

    $scope.$on('scroll.refreshComplete', function() {
      // prevent the complete from firing before the scroll has started
      $timeout(function() {

        ionic.requestAnimationFrame(tail);

        // scroll back to home during tail animation
        scrollTo(0, scrollTime, deactivate);

        // return to native scrolling after tail animation has time to finish
        $timeout(function() {

          if (isOverscrolling) {
            isOverscrolling = false;
            setScrollLock(false);
          }

        }, scrollTime);

      }, scrollTime);
    });

    function scrollTo(Y, duration, callback) {
      // scroll animation loop w/ easing
      // credit https://gist.github.com/dezinezync/5487119
      var start = Date.now(),
          from = lastOverscroll;

      if (from === Y) {
        callback();
        return; /* Prevent scrolling to the Y point if already there */
      }

      // decelerating to zero velocity
      function easeOutCubic(t) {
        return (--t) * t * t + 1;
      }

      // scroll loop
      function scroll() {
        var currentTime = Date.now(),
          time = Math.min(1, ((currentTime - start) / duration)),
          // where .5 would be 50% of time on a linear scale easedT gives a
          // fraction based on the easing method
          easedT = easeOutCubic(time);

        overscroll(parseInt((easedT * (Y - from)) + from, 10));

        if (time < 1) {
          ionic.requestAnimationFrame(scroll);

        } else {

          if (Y < 5 && Y > -5) {
            isOverscrolling = false;
            setScrollLock(false);
          }

          callback && callback();
        }
      }

      // start scroll loop
      ionic.requestAnimationFrame(scroll);
    }

    self.init = function() {
      scrollParent = $element.parent().parent()[0];
      scrollChild = $element.parent()[0];

      if (!scrollParent || !scrollParent.classList.contains('ionic-scroll') ||
        !scrollChild || !scrollChild.classList.contains('scroll')) {
        throw new Error('Refresher must be immediate child of ion-content or ion-scroll');
      }

      ionic.on('touchmove', handleTouchmove, scrollChild);
      ionic.on('touchend', handleTouchend, scrollChild);
      ionic.on('mousedown', handleMousedown, scrollChild);
      ionic.on('mousemove', handleTouchmove, scrollChild);
      ionic.on('mouseup', handleTouchend, scrollChild);
      ionic.on('scroll', handleScroll, scrollParent);

      // cleanup when done
      $scope.$on('$destroy', destroy);
    };

    function destroy() {
      ionic.off('touchmove', handleTouchmove, scrollChild);
      ionic.off('touchend', handleTouchend, scrollChild);
      ionic.off('mousedown', handleMousedown, scrollChild);
      ionic.off('mousemove', handleTouchmove, scrollChild);
      ionic.off('mouseup', handleTouchend, scrollChild);
      ionic.off('scroll', handleScroll, scrollParent);
      scrollParent = null;
      scrollChild = null;
    }

    // DOM manipulation and broadcast methods shared by JS and Native Scrolling
    // getter used by JS Scrolling
    self.getRefresherDomMethods = function() {
      return {
        activate: activate,
        deactivate: deactivate,
        start: start,
        show: show,
        hide: hide,
        tail: tail
      };
    };

    function activate() {
      $element[0].classList.add('active');
      $scope.$onPulling();
    }

    function deactivate() {
      // give tail 150ms to finish
      $timeout(function() {
        // deactivateCallback
        $element.removeClass('active refreshing refreshing-tail');
        if (activated) activated = false;
      }, 150);
    }

    function start() {
      // startCallback
      $element[0].classList.add('refreshing');
      var q = $scope.$onRefresh();

      if (q && q.then) {
        q['finally'](function() {
          $scope.$broadcast('scroll.refreshComplete');
        });
      }
    }

    function show() {
      // showCallback
      $element[0].classList.remove('invisible');
    }

    function hide() {
      // showCallback
      $element[0].classList.add('invisible');
    }

    function tail() {
      // tailCallback
      $element[0].classList.add('refreshing-tail');
    }

    // for testing
    self.__handleTouchmove = handleTouchmove;
    self.__getScrollChild = function() { return scrollChild; };
    self.__getScrollParent = function() { return scrollParent; };
  }
]);
<|endoftext|>


<commit_before>require('datejs');
var items = require('./items');
var Item = items.Item;
var path = require('path');
var fs = require('fs');
var stocks = {};

var get = function (itemId) {
	if (!stocks[itemId]) {
		stocks[itemId] = new Stock(itemId);
	}

	return stocks[itemId];
};

var Stock = function (itemId) {
	this._itemId = itemId;
	this._stockFile = path.join(exports.dataDir, 'stock-' + itemId + '.json');
	this._updates = null;
	this._load();
};

Stock.prototype._load = function () {
	if (this._updates) return;

	if (path.existsSync(this._stockFile)) {
		var data = fs.readFileSync(this._stockFile, 'UTF-8');
		this._updates = JSON.parse(data);
		return;
	}

	this._updates = [];
};

Stock.prototype._persist = function (path, callback) {
	if (typeof callback === 'undefined') {
		callback = path;
		path = null;
	}

	if (!path) path = this._stockFile;

	var data = JSON.stringify(this._updates);

	fs.writeFile(path, data, function (err) {
		if (err) throw err;
		callback();
	});
};

Stock.prototype.itemId = function () {
	return this._itemId;
};

Stock.prototype.update = function (dataset, callback) {
	dataset.time = Date.now();
	this._updates.push(dataset);
	this._persist(function () {
		if (typeof callback == 'function') callback();
	});
};

Stock.prototype.updateByBookingId = function (bookingId) {
	for (var i = 0; i < this._updates.length; i++) {
		var update = this._updates[i];
		if (update.bookingId == bookingId) return update;
	}

	return null;
};

Stock.prototype.info = function () {
	var updates = this._updates;
	var total = 0;
	var weeks = [];
	for (var i = 0; i < updates.length; i++) {
		var update = updates[i];
		if (update.type != 'consumption' && update.type != 'reverse') continue;

		var week = new Date(update.time).toString('yyyy-') + new Date(update.time).getISOWeek();
		if (weeks.indexOf(week) == -1) weeks.push(week);

		if (update.type == 'consumption') total++;
		if (update.type == 'reverse') total--;
	}

	var stock = this.stock();
	var item = items.get(this._itemId);
	var avgRations = total / weeks.length;
	var avgUnits = avgRations * item.ration();
	var percent = 100 / (avgUnits * 3) * stock;
	var health = 'perfect';
	if (percent < 100) health = 'good';
	if (percent < 50) health = 'critical';
	if (percent < 30) health = 'bad';

	return {
		'stock' : stock,
		'avgRations' : avgRations,
		'avgUnits' : avgUnits,
		'percent' : percent,
		'health' : health
	};
};

Stock.prototype.stock = function () {
	var stock = 0;
	for (var i = 0; i < this._updates.length; i++) {
		stock += this._updates[i].change;
	}

	return stock;
};

exports.dataDir = null;
exports.get = get;
exports.Stock = Stock;
<commit_msg>Claenup: Unused Items class<commit_after>require('datejs');
var items = require('./items');
var path = require('path');
var fs = require('fs');
var stocks = {};

var get = function (itemId) {
	if (!stocks[itemId]) {
		stocks[itemId] = new Stock(itemId);
	}

	return stocks[itemId];
};

var Stock = function (itemId) {
	this._itemId = itemId;
	this._stockFile = path.join(exports.dataDir, 'stock-' + itemId + '.json');
	this._updates = null;
	this._load();
};

Stock.prototype._load = function () {
	if (this._updates) return;

	if (path.existsSync(this._stockFile)) {
		var data = fs.readFileSync(this._stockFile, 'UTF-8');
		this._updates = JSON.parse(data);
		return;
	}

	this._updates = [];
};

Stock.prototype._persist = function (path, callback) {
	if (typeof callback === 'undefined') {
		callback = path;
		path = null;
	}

	if (!path) path = this._stockFile;

	var data = JSON.stringify(this._updates);

	fs.writeFile(path, data, function (err) {
		if (err) throw err;
		callback();
	});
};

Stock.prototype.itemId = function () {
	return this._itemId;
};

Stock.prototype.update = function (dataset, callback) {
	dataset.time = Date.now();
	this._updates.push(dataset);
	this._persist(function () {
		if (typeof callback == 'function') callback();
	});
};

Stock.prototype.updateByBookingId = function (bookingId) {
	for (var i = 0; i < this._updates.length; i++) {
		var update = this._updates[i];
		if (update.bookingId == bookingId) return update;
	}

	return null;
};

Stock.prototype.info = function () {
	var updates = this._updates;
	var total = 0;
	var weeks = [];
	for (var i = 0; i < updates.length; i++) {
		var update = updates[i];
		if (update.type != 'consumption' && update.type != 'reverse') continue;

		var week = new Date(update.time).toString('yyyy-') + new Date(update.time).getISOWeek();
		if (weeks.indexOf(week) == -1) weeks.push(week);

		if (update.type == 'consumption') total++;
		if (update.type == 'reverse') total--;
	}

	var stock = this.stock();
	var item = items.get(this._itemId);
	var avgRations = total / weeks.length;
	var avgUnits = avgRations * item.ration();
	var percent = 100 / (avgUnits * 3) * stock;
	var health = 'perfect';
	if (percent < 100) health = 'good';
	if (percent < 50) health = 'critical';
	if (percent < 30) health = 'bad';

	return {
		'stock' : stock,
		'avgRations' : avgRations,
		'avgUnits' : avgUnits,
		'percent' : percent,
		'health' : health
	};
};

Stock.prototype.stock = function () {
	var stock = 0;
	for (var i = 0; i < this._updates.length; i++) {
		stock += this._updates[i].change;
	}

	return stock;
};

exports.dataDir = null;
exports.get = get;
exports.Stock = Stock;
<|endoftext|>


<commit_before>var config = {};

config.proxy = 'http://mimoto.aimless';
config.dest = 'web/static';
config.src = './';

config.projectSrc = 'src/userinterface/components/Mimoto.CMS';
config.templates = config.projectSrc + '/**';

module.exports = config;
<commit_msg>Updated projectSrc<commit_after>var config = {};

config.proxy = 'http://mimoto.aimless';
config.dest = 'web/static';
config.src = './';

config.projectSrc = 'src/userinterface/MimotoCMS';
config.templates = config.projectSrc + '/**';

module.exports = config;
<|endoftext|>


<commit_before>import {uniq, isEmpty} from 'lodash';
import sortFolderContentFields from './sortFolderContentFields';
import DICTIONARY_LANGS from './../constants/dictionaryLangs';
import trimFractionLeadingZeros from './../helpers/trimFractionLeadingZeros';

export const FIELD_PAGE_NUM = 'page-num';
export const FIELD_CATEGORY = 'category';
export const FIELD_SECT = 'sect';
export const FIELD_EXPLANATION_NOTE = 'explanation-note';
export const FIELD_EXPLANATION_SOURCE = 'explanation-source';
export const FIELD_EXPLANATION_CATEGORY = 'explanation-category';

export const RE_SOURCE_ENTRY = /^source-entry-(.+)$/;
export const RE_TARGET_ENTRY = /^target-entry-(.+)$/;
export const RE_ORIGINAL = /^original-(.+)$/;
export const RE_EXPLANATION = /^explanation-(.+)$/;
export const RE_EXPLANATION_NOTE = /^explanation-note$/;
export const RE_EXPLANATION_CATEGORY = /^explanation-category$/;

const getSourceLang = (key) => {
  const [, lang] = key.match(RE_SOURCE_ENTRY) || [];
  return validLangs.includes(lang) ? lang : null;
};

const getExplanationLang = (key) => {
  const [, lang] = key.match(RE_EXPLANATION) || [];
  return validLangs.includes(lang) ? lang : null;
};

const isArrayField = (key) => {
  return [RE_EXPLANATION, RE_EXPLANATION_NOTE, RE_EXPLANATION_CATEGORY].some((re) => re.exec(key));
};

const validLangs = DICTIONARY_LANGS.map((row) => row.value);

export default class CsvProcessor {

  static isColumnRow(data) {
    return data.some((key) => {
      const sourceLanguage = getSourceLang(key);
      return !! sourceLanguage;
    });
  }

  static getColumnData(data) {

    const result = data.reduce((columnData, key, index) => {

      const sourceLanguage = getSourceLang(key);

      if (sourceLanguage) {
        columnData.sourceLanguage = sourceLanguage;
      }

      const explanationLanguage = getExplanationLang(key);

      if (explanationLanguage) {
        columnData.targetLanguages.push(explanationLanguage);
        columnData.contentFields.push(`explanation-lang-${explanationLanguage}`);
      }

      if (FIELD_PAGE_NUM === key) {
        columnData.contentFields.push(FIELD_PAGE_NUM);
      }

      return columnData;

    }, {sourceLanguage: '', targetLanguages: [], contentFields: []});

    result.targetLanguages = uniq(result.targetLanguages);
    result.contentFields = sortFolderContentFields(result.contentFields);

    return result;
  }

  static getFields(data) {

    return data.reduce((fields, key, index) => {

      const sourceLanguage = getSourceLang(key);
      const explanationLanguage = getExplanationLang(key);

      if (sourceLanguage) {
        fields[index] = 'sourceEntry';
      }
      else if (explanationLanguage) {
        fields[index] = `explanation-${explanationLanguage}`;
      }
      else if (FIELD_EXPLANATION_NOTE === key) {
        fields[index] = FIELD_EXPLANATION_NOTE;
      }
      else if (FIELD_EXPLANATION_SOURCE === key) {
        fields[index] = FIELD_EXPLANATION_SOURCE;
      }
      else if (FIELD_EXPLANATION_CATEGORY === key) {
        fields[index] = FIELD_EXPLANATION_CATEGORY;
      }
      else if (FIELD_PAGE_NUM === key) {
        fields[index] = FIELD_PAGE_NUM;
      }
      else {
        // unknown columns
        fields[index] = undefined;
      }
      return fields;
    }, []);
  }

  static getRowDataByFields(data, fields) {
    return fields.reduce((rowData, field, index) => {
      if (field) {

        if (FIELD_EXPLANATION_CATEGORY === field) {
          const value = data[index];
          rowData[field] = value ? [value.split(',').map(Number)] : [[]];
        }
        else if (isArrayField(field)) {
          rowData[field] = [data[index]]
        }
        else {
          rowData[field] = data[index];
        }
      }
      return rowData;
    }, {});
  }

  static appendData(newData, oldData, fields) {

    return fields.reduce((oldData, field, index) => {

      if (isArrayField(field)) {
        const arr = oldData[field];
        const value = newData[index];

        if (value && (FIELD_EXPLANATION_CATEGORY === field)) {
          arr.push(value.split(',').map(Number));
        }
        else if (value) {
          arr.push(value);
        }
      }
      return oldData;
    }, oldData);
  }

  // for csv export
  static getCsvRowsByEntry({folder, entry}) {

    const {sourceLanguage, contentFields} = folder.data;
    const defaultData = {
      [`source-entry-${sourceLanguage}`]: entry.sourceEntry
    };

    let hasHandledExplanationNote = false;
    let hasHandledExplanationSource = false;
    let hasHandledExplanationCategory = false;

    return contentFields.reduce((rows, field) => {

      if (FIELD_PAGE_NUM === field) {
        rows[0][FIELD_PAGE_NUM] = trimFractionLeadingZeros(entry.pageNum);
      }

      if (FIELD_CATEGORY === field) {
        rows[0][FIELD_CATEGORY] = entry.data.category;
      }

      if (FIELD_SECT === field) {
        rows[0][FIELD_SECT] = entry.data.sect;
      }

      const [, targetEntryLang] = field.match(/^target-entry-lang-(.+)$/) || [];

      if (targetEntryLang) {
        rows[0][`target-entry-${targetEntryLang}`] = entry.data[`target-entry-${targetEntryLang}`];
      }

      const [, originalLang] = field.match(/^original-lang-(.+)$/) || [];

      if (originalLang) {
        rows[0][`original-${originalLang}`] = entry.data[`original-${originalLang}`];
      }

      const [, explanationLang] = field.match(/^explanation-lang-(.+)$/) || [];

      if (explanationLang) {
        (entry.data[`explanation-${explanationLang}`] || []).forEach((explanation, index) => {
          if (isEmpty(rows[index])) {
            rows[index] = {};
          }
          rows[index][`explanation-${explanationLang}`] = explanation;
        });

        if (! hasHandledExplanationNote) {
          const notes = entry.data[FIELD_EXPLANATION_NOTE] || [];
          notes.forEach((note, index) => {
            if (isEmpty(rows[index])) {
              rows[index] = {};
            }
            rows[index][FIELD_EXPLANATION_NOTE] = note;
          });
          hasHandledExplanationNote = true;
        }

        if (! hasHandledExplanationSource) {
          const sources = entry.data[FIELD_EXPLANATION_SOURCE] || [];
          sources.forEach((source, index) => {
            if (isEmpty(rows[index])) {
              rows[index] = {};
            }
            rows[index][FIELD_EXPLANATION_SOURCE] = source;
          });
          hasHandledExplanationSource = true;
        }

        if (! hasHandledExplanationCategory) {
          const categories = entry.data[FIELD_EXPLANATION_CATEGORY] || [];
          categories.forEach((category, index) => {
            if (isEmpty(rows[index])) {
              rows[index] = {};
            }
            rows[index][FIELD_EXPLANATION_CATEGORY] = category;
          });
          hasHandledExplanationCategory = true;
        }
      }

      return rows;
    }, [defaultData])
  }
}
<commit_msg>add function getTargetEntryLang<commit_after>import {uniq, isEmpty} from 'lodash';
import sortFolderContentFields from './sortFolderContentFields';
import DICTIONARY_LANGS from './../constants/dictionaryLangs';
import trimFractionLeadingZeros from './../helpers/trimFractionLeadingZeros';

export const FIELD_PAGE_NUM = 'page-num';
export const FIELD_CATEGORY = 'category';
export const FIELD_SECT = 'sect';
export const FIELD_EXPLANATION_NOTE = 'explanation-note';
export const FIELD_EXPLANATION_SOURCE = 'explanation-source';
export const FIELD_EXPLANATION_CATEGORY = 'explanation-category';

export const RE_SOURCE_ENTRY = /^source-entry-(.+)$/;
export const RE_TARGET_ENTRY = /^target-entry-(.+)$/;
export const RE_ORIGINAL = /^original-(.+)$/;
export const RE_EXPLANATION = /^explanation-(.+)$/;
export const RE_EXPLANATION_NOTE = /^explanation-note$/;
export const RE_EXPLANATION_CATEGORY = /^explanation-category$/;

const getSourceLang = (key) => {
  const [, lang] = key.match(RE_SOURCE_ENTRY) || [];
  return validLangs.includes(lang) ? lang : null;
};

const getTargetEntryLang = (key) => {
  const [, lang] = key.match(RE_TARGET_ENTRY) || [];
  return validLangs.includes(lang) ? lang : null;
};

const getExplanationLang = (key) => {
  const [, lang] = key.match(RE_EXPLANATION) || [];
  return validLangs.includes(lang) ? lang : null;
};

const isArrayField = (key) => {
  return [RE_EXPLANATION, RE_EXPLANATION_NOTE, RE_EXPLANATION_CATEGORY].some((re) => re.exec(key));
};

const validLangs = DICTIONARY_LANGS.map((row) => row.value);

export default class CsvProcessor {

  static isColumnRow(data) {
    return data.some((key) => {
      const sourceLanguage = getSourceLang(key);
      return !! sourceLanguage;
    });
  }

  static getColumnData(data) {

    const result = data.reduce((columnData, key, index) => {

      const sourceLanguage = getSourceLang(key);

      if (sourceLanguage) {
        columnData.sourceLanguage = sourceLanguage;
      }

      const explanationLanguage = getExplanationLang(key);

      if (explanationLanguage) {
        columnData.targetLanguages.push(explanationLanguage);
        columnData.contentFields.push(`explanation-lang-${explanationLanguage}`);
      }

      if (FIELD_PAGE_NUM === key) {
        columnData.contentFields.push(FIELD_PAGE_NUM);
      }

      return columnData;

    }, {sourceLanguage: '', targetLanguages: [], contentFields: []});

    result.targetLanguages = uniq(result.targetLanguages);
    result.contentFields = sortFolderContentFields(result.contentFields);

    return result;
  }

  static getFields(data) {

    return data.reduce((fields, key, index) => {

      const sourceLanguage = getSourceLang(key);
      const explanationLanguage = getExplanationLang(key);

      if (sourceLanguage) {
        fields[index] = 'sourceEntry';
      }
      else if (explanationLanguage) {
        fields[index] = `explanation-${explanationLanguage}`;
      }
      else if (FIELD_EXPLANATION_NOTE === key) {
        fields[index] = FIELD_EXPLANATION_NOTE;
      }
      else if (FIELD_EXPLANATION_SOURCE === key) {
        fields[index] = FIELD_EXPLANATION_SOURCE;
      }
      else if (FIELD_EXPLANATION_CATEGORY === key) {
        fields[index] = FIELD_EXPLANATION_CATEGORY;
      }
      else if (FIELD_PAGE_NUM === key) {
        fields[index] = FIELD_PAGE_NUM;
      }
      else {
        // unknown columns
        fields[index] = undefined;
      }
      return fields;
    }, []);
  }

  static getRowDataByFields(data, fields) {
    return fields.reduce((rowData, field, index) => {
      if (field) {

        if (FIELD_EXPLANATION_CATEGORY === field) {
          const value = data[index];
          rowData[field] = value ? [value.split(',').map(Number)] : [[]];
        }
        else if (isArrayField(field)) {
          rowData[field] = [data[index]]
        }
        else {
          rowData[field] = data[index];
        }
      }
      return rowData;
    }, {});
  }

  static appendData(newData, oldData, fields) {

    return fields.reduce((oldData, field, index) => {

      if (isArrayField(field)) {
        const arr = oldData[field];
        const value = newData[index];

        if (value && (FIELD_EXPLANATION_CATEGORY === field)) {
          arr.push(value.split(',').map(Number));
        }
        else if (value) {
          arr.push(value);
        }
      }
      return oldData;
    }, oldData);
  }

  // for csv export
  static getCsvRowsByEntry({folder, entry}) {

    const {sourceLanguage, contentFields} = folder.data;
    const defaultData = {
      [`source-entry-${sourceLanguage}`]: entry.sourceEntry
    };

    let hasHandledExplanationNote = false;
    let hasHandledExplanationSource = false;
    let hasHandledExplanationCategory = false;

    return contentFields.reduce((rows, field) => {

      if (FIELD_PAGE_NUM === field) {
        rows[0][FIELD_PAGE_NUM] = trimFractionLeadingZeros(entry.pageNum);
      }

      if (FIELD_CATEGORY === field) {
        rows[0][FIELD_CATEGORY] = entry.data.category;
      }

      if (FIELD_SECT === field) {
        rows[0][FIELD_SECT] = entry.data.sect;
      }

      const [, targetEntryLang] = field.match(/^target-entry-lang-(.+)$/) || [];

      if (targetEntryLang) {
        rows[0][`target-entry-${targetEntryLang}`] = entry.data[`target-entry-${targetEntryLang}`];
      }

      const [, originalLang] = field.match(/^original-lang-(.+)$/) || [];

      if (originalLang) {
        rows[0][`original-${originalLang}`] = entry.data[`original-${originalLang}`];
      }

      const [, explanationLang] = field.match(/^explanation-lang-(.+)$/) || [];

      if (explanationLang) {
        (entry.data[`explanation-${explanationLang}`] || []).forEach((explanation, index) => {
          if (isEmpty(rows[index])) {
            rows[index] = {};
          }
          rows[index][`explanation-${explanationLang}`] = explanation;
        });

        if (! hasHandledExplanationNote) {
          const notes = entry.data[FIELD_EXPLANATION_NOTE] || [];
          notes.forEach((note, index) => {
            if (isEmpty(rows[index])) {
              rows[index] = {};
            }
            rows[index][FIELD_EXPLANATION_NOTE] = note;
          });
          hasHandledExplanationNote = true;
        }

        if (! hasHandledExplanationSource) {
          const sources = entry.data[FIELD_EXPLANATION_SOURCE] || [];
          sources.forEach((source, index) => {
            if (isEmpty(rows[index])) {
              rows[index] = {};
            }
            rows[index][FIELD_EXPLANATION_SOURCE] = source;
          });
          hasHandledExplanationSource = true;
        }

        if (! hasHandledExplanationCategory) {
          const categories = entry.data[FIELD_EXPLANATION_CATEGORY] || [];
          categories.forEach((category, index) => {
            if (isEmpty(rows[index])) {
              rows[index] = {};
            }
            rows[index][FIELD_EXPLANATION_CATEGORY] = category;
          });
          hasHandledExplanationCategory = true;
        }
      }

      return rows;
    }, [defaultData])
  }
}
<|endoftext|>


<commit_before>var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
    name:'Nintendo Life',
    version:'0.1',
    prepareImgLinks:function (callback) {
        var res = [];
        hoverZoom.urlReplace(res,
            'a img, img.framed',
            /(icon|tiny|small)\./,
            'large.'
        );
        callback($(res));
    }
});
<commit_msg>Update for plug-in : nintendolife.com<commit_after>var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
    name:'Nintendo Life',
    version:'0.2',
    prepareImgLinks:function (callback) {
        var res = [];
        var reFind = /\/\d+x\d+\./;
        var reReplace = '/large.';

        hoverZoom.urlReplace(res,
            'img[src]',
            /(avatar|icon|tiny|small)\./,
            'large.'
        );

        hoverZoom.urlReplace(res,
            'img[src]',
            reFind,
            reReplace
        );

        $('[style*=url]').each(function() {
            // extract url from style
            var backgroundImage = this.style.backgroundImage;
            var reUrl = /.*url\s*\(\s*(.*)\s*\).*/i
            backgroundImage = backgroundImage.replace(reUrl, '$1');
            // remove leading & trailing quotes
            var backgroundImageUrl = backgroundImage.replace(/^['"]/, '').replace(/['"]+$/, '');
            var fullsizeUrl = backgroundImageUrl.replace(reFind, reReplace);
            if (fullsizeUrl != backgroundImageUrl) {
                var link = $(this);
                if (link.data().hoverZoomSrc == undefined) { link.data().hoverZoomSrc = [] }
                if (link.data().hoverZoomSrc.indexOf(fullsizeUrl) == -1) {
                    link.data().hoverZoomSrc.unshift(fullsizeUrl);
                    res.push(link);
                }
            }
        });

        callback($(res), this.name);
    }
});
<|endoftext|>


<commit_before>/*
 * Copyright 2012 Amadeus s.a.s.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var util = require('util');
var path = require('path');

var BaseTestType = require('../base-test-type.js');
var TestsEnumerator = require('./at-tests-enumerator.js');

var url = require('../../util/url.js');
var merge = require('../../util/merge.js');
var attester = require('../../attester');

var sendAttesterTestSuite = function (req, res, next) {
    var output = ['Aria.classDefinition({$classpath:"MainTestSuite",$extends:"aria.jsunit.TestSuite",$constructor:function(){this.$TestSuite.constructor.call(this);\n'];
    var testCases = this.testCases;
    for (var i = 0, l = testCases.length; i < l; i++) {
        var curTest = testCases[i];
        output.push('this.addTests(', JSON.stringify(curTest.name), ');\n');
    }
    output.push('}});');
    res.setHeader('Content-Type', 'text/javascript');
    res.write(output.join(''));
    res.end();
};

var AriaTemplatesTests = function (campaign, inputConfig) {
    // Default values for the config:
    var testConfig = {
        rootFolderPath: '/',
        bootstrap: null,
        // the default value depends on the rootFolderPath, that's why it is processed later
        // moreover, it can be an array (legacy mode) or an object with "before" and "after" arrays, hence we can't make it an array here
        extraScripts: null,
        debug: true,
        memCheckMode: true,
        classpaths: {
            includes: [],
            excludes: []
        },
        files: {
            includes: [],
            excludes: []
        }
    };
    merge(testConfig, inputConfig);
    if (!testConfig.bootstrap) {
        testConfig.bootstrap = testConfig.rootFolderPath + 'aria/bootstrap.js';
    }

    BaseTestType.call(this, campaign, testConfig);
    var rootFolderPath = testConfig.rootFolderPath;

    var ariaConfig = {
        memCheckMode: testConfig.memCheckMode,
        debug: testConfig.debug,
        rootFolderPath: url.normalize(this.campaign.baseURL, rootFolderPath) + "/"
    };
    this.ariaConfig = ariaConfig;
    this.bootstrap = testConfig.bootstrap;

    this._testsEnumerator = new TestsEnumerator({
        resources: campaign.resources,
        files: testConfig.files,
        classpaths: testConfig.classpaths,
        rootFolderPath: testConfig.rootFolderPath
    }, this.campaign.logger);

    this.testPage("test.html", require("./templates/test-page.json"));
    this.testPage("interactive.html", require("./templates/interactive.json"));
    this.use((function (req, res, next) {
        if ("/MainTestSuite.js" === req.url) {
            sendAttesterTestSuite.call(this, req, res, next);
        } else {
            next();
        }
    }).bind(this));
    this.use(attester.middlewares.staticFolder(path.join(__dirname, 'client')));
};

util.inherits(AriaTemplatesTests, BaseTestType);

AriaTemplatesTests.prototype.name = "Aria Templates tests";
AriaTemplatesTests.prototype.type = "aria-templates";
AriaTemplatesTests.prototype.debug = "interactive.html#runIsolated=true";

AriaTemplatesTests.prototype.init = function (callback) {
    var self = this;
    var testsEnumerator = self._testsEnumerator;
    testsEnumerator.init(function () {
        self.testsTrees = self._testsEnumerator.testsTrees;
        var tests = testsEnumerator.testCases;
        self.testCases = tests;
        for (var i = 0, l = tests.length; i < l; i++) {
            var curTest = tests[i];
            curTest.url = 'test.html?testClasspath=' + encodeURIComponent(curTest.name);
        }
        callback();
    });
};

AriaTemplatesTests.prototype.dispose = function (baseURL) {
    this._testsEnumerator.dispose();
};

module.exports = AriaTemplatesTests;<commit_msg>fix #90 Classic Test Runner: unable to reload test suite<commit_after>/*
 * Copyright 2012 Amadeus s.a.s.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var util = require('util');
var path = require('path');

var BaseTestType = require('../base-test-type.js');
var TestsEnumerator = require('./at-tests-enumerator.js');

var url = require('../../util/url.js');
var merge = require('../../util/merge.js');
var attester = require('../../attester');

var sendAttesterTestSuite = function (req, res, next) {
    var output = ['Aria.classDefinition({$classpath:"MainTestSuite",$extends:"aria.jsunit.TestSuite",$constructor:function(){this.$TestSuite.constructor.call(this);\n'];
    var testCases = this.testCases;
    for (var i = 0, l = testCases.length; i < l; i++) {
        var curTest = testCases[i];
        output.push('this.addTests(', JSON.stringify(curTest.name), ');\n');
    }
    output.push('}});');
    res.setHeader('Content-Type', 'text/javascript');
    res.write(output.join(''));
    res.end();
};

var AriaTemplatesTests = function (campaign, inputConfig) {
    // Default values for the config:
    var testConfig = {
        rootFolderPath: '/',
        bootstrap: null,
        // the default value depends on the rootFolderPath, that's why it is processed later
        // moreover, it can be an array (legacy mode) or an object with "before" and "after" arrays, hence we can't make it an array here
        extraScripts: null,
        debug: true,
        memCheckMode: true,
        classpaths: {
            includes: [],
            excludes: []
        },
        files: {
            includes: [],
            excludes: []
        }
    };
    merge(testConfig, inputConfig);
    if (!testConfig.bootstrap) {
        testConfig.bootstrap = testConfig.rootFolderPath + 'aria/bootstrap.js';
    }

    BaseTestType.call(this, campaign, testConfig);
    var rootFolderPath = testConfig.rootFolderPath;

    var ariaConfig = {
        memCheckMode: testConfig.memCheckMode,
        debug: testConfig.debug,
        rootFolderPath: url.normalize(this.campaign.baseURL, rootFolderPath) + "/"
    };
    this.ariaConfig = ariaConfig;
    this.bootstrap = testConfig.bootstrap;

    this._testsEnumerator = new TestsEnumerator({
        resources: campaign.resources,
        files: testConfig.files,
        classpaths: testConfig.classpaths,
        rootFolderPath: testConfig.rootFolderPath
    }, this.campaign.logger);

    this.testPage("test.html", require("./templates/test-page.json"));
    this.testPage("interactive.html", require("./templates/interactive.json"));
    this.use((function (req, res, next) {
        if (/^\/MainTestSuite\.js(\?|$)/.test(req.url)) { // to allow timestamped requests
            sendAttesterTestSuite.call(this, req, res, next);
        } else {
            next();
        }
    }).bind(this));
    this.use(attester.middlewares.staticFolder(path.join(__dirname, 'client')));
};

util.inherits(AriaTemplatesTests, BaseTestType);

AriaTemplatesTests.prototype.name = "Aria Templates tests";
AriaTemplatesTests.prototype.type = "aria-templates";
AriaTemplatesTests.prototype.debug = "interactive.html#runIsolated=true";

AriaTemplatesTests.prototype.init = function (callback) {
    var self = this;
    var testsEnumerator = self._testsEnumerator;
    testsEnumerator.init(function () {
        self.testsTrees = self._testsEnumerator.testsTrees;
        var tests = testsEnumerator.testCases;
        self.testCases = tests;
        for (var i = 0, l = tests.length; i < l; i++) {
            var curTest = tests[i];
            curTest.url = 'test.html?testClasspath=' + encodeURIComponent(curTest.name);
        }
        callback();
    });
};

AriaTemplatesTests.prototype.dispose = function (baseURL) {
    this._testsEnumerator.dispose();
};

module.exports = AriaTemplatesTests;<|endoftext|>