<commit_before>
angular.module('CIVILITY')
.directive('submitTracto', function($routeParams,$location,clusterpost, $http){

  function link($scope,$attrs,$filter){

    $scope.jobSumitConfirmation = [];

    $scope.tools = {
      bedpostx : {},
      probtrackx2 : {}
    };
    //Bedpostx
    $scope.tools.bedpostx.param = "-n 2";
    $scope.tools.bedpostx.id = "bedpostxInfo";
    $scope.tools.bedpostx.modify = false;
    $http({
      method: 'GET',
      url: '/public/data/bedpostxHelp-FSL-5.0.8.txt'
    })
    .then(function(res){
      $scope.tools.bedpostx.help = res.data;
    });

    $http({
      method: 'GET',
      url: '/public/data/jsonDescriptionTableTemplate.txt'
    })
    .then(function(res){
      $scope.jsonTemplate = res.data;
    });

    //Probtrackx
    $scope.tools.probtrackx2.param = "-P 3000 --steplength=0.75 --sampvox=0.5";
    $scope.tools.probtrackx2.id = "probtrackx2Info";
    $scope.tools.probtrackx2.modify = false;
    $http({
      method: 'GET',
      url: '/public/data/probtrackx2Help-FSL-5.0.8.txt'
    })
    .then(function(res){
      $scope.tools.probtrackx2.help = res.data;
    });

    $scope.formOK = false;
    $scope.submitTractoButton = false;
    $scope.serverselect = {
      selection : null
    };
    $scope.Parameters = {
      subject : "",
      Files : {
                DWI : "",
                T1 : "",
                BrainMask:"",
                parcellationTable: "",
                innerSurface: "",
                colorSurface: ""
              },
      labelsetName: "colour",
      ignoreLabel: false,
      ignoreLabelID : "setlabelID",
      overlapping: true,
      loopcheck: true,
      bedpostX : $scope.tools.bedpostx.param,
      probtrackParam : $scope.tools.probtrackx2.param

    };

    $scope.usableInputBedpostx = function(toolX){

      var bool = toolX.modify;
      console.log(toolX.id);
      if(bool === true && confirm('Do you really want to modify bedpostx parameters ?') == true)
      {

        document.getElementById(toolX.id).disabled = false;
      }
      else
      {
        document.getElementById(toolX.id).disabled = true;
      }

    }

    $scope.paramSubmitJob = function(){
      $scope.formOK = $scope.formValidation();
      if($scope.formOK == true)
      {
        $scope.Parameters.overlapping = $scope.overlapping;
        $scope.Parameters.loopcheck = $scope.loopcheck;
        $scope.createJobObject();

      }
    };

    $scope.formValidation = function(){
      //Subject ID
      if(!$scope.Parameters.subject)
      {
        alert ("You must define a valid subject ID (only letters, numbers, \"-\", \"_\" are allowed - no space).");
        return false;
      }
      //DWI Image
      if(!$scope.Parameters.Files.DWI)
      {
        alert("You must select DWI file.");
        return false;
      }
      //T1 image
      if(!$scope.Parameters.Files.T1)
      {
        alert("You must select T1 file.");
        return false;
      }
      //Brain mask
      if(!$scope.Parameters.Files.BrainMask)
      {
        alert("You must select brainmask file.");
        return false;
      }
      //Parcellation Table
      if(!$scope.Parameters.Files.parcellationTable)
      {
        alert("You must select parcellation Table file.");
        return false;
      }
      //Inner Surface
      if(!$scope.Parameters.Files.innerSurface)
      {
        alert("You must select inner Surface file.");
        return false;
      }
      //Colored surface
      if($scope.checkedSurfaceColored  && $scope.Parameters.Files.innerSurface)
      {
        $scope.Parameters.Files.colorSurface = $scope.Parameters.Files.innerSurface;
      }
      else if ($scope.checkedSurfaceColored && !$scope.Parameters.Files.innerSurface)
      {
          //Do nothing
      }
      else
      {
        if(!$scope.alternativeSurface )
        {
          alert("You must select an alternative surface file containing color labels.");
          return false;
        }
        else
        {
          $scope.Parameters.Files.colorSurface = $scope.alternativeSurface;
        }
      }
      //Check LabelSetName format pattern
      if(!$scope.Parameters.labelsetName)
      {
        alert ("You must define a valid labelset name (only letters, numbers, \"-\", \"_\" are allowed - no space).");
        return false;
      }
      //default string if ignoreLabel = false
      if(!$scope.Parameters.ignoreLabel)
      {
        $scope.Parameters.ignoreLabelID = "set labelID";
      }
      else
      {
        if($scope.Parameters.ignoreLabelID == "set labelID")
        {
          alert ("You must specified the name of label to ignore - Change 'set labelID' by the name of label to ignore (example : 0 0 0)");
          return false;
        }
      }
      //Check email select
      if($scope.userEmail == undefined)
      {
        alert ("You must specify your email to receive tractography results");
        return false;
      }
      return true;
    };

    //Get servers available
    clusterpost.getExecutionServers().then(function(res){
      $scope.serverselect.servers = res.data;
      $scope.serverselect.selection = res.data[0];
    });

    //Create job object / document and then upload file and submit
    $scope.createJobObject = function(){
        $scope.submitTractoButton = true;
        var job = {};

        job.executable ="tractographyScriptApp.sh";

        job.parameters = [];
       _.each($scope.Parameters, function(value, key){
          if(key != "Files")
          {
            var param = {};
            param.flag = "";
            param.name = value.toString();
            job.parameters.push(param);
          }
          else if (key=="Files")
          {
            _.each($scope.Parameters.Files, function(value, key){
              var param = {};
              param.flag = "";
              param.name = value.name;
              job.parameters.push(param);
            });
          }
        });

      job.inputs = [];
      _.each($scope.Parameters.Files, function(value, key){
      var input = {};
          input.name = value.name;
          job.inputs.push(input);
      });

      job.outputs = [];
      //Output 1 : matrix file
      var param1 = {};
      param1.type = "file";
      param1.name = $scope.Parameters.subject + "/Network_overlapping_loopcheck/fdt_network_matrix";
      job.outputs.push(param1);
      //Output 2 : parcellation description table (json file)
      var param2 = {};
      param2.type = "file";
      param2.name = $scope.Parameters.subject + "/" + $scope.Parameters.Files.parcellationTable.name;
      job.outputs.push(param2);
      //Output 3 : {subject dir} -- all output dir (as tar.gz)
      var param3 = {};
      param3.type = "tar.gz";
      param3.name = $scope.Parameters.subject;
      job.outputs.push(param3);
      //Output 4 : output of job -- logFile
      var param4 = {};
      param4.type = "file";
      param4.name = "stdout.out";
      job.outputs.push(param4);
      //Output 5 :  output error of job -- logErrorFile
      var param5 = {};
      param5.type = "file";
      param5.name = "stderr.err";
      job.outputs.push(param5);

      job.type = "job";
      job.userEmail = $scope.userEmail;
      //job.executionserver =  "testserver";

      job.jobparameters = [];
      //Job param 1 : define the queue where is submit the job
      var paramJob1 = {};
      paramJob1.flag = "-q";
      paramJob1.name = "week";
      job.jobparameters.push(paramJob1);
      //Job param 2 : number of cpu
      var paramJob2 = {};
      paramJob2.flag = "-n";
      paramJob2.name = "1";
      job.jobparameters.push(paramJob2);
      //Job param 3 : request job on same host
      var paramJob3 = {};
      paramJob3.flag = "-R";
      paramJob3.name = "span[hosts=1]";
      job.jobparameters.push(paramJob3);
      //Job param 4 : define memory required to the job
      var paramJob4 = {};
      paramJob4.flag = "-M";
      paramJob4.name = "10";
      job.jobparameters.push(paramJob4);

      //Select server
      if($scope.serverselect.selection == "" || $scope.serverselect.selection == null)
      {
          alert("No server specified - you must choose one server to run a job on it");
      }
      else
      {
          job.executionserver = $scope.serverselect.selection.name;
      }
      var job_id = "";

    //Create Job
    clusterpost.createJob(job)
    .then(function(res){
      //Upload data
      var doc = res.data;
      job_id = doc.id;
      var val = $scope.readFilesAndSubmit(job_id);
    })
    .catch(function(e){
      console.log(e);
    });
 };

  $scope.submitJobX = function(jobid,force){
    clusterpost.submitJob(jobid,force).then(function(res){
        console.log("Job " + jobid + " submit");
        $scope.submitTractoButton = false;
        $scope.jobSumitConfirmation.push("Job " + $scope.Parameters.subject + " is submited.");
    })
    .catch(function(e){
      $scope.submitTractoButton = false;
      $scope.jobSumitConfirmation.push("Job " + $scope.Parameters.subject + " submission failed.");
      console.error(e);
      throw e;
    });
  };

    $scope.uploadFiles = function(jobid, keys, index){
      return  clusterpost.addAttachment(jobid, $scope.Parameters.Files[keys[index]].name, $scope.Parameters.Files[keys[index]])
      .then(function(res){
        if(index < keys.length - 1)
        {
          return $scope.uploadFiles(jobid, keys, index+1);
        }
        else
        {
        return 'Done';
        }
      })//upload file
      .catch(function(e){
        console.error(e);
        throw e;
      });
    };

    $scope.readFilesAndSubmit = function(jobid){
      var keys = _.keys($scope.Parameters.Files);
      $scope.uploadFiles(jobid, keys, 0).then(function(res){
          console.log(res);
          $scope.submitJobX(jobid,false);
      });
    };
    $scope.$watch("tools.bedpostx.modify", function(){
        console.log("HelloWatch tools.bedpostx.modify", $scope.tools.bedpostx.modify);
        $scope.usableInputBedpostx($scope.tools.bedpostx);
      });

    $scope.$watch("tools.probtrackx2.modify", function(){
        console.log("HelloWatch tools.probtrackx2.modify", $scope.tools.probtrackx2.modify);
        $scope.usableInputBedpostx($scope.tools.probtrackx2);
      });
};
return {
    restrict : 'E',
/*    scope: {
      jobID : "="
    },*/
    link : link,
    templateUrl: 'views/directives/directiveTracto.html'
}

});

<commit_msg>change alert when job create and submit or not<commit_after>
angular.module('CIVILITY')
.directive('submitTracto', function($routeParams,$location,clusterpost, $http){

  function link($scope,$attrs,$filter){

    $scope.jobSumitConfirmation = [];

    $scope.tools = {
      bedpostx : {},
      probtrackx2 : {}
    };
    //Bedpostx
    $scope.tools.bedpostx.param = "-n 2";
    $scope.tools.bedpostx.id = "bedpostxInfo";
    $scope.tools.bedpostx.modify = false;
    $http({
      method: 'GET',
      url: '/public/data/bedpostxHelp-FSL-5.0.8.txt'
    })
    .then(function(res){
      $scope.tools.bedpostx.help = res.data;
    });

    $http({
      method: 'GET',
      url: '/public/data/jsonDescriptionTableTemplate.txt'
    })
    .then(function(res){
      $scope.jsonTemplate = res.data;
    });

    //Probtrackx
    $scope.tools.probtrackx2.param = "-P 3000 --steplength=0.75 --sampvox=0.5";
    $scope.tools.probtrackx2.id = "probtrackx2Info";
    $scope.tools.probtrackx2.modify = false;
    $http({
      method: 'GET',
      url: '/public/data/probtrackx2Help-FSL-5.0.8.txt'
    })
    .then(function(res){
      $scope.tools.probtrackx2.help = res.data;
    });

    $scope.formOK = false;
    $scope.submitTractoButton = false;
    $scope.serverselect = {
      selection : null
    };
    $scope.Parameters = {
      subject : "",
      Files : {
                DWI : "",
                T1 : "",
                BrainMask:"",
                parcellationTable: "",
                innerSurface: "",
                colorSurface: ""
              },
      labelsetName: "colour",
      ignoreLabel: false,
      ignoreLabelID : "setlabelID",
      overlapping: true,
      loopcheck: true,
      bedpostX : $scope.tools.bedpostx.param,
      probtrackParam : $scope.tools.probtrackx2.param

    };

    $scope.usableInputBedpostx = function(toolX){

      var bool = toolX.modify;
      console.log(toolX.id);
      if(bool === true && confirm('Do you really want to modify bedpostx parameters ?') == true)
      {

        document.getElementById(toolX.id).disabled = false;
      }
      else
      {
        document.getElementById(toolX.id).disabled = true;
      }

    }

    $scope.paramSubmitJob = function(){
      $scope.formOK = $scope.formValidation();
      if($scope.formOK == true)
      {
        $scope.Parameters.overlapping = $scope.overlapping;
        $scope.Parameters.loopcheck = $scope.loopcheck;
        $scope.createJobObject();

      }
    };

    $scope.formValidation = function(){
      //Subject ID
      if(!$scope.Parameters.subject)
      {
        alert ("You must define a valid subject ID (only letters, numbers, \"-\", \"_\" are allowed - no space).");
        return false;
      }
      //DWI Image
      if(!$scope.Parameters.Files.DWI)
      {
        alert("You must select DWI file.");
        return false;
      }
      //T1 image
      if(!$scope.Parameters.Files.T1)
      {
        alert("You must select T1 file.");
        return false;
      }
      //Brain mask
      if(!$scope.Parameters.Files.BrainMask)
      {
        alert("You must select brainmask file.");
        return false;
      }
      //Parcellation Table
      if(!$scope.Parameters.Files.parcellationTable)
      {
        alert("You must select parcellation Table file.");
        return false;
      }
      //Inner Surface
      if(!$scope.Parameters.Files.innerSurface)
      {
        alert("You must select inner Surface file.");
        return false;
      }
      //Colored surface
      if($scope.checkedSurfaceColored  && $scope.Parameters.Files.innerSurface)
      {
        $scope.Parameters.Files.colorSurface = $scope.Parameters.Files.innerSurface;
      }
      else if ($scope.checkedSurfaceColored && !$scope.Parameters.Files.innerSurface)
      {
          //Do nothing
      }
      else
      {
        if(!$scope.alternativeSurface )
        {
          alert("You must select an alternative surface file containing color labels.");
          return false;
        }
        else
        {
          $scope.Parameters.Files.colorSurface = $scope.alternativeSurface;
        }
      }
      //Check LabelSetName format pattern
      if(!$scope.Parameters.labelsetName)
      {
        alert ("You must define a valid labelset name (only letters, numbers, \"-\", \"_\" are allowed - no space).");
        return false;
      }
      //default string if ignoreLabel = false
      if(!$scope.Parameters.ignoreLabel)
      {
        $scope.Parameters.ignoreLabelID = "set labelID";
      }
      else
      {
        if($scope.Parameters.ignoreLabelID == "set labelID")
        {
          alert ("You must specified the name of label to ignore - Change 'set labelID' by the name of label to ignore (example : 0 0 0)");
          return false;
        }
      }
      //Check email select
      if($scope.userEmail == undefined)
      {
        alert ("You must specify your email to receive tractography results");
        return false;
      }
      return true;
    };

    //Get servers available
    clusterpost.getExecutionServers().then(function(res){
      $scope.serverselect.servers = res.data;
      $scope.serverselect.selection = res.data[0];
    });

    //Create job object / document and then upload file and submit
    $scope.createJobObject = function(){
        $scope.submitTractoButton = true;
        var job = {};

        job.executable ="tractographyScriptApp.sh";

        job.parameters = [];
       _.each($scope.Parameters, function(value, key){
          if(key != "Files")
          {
            var param = {};
            param.flag = "";
            param.name = value.toString();
            job.parameters.push(param);
          }
          else if (key=="Files")
          {
            _.each($scope.Parameters.Files, function(value, key){
              var param = {};
              param.flag = "";
              param.name = value.name;
              job.parameters.push(param);
            });
          }
        });

      job.inputs = [];
      _.each($scope.Parameters.Files, function(value, key){
      var input = {};
          input.name = value.name;
          job.inputs.push(input);
      });

      job.outputs = [];
      //Output 1 : matrix file
      var param1 = {};
      param1.type = "file";
      param1.name = $scope.Parameters.subject + "/Network_overlapping_loopcheck/fdt_network_matrix";
      job.outputs.push(param1);
      //Output 2 : parcellation description table (json file)
      var param2 = {};
      param2.type = "file";
      param2.name = $scope.Parameters.subject + "/" + $scope.Parameters.Files.parcellationTable.name;
      job.outputs.push(param2);
      //Output 3 : {subject dir} -- all output dir (as tar.gz)
      var param3 = {};
      param3.type = "tar.gz";
      param3.name = $scope.Parameters.subject;
      job.outputs.push(param3);
      //Output 4 : output of job -- logFile
      var param4 = {};
      param4.type = "file";
      param4.name = "stdout.out";
      job.outputs.push(param4);
      //Output 5 :  output error of job -- logErrorFile
      var param5 = {};
      param5.type = "file";
      param5.name = "stderr.err";
      job.outputs.push(param5);

      job.type = "job";
      job.userEmail = $scope.userEmail;
      //job.executionserver =  "testserver";

      job.jobparameters = [];
      //Job param 1 : define the queue where is submit the job
      var paramJob1 = {};
      paramJob1.flag = "-q";
      paramJob1.name = "week";
      job.jobparameters.push(paramJob1);
      //Job param 2 : number of cpu
      var paramJob2 = {};
      paramJob2.flag = "-n";
      paramJob2.name = "1";
      job.jobparameters.push(paramJob2);
      //Job param 3 : request job on same host
      var paramJob3 = {};
      paramJob3.flag = "-R";
      paramJob3.name = "span[hosts=1]";
      job.jobparameters.push(paramJob3);
      //Job param 4 : define memory required to the job
      var paramJob4 = {};
      paramJob4.flag = "-M";
      paramJob4.name = "10";
      job.jobparameters.push(paramJob4);

      //Select server
      if($scope.serverselect.selection == "" || $scope.serverselect.selection == null)
      {
          alert("No server specified - you must choose one server to run a job on it");
      }
      else
      {
          job.executionserver = $scope.serverselect.selection.name;
      }
      var job_id = "";

    //Create Job
    clusterpost.createJob(job)
    .then(function(res){
      //Upload data
      var doc = res.data;
      job_id = doc.id;
      var val = $scope.readFilesAndSubmit(job_id);
    })
    .catch(function(e){
      console.log(e);
    });
 };

  $scope.submitJobX = function(jobid,force){
    clusterpost.submitJob(jobid,force).then(function(res){
        console.log("Job " + jobid + " submit");
        $scope.submitTractoButton = false;
        $scope.jobSumitConfirmation.push("Job " + $scope.Parameters.subject + " is created and is running.");
    })
    .catch(function(e){
      $scope.submitTractoButton = false;
      $scope.jobSumitConfirmation.push("Job " + $scope.Parameters.subject + " is created but it's not running. \n --Try to restart the job in the Jobs summary view");
      console.error(e);
      throw e;
    });
  };

    $scope.uploadFiles = function(jobid, keys, index){
      return  clusterpost.addAttachment(jobid, $scope.Parameters.Files[keys[index]].name, $scope.Parameters.Files[keys[index]])
      .then(function(res){
        if(index < keys.length - 1)
        {
          return $scope.uploadFiles(jobid, keys, index+1);
        }
        else
        {
        return 'Done';
        }
      })//upload file
      .catch(function(e){
        console.error(e);
        throw e;
      });
    };

    $scope.readFilesAndSubmit = function(jobid){
      var keys = _.keys($scope.Parameters.Files);
      $scope.uploadFiles(jobid, keys, 0).then(function(res){
          console.log(res);
          $scope.submitJobX(jobid,false);
      });
    };
    $scope.$watch("tools.bedpostx.modify", function(){
        console.log("HelloWatch tools.bedpostx.modify", $scope.tools.bedpostx.modify);
        $scope.usableInputBedpostx($scope.tools.bedpostx);
      });

    $scope.$watch("tools.probtrackx2.modify", function(){
        console.log("HelloWatch tools.probtrackx2.modify", $scope.tools.probtrackx2.modify);
        $scope.usableInputBedpostx($scope.tools.probtrackx2);
      });
};
return {
    restrict : 'E',
/*    scope: {
      jobID : "="
    },*/
    link : link,
    templateUrl: 'views/directives/directiveTracto.html'
}

});

<|endoftext|>


<commit_before>String.prototype.strReplaceNthSub = function(needle, replacement, occurrence){
  var arr = this.split(needle);
  if(occurrence < arr.length){
    arr[occurrence - 1] += replacement + arr[occurrence];
    arr[occurrence].unset();
    this = arr.join();
  }
  return this;
}

String.prototype.subStringCount = funciton(subString,step){
  if(step==null||step==undefined||step==0){
    step=subString.length;
  }
  if(subString.length<=0){
    return 0;
  }
  var pos = 0;
  var count = 0;
  while(true){
    pos = String.indexOf(subString,pos);
    if(pos>=0){
      count++;
      pos+=step;
    }else break;
  }
  return count;
}
<commit_msg>Update string.o.js<commit_after>String.strReplaceNthSub = function(needle, replacement, occurrence){
  var arr = this.split(needle);
  if(occurrence < arr.length){
    arr[occurrence - 1] += replacement + arr[occurrence];
    arr[occurrence].unset();
    this = arr.join();
  }
  return this;
}

String.subStringCount = function(subString,step){
  if(step==null||step==undefined||step==0){
    step=subString.length;
  }
  if(subString.length<=0){
    return 0;
  }
  var pos = 0;
  var count = 0;
  while(true){
    pos = String.indexOf(subString,pos);
    if(pos>=0){
      count++;
      pos+=step;
    }else break;
  }
  return count;
}
<|endoftext|>


<commit_before>// This program tests the quality of the dagre odering algorithm.

var path = require("path"),
    fs = require("fs"),
    dagre = require("../index"),
    util = require("../lib/util"),
    dot = require("../lib/dot"),
    acyclic = require("../lib/layout/acyclic"),
    rank = require("../lib/layout/rank"),
    order = require("../lib/layout/order"),
    layout = require("../lib/layout/layout");

var benchmarkFiles = process.argv.slice(2);
if (benchmarkFiles.length === 0) {
  process.stderr.write("Usage: " + __filename + " [DOT file]+\n");
  process.exit(1);
}

var samples = [];
var times = [];
var skipped = 0;
var failed = 0;

var entry;
while ((entry = benchmarkFiles.pop()) !== undefined) {
  // If we see a directory, push all of its files to the queue and move to the next entry.
  if (fs.statSync(entry).isDirectory()) {
    fs.readdirSync(entry).forEach(function(f) {
      benchmarkFiles.push(path.resolve(entry, f));
    });
    continue;
  }

  process.stdout.write(leftPad(20, entry) + ": ");
  var f = fs.readFileSync(entry, "UTF-8");
  try {
    var g = dot.toGraph(f);
    acyclic().run(g);
    rank(g);
    layout()._normalize(g);
    var preLayering = order()._initOrder(g);
    var pre = order().crossCount(g, preLayering);
    if (pre !== 0) {
      var start = new Date().getTime();
      var postLayering = order().run(g);
      var end = new Date().getTime();
      var post = order().crossCount(g, postLayering);
      var eff = (pre - post) / pre;
      console.log("SUCCESS  -" +
                  "  PRE: " + leftPad(8, pre) +
                  "  POST: " + leftPad(8, post) +
                  "  Efficiency: " + leftPad(8, eff.toString().substring(0, 8)) +
                  "  Time: " + leftPad(5, (end - start)) + "ms");
      samples.push(eff);
      times.push(end - start);
    } else {
      console.log("SKIPPING - 0 CROSSINGS");
      ++skipped;
    }
  } catch (e) {
    console.log("FAILED   - " + e.toString().split("\n")[0]);
    ++failed;
  }
};

console.log("# Graphs: " + leftPad(8, samples.length + skipped + failed));
console.log("Skipped : " + leftPad(8, skipped));
console.log("Failed  : " + leftPad(8, failed));
console.log("Reduction efficiency (larger is better): " + (util.sum(samples) / samples.length));
console.log("Execution time: " + util.sum(times) + "ms (avg: " + Math.round(util.sum(times) / times.length) + "ms)");

function leftPad(len, str) {
  var result = [];
  for (i = 0; i < len; ++i) {
    result.push(" ");
  }
  result.push(str);
  return result.join("").slice(-len);
}
<commit_msg>Print results even when aborting<commit_after>// This program tests the quality of the dagre odering algorithm.

var path = require("path"),
    fs = require("fs"),
    dagre = require("../index"),
    util = require("../lib/util"),
    dot = require("../lib/dot"),
    acyclic = require("../lib/layout/acyclic"),
    rank = require("../lib/layout/rank"),
    order = require("../lib/layout/order"),
    layout = require("../lib/layout/layout");

var benchmarkFiles = process.argv.slice(2);
if (benchmarkFiles.length === 0) {
  process.stderr.write("Usage: " + __filename + " [DOT file]+\n");
  process.exit(1);
}

var samples = [];
var times = [];
var skipped = 0;
var failed = 0;

process.on('SIGINT', function() {
  console.log("\n\n!! Aborting...");
  process.exit(1);
});
process.on('exit', function() { finish(); });

// Start the loop
handleNext();

function handleNext() {
  var entry = benchmarkFiles.pop();
  if (entry === undefined) {
    return;
  }

  if (fs.statSync(entry).isDirectory()) {
    pushDirectory(entry);
  } else {
    processFile(entry);
  }
}

function pushDirectory(dir) {
  fs.readdir(dir, function(err, files) {
    if (err) throw err;
    files.forEach(function(file) {
      benchmarkFiles.push(path.resolve(dir, file));
    });
    handleNext();
  });
}

function processFile(file) {
  process.stdout.write(leftPad(20, file) + ": ");
  fs.readFile(file, function(err, data) {
    if (err) throw err;
    var f = data.toString("utf-8");
    try {
      var g = dot.toGraph(f);
      acyclic().run(g);
      rank(g);
      layout()._normalize(g);
      var preLayering = order()._initOrder(g);
      var pre = order().crossCount(g, preLayering);
      if (pre !== 0) {
        var start = new Date().getTime();
        var postLayering = order().run(g);
        var end = new Date().getTime();
        var post = order().crossCount(g, postLayering);
        var eff = (pre - post) / pre;
        console.log("SUCCESS  -" +
                    "  PRE: " + leftPad(8, pre) +
                    "  POST: " + leftPad(8, post) +
                    "  Efficiency: " + leftPad(8, eff.toString().substring(0, 8)) +
                    "  Time: " + leftPad(5, (end - start)) + "ms");
        samples.push(eff);
        times.push(end - start);
      } else {
        console.log("SKIPPING - 0 CROSSINGS");
        ++skipped;
      }
    } catch (e) {
      console.log("FAILED   - " + e.toString().split("\n")[0]);
      ++failed;
    }
    handleNext();
  });
}

function finish() {
  console.log();
  console.log("Results");
  console.log("-------");
  console.log("# Graphs: " + leftPad(8, samples.length + skipped + failed));
  console.log("Skipped : " + leftPad(8, skipped));
  console.log("Failed  : " + leftPad(8, failed));
  console.log("Reduction efficiency (larger is better): " + (util.sum(samples) / samples.length));
  console.log("Execution time: " + util.sum(times) + "ms (avg: " + Math.round(util.sum(times) / times.length) + "ms)");
}

function leftPad(len, str) {
  var result = [];
  for (i = 0; i < len; ++i) {
    result.push(" ");
  }
  result.push(str);
  return result.join("").slice(-len);
}
<|endoftext|>


<commit_before>/*
imgLiquid v0.9.944 / 03-05-2013
jQuery plugin to resize images to fit in a container.
Copyright (c) 2012 Alejandro Emparan (karacas) @krc_ale
Dual licensed under the MIT and GPL licenses
https://github.com/karacas/imgLiquid

ex:
	$('.imgLiquid').imgLiquid({fill:true});

	// OPTIONS:

	> js:
			fill: true,
			verticalAlign:		// 'center' //	'top'	//	'bottom' // '50%'  // '10%'
			horizontalAlign:	// 'center' //	'left'	//	'right'  // '50%'  // '10%'

	> CallBacks:
			onStart:		function(){},
			onFinish:		function(){},
			onItemStart:	function(index, container, img){},
			onItemFinish:	function(index, container, img){}

	> hml5 data attr (overwrite all)
			data-imgLiquid-fill='true'
			data-imgLiquid-horizontalAlign='center'
			data-imgLiquid-verticalAlign='center'
*/
//

var imgLiquid = imgLiquid || {VER: '0.9.944'};
imgLiquid.bgs_Available = false;
imgLiquid.bgs_CheckRunned = false;
imgLiquid.injectCss = '.imgLiquid img {visibility:hidden}';

(function ($) {

	// ___________________________________________________________________

	function checkBgsIsavailable() {
		if (imgLiquid.bgs_CheckRunned) return;
		else imgLiquid.bgs_CheckRunned = true;

		var spanBgs = $('');
		$('body').append(spanBgs);

		!function () {
			var bgs_Check = spanBgs[0];
			if (!bgs_Check || !window.getComputedStyle) return;
			var compStyle = window.getComputedStyle(bgs_Check, null);
			if (!compStyle || !compStyle.backgroundSize) return;
			imgLiquid.bgs_Available = (compStyle.backgroundSize === 'cover');
		}();

		spanBgs.remove();
	}

	// ___________________________________________________________________

	$.fn.extend({
		imgLiquid: function (options) {

			this.defaults = {
				fill: true,
				verticalAlign: 'center',			//	'top'	//	'bottom' // '50%'  // '10%'
				horizontalAlign: 'center',			//	'left'	//	'right'  // '50%'  // '10%'
				useBackgroundSize: true,
				useDataHtmlAttr: true,

				responsive: true,					/* Only for use with BackgroundSize false (or old browsers) */
				delay: 0,							/* Only for use with BackgroundSize false (or old browsers) */
				fadeInTime: 0,						/* Only for use with BackgroundSize false (or old browsers) */
				removeBoxBackground: true,			/* Only for use with BackgroundSize false (or old browsers) */
				hardPixels: true,					/* Only for use with BackgroundSize false (or old browsers) */
				responsiveCheckTime: 500,			/* Only for use with BackgroundSize false (or old browsers) */ /* time to check div resize */
				timecheckvisibility: 500,			/* Only for use with BackgroundSize false (or old browsers) */ /* time to recheck if visible/loaded */

				// CALLBACKS
				onStart: null,						// no-params
				onFinish: null,						// no-params
				onItemStart: null,					// params: (index, container, img )
				onItemFinish: null,					// params: (index, container, img )
				onItemError: null					// params: (index, container, img )
			};

			checkBgsIsavailable();
			var imgLiquidRoot = this;

			// Extend global settings
			this.options = options;
			this.settings = $.extend({}, this.defaults, this.options);

			// CallBack
			if (this.settings.onStart) this.settings.onStart();

			// ___________________________________________________________________

			return this.each(function ($i) {

				// MAIN >> each for image

				var settings = imgLiquidRoot.settings,
				$imgBoxCont = $(this),
				$img = $('img:first',$imgBoxCont);
				if (!$img.length) {onError(); return;}

				// Extend settings
				if (!$img.data('imgLiquid_settings')) {
					// First time
					settings = $.extend({}, imgLiquidRoot.settings, getSettingsOverwrite());
				} else {
					// Recall
					// Remove Classes
					$imgBoxCont.removeClass('imgLiquid_error').removeClass('imgLiquid_ready');
					settings = $.extend({}, $img.data('imgLiquid_settings'), imgLiquidRoot.options);
				}
				$img.data('imgLiquid_settings', settings);

				// Start CallBack
				if (settings.onItemStart) settings.onItemStart($i, $imgBoxCont, $img); /* << CallBack */

				// Process
				if (imgLiquid.bgs_Available && settings.useBackgroundSize)
					processBgSize();
				else
					processOldMethod();

				// END MAIN <<

				// ___________________________________________________________________

				function processBgSize() {

					// Check change img src
					if ($imgBoxCont.css('background-image').indexOf(encodeURI($img.attr('src'))) === -1) {
						// Change
						$imgBoxCont.css({'background-image': 'url("' + encodeURI($img.attr('src')) + '")'});
					}

					$imgBoxCont.css({
						'background-size':		(settings.fill) ? 'cover' : 'contain',
						'background-position':	(settings.horizontalAlign + ' ' + settings.verticalAlign).toLowerCase(),
						'background-repeat':	'no-repeat'
					});

					$('a:first', $imgBoxCont).css({
						'display':	'block',
						'width':	'100%',
						'height':	'100%'
					});

					$('img', $imgBoxCont).css({'display': 'none'});

					if (settings.onItemFinish) settings.onItemFinish($i, $imgBoxCont, $img); /* << CallBack */

					$imgBoxCont.addClass('imgLiquid_bgSize');
					$imgBoxCont.addClass('imgLiquid_ready');
					checkFinish();
				}

				// ___________________________________________________________________

				function processOldMethod() {

					// Check change img src
					if ($img.data('oldSrc') && $img.data('oldSrc') !== $img.attr('src')) {

						/* Clone & Reset img */
						var $imgCopy = $img.clone().removeAttr('style');
						$imgCopy.data('imgLiquid_settings', $img.data('imgLiquid_settings'));
						$img.parent().prepend($imgCopy);
						$img.remove();
						$img = $imgCopy;
						$img[0].width = 0;

						// Bug ie with > if (!$img[0].complete && $img[0].width) onError();
						setTimeout(processOldMethod, 10);
						return;
					}

					// Reproceess?
					if ($img.data('imgLiquid_oldProcessed')) {
						makeOldProcess(); return;
					}

					// Set data
					$img.data('imgLiquid_oldProcessed', false);
					$img.data('oldSrc', $img.attr('src'));

					// Hide others images
					$('img:not(:first)', $imgBoxCont).css('display', 'none');

					// CSSs
					$imgBoxCont.css({'overflow': 'hidden'});
					$img.fadeTo(0, 0).removeAttr('width').removeAttr('height').css({
						'visibility': 'visible',
						'max-width': 'none',
						'max-height': 'none',
						'width': 'auto',
						'height': 'auto',
						'display': 'block'
					});

					// CheckErrors
					$img.on('error', onError);
					$img[0].onerror = onError;

					// loop until load
					function onLoad() {
						if ($img.data('imgLiquid_error') || $img.data('imgLiquid_loaded') || $img.data('imgLiquid_oldProcessed')) return;
						if ($imgBoxCont.is(':visible') && $img[0].complete && $img[0].width > 0 && $img[0].height > 0) {
							$img.data('imgLiquid_loaded', true);
							setTimeout(makeOldProcess, $i * settings.delay);
						} else {
							setTimeout(onLoad, settings.timecheckvisibility);
						}
					}

					onLoad();
					checkResponsive();
				}

				// ___________________________________________________________________

				function checkResponsive() {

					/* Only for oldProcessed method (background-size dont need) */

					if (!settings.responsive && !$img.data('imgLiquid_oldProcessed')) return;
					if (!$img.data('imgLiquid_settings')) return;

					settings = $img.data('imgLiquid_settings');

					$imgBoxCont.actualSize = $imgBoxCont.get(0).offsetWidth + ($imgBoxCont.get(0).offsetHeight / 10000);
					if ($imgBoxCont.sizeOld && $imgBoxCont.actualSize !== $imgBoxCont.sizeOld) makeOldProcess();

					$imgBoxCont.sizeOld = $imgBoxCont.actualSize;
					setTimeout(checkResponsive, settings.responsiveCheckTime);
				}

				// ___________________________________________________________________

				function onError() {
					$img.data('imgLiquid_error', true);
					$imgBoxCont.addClass('imgLiquid_error');
					if (settings.onItemError) settings.onItemError($i, $imgBoxCont, $img); /* << CallBack */
					checkFinish();
				}

				// ___________________________________________________________________

				function getSettingsOverwrite() {
					var SettingsOverwrite = {};

					if (imgLiquidRoot.settings.useDataHtmlAttr) {
						var dif = $imgBoxCont.attr('data-imgLiquid-fill'),
						ha =  $imgBoxCont.attr('data-imgLiquid-horizontalAlign'),
						va =  $imgBoxCont.attr('data-imgLiquid-verticalAlign');

						if (dif === 'true' || dif === 'false') SettingsOverwrite.fill = Boolean (dif === 'true');
						if (ha !== undefined && (ha === 'left' || ha === 'center' || ha === 'right' || ha.indexOf('%') !== -1)) SettingsOverwrite.horizontalAlign = ha;
						if (va !== undefined && (va === 'top' ||  va === 'bottom' || va === 'center' || va.indexOf('%') !== -1)) SettingsOverwrite.verticalAlign = va;
					}

					if (imgLiquid.isIE && imgLiquidRoot.settings.ieFadeInDisabled) SettingsOverwrite.fadeInTime = 0; //ie no anims
					return SettingsOverwrite;
				}

				// ___________________________________________________________________

				function makeOldProcess() { /* Only for old browsers, or useBackgroundSize seted false */

					// Calculate size
					var w, h, wn, hn, ha, va, hdif, vdif,
					margT = 0,
					margL = 0,
					$imgCW = $imgBoxCont.width(),
					$imgCH = $imgBoxCont.height();

					// Save original sizes
					if ($img.data('owidth')	=== undefined) $img.data('owidth',	$img[0].width);
					if ($img.data('oheight') === undefined) $img.data('oheight', $img[0].height);

					// Compare ratio
					if (settings.fill === ($imgCW / $imgCH) >= ($img.data('owidth') / $img.data('oheight'))) {
						w = '100%';
						h = 'auto';
						wn = Math.floor($imgCW);
						hn = Math.floor($imgCW * ($img.data('oheight') / $img.data('owidth')));
					} else {
						w = 'auto';
						h = '100%';
						wn = Math.floor($imgCH * ($img.data('owidth') / $img.data('oheight')));
						hn = Math.floor($imgCH);
					}

					// Align X
					ha = settings.horizontalAlign.toLowerCase();
					hdif = $imgCW - wn;
					if (ha === 'left') margL = 0;
					if (ha === 'center') margL = hdif * 0.5;
					if (ha === 'right') margL = hdif;
					if (ha.indexOf('%') !== -1){
						ha = parseInt (ha.replace('%',''), 10);
						if (ha > 0) margL = hdif * ha * 0.01;
					}

					// Align Y
					va = settings.verticalAlign.toLowerCase();
					vdif = $imgCH - hn;
					if (va === 'left') margT = 0;
					if (va === 'center') margT = vdif * 0.5;
					if (va === 'bottom') margT = vdif;
					if (va.indexOf('%') !== -1){
						va = parseInt (va.replace('%',''), 10);
						if (va > 0) margT = vdif * va * 0.01;
					}

					// Add Css
					if (settings.hardPixels) {w = wn; h = hn;}
					$img.css({
						'width': w,
						'height': h,
						'margin-left': Math.floor(margL),
						'margin-top': Math.floor(margT)
					});

					// FadeIn > Only first time
					if (!$img.data('imgLiquid_oldProcessed')) {
						$img.fadeTo(settings.fadeInTime, 1);
						$img.data('imgLiquid_oldProcessed', true);
						if (settings.removeBoxBackground) $imgBoxCont.css('background-image', 'none');
						$imgBoxCont.addClass('imgLiquid_nobgSize');
						$imgBoxCont.addClass('imgLiquid_ready');
					}

					if (settings.onItemFinish) settings.onItemFinish($i, $imgBoxCont, $img); /* << CallBack */
					checkFinish();
				}

				// ___________________________________________________________________

				function checkFinish() { /* Check callBack */
					if ($i === imgLiquidRoot.length - 1) if (imgLiquidRoot.settings.onFinish) imgLiquidRoot.settings.onFinish();
				}

			});
		}
	});
})(jQuery);

// Inject css styles ______________________________________________________
!function () {
	var css = imgLiquid.injectCss,
	head = document.getElementsByTagName('head')[0],
	style = document.createElement('style');
	style.type = 'text/css';
	if (style.styleSheet) {
		style.styleSheet.cssText = css;
	} else {
		style.appendChild(document.createTextNode(css));
	}
	head.appendChild(style);
}();<commit_msg>save the credit for yuicompressor<commit_after>/*!
imgLiquid v0.9.944 / 03-05-2013
jQuery plugin to resize images to fit in a container.
Copyright (c) 2012 Alejandro Emparan (karacas) @krc_ale
Dual licensed under the MIT and GPL licenses
https://github.com/karacas/imgLiquid
**/
/*
ex:
	$('.imgLiquid').imgLiquid({fill:true});

	// OPTIONS:

	> js:
			fill: true,
			verticalAlign:		// 'center' //	'top'	//	'bottom' // '50%'  // '10%'
			horizontalAlign:	// 'center' //	'left'	//	'right'  // '50%'  // '10%'

	> CallBacks:
			onStart:		function(){},
			onFinish:		function(){},
			onItemStart:	function(index, container, img){},
			onItemFinish:	function(index, container, img){}

	> hml5 data attr (overwrite all)
			data-imgLiquid-fill='true'
			data-imgLiquid-horizontalAlign='center'
			data-imgLiquid-verticalAlign='center'
*/
//

var imgLiquid = imgLiquid || {VER: '0.9.944'};
imgLiquid.bgs_Available = false;
imgLiquid.bgs_CheckRunned = false;
imgLiquid.injectCss = '.imgLiquid img {visibility:hidden}';

(function ($) {

	// ___________________________________________________________________

	function checkBgsIsavailable() {
		if (imgLiquid.bgs_CheckRunned) return;
		else imgLiquid.bgs_CheckRunned = true;

		var spanBgs = $('');
		$('body').append(spanBgs);

		!function () {
			var bgs_Check = spanBgs[0];
			if (!bgs_Check || !window.getComputedStyle) return;
			var compStyle = window.getComputedStyle(bgs_Check, null);
			if (!compStyle || !compStyle.backgroundSize) return;
			imgLiquid.bgs_Available = (compStyle.backgroundSize === 'cover');
		}();

		spanBgs.remove();
	}

	// ___________________________________________________________________

	$.fn.extend({
		imgLiquid: function (options) {

			this.defaults = {
				fill: true,
				verticalAlign: 'center',			//	'top'	//	'bottom' // '50%'  // '10%'
				horizontalAlign: 'center',			//	'left'	//	'right'  // '50%'  // '10%'
				useBackgroundSize: true,
				useDataHtmlAttr: true,

				responsive: true,					/* Only for use with BackgroundSize false (or old browsers) */
				delay: 0,							/* Only for use with BackgroundSize false (or old browsers) */
				fadeInTime: 0,						/* Only for use with BackgroundSize false (or old browsers) */
				removeBoxBackground: true,			/* Only for use with BackgroundSize false (or old browsers) */
				hardPixels: true,					/* Only for use with BackgroundSize false (or old browsers) */
				responsiveCheckTime: 500,			/* Only for use with BackgroundSize false (or old browsers) */ /* time to check div resize */
				timecheckvisibility: 500,			/* Only for use with BackgroundSize false (or old browsers) */ /* time to recheck if visible/loaded */

				// CALLBACKS
				onStart: null,						// no-params
				onFinish: null,						// no-params
				onItemStart: null,					// params: (index, container, img )
				onItemFinish: null,					// params: (index, container, img )
				onItemError: null					// params: (index, container, img )
			};

			checkBgsIsavailable();
			var imgLiquidRoot = this;

			// Extend global settings
			this.options = options;
			this.settings = $.extend({}, this.defaults, this.options);

			// CallBack
			if (this.settings.onStart) this.settings.onStart();

			// ___________________________________________________________________

			return this.each(function ($i) {

				// MAIN >> each for image

				var settings = imgLiquidRoot.settings,
				$imgBoxCont = $(this),
				$img = $('img:first',$imgBoxCont);
				if (!$img.length) {onError(); return;}

				// Extend settings
				if (!$img.data('imgLiquid_settings')) {
					// First time
					settings = $.extend({}, imgLiquidRoot.settings, getSettingsOverwrite());
				} else {
					// Recall
					// Remove Classes
					$imgBoxCont.removeClass('imgLiquid_error').removeClass('imgLiquid_ready');
					settings = $.extend({}, $img.data('imgLiquid_settings'), imgLiquidRoot.options);
				}
				$img.data('imgLiquid_settings', settings);

				// Start CallBack
				if (settings.onItemStart) settings.onItemStart($i, $imgBoxCont, $img); /* << CallBack */

				// Process
				if (imgLiquid.bgs_Available && settings.useBackgroundSize)
					processBgSize();
				else
					processOldMethod();

				// END MAIN <<

				// ___________________________________________________________________

				function processBgSize() {

					// Check change img src
					if ($imgBoxCont.css('background-image').indexOf(encodeURI($img.attr('src'))) === -1) {
						// Change
						$imgBoxCont.css({'background-image': 'url("' + encodeURI($img.attr('src')) + '")'});
					}

					$imgBoxCont.css({
						'background-size':		(settings.fill) ? 'cover' : 'contain',
						'background-position':	(settings.horizontalAlign + ' ' + settings.verticalAlign).toLowerCase(),
						'background-repeat':	'no-repeat'
					});

					$('a:first', $imgBoxCont).css({
						'display':	'block',
						'width':	'100%',
						'height':	'100%'
					});

					$('img', $imgBoxCont).css({'display': 'none'});

					if (settings.onItemFinish) settings.onItemFinish($i, $imgBoxCont, $img); /* << CallBack */

					$imgBoxCont.addClass('imgLiquid_bgSize');
					$imgBoxCont.addClass('imgLiquid_ready');
					checkFinish();
				}

				// ___________________________________________________________________

				function processOldMethod() {

					// Check change img src
					if ($img.data('oldSrc') && $img.data('oldSrc') !== $img.attr('src')) {

						/* Clone & Reset img */
						var $imgCopy = $img.clone().removeAttr('style');
						$imgCopy.data('imgLiquid_settings', $img.data('imgLiquid_settings'));
						$img.parent().prepend($imgCopy);
						$img.remove();
						$img = $imgCopy;
						$img[0].width = 0;

						// Bug ie with > if (!$img[0].complete && $img[0].width) onError();
						setTimeout(processOldMethod, 10);
						return;
					}

					// Reproceess?
					if ($img.data('imgLiquid_oldProcessed')) {
						makeOldProcess(); return;
					}

					// Set data
					$img.data('imgLiquid_oldProcessed', false);
					$img.data('oldSrc', $img.attr('src'));

					// Hide others images
					$('img:not(:first)', $imgBoxCont).css('display', 'none');

					// CSSs
					$imgBoxCont.css({'overflow': 'hidden'});
					$img.fadeTo(0, 0).removeAttr('width').removeAttr('height').css({
						'visibility': 'visible',
						'max-width': 'none',
						'max-height': 'none',
						'width': 'auto',
						'height': 'auto',
						'display': 'block'
					});

					// CheckErrors
					$img.on('error', onError);
					$img[0].onerror = onError;

					// loop until load
					function onLoad() {
						if ($img.data('imgLiquid_error') || $img.data('imgLiquid_loaded') || $img.data('imgLiquid_oldProcessed')) return;
						if ($imgBoxCont.is(':visible') && $img[0].complete && $img[0].width > 0 && $img[0].height > 0) {
							$img.data('imgLiquid_loaded', true);
							setTimeout(makeOldProcess, $i * settings.delay);
						} else {
							setTimeout(onLoad, settings.timecheckvisibility);
						}
					}

					onLoad();
					checkResponsive();
				}

				// ___________________________________________________________________

				function checkResponsive() {

					/* Only for oldProcessed method (background-size dont need) */

					if (!settings.responsive && !$img.data('imgLiquid_oldProcessed')) return;
					if (!$img.data('imgLiquid_settings')) return;

					settings = $img.data('imgLiquid_settings');

					$imgBoxCont.actualSize = $imgBoxCont.get(0).offsetWidth + ($imgBoxCont.get(0).offsetHeight / 10000);
					if ($imgBoxCont.sizeOld && $imgBoxCont.actualSize !== $imgBoxCont.sizeOld) makeOldProcess();

					$imgBoxCont.sizeOld = $imgBoxCont.actualSize;
					setTimeout(checkResponsive, settings.responsiveCheckTime);
				}

				// ___________________________________________________________________

				function onError() {
					$img.data('imgLiquid_error', true);
					$imgBoxCont.addClass('imgLiquid_error');
					if (settings.onItemError) settings.onItemError($i, $imgBoxCont, $img); /* << CallBack */
					checkFinish();
				}

				// ___________________________________________________________________

				function getSettingsOverwrite() {
					var SettingsOverwrite = {};

					if (imgLiquidRoot.settings.useDataHtmlAttr) {
						var dif = $imgBoxCont.attr('data-imgLiquid-fill'),
						ha =  $imgBoxCont.attr('data-imgLiquid-horizontalAlign'),
						va =  $imgBoxCont.attr('data-imgLiquid-verticalAlign');

						if (dif === 'true' || dif === 'false') SettingsOverwrite.fill = Boolean (dif === 'true');
						if (ha !== undefined && (ha === 'left' || ha === 'center' || ha === 'right' || ha.indexOf('%') !== -1)) SettingsOverwrite.horizontalAlign = ha;
						if (va !== undefined && (va === 'top' ||  va === 'bottom' || va === 'center' || va.indexOf('%') !== -1)) SettingsOverwrite.verticalAlign = va;
					}

					if (imgLiquid.isIE && imgLiquidRoot.settings.ieFadeInDisabled) SettingsOverwrite.fadeInTime = 0; //ie no anims
					return SettingsOverwrite;
				}

				// ___________________________________________________________________

				function makeOldProcess() { /* Only for old browsers, or useBackgroundSize seted false */

					// Calculate size
					var w, h, wn, hn, ha, va, hdif, vdif,
					margT = 0,
					margL = 0,
					$imgCW = $imgBoxCont.width(),
					$imgCH = $imgBoxCont.height();

					// Save original sizes
					if ($img.data('owidth')	=== undefined) $img.data('owidth',	$img[0].width);
					if ($img.data('oheight') === undefined) $img.data('oheight', $img[0].height);

					// Compare ratio
					if (settings.fill === ($imgCW / $imgCH) >= ($img.data('owidth') / $img.data('oheight'))) {
						w = '100%';
						h = 'auto';
						wn = Math.floor($imgCW);
						hn = Math.floor($imgCW * ($img.data('oheight') / $img.data('owidth')));
					} else {
						w = 'auto';
						h = '100%';
						wn = Math.floor($imgCH * ($img.data('owidth') / $img.data('oheight')));
						hn = Math.floor($imgCH);
					}

					// Align X
					ha = settings.horizontalAlign.toLowerCase();
					hdif = $imgCW - wn;
					if (ha === 'left') margL = 0;
					if (ha === 'center') margL = hdif * 0.5;
					if (ha === 'right') margL = hdif;
					if (ha.indexOf('%') !== -1){
						ha = parseInt (ha.replace('%',''), 10);
						if (ha > 0) margL = hdif * ha * 0.01;
					}

					// Align Y
					va = settings.verticalAlign.toLowerCase();
					vdif = $imgCH - hn;
					if (va === 'left') margT = 0;
					if (va === 'center') margT = vdif * 0.5;
					if (va === 'bottom') margT = vdif;
					if (va.indexOf('%') !== -1){
						va = parseInt (va.replace('%',''), 10);
						if (va > 0) margT = vdif * va * 0.01;
					}

					// Add Css
					if (settings.hardPixels) {w = wn; h = hn;}
					$img.css({
						'width': w,
						'height': h,
						'margin-left': Math.floor(margL),
						'margin-top': Math.floor(margT)
					});

					// FadeIn > Only first time
					if (!$img.data('imgLiquid_oldProcessed')) {
						$img.fadeTo(settings.fadeInTime, 1);
						$img.data('imgLiquid_oldProcessed', true);
						if (settings.removeBoxBackground) $imgBoxCont.css('background-image', 'none');
						$imgBoxCont.addClass('imgLiquid_nobgSize');
						$imgBoxCont.addClass('imgLiquid_ready');
					}

					if (settings.onItemFinish) settings.onItemFinish($i, $imgBoxCont, $img); /* << CallBack */
					checkFinish();
				}

				// ___________________________________________________________________

				function checkFinish() { /* Check callBack */
					if ($i === imgLiquidRoot.length - 1) if (imgLiquidRoot.settings.onFinish) imgLiquidRoot.settings.onFinish();
				}

			});
		}
	});
})(jQuery);

// Inject css styles ______________________________________________________
!function () {
	var css = imgLiquid.injectCss,
	head = document.getElementsByTagName('head')[0],
	style = document.createElement('style');
	style.type = 'text/css';
	if (style.styleSheet) {
		style.styleSheet.cssText = css;
	} else {
		style.appendChild(document.createTextNode(css));
	}
	head.appendChild(style);
}();
<|endoftext|>


<commit_before>(function( window , document , $ , MOJO , hxManager ) {

    var NULL = null;

    var Helper = hxManager.Helper;
    var VendorPatch = hxManager.VendorPatch;
    var StyleDefinition = hxManager.StyleDefinition;
    var Bezier = hxManager.Bezier;
    var TimingMOJO = hxManager.TimingMOJO;

    var DefineProperty = StyleDefinition.define;
    var DefineBezier = Bezier.define;
    var EnsureArray = Helper.ensureArray;

    // Do some important stuff when hx is loaded

    $.hx = {
        defineProperty: DefineProperty,
        defineBezier: DefineBezier,
        subscribe: function( callback ) {

            var startTime = NULL;

            TimingMOJO.subscribe( timingCallback );

            function timingCallback( e , timestamp ) {
                startTime = (startTime === NULL ? timestamp : startTime);
                callback(( timestamp - startTime ));
            }

            return function() {
                TimingMOJO.unsubscribe( timingCallback );
            };
        },
        error: function( error ) {
            $(document).trigger( 'hx.error' , error );
            try { console.error( error.stack ); }
            catch( err ) {}
        }
    };

    // define a bunch of properties
    [
        [
            [ 'matrix' , 'matrix3d' ],
            [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ],
            [ 'a1', 'b1', 'c1', 'd1', 'a2', 'b2', 'c2', 'd2', 'a3', 'b3', 'c3', 'd3', 'a4', 'b4', 'c4', 'd4' ],
            function( name , CSSProperty ) {
                return name + '(' + CSSProperty.join( ',' ) + ')';
            }
        ],
        [
            [ 'translate' , 'translate3d' ],
            [ 0 , 0 , 0 ],
            [ 'x' , 'y' , 'z' ],
            function( name , CSSProperty ) {
                return name + '(' + CSSProperty.join( 'px,' ) + 'px)';
            }
        ],
        [
            [ 'scale' , 'scale3d' ],
            [ 1 , 1 , 1 ],
            [ 'x' , 'y' , 'z' ],
            function( name , CSSProperty ) {
                return name + '(' + CSSProperty.join( ',' ) + ')';
            }
        ],
        [
            [ 'rotate' , 'rotate3d' ],
            [ 0 , 0 , 0 , 0 ],
            [ 'x' , 'y' , 'z' ],
            function( name , CSSProperty ) {
                return name + '(' + CSSProperty.join( ',' ) + 'deg)';
            }
        ],
        [
            [ 'rotateX' ],
            0,
            NULL,
            function( name , CSSProperty ) {
                return name + '(' + CSSProperty[0] + 'deg)';
            }
        ],
        [
            [ 'rotateY' ],
            0,
            NULL,
            function( name , CSSProperty ) {
                return name + '(' + CSSProperty[0] + 'deg)';
            }
        ],
        [
            [ 'rotateZ' ],
            0,
            NULL,
            function( name , CSSProperty ) {
                return name + '(' + CSSProperty[0] + 'deg)';
            }
        ],
        [
            [ 'matrix2d' , 'matrix' ],
            [ 1 , 0 , 0 , 1 , 0 , 0 ],
            [ 'a1' , 'b1' , 'c1' , 'd1' , 'a4' , 'b4' ],
            function( name , CSSProperty ) {
                return name + '(' + CSSProperty.join( ',' ) + ')';
            }
        ],
        [
            [ 'translate2d' , 'translate' ],
            [ 0 , 0 ],
            [ 'x' , 'y' ],
            function( name , CSSProperty ) {
                return name + '(' + CSSProperty.join( 'px,' ) + 'px)';
            }
        ],
        [
            [ 'scale2d' , 'scale' ],
            [ 1 , 1 ],
            [ 'x' , 'y' ],
            function( name , CSSProperty ) {
                return name + '(' + CSSProperty.join( ',' ) + ')';
            }
        ],
        [
            [ 'opacity' ],
            1,
            NULL,
            NULL
        ]
    ]
    .forEach(function( definition ) {

        var property = DefineProperty.apply( NULL , definition[0] );

        [ 'defaults' , 'keymap' , 'stringGetter' ]
        .forEach(function( key , i ) {

            var args = definition[i+1];

            if (args !== NULL) {
                property.set( key , args );
            }
        });
    });

    /*
    **  Derived from AliceJS easing definitions
    **  http://blackberry.github.io/Alice/
    */
    var beziers = {
        linear: [ 0.25 , 0.25 , 0.75 , 0.75 ],
        ease: [ 0.25 , 0.1 , 0.25 , 1 ],
        'ease-in': [ 0.42 , 0 , 1 , 1 ],
        'ease-out': [ 0 , 0 , 0.58 , 1 ],
        'ease-in-out': [ 0.42 , 0 , 0.58 , 1 ],
        easeInQuad: [ 0.55 , 0.085 , 0.68 , 0.53 ],
        easeInCubic: [ 0.55 , 0.055 , 0.675 , 0.19 ],
        easeInQuart: [ 0.895 , 0.03 , 0.685 , 0.22 ],
        easeInQuint: [ 0.755 , 0.05 , 0.855 , 0.06 ],
        easeInSine: [ 0.47 , 0 , 0.745 , 0.715 ],
        easeInExpo: [ 0.95 , 0.05 , 0.795 , 0.035 ],
        easeInCirc: [ 0.6 , 0.04 , 0.98 , 0.335 ],
        easeInBack: [ 0.6 , -0.28 , 0.735 , 0.045 ],
        easeOutQuad: [ 0.25 , 0.46 , 0.45 , 0.94 ],
        easeOutCubic: [ 0.215 , 0.61 , 0.355 , 1 ],
        easeOutQuart: [ 0.165 , 0.84 , 0.44 , 1 ],
        easeOutQuint: [ 0.23 , 1 , 0.32 , 1 ],
        easeOutSine: [ 0.39 , 0.575 , 0.565 , 1 ],
        easeOutExpo: [ 0.19 , 1 , 0.22 , 1 ],
        easeOutCirc: [ 0.075 , 0.82 , 0.165 , 1 ],
        easeOutBack: [ 0.175 , 0.885 , 0.32 , 1.275 ],
        easeInOutQuad: [ 0.455 , 0.03 , 0.515 , 0.955 ],
        easeInOutCubic: [ 0.645 , 0.045 , 0.355 , 1 ],
        easeInOutQuart: [ 0.77 , 0 , 0.175 , 1 ],
        easeInOutQuint: [ 0.86 , 0 , 0.07 , 1 ],
        easeInOutSine: [ 0.445 , 0.05 , 0.55 , 0.95 ],
        easeInOutExpo: [ 1 , 0 , 0 , 1 ],
        easeInOutCirc: [ 0.785 , 0.135 , 0.15 , 0.86 ],
        easeInOutBack: [ 0.68 , -0.55 , 0.265 , 1.55 ],
        easeOutBackMod1: [ 0.7 , -1 , 0.5 , 2 ],
        easeMod1: [ 0.25 , 0.2 , 0.25 , 1 ],
        gravityUp: [ 0.05 , 0.6 , 0.3 , 1 ],
        gravityDown: [ 0.65 , 0.01 , 0.78 , 0.5 ]
    };

    MOJO.Each( beziers , function( points , name ) {
        DefineBezier( name , points );
    });

    function hxReady() {
        $(window).off( 'load' , hxReady );
        $(document).trigger( 'hx.ready' );
    }

    if (document.readyState !== 'complete') {
        $(window).on( 'load' , hxReady );
    }
    else {
        hxReady();
    }

}( window , document , jQuery , MOJO , hxManager ));

<commit_msg>fixing issue #7<commit_after>(function( window , document , $ , MOJO , hxManager ) {

    var NULL = null;

    var Helper = hxManager.Helper;
    var VendorPatch = hxManager.VendorPatch;
    var StyleDefinition = hxManager.StyleDefinition;
    var Bezier = hxManager.Bezier;
    var TimingMOJO = hxManager.TimingMOJO;

    var DefineProperty = StyleDefinition.define;
    var DefineBezier = Bezier.define;
    var EnsureArray = Helper.ensureArray;

    // Do some important stuff when hx is loaded

    $.hx = {
        defineProperty: DefineProperty,
        defineBezier: DefineBezier,
        subscribe: function( callback ) {

            var startTime = NULL;

            TimingMOJO.subscribe( timingCallback );

            function timingCallback( e , timestamp ) {
                startTime = (startTime === NULL ? timestamp : startTime);
                callback(( timestamp - startTime ));
            }

            return function() {
                TimingMOJO.unsubscribe( timingCallback );
            };
        },
        error: function( error ) {
            $(document).trigger( 'hx.error' , error );
            try { console.error( error.stack ); }
            catch( err ) {}
        }
    };

    // define a bunch of properties
    [
        [
            [ 'matrix' , 'matrix3d' ],
            [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ],
            [ 'a1', 'b1', 'c1', 'd1', 'a2', 'b2', 'c2', 'd2', 'a3', 'b3', 'c3', 'd3', 'a4', 'b4', 'c4', 'd4' ],
            function( name , CSSProperty ) {
                return name + '(' + CSSProperty.join( ',' ) + ')';
            }
        ],
        [
            [ 'translate' , 'translate3d' ],
            [ 0 , 0 , 0 ],
            [ 'x' , 'y' , 'z' ],
            function( name , CSSProperty ) {
                return name + '(' + CSSProperty.join( 'px,' ) + 'px)';
            }
        ],
        [
            [ 'scale' , 'scale3d' ],
            [ 1 , 1 , 1 ],
            [ 'x' , 'y' , 'z' ],
            function( name , CSSProperty ) {
                return name + '(' + CSSProperty.join( ',' ) + ')';
            }
        ],
        [
            [ 'rotate' , 'rotate3d' ],
            [ 0 , 0 , 0 , 0 ],
            [ 'x' , 'y' , 'z' , 'a' ],
            function( name , CSSProperty ) {
                return name + '(' + CSSProperty.join( ',' ) + 'deg)';
            }
        ],
        [
            [ 'rotateX' ],
            0,
            NULL,
            function( name , CSSProperty ) {
                return name + '(' + CSSProperty[0] + 'deg)';
            }
        ],
        [
            [ 'rotateY' ],
            0,
            NULL,
            function( name , CSSProperty ) {
                return name + '(' + CSSProperty[0] + 'deg)';
            }
        ],
        [
            [ 'rotateZ' ],
            0,
            NULL,
            function( name , CSSProperty ) {
                return name + '(' + CSSProperty[0] + 'deg)';
            }
        ],
        [
            [ 'matrix2d' , 'matrix' ],
            [ 1 , 0 , 0 , 1 , 0 , 0 ],
            [ 'a1' , 'b1' , 'c1' , 'd1' , 'a4' , 'b4' ],
            function( name , CSSProperty ) {
                return name + '(' + CSSProperty.join( ',' ) + ')';
            }
        ],
        [
            [ 'translate2d' , 'translate' ],
            [ 0 , 0 ],
            [ 'x' , 'y' ],
            function( name , CSSProperty ) {
                return name + '(' + CSSProperty.join( 'px,' ) + 'px)';
            }
        ],
        [
            [ 'scale2d' , 'scale' ],
            [ 1 , 1 ],
            [ 'x' , 'y' ],
            function( name , CSSProperty ) {
                return name + '(' + CSSProperty.join( ',' ) + ')';
            }
        ],
        [
            [ 'opacity' ],
            1,
            NULL,
            NULL
        ]
    ]
    .forEach(function( definition ) {

        var property = DefineProperty.apply( NULL , definition[0] );

        [ 'defaults' , 'keymap' , 'stringGetter' ]
        .forEach(function( key , i ) {

            var args = definition[i+1];

            if (args !== NULL) {
                property.set( key , args );
            }
        });
    });

    /*
    **  Derived from AliceJS easing definitions
    **  http://blackberry.github.io/Alice/
    */
    var beziers = {
        linear: [ 0.25 , 0.25 , 0.75 , 0.75 ],
        ease: [ 0.25 , 0.1 , 0.25 , 1 ],
        'ease-in': [ 0.42 , 0 , 1 , 1 ],
        'ease-out': [ 0 , 0 , 0.58 , 1 ],
        'ease-in-out': [ 0.42 , 0 , 0.58 , 1 ],
        easeInQuad: [ 0.55 , 0.085 , 0.68 , 0.53 ],
        easeInCubic: [ 0.55 , 0.055 , 0.675 , 0.19 ],
        easeInQuart: [ 0.895 , 0.03 , 0.685 , 0.22 ],
        easeInQuint: [ 0.755 , 0.05 , 0.855 , 0.06 ],
        easeInSine: [ 0.47 , 0 , 0.745 , 0.715 ],
        easeInExpo: [ 0.95 , 0.05 , 0.795 , 0.035 ],
        easeInCirc: [ 0.6 , 0.04 , 0.98 , 0.335 ],
        easeInBack: [ 0.6 , -0.28 , 0.735 , 0.045 ],
        easeOutQuad: [ 0.25 , 0.46 , 0.45 , 0.94 ],
        easeOutCubic: [ 0.215 , 0.61 , 0.355 , 1 ],
        easeOutQuart: [ 0.165 , 0.84 , 0.44 , 1 ],
        easeOutQuint: [ 0.23 , 1 , 0.32 , 1 ],
        easeOutSine: [ 0.39 , 0.575 , 0.565 , 1 ],
        easeOutExpo: [ 0.19 , 1 , 0.22 , 1 ],
        easeOutCirc: [ 0.075 , 0.82 , 0.165 , 1 ],
        easeOutBack: [ 0.175 , 0.885 , 0.32 , 1.275 ],
        easeInOutQuad: [ 0.455 , 0.03 , 0.515 , 0.955 ],
        easeInOutCubic: [ 0.645 , 0.045 , 0.355 , 1 ],
        easeInOutQuart: [ 0.77 , 0 , 0.175 , 1 ],
        easeInOutQuint: [ 0.86 , 0 , 0.07 , 1 ],
        easeInOutSine: [ 0.445 , 0.05 , 0.55 , 0.95 ],
        easeInOutExpo: [ 1 , 0 , 0 , 1 ],
        easeInOutCirc: [ 0.785 , 0.135 , 0.15 , 0.86 ],
        easeInOutBack: [ 0.68 , -0.55 , 0.265 , 1.55 ],
        easeOutBackMod1: [ 0.7 , -1 , 0.5 , 2 ],
        easeMod1: [ 0.25 , 0.2 , 0.25 , 1 ],
        gravityUp: [ 0.05 , 0.6 , 0.3 , 1 ],
        gravityDown: [ 0.65 , 0.01 , 0.78 , 0.5 ]
    };

    MOJO.Each( beziers , function( points , name ) {
        DefineBezier( name , points );
    });

    function hxReady() {
        $(window).off( 'load' , hxReady );
        $(document).trigger( 'hx.ready' );
    }

    if (document.readyState !== 'complete') {
        $(window).on( 'load' , hxReady );
    }
    else {
        hxReady();
    }

}( window , document , jQuery , MOJO , hxManager ));

<|endoftext|>


<commit_before>var loadImages = function(dataPath, groupName, pictureName){
	var groupName = groupName || 'picture';
		pictureName = pictureName || 'picture';

	function loadImages(imgAmount){
		var imagesCollection = [],
			fileManager = [NSFileManager defaultManager];

		if(tools.majorVersion() == 3){
			var scriptPath = sketch.scriptPath;
			var pluginFolder = scriptPath.match(/Plugins\/([\w -])*/)[0] + "/";
			var sketchPluginsPath = scriptPath.replace(/Plugins([\w \/ -])*.sketchplugin$/, "");
			imagesPath =  sketchPluginsPath + pluginFolder + dataPath;
		}
		log(imagesPath)
		var imagesFileNames = [fileManager contentsOfDirectoryAtPath:imagesPath error:nil],
			imgLen = [imagesFileNames count];

		for(var i = 0; i < imgAmount; i++){
			var r = Math.ceil(Math.random() * imgLen);
			var fileName = imagesPath+imagesFileNames[r];
			if ([fileManager fileExistsAtPath: fileName]) {
				var newImage = [[NSImage alloc] initWithContentsOfFile:fileName];
				imagesCollection.push(newImage);
			}
		}

		return imagesCollection;
	}

	function main(){
		var allLayers = [[doc currentPage] layers],
			imagesCollection = loadImages([selection count]);

		for(var i = 0; i < [selection count]; i++){
			var layer = selection[i];
            if([layer class] == MSShapeGroup){
                var image = imagesCollection[i];
                var fill = layer.style().fills().firstObject();
                fill.setFillType(4);
                log(tools.minorVersion())
                if(tools.minorVersion() >= 1){
                	var coll = layer.style().fills().firstObject().documentData().images();
                	[fill setPatternImage:image collection:coll]
                }
                else{
                	layer.style().fills().firstObject().setPatternImage( image );
                }
                layer.style().fills().firstObject().setPatternFillType(1);
            }
		}

		if([selection count] == 0) alert('Select at least one vector shape');
	}
	main();
}

<commit_msg>fix off-by-one error in loadImage.js<commit_after>var loadImages = function(dataPath, groupName, pictureName){
	var groupName = groupName || 'picture';
		pictureName = pictureName || 'picture';

	function loadImages(imgAmount){
		var imagesCollection = [],
			fileManager = [NSFileManager defaultManager];

		if(tools.majorVersion() == 3){
			var scriptPath = sketch.scriptPath;
			var pluginFolder = scriptPath.match(/Plugins\/([\w -])*/)[0] + "/";
			var sketchPluginsPath = scriptPath.replace(/Plugins([\w \/ -])*.sketchplugin$/, "");
			imagesPath =  sketchPluginsPath + pluginFolder + dataPath;
		}
		log(imagesPath)
		var imagesFileNames = [fileManager contentsOfDirectoryAtPath:imagesPath error:nil],
			imgLen = [imagesFileNames count];

		for(var i = 0; i < imgAmount; i++){
			var r = Math.floor(Math.random() * imgLen);
			var fileName = imagesPath+imagesFileNames[r];
			if ([fileManager fileExistsAtPath: fileName]) {
				var newImage = [[NSImage alloc] initWithContentsOfFile:fileName];
				imagesCollection.push(newImage);
			}
		}

		return imagesCollection;
	}

	function main(){
		var allLayers = [[doc currentPage] layers],
			imagesCollection = loadImages([selection count]);

		for(var i = 0; i < [selection count]; i++){
			var layer = selection[i];
            if([layer class] == MSShapeGroup){
                var image = imagesCollection[i];
                var fill = layer.style().fills().firstObject();
                fill.setFillType(4);
                log(tools.minorVersion())
                if(tools.minorVersion() >= 1){
                	var coll = layer.style().fills().firstObject().documentData().images();
                	[fill setPatternImage:image collection:coll]
                }
                else{
                	layer.style().fills().firstObject().setPatternImage( image );
                }
                layer.style().fills().firstObject().setPatternFillType(1);
            }
		}

		if([selection count] == 0) alert('Select at least one vector shape');
	}
	main();
}

<|endoftext|>


<commit_before>var locations = [
  { name: 'Tim Brownawell', origin: 'Fulton, MO', latitude: 38.86517, longitude: -91.98643, slack_handle: "tbrownaw" },
  { name: 'Wayne Bills', origin: 'Memphis, TN', latitude: 35.26507, longitude: -90.04078, company: 'Mosaik', slack_handle: 'wbills' },
  { name: 'Brad Montgomery', origin: 'Lepanto, AR', latitude: 35.61046, longitude: -90.33114, company: "Preteckt", slack_handle: "bkmontgomery"},
  { name: 'Stephen Bramlett', origin: 'memphis, tn', latitude: 35.2243923520236, longitude: -90.00089585781097, company: 'Semmes Murphey Clinic', slack_handle: "sbramlett"  },
  { name: 'Eric Terpstra', origin: 'Kellogg, IA', latitude: 41.776711, longitude:-92.964886, slack_handle: "eterps" },
  { name: 'josh lewis', origin: 'rogersville, mo', latitude: 37.110618, longitude: -93.053759 },
  { name: 'Daniel Pritchett', origin: 'Dothan, AL', latitude: 31.2290238, longitude: -85.4766258, slack_handle: "dpritchett" },
  { name: 'Joe Ferguson', origin: 'memphis, tn', latitude: 35.2246054, longitude: -90.0001485, company: "Aol, inc", slack_handle: "joe"},
  { name: 'David Hiltenbrand', origin: 'Pine Bluff, AR', latitude: 34.231984, longitude: -92.135550 },
  { name: 'Ismael Alonso', origin: 'Valladolid, ES-VA', latitude: 41.6519094, longitude: -4.730486 },
  { name: 'Collin Barrett', origin: 'Kalamazoo, MI', latitude: 42.271161, longitude: -85.660178, company: "Shelby Systems", slack_handle: "cbarrett" },
  { name: 'Claudio Donndelinger', origin: 'Tucson, AZ', latitude: 32.2274179, longitude: -110.9604492 },
  { name: 'Jason Myers', origin: 'Sacramento, CA', latitude: 38.601524,longitude: -121.392555,company: 'Shelby Systems', slack_handle: "syliddar"  },
  { name: 'Daniel Soskel', origin: 'Salt Lake City, UT', latitude: 40.7762692, longitude: -112.2006695, slack_handle: "meltheous", company: "International Paper"},
  { name: 'Mike Cochran', origin: 'Memphis, TN', latitude: 35.15497509873826, longitude: -90.01109898090363, slack_handle: 'vongrippen', company: "Telarray" },
  { name: 'Forrest Williams', origin: 'Memphis, TN', latitude: 35.036800, longitude: -89.823446, company: "Mosaik", slack_handle: 'serroft' },
  { name: 'George Spake', origin: 'Memphis, TN', latitude: 35.1182222, longitude: -90.0053115, company: 'UTHSC', slack_handle: 'gpspake' },
  { name: 'Tony Colston', origin: 'Collierville, TN', latitude: 35.075099, longitude: -89.667718, slack_handle: 'tony' },
  { name: 'Ben Robin', origin: 'Bartlesville, OK', latitude: 36.728010, longitude: -95.935164, slack_handle: 'benjaminjrobin' },
  { name: 'David Mohundro', origin: 'Bonham, TX', latitude: 33.5939801, longitude: -96.2210445, company: 'Clear Function', slack_handle: 'drmohundro' },
  { name: 'Matt McCullar', origin: 'Medford, Oregon', latitude: 35.1187, longitude: -89.9381, slack_handle: 'mattm' },
  { name: 'Michael Johnsey', origin: 'Southaven, MS', latitude: 34.9332, longitude: -89.9367, company: 'Mosaik', slack_handle:'mjohnsey' },
  { name: 'Ed Anderson', origin: 'Seattle, WA', latitude: 47.620422, longitude: -122.349358, company: '', slack_handle:'ed' },
  { name: 'Harold Schreckengost', origin: 'Hernando, MS', latitude: 34.8435569, longitude:-89.996908, company: 'ER2', slack_handle: 'hmschreck'},
  { name: 'Keaton Burleson', origin: 'Denton, TX', latitude: 33.240420, longitude: -97.143596, company: 'ER2', slack_handle: '128keaton'},
  { name: 'Cameron Roe', origin: 'Memphis, TN', latitude: 35.1545029, longitude: -89.8414891, company: 'Archer Malmo', slack_handle: 'cameronroe'},
  { name: 'Matthew Bledsoe', origin: 'Memphis, TN', latitude: 35.110297, longitude: -89.914127, company: 'Quire Data', slack_handle: 'mjb'},
  { name: 'Chris House', origin: 'Green Bay, WI', latitude: 44.5228598, longitude: -88.130578, company: 'LDC', slack_handle: 'chris'}
  ];
<commit_msg>Update locations.js<commit_after>var locations = [
  { name: 'Tim Brownawell', origin: 'Fulton, MO', latitude: 38.86517, longitude: -91.98643, slack_handle: "tbrownaw" },
  { name: 'Wayne Bills', origin: 'Memphis, TN', latitude: 35.26507, longitude: -90.04078, company: 'Mosaik', slack_handle: 'wbills' },
  { name: 'Brad Montgomery', origin: 'Lepanto, AR', latitude: 35.61046, longitude: -90.33114, company: "Preteckt", slack_handle: "bkmontgomery"},
  { name: 'Stephen Bramlett', origin: 'memphis, tn', latitude: 35.2243923520236, longitude: -90.00089585781097, company: 'Semmes Murphey Clinic', slack_handle: "sbramlett"  },
  { name: 'Eric Terpstra', origin: 'Kellogg, IA', latitude: 41.776711, longitude:-92.964886, slack_handle: "eterps" },
  { name: 'josh lewis', origin: 'rogersville, mo', latitude: 37.110618, longitude: -93.053759 },
  { name: 'Daniel Pritchett', origin: 'Dothan, AL', latitude: 31.2290238, longitude: -85.4766258, slack_handle: "dpritchett" },
  { name: 'Joe Ferguson', origin: 'memphis, tn', latitude: 35.2246054, longitude: -90.0001485, company: "Aol, inc", slack_handle: "joe"},
  { name: 'David Hiltenbrand', origin: 'Pine Bluff, AR', latitude: 34.231984, longitude: -92.135550 },
  { name: 'Ismael Alonso', origin: 'Valladolid, ES-VA', latitude: 41.6519094, longitude: -4.730486 },
  { name: 'Collin Barrett', origin: 'Kalamazoo, MI', latitude: 42.271161, longitude: -85.660178, company: "Shelby Systems", slack_handle: "cbarrett" },
  { name: 'Claudio Donndelinger', origin: 'Tucson, AZ', latitude: 32.2274179, longitude: -110.9604492 },
  { name: 'Jason Myers', origin: 'Sacramento, CA', latitude: 38.601524,longitude: -121.392555,company: 'Shelby Systems', slack_handle: "syliddar"  },
  { name: 'Daniel Soskel', origin: 'Salt Lake City, UT', latitude: 40.7762692, longitude: -112.2006695, slack_handle: "meltheous", company: "International Paper"},
  { name: 'Mike Cochran', origin: 'Memphis, TN', latitude: 35.15497509873826, longitude: -90.01109898090363, slack_handle: 'vongrippen', company: "Telarray" },
  { name: 'Forrest Williams', origin: 'Memphis, TN', latitude: 35.036800, longitude: -89.823446, company: "Mosaik", slack_handle: 'serroft' },
  { name: 'George Spake', origin: 'Memphis, TN', latitude: 35.1182222, longitude: -90.0053115, company: 'UTHSC', slack_handle: 'gpspake' },
  { name: 'Tony Colston', origin: 'Collierville, TN', latitude: 35.075099, longitude: -89.667718, slack_handle: 'tony' },
  { name: 'Ben Robin', origin: 'Bartlesville, OK', latitude: 36.728010, longitude: -95.935164, slack_handle: 'benjaminjrobin' },
  { name: 'David Mohundro', origin: 'Bonham, TX', latitude: 33.5939801, longitude: -96.2210445, company: 'Clear Function', slack_handle: 'drmohundro' },
  { name: 'Matt McCullar', origin: 'Medford, Oregon', latitude: 35.1187, longitude: -89.9381, slack_handle: 'mattm' },
  { name: 'Michael Johnsey', origin: 'Southaven, MS', latitude: 34.9332, longitude: -89.9367, company: 'Mosaik', slack_handle:'mjohnsey' },
  { name: 'Ed Anderson', origin: 'Seattle, WA', latitude: 47.620422, longitude: -122.349358, company: '', slack_handle:'ed' },
  { name: 'Harold Schreckengost', origin: 'Hernando, MS', latitude: 34.8435569, longitude:-89.996908, company: 'ER2', slack_handle: 'hmschreck'},
  { name: 'Keaton Burleson', origin: 'Denton, TX', latitude: 33.240420, longitude: -97.143596, company: 'ER2', slack_handle: '128keaton'},
  { name: 'Cameron Roe', origin: 'Memphis, TN', latitude: 35.1545029, longitude: -89.8414891, company: 'CrossBrowserTesting', slack_handle: 'cameronroe'},
  { name: 'Matthew Bledsoe', origin: 'Memphis, TN', latitude: 35.110297, longitude: -89.914127, company: 'Quire Data', slack_handle: 'mjb'},
  { name: 'Chris House', origin: 'Green Bay, WI', latitude: 44.5228598, longitude: -88.130578, company: 'LDC', slack_handle: 'chris'}
  ];
<|endoftext|>


<commit_before>var loc = [];
function generateMap(latlong) {
	loc = latlong.split(":");
		if(markers.length > 0) {
			jQuery(function($) {
			    // Asynchronously Load the map API
			    var script = document.createElement('script');
			    script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
			    document.body.appendChild(script);
			});
		}
	}

	// function to calculate distance between two points
	function getDistance(lat1, lon1, lat2, lon2){
	    var R = 6371; // km
		var dLat = (lat2-lat1) * (Math.PI / 180);
		var dLon = (lon2-lon1) * (Math.PI / 180);
		var lat1 = lat1 * (Math.PI / 180);
		var lat2 = lat2 * (Math.PI / 180);

		var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
		        Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
		var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
		var d = (R * c*0.62137).toFixed(3);
		return d;
	}

	function initialize() {
	    var map;
	    var bounds = new google.maps.LatLngBounds();
	    var mapOptions = {
	        mapTypeId: 'roadmap'
	    };

	    // Display a map on the page
	    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
	    map.setTilt(45);

	    // Info Window Content
	    var infoWindowContent = [];
	    var len = markers.length;

	    //generate info window content by looping through data to display name and address
	    for( i = 0; i < markers.length-1; i++ ) {
		    var tmp = markers[i].split(";");
		    var location = tmp[0];
		    var addr = tmp[3];
	    	var dist = getDistance(loc[0], loc[1],tmp[1],tmp[2]);
		    var ele = '
' + "
" + location + "
" + "
" + addr + "
" + "
" + dist + " miles away
" + "
";
	    	infoWindowContent[i] = ele;
    	}
    	var tmp = markers[len-1].split(";");
	    var dist = getDistance(loc[0], loc[1],tmp[1],tmp[2]);
	    infoWindowContent[i] = '
' + "
" + tmp[0] + "
" + "
" + tmp[3] + "
" + "
" + dist + " miles away
" + "
";

	    // Display multiple markers on a map
	    var infoWindow = new google.maps.InfoWindow(), marker, i;

	    // Loop through our array of markers & place each one on the map
	    for( i = 0; i < markers.length; i++ ) {
		    var tmp = markers[i].split(";");
	        var position = new google.maps.LatLng(tmp[1], tmp[2]);
	        bounds.extend(position);
	        marker = new google.maps.Marker({
	            position: position,
	            map: map,
	            title: tmp[0]
	        });

	        // Allow each marker to have an info window
	        google.maps.event.addListener(marker, 'click', (function(marker, i) {
	            return function() {
	                infoWindow.setContent(infoWindowContent[i]);
	                infoWindow.open(map, marker);
	            }
	        })(marker, i));

	        // Automatically center the map fitting all markers on the screen
	        map.fitBounds(bounds);
	    }

	    // Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
	    var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
	        this.setZoom(15);
	        google.maps.event.removeListener(boundsListener);
	    });

	}
<commit_msg>Update mapScript.js<commit_after>var loc = [];
function generateMap(latlong) {
	loc = latlong.split(":");
		if(markers.length > 0) {
			jQuery(function($) {
			    // Asynchronously Load the map API
			    var script = document.createElement('script');
			    script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
			    document.body.appendChild(script);
			});
		}
	}

	// function to calculate distance between two points
	function getDistance(lat1, lon1, lat2, lon2){
	    var R = 6371; // km
		var dLat = (lat2-lat1) * (Math.PI / 180);
		var dLon = (lon2-lon1) * (Math.PI / 180);
		var lat1 = lat1 * (Math.PI / 180);
		var lat2 = lat2 * (Math.PI / 180);

		var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
		        Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
		var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
		var d = (R * c*0.62137).toFixed(3);
		return d;
	}

	function initialize() {
	    var map;
	    var bounds = new google.maps.LatLngBounds();
	    var mapOptions = {
	        mapTypeId: 'roadmap'
	    };

	    // Display a map on the page
	    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
	    map.setTilt(45);

	    // Info Window Content
	    var infoWindowContent = [];
	    var len = markers.length;

	    //generate info window content by looping through data to display name and address
	    for( i = 0; i < markers.length-1; i++ ) {
		    var tmp = markers[i].split(";");
		    var location = tmp[0];
		    var addr = tmp[3];
		    var items = "";
		    if(tmp.length > 4)
		    	items = tmp[4];
	    	var dist = getDistance(loc[0], loc[1],tmp[1],tmp[2]);
		    var ele = '
' + "
" + location + "
" + "
" + addr + "
" + items + "
" + "
" + dist + " miles away
" + "
";
	    	infoWindowContent[i] = ele;
    		}
    		var tmp = markers[len-1].split(";");
    		var items = "";
		    if(tmp.length > 4)
		    	items = tmp[4];
	    var dist = getDistance(loc[0], loc[1],tmp[1],tmp[2]);
	    infoWindowContent[i] = '
' + "
" + tmp[0] + "
" + "
" + tmp[3] + "
" + items + "

" + dist + " miles away

";

	    // Display multiple markers on a map
	    var infoWindow = new google.maps.InfoWindow(), marker, i;

	    // Loop through our array of markers & place each one on the map
	    for( i = 0; i < markers.length; i++ ) {
		    var tmp = markers[i].split(";");
	        var position = new google.maps.LatLng(tmp[1], tmp[2]);
	        bounds.extend(position);
	        marker = new google.maps.Marker({
	            position: position,
	            map: map,
	            title: tmp[0]
	        });

	        // Allow each marker to have an info window
	        google.maps.event.addListener(marker, 'click', (function(marker, i) {
	            return function() {
	                infoWindow.setContent(infoWindowContent[i]);
	                infoWindow.open(map, marker);
	            }
	        })(marker, i));

	        // Automatically center the map fitting all markers on the screen
	        map.fitBounds(bounds);
	    }

	    // Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
	    var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
	        this.setZoom(15);
	        google.maps.event.removeListener(boundsListener);
	    });

	}
<|endoftext|>


<commit_before>$(document).ready(function() {

	$('.edit_narrative_inline').live('click', function(event){
		//var action = confirm("Are you sure you want to edit this here? This provides limited editing here and provides text only in raw html.");
		//if(action) {
			var myTeach = $("#kTeach").val();
			var myNarrative = this.id.split('_')[1];

			var form_data = {
					kNarrative: myNarrative,
					kTeach: myTeach,
			};
			var myUrl = base_url + "narrative/edit_inline";

			$.ajax({
				url: myUrl,
				type: 'POST',
				data: form_data,
				success: function(data){
						$("#text_" + myNarrative).html(data);
						$("#enil_" + myNarrative).html("Save").addClass("new").removeClass("edit").removeClass("edit_narrative_inline").addClass("save_narrative_inline");

				} //end function
			});//end ajax
			$('html, body').animate({ scrollTop: $("#student-text_" + myNarrative).offset().top}, 1000);

	}); //end edit_narrative_inline

	$('.save_narrative_inline').live('click', function(event){
			tinyMCE.triggerSave();

			var myNarrative = $("#kNarrative").val();
			var myTeach = $("#kTeach").val();
			var myText = $("#narrText_" + myNarrative).val();
			var form_data = {
					kNarrative: myNarrative,
					narrText: myText,
					kTeach: myTeach
			};
			var myUrl = base_url + "narrative/update_inline";
			$.ajax({
				dataType: "json",
				url: myUrl,
				type: 'POST',
				data: form_data,
				success: function(data){

					$("#text_" + myNarrative).html(data['narrText']);
					$("#time_" + myNarrative).html(data['datestamp']);
					$("#enil_" + myNarrative).html("Edit Inline").addClass("edit").removeClass("new").removeClass("save_narrative_inline").addClass("edit_narrative_inline").focus();
				},
				error: function(data){
					console.log(data);
				}// end success-function
			}); //end ajax
			$('html, body').animate({ scrollTop: $("#student-text_" + myNarrative).offset().top}, 1000);

	});//end edit_narrative_inplace

	$('.grade_edit').live("click",function(event){
		var myId = this.id.split("_")[1];
		var myValue = $("#ngtext_" + myId).html();
		$("#ngtext_" + myId).html("<input type='text' id='grade_" + myId + "' value='" + myValue + "'/>");
		$(this).html("Save").removeClass("grade_edit").addClass("grade_save").removeClass("edit").removeClass("new");
	});

	$('.grade_save').live("click",function(event){
		var myId = this.id.split("_")[1];
		var myValue = $("#grade_" + myId).val();
		var myUrl = base_url + "narrative/update_grade";
		form_data = {
				kNarrative: myId,
				narrGrade: myValue
		};
		$(this).html("Edit Grade").addClass("edit").removeClass("grade_save").addClass("grade_edit");
		$.ajax({
			type:"POST",
			url: myUrl,
			data: form_data,
			success: function(data){
				$("#ngtext_" + myId).html(data);//expecting the grade returned.
			}
		});

	});

	$('.override-narrative-grade').live("click",function(event){
		val = $("#course_grade").html();
		$('.override-narrative-grade').hide();
		$("#course_grade").html("<input type='text' name='narrGrade' id='narrGrade' value='" + val + "'/>");
	});

$(".approve_narrative.inline").live("click",function(event){
	event.preventDefault();
	me = $(this);
	if(me.hasClass("edit")){
	my_url = me.href;
	form_data = {
			ajax: 1
	}
	$.ajax({
		type: "post",
		url: my_url,
		data: form_data,
		success: function(data){
			me.removeClass("approve_narrative").removeClass("edit").addClass("inactive").html("Approved");
		}
	});
	}
});

	$('.save_close_narrative').live("click",function(event) {
		event.preventDefault();
		var narrText = $('#narrText').val();
		if (narrText == "") {
			alert("You haven't entered any text in the narrative yet. No need to save.");
		} else {
			$('#save_action').val('view');
			document.forms['narrativeEditor'].submit();
		}
	});// end function(event) end click

	$('.save_continue_narrative').live('click', function(event) {
		event.preventDefault();
		save_continue_narrative();
	}); // end function(event)

	$('.delete_narrative').live('click', function(event) {
		var kNarrative = $("#kNarrative").val();
		var kStudent = $("#kStudent").val();
		if(kNarrative == ""){
			kNarrative = this.id.split("_")[1];
		}
		delete_narrative(kNarrative, kStudent);
	}); // end function(event)

	$('.cancel_narrative').live('click',function(event) {
		var myNarrative = $("#kNarrative").val();
		var narrText = $('#narrText').val();
		var myStudent = $("#kStudent").val();
		action = confirm("You sure you want to cancel? Any changes you have made will not be saved.\r(Some day I'll be able to tell if you have actually made any changes since the last save.)");
		if (action) {
			if (myNarrative != "") {
				document.location = base_url + "narrative/view/" + myNarrative;
			} else {
				document.location = base_url + "narrative/student_list/"
						+ myStudent;
			}
		}
	});

	$('.add_narrative').live('click',

		function(event) {
			if (this.id) {
				$("#kTemplate").val(this.id.split("_")[1]);
			}
			document.forms['template_selector'].submit();

		});// end new_narrative.click

	$('.return_to_narrative').live('click', function(event) {
		var myNarrative = this.id.split('_')[1];
		editNarrative(myNarrative);
	}); // end function(event)

	$(".draggable").draggable(function() {
		$("#narrText").fadeIn();
	});

	$("#narrText").droppable( {
		drop : function(event, ui) {
			var existingValue = $("#narrText").val();
			textValue = ui.draggable.text();
			$(this).val(existingValue + " " + textValue);
			ui.draggable.fadeOut();
		}
	});

	$('#narrYear').live('change', function() {
		var myYear = parseInt($('#narrYear').val());
		var nextYear = myYear + 1;
		$('#yearEnd').val(nextYear);
		});

	}// end function()
	);// end document.ready

function save_continue_narrative(){
	tinyMCE.triggerSave();
	var narrText = $('#narrText').val();
	$("#originalText").val(narrText);
	if (narrText == "") {
		alert("You haven't entered any text in the narrative yet. No need to save.");
	} else {
	var action = $("#action").val();
	$("#ajax").val(1);
	var formData = $("#narrativeEditor").serialize();
	var myUrl = base_url + "narrative/" + action;
	$.ajax({
		dataType: "json",
		url: myUrl,
		type: 'POST',
		data: formData,
		success: function(data){
			if(action == "insert"){
				$("#kNarrative").val(data.kNarrative);
				$("#action").val("update");
				$("#narrativeEditor").attr("action",base_url + "narrative/update");
				$("#editing-buttons .button-list").append("
Delete
");
			}
			$("#message").html("Narrative auto-saved: " + data.timestamp).show();

		},
		error: function(data){
			$("#message").html("An error occurred. Press 'Save and Continue' to save your work.").show();
		}
	});
		$("#ajax").val(0);
		//saveNarrative();
}
}

/*
 * @function deleteNarrative @params kNarrative int database keydescription:
 * delete a narrative from the database (note that the narrative is removed from
 * active use and stored in a backups database. See narrative_edit.php for
 * details. @dependencies NARRATIVE_EDIT_INC
 */
function delete_narrative(myNarrative, myStudent) {
	action = confirm("You sure you want to delete this?");
	if (action) {
		form_data = {
			kNarrative : myNarrative,
			kStudent : myStudent
		};
		myUrl = base_url + "narrative/delete";
		$.ajax({
			url: myUrl,
			type: 'post',
			data: form_data,
			success: function(data) {
			alert(data);
			document.location = base_url + "narrative/student_list/" + myStudent;
		}
		});
	}//end if
}
<commit_msg>Clean up notices for cancelling narrative editing<commit_after>$(document).ready(function() {

	$('.edit_narrative_inline').live('click', function(event){
		//var action = confirm("Are you sure you want to edit this here? This provides limited editing here and provides text only in raw html.");
		//if(action) {
			var myTeach = $("#kTeach").val();
			var myNarrative = this.id.split('_')[1];

			var form_data = {
					kNarrative: myNarrative,
					kTeach: myTeach,
			};
			var myUrl = base_url + "narrative/edit_inline";

			$.ajax({
				url: myUrl,
				type: 'POST',
				data: form_data,
				success: function(data){
						$("#text_" + myNarrative).html(data);
						$("#enil_" + myNarrative).html("Save").addClass("new").removeClass("edit").removeClass("edit_narrative_inline").addClass("save_narrative_inline");

				} //end function
			});//end ajax
			$('html, body').animate({ scrollTop: $("#student-text_" + myNarrative).offset().top}, 1000);

	}); //end edit_narrative_inline

	$('.save_narrative_inline').live('click', function(event){
			tinyMCE.triggerSave();

			var myNarrative = $("#kNarrative").val();
			var myTeach = $("#kTeach").val();
			var myText = $("#narrText_" + myNarrative).val();
			var form_data = {
					kNarrative: myNarrative,
					narrText: myText,
					kTeach: myTeach
			};
			var myUrl = base_url + "narrative/update_inline";
			$.ajax({
				dataType: "json",
				url: myUrl,
				type: 'POST',
				data: form_data,
				success: function(data){

					$("#text_" + myNarrative).html(data['narrText']);
					$("#time_" + myNarrative).html(data['datestamp']);
					$("#enil_" + myNarrative).html("Edit Inline").addClass("edit").removeClass("new").removeClass("save_narrative_inline").addClass("edit_narrative_inline").focus();
				},
				error: function(data){
					console.log(data);
				}// end success-function
			}); //end ajax
			$('html, body').animate({ scrollTop: $("#student-text_" + myNarrative).offset().top}, 1000);

	});//end edit_narrative_inplace

	$('.grade_edit').live("click",function(event){
		var myId = this.id.split("_")[1];
		var myValue = $("#ngtext_" + myId).html();
		$("#ngtext_" + myId).html("<input type='text' id='grade_" + myId + "' value='" + myValue + "'/>");
		$(this).html("Save").removeClass("grade_edit").addClass("grade_save").removeClass("edit").removeClass("new");
	});

	$('.grade_save').live("click",function(event){
		var myId = this.id.split("_")[1];
		var myValue = $("#grade_" + myId).val();
		var myUrl = base_url + "narrative/update_grade";
		form_data = {
				kNarrative: myId,
				narrGrade: myValue
		};
		$(this).html("Edit Grade").addClass("edit").removeClass("grade_save").addClass("grade_edit");
		$.ajax({
			type:"POST",
			url: myUrl,
			data: form_data,
			success: function(data){
				$("#ngtext_" + myId).html(data);//expecting the grade returned.
			}
		});

	});

	$('.override-narrative-grade').live("click",function(event){
		val = $("#course_grade").html();
		$('.override-narrative-grade').hide();
		$("#course_grade").html("<input type='text' name='narrGrade' id='narrGrade' value='" + val + "'/>");
	});

$(".approve_narrative.inline").live("click",function(event){
	event.preventDefault();
	me = $(this);
	if(me.hasClass("edit")){
	my_url = me.href;
	form_data = {
			ajax: 1
	}
	$.ajax({
		type: "post",
		url: my_url,
		data: form_data,
		success: function(data){
			me.removeClass("approve_narrative").removeClass("edit").addClass("inactive").html("Approved");
		}
	});
	}
});

	$('.save_close_narrative').live("click",function(event) {
		event.preventDefault();
		var narrText = $('#narrText').val();
		if (narrText == "") {
			alert("You haven't entered any text in the narrative yet. No need to save.");
		} else {
			$('#save_action').val('view');
			document.forms['narrativeEditor'].submit();
		}
	});// end function(event) end click

	$('.save_continue_narrative').live('click', function(event) {
		event.preventDefault();
		save_continue_narrative();
	}); // end function(event)

	$('.delete_narrative').live('click', function(event) {
		var kNarrative = $("#kNarrative").val();
		var kStudent = $("#kStudent").val();
		if(kNarrative == ""){
			kNarrative = this.id.split("_")[1];
		}
		delete_narrative(kNarrative, kStudent);
	}); // end function(event)

	$('.cancel_narrative').live('click',function(event) {
		var myNarrative = $("#kNarrative").val();
		var narrText = $('#narrText').val();
		var myStudent = $("#kStudent").val();
		action = confirm("You sure you want to cancel? Any changes you have made will not be saved.");
		if (action) {
			if (myNarrative != "") {
				document.location = base_url + "narrative/view/" + myNarrative;
			} else {
				document.location = base_url + "narrative/student_list/"
						+ myStudent;
			}
		}
	});

	$('.add_narrative').live('click',

		function(event) {
			if (this.id) {
				$("#kTemplate").val(this.id.split("_")[1]);
			}
			document.forms['template_selector'].submit();

		});// end new_narrative.click

	$('.return_to_narrative').live('click', function(event) {
		var myNarrative = this.id.split('_')[1];
		editNarrative(myNarrative);
	}); // end function(event)

	$(".draggable").draggable(function() {
		$("#narrText").fadeIn();
	});

	$("#narrText").droppable( {
		drop : function(event, ui) {
			var existingValue = $("#narrText").val();
			textValue = ui.draggable.text();
			$(this).val(existingValue + " " + textValue);
			ui.draggable.fadeOut();
		}
	});

	$('#narrYear').live('change', function() {
		var myYear = parseInt($('#narrYear').val());
		var nextYear = myYear + 1;
		$('#yearEnd').val(nextYear);
		});

	}// end function()
	);// end document.ready

function save_continue_narrative(){
	tinyMCE.triggerSave();
	var narrText = $('#narrText').val();
	$("#originalText").val(narrText);
	if (narrText == "") {
		alert("You haven't entered any text in the narrative yet. No need to save.");
	} else {
	var action = $("#action").val();
	$("#ajax").val(1);
	var formData = $("#narrativeEditor").serialize();
	var myUrl = base_url + "narrative/" + action;
	$.ajax({
		dataType: "json",
		url: myUrl,
		type: 'POST',
		data: formData,
		success: function(data){
			if(action == "insert"){
				$("#kNarrative").val(data.kNarrative);
				$("#action").val("update");
				$("#narrativeEditor").attr("action",base_url + "narrative/update");
				$("#editing-buttons .button-list").append("
Delete
");
			}
			$("#message").html("Narrative auto-saved: " + data.timestamp).show();

		},
		error: function(data){
			$("#message").html("An error occurred. Press 'Save and Continue' to save your work.").show();
		}
	});
		$("#ajax").val(0);
		//saveNarrative();
}
}

/*
 * @function deleteNarrative @params kNarrative int database keydescription:
 * delete a narrative from the database (note that the narrative is removed from
 * active use and stored in a backups database. See narrative_edit.php for
 * details. @dependencies NARRATIVE_EDIT_INC
 */
function delete_narrative(myNarrative, myStudent) {
	action = confirm("You sure you want to delete this?");
	if (action) {
		form_data = {
			kNarrative : myNarrative,
			kStudent : myStudent
		};
		myUrl = base_url + "narrative/delete";
		$.ajax({
			url: myUrl,
			type: 'post',
			data: form_data,
			success: function(data) {
			alert(data);
			document.location = base_url + "narrative/student_list/" + myStudent;
		}
		});
	}//end if
}
<|endoftext|>