<commit_before>function update_currentPath(newPath) {
  var rootname = newPath.split('/')[1];
  if (state.currentPath) {
      state.lastCurrentPath[rootname]=newPath;
  }
  state.currentPath = newPath;
  console.log(newPath.split('/').length);
  if (rootname === state.username) {
     showUpload();
  }
  else if (newPath.split('/').length > 2) {
     showUpload();
  }
  else {
     hideUpload();
  }
  update_path_nav();
  update_table();
}

function update_path_nav() {
  var pathFragments = state.currentPath.split("/");
  var aggregatedPath = "";
  var pathNav = $('#pathNav');
  pathNav.html('');
  for(var i = 1; i < pathFragments.length; i++) {
    aggregatedPath += "/" + pathFragments[i];

    // var li = $('
').attr('data-path',aggregatedPath).text(pathFragments[i]);
    var a = $('').text(pathFragments[i]).attr('href', '#');
    var li = $('
').attr('data-path', aggregatedPath);
    li.append(a);
    pathNav.append(li);
  }
}

function onPathNavClick(event) {
  var li = $(event.target).closest("li[data-path]",this);
  if (li.length==0) return; //did not click in a li item
  var path = li.attr("data-path");
  update_currentPath(path);
}

function onFileTableClick(event) {
  // TODO: check if it is a file or a directory
  var t = $(event.target);
  while (!t.is(this)) {
    if (t.is("tr")) break;
    if (t.is("table")) return;
    if (t.hasClass('delbtn')){
      if (!t.hasClass('disabled')) {
        t.addClass('disabled')
        delItem(t.attr('data-path'));
      }
      return;
    }
    if (t.hasClass('shareItem')) {
      return shareItem(t.attr('data-path'), t.attr('data-group'));
    }
    if (t.hasClass('dropdown')){
      return;
    }
    t = t.parent();
  }
  if (!t.parent().is("tbody")) {
    return;
  }
  if (t.children().length == 1) return;
  var currentDataIndex = t.find("div[data-index]").attr("data-index");
  if (elementIsDocument(currentListData[currentDataIndex].type)) {
    download(currentListData[currentDataIndex].path);
  } else {
    update_currentPath(currentListData[currentDataIndex].path);
  }
}

function download(path) {
  inpherapi_auth_get("/download", {fileName: path}, function(data, status, request){
    console.log(request);
    var blob = new Blob([data], {type: "txt"});
    saveAs(blob, path.substring(path.lastIndexOf("/") + 1, path.length));
  })
}

function shareItem(path, group) {
  ui.shareModal = {path: path, group: group};
  $('#createShareModal').modal("show");
}

function handleShareItemFormSubmit(event) {
    event.stopPropagation();
    event.preventDefault();
    var shareName = $('#createShareName').val();
    $('#createShareModal').modal("hide");
    inpherapiShareElement(ui.shareModal.path, ui.shareModal.group, shareName);
}

function inpherapiShareElement(path, group, shareName) {
  var queryParam = {
    "groupName" : group,
    "filePath" : path,
    "shareName" : shareName,
  };
  inpherapi_auth_post("/shareElement", queryParam, function(data, status) {
    if(status === "success")
            $('#alertContainer').bs_info("element shared succefully");
    else
            $('#alertContainer').bs_alert(data);
  });
}

$(function () {
  // Load the table content
  state.currentPath = '/' + sessionStorage.getItem('username');
  state.username = sessionStorage.getItem('username');
  update_path_nav();
  init_table();
  $('#pathNav').click(onPathNavClick);
  $('#files').click(onFileTableClick);
  $('#uploadFileModal').submit(fileUploadForm);
});

function fileUploadForm(e){
	e.preventDefault();
  e.stopPropagation();
  var obj = $('#file-list-page');
 	handleFileUpload($('#uploadFileModal input[type=file]')[0].files, obj);
 	$('#uploadFileModal').modal('hide');
}

function init_table() {
  $("#files").DataTable({
  	'searching':false,
  	dom: 'Bfrtip',
    buttons: [
	      {
	        text:      '<button class="btn btn-success btn-circle"></button>',
	        titleAttr: 'Upload',
		        action: function ( e, dt, node, config ) {
		            $('#uploadFileModal').modal();
		        }
	      },
	      {
	        text:      '<button class="btn btn-success btn-circle"></button>',
	        titleAttr: 'Create Folder',
		        action: function ( e, dt, node, config ) {
		            showAddFolder();
		        }
	      }
		]
  });
  update_table();
}

function showAddFolder() {
  $('#mkdir-footer').toggleClass('hidden');
  var mkdirName = $('#mkdirname');
  mkdirName.val("");
  mkdirName.focus();
}

function update_table() {
  inpherapi_list(state.currentPath, function(data, status) {
    if (status !== "success"){
              $('#alertContainer').bs_alert(data);
    }
    currentListData = data.list;
    var table = $('#files').dataTable();
    table.fnClearTable();
    if (data.list.length > 0) {
      var tableData = [];
      for (var i = 0; i < data.list.length; i++) {
        tableData.push(inpherapi_list_res_to_row(data.list[i], i));
      }
      table.fnAddData(tableData);
    }
  });
}

/**
* This function returns the outerHTML jQuert element which is not connected to the DOM
* (Unpredictable behaviour if the element is in the DOM)
*/
function outerHTML(element) {
  var try1 = element[0].outerHTML;
  if (try1) return try1;
  return element.wrapAll('
').parent().html();
}

function inpherapi_list_res_to_row(a, i) {
  var delbtn = $('<button type="button" class="btn btn-danger btn-circle delbtn"></button>');
  delbtn.attr('data-path', a.path);
  return [
    outerHTML(fsElementIconAndNameHtml(a.type, a.path, i)),
    a.size,
    a.groups,
    outerHTML($("
").append(delbtn).append(createShareElementButton(a.path)))
  ];
}

function fsElementIconAndNameHtml(elementType, path, i) {
  var name = path.substring(path.lastIndexOf("/") + 1, path.length);
  var reps = $('

');
  return reps.attr('data-index',i).prepend(fsElementTypeHtmlIcon(elementType)).append(document.createTextNode(name));
}

function elementIsDocument(elementType) {
  return elementType === "DOCUMENT";
}

function fsElementTypeHtmlIcon(elementType) {
  var reps=$('').addClass('fa');
  if (elementIsDocument(elementType)) {
    return reps.addClass('fa-file-text');
  } else {
    return reps.addClass('fa-folder');
  }
}

function createShareElementButton(path) {
  var dropdown = $("
").attr("class", "dropdown");
  var button = $("<button>").attr("class", "btn btn-primary btn-circle").attr("type", "button").attr("data-toggle", "dropdown");
  button.append('')
  dropdown.append(button);
  var listHtml = $("
");
  var listGroups = inpherListGroups();
  for(var i = 0; i < listGroups.length; i++) {
    var li = $("
").append(listGroups[i]);
    li.attr("data-group", listGroups[i]).attr("data-path", path);
    listHtml.append(li);
  }
  dropdown.append(listHtml);
  return dropdown;
}

function inpherListGroups() {
  return state.sharingGroupList;
}

function inpherapi_list(path, callback) {
  inpherapi_auth_get("/listDir", {dir: path}, callback);
}

function delItem(path) {
  return inpherapi_auth_delete('/delete', {path: path, recursive: true},update_table);
}

// ------------------------------------------------
// Upload shit below
function sendFileToServer(formData,status) {
  var options = {
    type: "POST",
    contentType:false,
    processData: false,
    cache: false,
    data: formData,
  };
  options.xhr = function() {
    var xhrobj = $.ajaxSettings.xhr();
    if (xhrobj.upload) {
      xhrobj.upload.addEventListener('progress', function(event) {
        var percent = 0;
        var position = event.loaded || event.position;
        var total = event.total;
        if (event.lengthComputable) {
          percent = Math.ceil(position / total * 100);
        }
        //Set progress
        status.setProgress(percent);
      }, false);
    }
    return xhrobj;
  };
  return inpherapi_auth_ajax('/upload', next1, options);
  function next1(data) {
    status.setProgress(100);
    $("#status1").append("File upload Done
");
    update_table(state.currentPath);
  }
}

var rowCount=0;
function createStatusbar(obj)
{
  rowCount++;
  var row="odd";
  if(rowCount %2 ==0) row ="even";
  this.statusbar = $("

");
  this.filename = $("

").appendTo(this.statusbar);
  this.size = $("

").appendTo(this.statusbar);
  this.progressBar = $("

").appendTo(this.statusbar);
  this.abort = $("
Abort
").appendTo(this.statusbar);
  obj.append(this.statusbar);

  this.setFileNameSize = function(name,size) {
    var sizeStr="";
    var sizeKB = size/1024;
    var sizeMB = sizeKB/1024;
    if(sizeMB > 1) {
      sizeStr = sizeMB.toFixed(2)+" MB";
    } else {
      sizeStr = sizeKB.toFixed(2)+" KB";
    }
    this.filename.text(name);
    this.size.text(sizeStr);
  };
  this.setProgress = function(progress) {
    var progressBarWidth =progress*this.progressBar.width()/ 100;
    this.progressBar.find('div').animate({ width: progressBarWidth }, 10).text(progress + "% ");
    if(parseInt(progress) >= 100)
    {
      this.abort.hide();
    }
  };
  this.setAbort = function(jqxhr) {
    var sb = this.statusbar;
    this.abort.click(function() {
      jqxhr.abort();
      sb.hide();
    });
  };
}

function handleFileUpload(file, path, obj) {
  var fd = new FormData();
  fd.append('content', file);
  fd.append('name', state.currentPath + '/' + path + file.name);

  var status = new createStatusbar(obj); //Using this we can set progress.
  status.setFileNameSize(file.name,file.size);
  sendFileToServer(fd,status);
}

function handleMkdir(event) {
  if (event.isDefaultPrevented()) {
    // TODO: failure
  } else {
    event.stopPropagation();
    event.preventDefault();
    var dirname = $("#mkdirname").val();
    inpherapi_auth_post('/mkdir', { dir: state.currentPath + "/"  + dirname }, update_table);
    $('#mkdir-footer').toggleClass('hidden');
  }
}

function traverseFileTree(item, path) {
  path = path || "";
  if (item.isFile) {
    // Get file
    item.file(function(file) {
      console.log("File:", path + file.name);
      handleFileUpload(file, path, $("#dragandrophandler"));
    });
  } else if (item.isDirectory) {
    // Get folder contents and mkdir
    var dirname = item.name
    console.log("Dir:", item.name);
    inpherapi_auth_post('/mkdir', { dir: state.currentPath + "/"  + path + dirname}, recurse(item,path));
  }
}

var recurse = function(item,path) {
  return function(data, textStatus, jqXHR) {
    var dirReader = item.createReader();
    dirReader.readEntries(function(entries) {
      for (var i=0; i<entries.length; i++) {
        traverseFileTree(entries[i], path + item.name + "/");
      }
    });
  };
}

$(function() {
  $("#mkdir-form").validator().submit(handleMkdir);
  $("#shareItemForm").submit(handleShareItemFormSubmit);

	var dragging = 0;
  var obj = $(".dragandrophandler");
  obj.on('dragenter', function (e) {
  	dragging++;
    e.stopPropagation();
    e.preventDefault();
    $('#dragandrophandler').removeClass('hidden');
    $('#uploadFileModal').modal('hide');
    console.log('dragenter');
  });
  obj.on('dragover', function (e) {
    e.stopPropagation();
    e.preventDefault();
    $('#uploadFileModal').modal('hide');
  });
  obj.on('drop', function (e) {
  	dragging = 0;
    e.preventDefault();
    $('#dragandrophandler').addClass('hidden');
    console.log('drop');
    var items = e.originalEvent.dataTransfer.items;
    for (var i=0; i<items.length; i++) {
    // webkitGetAsEntry is where the magic happens
      var item = items[i].webkitGetAsEntry();
      if (item) {
        traverseFileTree(item);
      }
    }
  });
  obj.on('dragleave', function (e) {
  	dragging--;
    e.stopPropagation();
    e.preventDefault();
  	if (dragging === 0) {
  		$('#dragandrophandler').addClass('hidden');
  	}
  	console.log('dragleave');
  });
  var doc = $(document);
  doc.on('dragenter', function (e) {
    e.stopPropagation();
    e.preventDefault();
  });
  doc.on('dragover', function (e) {
    e.stopPropagation();
    e.preventDefault();
  });
  doc.on('drop', function (e) {
    e.stopPropagation();
    e.preventDefault();
  });

});
// ------------------------------------------------
// Upload shit above
// ------------------------------------------------
<commit_msg>fixed upload button<commit_after>function update_currentPath(newPath) {
  var rootname = newPath.split('/')[1];
  if (state.currentPath) {
      state.lastCurrentPath[rootname]=newPath;
  }
  state.currentPath = newPath;
  console.log(newPath.split('/').length);
  if (rootname === state.username) {
     showUpload();
  }
  else if (newPath.split('/').length > 2) {
     showUpload();
  }
  else {
     hideUpload();
  }
  update_path_nav();
  update_table();
}

function update_path_nav() {
  var pathFragments = state.currentPath.split("/");
  var aggregatedPath = "";
  var pathNav = $('#pathNav');
  pathNav.html('');
  for(var i = 1; i < pathFragments.length; i++) {
    aggregatedPath += "/" + pathFragments[i];

    // var li = $('
').attr('data-path',aggregatedPath).text(pathFragments[i]);
    var a = $('').text(pathFragments[i]).attr('href', '#');
    var li = $('
').attr('data-path', aggregatedPath);
    li.append(a);
    pathNav.append(li);
  }
}

function onPathNavClick(event) {
  var li = $(event.target).closest("li[data-path]",this);
  if (li.length==0) return; //did not click in a li item
  var path = li.attr("data-path");
  update_currentPath(path);
}

function onFileTableClick(event) {
  // TODO: check if it is a file or a directory
  var t = $(event.target);
  while (!t.is(this)) {
    if (t.is("tr")) break;
    if (t.is("table")) return;
    if (t.hasClass('delbtn')){
      if (!t.hasClass('disabled')) {
        t.addClass('disabled')
        delItem(t.attr('data-path'));
      }
      return;
    }
    if (t.hasClass('shareItem')) {
      return shareItem(t.attr('data-path'), t.attr('data-group'));
    }
    if (t.hasClass('dropdown')){
      return;
    }
    t = t.parent();
  }
  if (!t.parent().is("tbody")) {
    return;
  }
  if (t.children().length == 1) return;
  var currentDataIndex = t.find("div[data-index]").attr("data-index");
  if (elementIsDocument(currentListData[currentDataIndex].type)) {
    download(currentListData[currentDataIndex].path);
  } else {
    update_currentPath(currentListData[currentDataIndex].path);
  }
}

function download(path) {
  inpherapi_auth_get("/download", {fileName: path}, function(data, status, request){
    console.log(request);
    var blob = new Blob([data], {type: "txt"});
    saveAs(blob, path.substring(path.lastIndexOf("/") + 1, path.length));
  })
}

function shareItem(path, group) {
  ui.shareModal = {path: path, group: group};
  $('#createShareModal').modal("show");
}

function handleShareItemFormSubmit(event) {
    event.stopPropagation();
    event.preventDefault();
    var shareName = $('#createShareName').val();
    $('#createShareModal').modal("hide");
    inpherapiShareElement(ui.shareModal.path, ui.shareModal.group, shareName);
}

function inpherapiShareElement(path, group, shareName) {
  var queryParam = {
    "groupName" : group,
    "filePath" : path,
    "shareName" : shareName,
  };
  inpherapi_auth_post("/shareElement", queryParam, function(data, status) {
    if(status === "success")
            $('#alertContainer').bs_info("element shared succefully");
    else
            $('#alertContainer').bs_alert(data);
  });
}

$(function () {
  // Load the table content
  state.currentPath = '/' + sessionStorage.getItem('username');
  state.username = sessionStorage.getItem('username');
  update_path_nav();
  init_table();
  $('#pathNav').click(onPathNavClick);
  $('#files').click(onFileTableClick);
  $('#uploadFileModal').submit(fileUploadForm);
});

function fileUploadForm(e){
	e.preventDefault();
  e.stopPropagation();
  var obj = $('#dragandrophandler');
 	handleFileUpload($('#uploadFileModal input[type=file]')[0].files, '/' , obj);
 	$('#uploadFileModal').modal('hide');
}

function init_table() {
  $("#files").DataTable({
  	'searching':false,
  	dom: 'Bfrtip',
    buttons: [
	      {
	        text:      '<button class="btn btn-success btn-circle"></button>',
	        titleAttr: 'Upload',
		        action: function ( e, dt, node, config ) {
		            $('#uploadFileModal').modal();
		        }
	      },
	      {
	        text:      '<button class="btn btn-success btn-circle"></button>',
	        titleAttr: 'Create Folder',
		        action: function ( e, dt, node, config ) {
		            showAddFolder();
		        }
	      }
		]
  });
  update_table();
}

function showAddFolder() {
  $('#mkdir-footer').toggleClass('hidden');
  var mkdirName = $('#mkdirname');
  mkdirName.val("");
  mkdirName.focus();
}

function update_table() {
  inpherapi_list(state.currentPath, function(data, status) {
    if (status !== "success"){
              $('#alertContainer').bs_alert(data);
    }
    currentListData = data.list;
    var table = $('#files').dataTable();
    table.fnClearTable();
    if (data.list.length > 0) {
      var tableData = [];
      for (var i = 0; i < data.list.length; i++) {
        tableData.push(inpherapi_list_res_to_row(data.list[i], i));
      }
      table.fnAddData(tableData);
    }
  });
}

/**
* This function returns the outerHTML jQuert element which is not connected to the DOM
* (Unpredictable behaviour if the element is in the DOM)
*/
function outerHTML(element) {
  var try1 = element[0].outerHTML;
  if (try1) return try1;
  return element.wrapAll('
').parent().html();
}

function inpherapi_list_res_to_row(a, i) {
  var delbtn = $('<button type="button" class="btn btn-danger btn-circle delbtn"></button>');
  delbtn.attr('data-path', a.path);
  return [
    outerHTML(fsElementIconAndNameHtml(a.type, a.path, i)),
    a.size,
    a.groups,
    outerHTML($("
").append(delbtn).append(createShareElementButton(a.path)))
  ];
}

function fsElementIconAndNameHtml(elementType, path, i) {
  var name = path.substring(path.lastIndexOf("/") + 1, path.length);
  var reps = $('

');
  return reps.attr('data-index',i).prepend(fsElementTypeHtmlIcon(elementType)).append(document.createTextNode(name));
}

function elementIsDocument(elementType) {
  return elementType === "DOCUMENT";
}

function fsElementTypeHtmlIcon(elementType) {
  var reps=$('').addClass('fa');
  if (elementIsDocument(elementType)) {
    return reps.addClass('fa-file-text');
  } else {
    return reps.addClass('fa-folder');
  }
}

function createShareElementButton(path) {
  var dropdown = $("
").attr("class", "dropdown");
  var button = $("<button>").attr("class", "btn btn-primary btn-circle").attr("type", "button").attr("data-toggle", "dropdown");
  button.append('')
  dropdown.append(button);
  var listHtml = $("
");
  var listGroups = inpherListGroups();
  for(var i = 0; i < listGroups.length; i++) {
    var li = $("
").append(listGroups[i]);
    li.attr("data-group", listGroups[i]).attr("data-path", path);
    listHtml.append(li);
  }
  dropdown.append(listHtml);
  return dropdown;
}

function inpherListGroups() {
  return state.sharingGroupList;
}

function inpherapi_list(path, callback) {
  inpherapi_auth_get("/listDir", {dir: path}, callback);
}

function delItem(path) {
  return inpherapi_auth_delete('/delete', {path: path, recursive: true},update_table);
}

// ------------------------------------------------
// Upload shit below
function sendFileToServer(formData,status) {
  var options = {
    type: "POST",
    contentType:false,
    processData: false,
    cache: false,
    data: formData,
  };
  options.xhr = function() {
    var xhrobj = $.ajaxSettings.xhr();
    if (xhrobj.upload) {
      xhrobj.upload.addEventListener('progress', function(event) {
        var percent = 0;
        var position = event.loaded || event.position;
        var total = event.total;
        if (event.lengthComputable) {
          percent = Math.ceil(position / total * 100);
        }
        //Set progress
        status.setProgress(percent);
      }, false);
    }
    return xhrobj;
  };
  return inpherapi_auth_ajax('/upload', next1, options);
  function next1(data) {
    status.setProgress(100);
    $("#status1").append("File upload Done
");
    update_table(state.currentPath);
  }
}

var rowCount=0;
function createStatusbar(obj)
{
  rowCount++;
  var row="odd";
  if(rowCount %2 ==0) row ="even";
  this.statusbar = $("

");
  this.filename = $("

").appendTo(this.statusbar);
  this.size = $("

").appendTo(this.statusbar);
  this.progressBar = $("

").appendTo(this.statusbar);
  this.abort = $("
Abort
").appendTo(this.statusbar);
  obj.append(this.statusbar);

  this.setFileNameSize = function(name,size) {
    var sizeStr="";
    var sizeKB = size/1024;
    var sizeMB = sizeKB/1024;
    if(sizeMB > 1) {
      sizeStr = sizeMB.toFixed(2)+" MB";
    } else {
      sizeStr = sizeKB.toFixed(2)+" KB";
    }
    this.filename.text(name);
    this.size.text(sizeStr);
  };
  this.setProgress = function(progress) {
    var progressBarWidth =progress*this.progressBar.width()/ 100;
    this.progressBar.find('div').animate({ width: progressBarWidth }, 10).text(progress + "% ");
    if(parseInt(progress) >= 100)
    {
      this.abort.hide();
    }
  };
  this.setAbort = function(jqxhr) {
    var sb = this.statusbar;
    this.abort.click(function() {
      jqxhr.abort();
      sb.hide();
    });
  };
}

function handleFileUpload(files, path, obj) {
  for (var i = 0; i < files.length; i++) {
    var fd = new FormData();
    fd.append('content', files[i]);
    fd.append('name', state.currentPath + '/' + path + files[i].name);
    var status = new createStatusbar(obj);
    status.setFileNameSize(files[i].name,files[i].size);
    sendFileToServer(fd,status);
  }
 }

function handleMkdir(event) {
  if (event.isDefaultPrevented()) {
    // TODO: failure
  } else {
    event.stopPropagation();
    event.preventDefault();
    var dirname = $("#mkdirname").val();
    inpherapi_auth_post('/mkdir', { dir: state.currentPath + "/"  + dirname }, update_table);
    $('#mkdir-footer').toggleClass('hidden');
  }
}

function traverseFileTree(item, path) {
  path = path || "";
  if (item.isFile) {
    // Get file
    item.file(function(file) {
      console.log("File:", path + file.name);
      handleFileUpload([file], path, $("#dragandrophandler"));
    });
  } else if (item.isDirectory) {
    // Get folder contents and mkdir
    var dirname = item.name
    console.log("Dir:", item.name);
    inpherapi_auth_post('/mkdir', { dir: state.currentPath + "/"  + path + dirname}, recurse(item,path));
  }
}

var recurse = function(item,path) {
  return function(data, textStatus, jqXHR) {
    var dirReader = item.createReader();
    dirReader.readEntries(function(entries) {
      for (var i=0; i<entries.length; i++) {
        traverseFileTree(entries[i], path + item.name + "/");
      }
    });
  };
}

$(function() {
  $("#mkdir-form").validator().submit(handleMkdir);
  $("#shareItemForm").submit(handleShareItemFormSubmit);

	var dragging = 0;
  var obj = $(".dragandrophandler");
  obj.on('dragenter', function (e) {
  	dragging++;
    e.stopPropagation();
    e.preventDefault();
    $('#dragandrophandler').removeClass('hidden');
    $('#uploadFileModal').modal('hide');
    console.log('dragenter');
  });
  obj.on('dragover', function (e) {
    e.stopPropagation();
    e.preventDefault();
    $('#uploadFileModal').modal('hide');
  });
  obj.on('drop', function (e) {
  	dragging = 0;
    e.preventDefault();
    $('#dragandrophandler').addClass('hidden');
    console.log('drop');
    var items = e.originalEvent.dataTransfer.items;
    for (var i=0; i<items.length; i++) {
    // webkitGetAsEntry is where the magic happens
      var item = items[i].webkitGetAsEntry();
      if (item) {
        traverseFileTree(item);
      }
    }
  });
  obj.on('dragleave', function (e) {
  	dragging--;
    e.stopPropagation();
    e.preventDefault();
  	if (dragging === 0) {
  		$('#dragandrophandler').addClass('hidden');
  	}
  	console.log('dragleave');
  });
  var doc = $(document);
  doc.on('dragenter', function (e) {
    e.stopPropagation();
    e.preventDefault();
  });
  doc.on('dragover', function (e) {
    e.stopPropagation();
    e.preventDefault();
  });
  doc.on('drop', function (e) {
    e.stopPropagation();
    e.preventDefault();
  });

});
// ------------------------------------------------
// Upload shit above
// ------------------------------------------------
<|endoftext|>


<commit_before>var zeit = require('../'),
    moment = require('moment');

// 1. Schedule a single execution of a callback for 3 seconds in the future.
var dateClock = new zeit.DateClock();
new zeit.Scheduler(dateClock).execute(function () {
       console.log('every 3 seconds: ' + dateClock.now());
    }).after(3000).start();

//// 2. Schedule a Q promise to execute 5 times at 30 second intervals, starting immediately.
//new zeit.Scheduler(new zeit.MomentClock())
//    .execute(function () {
//        return q.resolve('some happy path resolving promise');
//    })
//    .exactly(5)
//    .atFixedIntervalOf(moment.duration(30000))
//    .start();

// 3. Schedule repeatedly to trigger a callback at 5 second breaks (wait for completion) while
//    executed less than 1000 times and no error is thrown by the callback. Starts immediately.
new zeit.Scheduler(dateClock)
    .execute(function () {
        console.log('every 5 seconds: ' + dateClock.now());
    })
    .andRepeatAfter(5000)
    .whilst(function (scheduleItemDetails) {
        return scheduleItemDetails.invocationCount < 1000;
    })
    .until(function (err, result) {
        return err;
    })
    .start();
<commit_msg>added examples folder<commit_after>var zeit = require('../'),
    moment = require('moment');

// 1. Schedule a single execution of a callback for 3 seconds in the future.
var dateClock = new zeit.DateClock();
new zeit.Scheduler(dateClock).execute(function () {
       console.log('every 3 seconds: ' + dateClock.now());
    }).after(3000).start();

// 2. Schedule a Q promise to execute 5 times at 7 second intervals, starting immediately.
var momentClock = new zeit.MomentClock();
new zeit.Scheduler(momentClock)
    .execute(function () {
        console.log('every 7 seconds: ' + momentClock.now());
    })
    .after(moment.duration(6000))
    .exactly(5)
    .atFixedIntervalOf(moment.duration(7000))
    .start();

// 3. Schedule repeatedly to trigger a callback at 5 second breaks (wait for completion) while
//    executed less than 1000 times and no error is thrown by the callback. Starts immediately.
new zeit.Scheduler(dateClock)
    .execute(function () {
        console.log('every 5 seconds: ' + dateClock.now());
    })
    .andRepeatAfter(5000)
    .whilst(function (scheduleItemDetails) {
        return scheduleItemDetails.invocationCount < 1000;
    })
    .until(function (err, result) {
        return err;
    })
    .start();
<|endoftext|>


<commit_before>function update_currentPath(newPath) {
  var rootname = newPath.split('/')[1];
  if (state.currentPath) {
      state.lastCurrentPath[rootname]=newPath;
  }
  state.currentPath = newPath;
  console.log(newPath.split('/').length);
  if (rootname === state.username) {
     showUpload();
  }
  else if (newPath.split('/').length > 2) {
     showUpload();
  }
  else {
     hideUpload();
  }
  update_path_nav();
  update_table();
}

function update_path_nav() {
  var pathFragments = state.currentPath.split("/");
  var aggregatedPath = "";
  var pathNav = $('#pathNav');
  pathNav.html('');
  for(var i = 1; i < pathFragments.length; i++) {
    aggregatedPath += "/" + pathFragments[i];

    // var li = $('
').attr('data-path',aggregatedPath).text(pathFragments[i]);
    var a = $('').text(pathFragments[i]).attr('href', '#');
    var li = $('
').attr('data-path', aggregatedPath);
    li.append(a);
    pathNav.append(li);
  }
}

function onPathNavClick(event) {
  var li = $(event.target).closest("li[data-path]",this);
  if (li.length==0) return; //did not click in a li item
  var path = li.attr("data-path");
  update_currentPath(path);
}

function onFileTableClick(event) {
  // TODO: check if it is a file or a directory
  var t = $(event.target);
  while (!t.is(this)) {
    if (t.is("tr")) break;
    if (t.is("table")) return;
    if (t.hasClass('delbtn')){
      if (!t.hasClass('disabled')) {
        t.addClass('disabled')
        delItem(t.attr('data-path'));
      }
      return;
    }
    if (t.hasClass('shareItem')) {
      return shareItem(t.attr('data-path'), t.attr('data-group'));
    }
    if (t.hasClass('dropdown')){
      return;
    }
    t = t.parent();
  }
  if (!t.parent().is("tbody")) {
    return;
  }
  if (t.children().length == 1) return;
  var currentDataIndex = t.find("div[data-index]").attr("data-index");
  if (elementIsDocument(currentListData[currentDataIndex].type)) {
    download(currentListData[currentDataIndex].path);
  } else {
    update_currentPath(currentListData[currentDataIndex].path);
  }
}

function download(path) {
  inpherapi_auth_get("/download", {fileName: path}, function(data, status, request){
    console.log(request);
    var blob = new Blob([data], {type: "txt"});
    saveAs(blob, "file.txt");
  })
}

function shareItem(path, group) {
  ui.shareModal = {path: path, group: group};
  $('#createShareModal').modal("show");
}

function handleShareItemFormSubmit(event) {
    event.stopPropagation();
    event.preventDefault();
    var shareName = $('#createShareName').val();
    $('#createShareModal').modal("hide");
    inpherapiShareElement(ui.shareModal.path, ui.shareModal.group, shareName);
}

function inpherapiShareElement(path, group, shareName) {
  var queryParam = {
    "groupName" : group,
    "filePath" : path,
    "shareName" : shareName,
  };
  inpherapi_auth_post("/shareElement", queryParam, function(data, status) {
    if(status === "success")
            $('#alertContainer').bs_info("element shared succefully");
    else
            $('#alertContainer').bs_alert(data);
  });
}

$(function () {
  // Load the table content
  state.currentPath = '/' + sessionStorage.getItem('username');
  state.username = sessionStorage.getItem('username');
  update_path_nav();
  init_table();
  $('#pathNav').click(onPathNavClick);
  $('#files').click(onFileTableClick);
  $('#uploadFileModal').submit(fileUploadForm);
});

function fileUploadForm(e){
	e.preventDefault();
  e.stopPropagation();
  var obj = $('#file-list-page');
 	handleFileUpload($('#uploadFileModal input[type=file]')[0].files, obj);
 	$('#uploadFileModal').modal('hide');
}

function init_table() {
  $("#files").DataTable({
  	'searching':false,
  	dom: 'Bfrtip',
    buttons: [
	      {
	        text:      '<button class="btn btn-success btn-circle"></button>',
	        titleAttr: 'Upload',
		        action: function ( e, dt, node, config ) {
		            $('#uploadFileModal').modal();
		        }
	      },
	      {
	        text:      '<button class="btn btn-success btn-circle"></button>',
	        titleAttr: 'Create Folder',
		        action: function ( e, dt, node, config ) {
		            showAddFolder();
		        }
	      }
		]
  });
  update_table();
}

function showAddFolder() {
  $('#mkdir-footer').toggleClass('hidden');
  $('#mkdirname').focus();
}

function update_table() {
  inpherapi_list(state.currentPath, function(data, status) {
    if (status !== "success"){
              $('#alertContainer').bs_alert(data);
    }
    currentListData = data.list;
    var table = $('#files').dataTable();
    table.fnClearTable();
    if (data.list.length > 0) {
      var tableData = [];
      for (var i = 0; i < data.list.length; i++) {
        tableData.push(inpherapi_list_res_to_row(data.list[i], i));
      }
      table.fnAddData(tableData);
    }
  });
}

/**
* This function returns the outerHTML jQuert element which is not connected to the DOM
* (Unpredictable behaviour if the element is in the DOM)
*/
function outerHTML(element) {
  var try1 = element[0].outerHTML;
  if (try1) return try1;
  return element.wrapAll('
').parent().html();
}

function inpherapi_list_res_to_row(a, i) {
  var delbtn = $('<button type="button" class="btn btn-danger btn-circle delbtn"></button>');
  delbtn.attr('data-path', a.path);
  return [
    outerHTML(fsElementIconAndNameHtml(a.type, a.path, i)),
    a.size,
    a.groups,
    outerHTML($("
").append(delbtn).append(createShareElementButton(a.path)))
  ];
}

function fsElementIconAndNameHtml(elementType, path, i) {
  var name = path.substring(path.lastIndexOf("/") + 1, path.length);
  var reps = $('

');
  return reps.attr('data-index',i).prepend(fsElementTypeHtmlIcon(elementType)).append(document.createTextNode(name));
}

function elementIsDocument(elementType) {
  return elementType === "DOCUMENT";
}

function fsElementTypeHtmlIcon(elementType) {
  var reps=$('').addClass('fa');
  if (elementIsDocument(elementType)) {
    return reps.addClass('fa-file-text');
  } else {
    return reps.addClass('fa-folder');
  }
}

function createShareElementButton(path) {
  var dropdown = $("
").attr("class", "dropdown");
  var button = $("<button>").attr("class", "btn btn-primary btn-circle").attr("type", "button").attr("data-toggle", "dropdown");
  button.append('')
  dropdown.append(button);
  var listHtml = $("
");
  var listGroups = inpherListGroups();
  for(var i = 0; i < listGroups.length; i++) {
    var li = $("
").append(listGroups[i]);
    li.attr("data-group", listGroups[i]).attr("data-path", path);
    listHtml.append(li);
  }
  dropdown.append(listHtml);
  return dropdown;
}

function inpherListGroups() {
  return state.sharingGroupList;
}

function inpherapi_list(path, callback) {
  inpherapi_auth_get("/listDir", {dir: path}, callback);
}

function delItem(path) {
  return inpherapi_auth_delete('/delete', {path: path, recursive: true},update_table);
}

// ------------------------------------------------
// Upload shit below
function sendFileToServer(formData,status) {
  var options = {
    type: "POST",
    contentType:false,
    processData: false,
    cache: false,
    data: formData,
  };
  options.xhr = function() {
    var xhrobj = $.ajaxSettings.xhr();
    if (xhrobj.upload) {
      xhrobj.upload.addEventListener('progress', function(event) {
        var percent = 0;
        var position = event.loaded || event.position;
        var total = event.total;
        if (event.lengthComputable) {
          percent = Math.ceil(position / total * 100);
        }
        //Set progress
        status.setProgress(percent);
      }, false);
    }
    return xhrobj;
  };
  return inpherapi_auth_ajax('/upload', next1, options);
  function next1(data) {
    status.setProgress(100);
    $("#status1").append("File upload Done
");
    update_table(state.currentPath);
  }
}

var rowCount=0;
function createStatusbar(obj)
{
  rowCount++;
  var row="odd";
  if(rowCount %2 ==0) row ="even";
  this.statusbar = $("

");
  this.filename = $("

").appendTo(this.statusbar);
  this.size = $("

").appendTo(this.statusbar);
  this.progressBar = $("

").appendTo(this.statusbar);
  this.abort = $("
Abort
").appendTo(this.statusbar);
  obj.after(this.statusbar);

  this.setFileNameSize = function(name,size) {
    var sizeStr="";
    var sizeKB = size/1024;
    var sizeMB = sizeKB/1024;
    if(sizeMB > 1) {
      sizeStr = sizeMB.toFixed(2)+" MB";
    } else {
      sizeStr = sizeKB.toFixed(2)+" KB";
    }
    this.filename.text(name);
    this.size.text(sizeStr);
  };
  this.setProgress = function(progress) {
    var progressBarWidth =progress*this.progressBar.width()/ 100;
    this.progressBar.find('div').animate({ width: progressBarWidth }, 10).text(progress + "% ");
    if(parseInt(progress) >= 100)
    {
      this.abort.hide();
    }
  };
  this.setAbort = function(jqxhr) {
    var sb = this.statusbar;
    this.abort.click(function() {
      jqxhr.abort();
      sb.hide();
    });
  };
}

function handleFileUpload(files,obj) {
  for (var i = 0; i < files.length; i++) {
    var fd = new FormData();
    fd.append('content', files[i]);
    fd.append('name', state.currentPath + '/' + files[i].name);

    var status = new createStatusbar(obj); //Using this we can set progress.
    status.setFileNameSize(files[i].name,files[i].size);
    sendFileToServer(fd,status);
  }
}

function handleMkdir(event) {
  if (event.isDefaultPrevented()) {
    // TODO: failure
  } else {
    event.stopPropagation();
    event.preventDefault();
    var dirname = $("#mkdirname").val();
    inpherapi_auth_post('/mkdir', { dir: state.currentPath + "/"  + dirname }, update_table);
    $('#mkdir-footer').toggleClass('hidden');
  }
}

$(function() {
  $("#mkdir-form").validator().submit(handleMkdir);
  $("#shareItemForm").submit(handleShareItemFormSubmit);

	var dragging = 0;
  var obj = $(".dragandrophandler");
  obj.on('dragenter', function (e) {
  	dragging++;
    e.stopPropagation();
    e.preventDefault();
    $('#dragandrophandler').removeClass('hidden');
    $('#uploadFileModal').modal('hide');
    console.log('dragenter');
  });
  obj.on('dragover', function (e) {
    e.stopPropagation();
    e.preventDefault();
    $('#uploadFileModal').modal('hide');
  });
  obj.on('drop', function (e) {
  	dragging = 0;
    e.preventDefault();
    var files = e.originalEvent.dataTransfer.files;
    $('#dragandrophandler').addClass('hidden');
    console.log('drop');
    //We need to send dropped files to Server
    handleFileUpload(files, $('#file-list-page'));
  });
  obj.on('dragleave', function (e) {
  	dragging--;
    e.stopPropagation();
    e.preventDefault();
  	if (dragging === 0) {
  		$('#dragandrophandler').addClass('hidden');
  	}
  	console.log('dragleave');
  });
  var doc = $(document);
  doc.on('dragenter', function (e) {
    e.stopPropagation();
    e.preventDefault();
  });
  doc.on('dragover', function (e) {
    e.stopPropagation();
    e.preventDefault();
  });
  doc.on('drop', function (e) {
    e.stopPropagation();
    e.preventDefault();
  });

});
// ------------------------------------------------
// Upload shit above
// ------------------------------------------------
<commit_msg>Focus and empty dir name on mkdir<commit_after>function update_currentPath(newPath) {
  var rootname = newPath.split('/')[1];
  if (state.currentPath) {
      state.lastCurrentPath[rootname]=newPath;
  }
  state.currentPath = newPath;
  console.log(newPath.split('/').length);
  if (rootname === state.username) {
     showUpload();
  }
  else if (newPath.split('/').length > 2) {
     showUpload();
  }
  else {
     hideUpload();
  }
  update_path_nav();
  update_table();
}

function update_path_nav() {
  var pathFragments = state.currentPath.split("/");
  var aggregatedPath = "";
  var pathNav = $('#pathNav');
  pathNav.html('');
  for(var i = 1; i < pathFragments.length; i++) {
    aggregatedPath += "/" + pathFragments[i];

    // var li = $('
').attr('data-path',aggregatedPath).text(pathFragments[i]);
    var a = $('').text(pathFragments[i]).attr('href', '#');
    var li = $('
').attr('data-path', aggregatedPath);
    li.append(a);
    pathNav.append(li);
  }
}

function onPathNavClick(event) {
  var li = $(event.target).closest("li[data-path]",this);
  if (li.length==0) return; //did not click in a li item
  var path = li.attr("data-path");
  update_currentPath(path);
}

function onFileTableClick(event) {
  // TODO: check if it is a file or a directory
  var t = $(event.target);
  while (!t.is(this)) {
    if (t.is("tr")) break;
    if (t.is("table")) return;
    if (t.hasClass('delbtn')){
      if (!t.hasClass('disabled')) {
        t.addClass('disabled')
        delItem(t.attr('data-path'));
      }
      return;
    }
    if (t.hasClass('shareItem')) {
      return shareItem(t.attr('data-path'), t.attr('data-group'));
    }
    if (t.hasClass('dropdown')){
      return;
    }
    t = t.parent();
  }
  if (!t.parent().is("tbody")) {
    return;
  }
  if (t.children().length == 1) return;
  var currentDataIndex = t.find("div[data-index]").attr("data-index");
  if (elementIsDocument(currentListData[currentDataIndex].type)) {
    download(currentListData[currentDataIndex].path);
  } else {
    update_currentPath(currentListData[currentDataIndex].path);
  }
}

function download(path) {
  inpherapi_auth_get("/download", {fileName: path}, function(data, status, request){
    console.log(request);
    var blob = new Blob([data], {type: "txt"});
    saveAs(blob, "file.txt");
  })
}

function shareItem(path, group) {
  ui.shareModal = {path: path, group: group};
  $('#createShareModal').modal("show");
}

function handleShareItemFormSubmit(event) {
    event.stopPropagation();
    event.preventDefault();
    var shareName = $('#createShareName').val();
    $('#createShareModal').modal("hide");
    inpherapiShareElement(ui.shareModal.path, ui.shareModal.group, shareName);
}

function inpherapiShareElement(path, group, shareName) {
  var queryParam = {
    "groupName" : group,
    "filePath" : path,
    "shareName" : shareName,
  };
  inpherapi_auth_post("/shareElement", queryParam, function(data, status) {
    if(status === "success")
            $('#alertContainer').bs_info("element shared succefully");
    else
            $('#alertContainer').bs_alert(data);
  });
}

$(function () {
  // Load the table content
  state.currentPath = '/' + sessionStorage.getItem('username');
  state.username = sessionStorage.getItem('username');
  update_path_nav();
  init_table();
  $('#pathNav').click(onPathNavClick);
  $('#files').click(onFileTableClick);
  $('#uploadFileModal').submit(fileUploadForm);
});

function fileUploadForm(e){
	e.preventDefault();
  e.stopPropagation();
  var obj = $('#file-list-page');
 	handleFileUpload($('#uploadFileModal input[type=file]')[0].files, obj);
 	$('#uploadFileModal').modal('hide');
}

function init_table() {
  $("#files").DataTable({
  	'searching':false,
  	dom: 'Bfrtip',
    buttons: [
	      {
	        text:      '<button class="btn btn-success btn-circle"></button>',
	        titleAttr: 'Upload',
		        action: function ( e, dt, node, config ) {
		            $('#uploadFileModal').modal();
		        }
	      },
	      {
	        text:      '<button class="btn btn-success btn-circle"></button>',
	        titleAttr: 'Create Folder',
		        action: function ( e, dt, node, config ) {
		            showAddFolder();
		        }
	      }
		]
  });
  update_table();
}

function showAddFolder() {
  $('#mkdir-footer').toggleClass('hidden');
  var mkdirName = $('#mkdirname');
  mkdirName.val("");
  mkdirName.focus();
}

function update_table() {
  inpherapi_list(state.currentPath, function(data, status) {
    if (status !== "success"){
              $('#alertContainer').bs_alert(data);
    }
    currentListData = data.list;
    var table = $('#files').dataTable();
    table.fnClearTable();
    if (data.list.length > 0) {
      var tableData = [];
      for (var i = 0; i < data.list.length; i++) {
        tableData.push(inpherapi_list_res_to_row(data.list[i], i));
      }
      table.fnAddData(tableData);
    }
  });
}

/**
* This function returns the outerHTML jQuert element which is not connected to the DOM
* (Unpredictable behaviour if the element is in the DOM)
*/
function outerHTML(element) {
  var try1 = element[0].outerHTML;
  if (try1) return try1;
  return element.wrapAll('
').parent().html();
}

function inpherapi_list_res_to_row(a, i) {
  var delbtn = $('<button type="button" class="btn btn-danger btn-circle delbtn"></button>');
  delbtn.attr('data-path', a.path);
  return [
    outerHTML(fsElementIconAndNameHtml(a.type, a.path, i)),
    a.size,
    a.groups,
    outerHTML($("
").append(delbtn).append(createShareElementButton(a.path)))
  ];
}

function fsElementIconAndNameHtml(elementType, path, i) {
  var name = path.substring(path.lastIndexOf("/") + 1, path.length);
  var reps = $('

');
  return reps.attr('data-index',i).prepend(fsElementTypeHtmlIcon(elementType)).append(document.createTextNode(name));
}

function elementIsDocument(elementType) {
  return elementType === "DOCUMENT";
}

function fsElementTypeHtmlIcon(elementType) {
  var reps=$('').addClass('fa');
  if (elementIsDocument(elementType)) {
    return reps.addClass('fa-file-text');
  } else {
    return reps.addClass('fa-folder');
  }
}

function createShareElementButton(path) {
  var dropdown = $("
").attr("class", "dropdown");
  var button = $("<button>").attr("class", "btn btn-primary btn-circle").attr("type", "button").attr("data-toggle", "dropdown");
  button.append('')
  dropdown.append(button);
  var listHtml = $("
");
  var listGroups = inpherListGroups();
  for(var i = 0; i < listGroups.length; i++) {
    var li = $("
").append(listGroups[i]);
    li.attr("data-group", listGroups[i]).attr("data-path", path);
    listHtml.append(li);
  }
  dropdown.append(listHtml);
  return dropdown;
}

function inpherListGroups() {
  return state.sharingGroupList;
}

function inpherapi_list(path, callback) {
  inpherapi_auth_get("/listDir", {dir: path}, callback);
}

function delItem(path) {
  return inpherapi_auth_delete('/delete', {path: path, recursive: true},update_table);
}

// ------------------------------------------------
// Upload shit below
function sendFileToServer(formData,status) {
  var options = {
    type: "POST",
    contentType:false,
    processData: false,
    cache: false,
    data: formData,
  };
  options.xhr = function() {
    var xhrobj = $.ajaxSettings.xhr();
    if (xhrobj.upload) {
      xhrobj.upload.addEventListener('progress', function(event) {
        var percent = 0;
        var position = event.loaded || event.position;
        var total = event.total;
        if (event.lengthComputable) {
          percent = Math.ceil(position / total * 100);
        }
        //Set progress
        status.setProgress(percent);
      }, false);
    }
    return xhrobj;
  };
  return inpherapi_auth_ajax('/upload', next1, options);
  function next1(data) {
    status.setProgress(100);
    $("#status1").append("File upload Done
");
    update_table(state.currentPath);
  }
}

var rowCount=0;
function createStatusbar(obj)
{
  rowCount++;
  var row="odd";
  if(rowCount %2 ==0) row ="even";
  this.statusbar = $("

");
  this.filename = $("

").appendTo(this.statusbar);
  this.size = $("

").appendTo(this.statusbar);
  this.progressBar = $("

").appendTo(this.statusbar);
  this.abort = $("
Abort
").appendTo(this.statusbar);
  obj.after(this.statusbar);

  this.setFileNameSize = function(name,size) {
    var sizeStr="";
    var sizeKB = size/1024;
    var sizeMB = sizeKB/1024;
    if(sizeMB > 1) {
      sizeStr = sizeMB.toFixed(2)+" MB";
    } else {
      sizeStr = sizeKB.toFixed(2)+" KB";
    }
    this.filename.text(name);
    this.size.text(sizeStr);
  };
  this.setProgress = function(progress) {
    var progressBarWidth =progress*this.progressBar.width()/ 100;
    this.progressBar.find('div').animate({ width: progressBarWidth }, 10).text(progress + "% ");
    if(parseInt(progress) >= 100)
    {
      this.abort.hide();
    }
  };
  this.setAbort = function(jqxhr) {
    var sb = this.statusbar;
    this.abort.click(function() {
      jqxhr.abort();
      sb.hide();
    });
  };
}

function handleFileUpload(files,obj) {
  for (var i = 0; i < files.length; i++) {
    var fd = new FormData();
    fd.append('content', files[i]);
    fd.append('name', state.currentPath + '/' + files[i].name);

    var status = new createStatusbar(obj); //Using this we can set progress.
    status.setFileNameSize(files[i].name,files[i].size);
    sendFileToServer(fd,status);
  }
}

function handleMkdir(event) {
  if (event.isDefaultPrevented()) {
    // TODO: failure
  } else {
    event.stopPropagation();
    event.preventDefault();
    var dirname = $("#mkdirname").val();
    inpherapi_auth_post('/mkdir', { dir: state.currentPath + "/"  + dirname }, update_table);
    $('#mkdir-footer').toggleClass('hidden');
  }
}

$(function() {
  $("#mkdir-form").validator().submit(handleMkdir);
  $("#shareItemForm").submit(handleShareItemFormSubmit);

	var dragging = 0;
  var obj = $(".dragandrophandler");
  obj.on('dragenter', function (e) {
  	dragging++;
    e.stopPropagation();
    e.preventDefault();
    $('#dragandrophandler').removeClass('hidden');
    $('#uploadFileModal').modal('hide');
    console.log('dragenter');
  });
  obj.on('dragover', function (e) {
    e.stopPropagation();
    e.preventDefault();
    $('#uploadFileModal').modal('hide');
  });
  obj.on('drop', function (e) {
  	dragging = 0;
    e.preventDefault();
    var files = e.originalEvent.dataTransfer.files;
    $('#dragandrophandler').addClass('hidden');
    console.log('drop');
    //We need to send dropped files to Server
    handleFileUpload(files, $('#file-list-page'));
  });
  obj.on('dragleave', function (e) {
  	dragging--;
    e.stopPropagation();
    e.preventDefault();
  	if (dragging === 0) {
  		$('#dragandrophandler').addClass('hidden');
  	}
  	console.log('dragleave');
  });
  var doc = $(document);
  doc.on('dragenter', function (e) {
    e.stopPropagation();
    e.preventDefault();
  });
  doc.on('dragover', function (e) {
    e.stopPropagation();
    e.preventDefault();
  });
  doc.on('drop', function (e) {
    e.stopPropagation();
    e.preventDefault();
  });

});
// ------------------------------------------------
// Upload shit above
// ------------------------------------------------
<|endoftext|>


<commit_before>var fs = require('fs');
var os = require('os');
var bbt = require('../../lib/bbt-node');

var bclient = new bbt.Connector(
  {
    keyId: process.env.key,
    secretKey: process.env.skey,
    hostname: 'x.beebotte.com',
    port: 8080
});

var cpus = null;
var avg_cpu = {user: 0, nice: 0, sys: 0, idle: 0, irq: 0};

function getAvgCpu(r1, r2) {
  var avg_cpu = {user: 0, nice: 0, sys: 0, idle: 0, irq: 0};
  var tot_time = 0;
  for(var c in r2) {
    avg_cpu.user += r2[c].times.user;
    avg_cpu.nice += r2[c].times.nice;
    avg_cpu.sys  += r2[c].times.sys;
    avg_cpu.idle += r2[c].times.idle;
    avg_cpu.irq  += r2[c].times.irq;
  }
  for(var c in r1) {
    avg_cpu.user -= r1[c].times.user;
    avg_cpu.nice -= r1[c].times.nice;
    avg_cpu.sys  -= r1[c].times.sys;
    avg_cpu.idle -= r1[c].times.idle;
    avg_cpu.irq  -= r1[c].times.irq;
  }

  tot_time += avg_cpu.user + avg_cpu.nice + avg_cpu.sys + avg_cpu.idle + avg_cpu.irq;

  avg_cpu.user = (avg_cpu.user / tot_time) * 100;
  avg_cpu.nice = (avg_cpu.nice / tot_time) * 100;
  avg_cpu.sys  = (avg_cpu.sys  / tot_time) * 100;
  avg_cpu.idle = (avg_cpu.idle / tot_time) * 100;
  avg_cpu.irq  = (avg_cpu.irq  / tot_time) * 100;

  return avg_cpu;
}

function meminfo(callback, elems) {
  fs.readFile('/proc/meminfo', 'utf8', function (err, minfo) {
    if (err) {
      return callback(err);
    }
    var minfo = minfo.split('\n')
    var data = {};
    minfo.forEach(function (line) {
      var line = line.replace(/\s+/, '');
      line = line.replace(/\skB/, '');
      var record = line.split(/\:/);
      if (record[0] !== '') {
        data[record[0].toLowerCase()] = parseInt(record[1]);
      }
    });
    if(elems) {
      var retval = {};
      for( e in elems) {
        retval[elems[e].toLowerCase()] = data[elems[e].toLowerCase()];
      }
      return callback(null, retval);
    }
    return callback(data);
  });
}

setInterval(function()
  {
    if(!cpus) cpus = os.cpus();
    else {
      var new_cpus = os.cpus();
      var avg_cpu = getAvgCpu(cpus, new_cpus);
      //Send an array of records (Bulk Write), improved performance
      bclient.writeResource({
        device: 'sandbox',
        service: 'performance',
        resource: 'CPU',
        value: avg_cpu
      }, function(err, res) {
        if(err) console.log(err);
      });

      meminfo(function (err, data) {
        console.log(data);
        if(err) return console.log(err);
        bclient.writeResource({
          device: 'sandbox',
          service: 'performance',
          resource: 'memory',
          value: data
        }, function(err, res) {
          if(err) console.log(err);
        });
      }, ['MemTotal', 'memfree', 'cached', 'dirty']);
      console.log(avg_cpu);
      cpus = new_cpus;
    }
  }, 60 * 1000
);

<commit_msg>Updated server activity reporter script<commit_after>/*
 * Example showing how to use Beebotte to monitor the CPU and memory usage of a server.
 * Works on any Linux platform.
 * Microsoft Windows is not (yet) supported.
 *
 * Copyright, Beebotte.com
 * MIT license
 */

var fs = require('fs');
var os = require('os');
var bbt = require('../../lib/bbt-node');

var bclient = new bbt.Connector(
  {
    //API keys for your account
    keyId: process.env.ACCESS_KEY,
    secretKey: process.env.SECURITY_KEY,
    hostname: 'api.beebotte.com', //This is the default host anyway
    port: 80 //This is the default port number anyway
});

var cpus = null;
var avg_cpu = {user: 0, nice: 0, sys: 0, idle: 0, irq: 0};

function getAvgCpu(r1, r2) {
  var avg_cpu = {user: 0, nice: 0, sys: 0, idle: 0, irq: 0};
  var tot_time = 0;
  for(var c in r2) {
    avg_cpu.user += r2[c].times.user;
    avg_cpu.nice += r2[c].times.nice;
    avg_cpu.sys  += r2[c].times.sys;
    avg_cpu.idle += r2[c].times.idle;
    avg_cpu.irq  += r2[c].times.irq;
  }
  for(var c in r1) {
    avg_cpu.user -= r1[c].times.user;
    avg_cpu.nice -= r1[c].times.nice;
    avg_cpu.sys  -= r1[c].times.sys;
    avg_cpu.idle -= r1[c].times.idle;
    avg_cpu.irq  -= r1[c].times.irq;
  }

  tot_time += avg_cpu.user + avg_cpu.nice + avg_cpu.sys + avg_cpu.idle + avg_cpu.irq;

  avg_cpu.user = (avg_cpu.user / tot_time) * 100;
  avg_cpu.nice = (avg_cpu.nice / tot_time) * 100;
  avg_cpu.sys  = (avg_cpu.sys  / tot_time) * 100;
  avg_cpu.idle = (avg_cpu.idle / tot_time) * 100;
  avg_cpu.irq  = (avg_cpu.irq  / tot_time) * 100;

  return avg_cpu;
}

function meminfo(callback, elems) {
  fs.readFile('/proc/meminfo', 'utf8', function (err, minfo) {
    if (err) {
      return callback(err);
    }
    var minfo = minfo.split('\n')
    var data = {};
    minfo.forEach(function (line) {
      var line = line.replace(/\s+/, '');
      line = line.replace(/\skB/, '');
      var record = line.split(/\:/);
      if (record[0] !== '') {
        data[record[0].toLowerCase()] = parseInt(record[1]);
      }
    });
    if(elems) {
      var retval = {};
      for( e in elems) {
        retval[elems[e].toLowerCase()] = data[elems[e].toLowerCase()];
      }
      return callback(null, retval);
    }
    return callback(data);
  });
}

setInterval(function()
  {
    if(!cpus) cpus = os.cpus();
    else {
      var new_cpus = os.cpus();
      var avg_cpu = getAvgCpu(cpus, new_cpus);
      //Write a record to the CPU resource
      bclient.writeResource({
        device: 'sandbox',
        service: 'performance',
        resource: 'CPU',
        value: avg_cpu
      }, function(err, res) {
        if(err) console.log(err);
      });

      meminfo(function (err, data) {
        console.log(data);
        if(err) return console.log(err);
        //Write a record to the memory resource
        bclient.writeResource({
          device: 'sandbox',
          service: 'performance',
          resource: 'memory',
          value: data
        }, function(err, res) {
          if(err) console.log(err);
        });
      }, ['MemTotal', 'memfree', 'cached', 'dirty']);
      console.log(avg_cpu);
      cpus = new_cpus;
    }
  }, process.env.FREQUECY || (60 * 1000 /* 1 minute */)
);

<|endoftext|>


<commit_before>/*
 * ava configuration file must be in the same directory as the package.json file
 *
 * https://github.com/avajs/ava/blob/master/docs/06-configuration.md#alternative-configuration-files
 */

const config = {
  files: ["tests/e2e/*.js"],
  failFast: true,
  verbose: true,
  timeout: "3m",
  serial: true
}

const testEnv = (process.env.GIT_TAG_NAME && "remote") || process.env.TEST_ENV || "local"

if (testEnv === "local") {
  config.serial = false
}

if (testEnv === "remote") {
  /*
   * We have 5 parallel tests in our BrowserStack plan. But, when we try to run more than
   * 10 tests in parallel on BrowserStack, tests fail with a message indicating that all
   * parallel tests are in use.
   *
   * https://www.browserstack.com/question/617
   *
   * That's why we cannot run ava without `serial` or `concurrency` flags because,
   * the number of test files running at the same time is number of CPU cores.
   * Our best shot is to tell ava run one test file at a time and never keep more than
   * 10 parallel tests in a single test file.
   *
   * https://github.com/avajs/ava/blob/master/docs/05-command-line.md#cli
   *
   * Also please note that all report.js tests and some permissions.js tests are always
   * serialized with test.serialize for the time being.
   */
  config.serial = false
  config.concurrency = 1
}

/*
 * For ava.config.js files `export default` must be used
 *
 * https://github.com/avajs/ava/blob/master/docs/06-configuration.md#avaconfigjs
 */
export default config
<commit_msg>nci-agency/anet#212: Fix lint errors<commit_after>/*
 * ava configuration file must be in the same directory as the package.json file
 *
 * https://github.com/avajs/ava/blob/master/docs/06-configuration.md#alternative-configuration-files
 */

const config = {
  files: ["tests/e2e/*.js"],
  failFast: true,
  verbose: true,
  timeout: "3m",
  serial: true
}

const testEnv =
  (process.env.GIT_TAG_NAME && "remote") || process.env.TEST_ENV || "local"

if (testEnv === "local") {
  config.serial = false
}

if (testEnv === "remote") {
  /*
   * We have 5 parallel tests in our BrowserStack plan. But, when we try to run more than
   * 10 tests in parallel on BrowserStack, tests fail with a message indicating that all
   * parallel tests are in use.
   *
   * https://www.browserstack.com/question/617
   *
   * That's why we cannot run ava without `serial` or `concurrency` flags because,
   * the number of test files running at the same time is number of CPU cores.
   * Our best shot is to tell ava run one test file at a time and never keep more than
   * 10 parallel tests in a single test file.
   *
   * https://github.com/avajs/ava/blob/master/docs/05-command-line.md#cli
   *
   * Also please note that all report.js tests and some permissions.js tests are always
   * serialized with test.serialize for the time being.
   */
  config.serial = false
  config.concurrency = 1
}

/*
 * For ava.config.js files `export default` must be used
 *
 * https://github.com/avajs/ava/blob/master/docs/06-configuration.md#avaconfigjs
 */
export default config
<|endoftext|>


<commit_before>function mapConf(map, ol) {
 usercontrols = [];
 WGL.the_map = map;

    var featureOverlay = new ol.FeatureOverlay({
        style: new ol.style.Style({
            fill: new ol.style.Fill({
                color: 'rgba(255, 255, 255, 0.2)'
            }),
            stroke: new ol.style.Stroke({
                color: '#ffcc33',
                width: 2
            }),
            image: new ol.style.Circle({
                radius: 7,
                fill: new ol.style.Fill({
                    color: '#ffcc33'
                })
            })
        })
    });
    featureOverlay.setMap(map);

 // select interaction working on "singleclick"

    // select interaction working on "click"
    var selectClick = new ol.interaction.Select({
      condition: ol.events.condition.click,
       features: featureOverlay.getFeatures()
    });

	 function deleteFeatures(e){
		var f = selectClick.getFeatures();
		 f.forEach( function(ff){
     	 featureOverlay.removeFeature(ff);
   		})

	}

    selectClick.on('select', function(e) {
    	 deleteFeatures(e);
    })

 	usercontrols['select'] =  selectClick;

    var modify = new ol.interaction.Modify({
        features: featureOverlay.getFeatures(),

        // the SHIFT key must be pressed to delete vertices, so
        // that new vertices can be drawn at the same position
        // of existing vertices
        deleteCondition: function(event) {
            return ol.events.condition.shiftKeyOnly(event) &&
                ol.events.condition.singleClick(event);
        }

    });

	//usercontrols['modify'] = modify;

    featureOverlay.getFeatures();

    //map.addInteraction(modify);

    var draw; // global so we can remove it lat	 console.log(this);er

        draw = new ol.interaction.Draw({
            features: featureOverlay.getFeatures(),
            type: "Polygon"
        });

        draw.on("drawstart", function(e) {
            e.feature.on('change', function(ff) {
                var res = [];
                var features = ff.target.getGeometry().getCoordinates();
                //for (var i = 0; i < features.length; i++) {
                for (var j = 0; j < features[0].length; j++) {
                    var pp = transform(features[0][j]);
                    res.push(pp);
                }
                //console.log("feature num "+features.length);

                try {
                    var polygons = [];
                    var polid = 0;
                    var ts = new poly2tri.SweepContext(res);
                    ts.triangulate();
                    polygons[polid++] = trianglesToArray(ts.getTriangles());
                    polygons.length = Object.keys(polygons).length;
                    WGL.filterDim('themap','polybrush',polygons);
                } catch (e) {
                    console.log(e);
                }

            }, draw);
        });

	usercontrols['draw'] = draw;

   // addInteraction();

    function transform(p) {
        var tl = getTopLeftTC();

        var v = map.getPixelFromCoordinate(p);
        console.log(v);
        var prop = map.getProperties()
            // var v = map.getViewPortPxFromLonLat( new OpenLayers.LonLat(90,0));
        var v0 = toLevel0(v, tl, prop.view.getZoom());
        return v0;

    }

    function toLevel0(pt, tl, zoom) {
        var p = [];
        var ts = 256;
        var scale = Math.pow(2, zoom);
        p.x = pt[0] / scale + tl.x;
        p.y = pt[1] / scale + tl.y;
        return p;
    }
    var tlwgs = [-20037508.34, 20037508.34];

    function getTopLeftTC() {

        var s = Math.pow(2, map.getView().getZoom());
        var tlpixel = map.getPixelFromCoordinate(tlwgs);
        var res = {
            x: -tlpixel[0] / s,
            y: -tlpixel[1] / s
        }
        return res
    }

    function trianglesToArray(trig) {
        var points = [];
        for (var i in trig) {
            for (var j in trig[i].points_) {
                points.push(trig[i].points_[j].x);
                points.push(trig[i].points_[j].y);
            }
        }
        return points;

    }

}
toggleControl = function(element) {

	for (key in usercontrols) {
		var control = usercontrols[key];

		if (element.value == key && element.checked) {
			 WGL.the_map.addInteraction(control);
			console.log('activate '+control);
		} else {
			 WGL.the_map.removeInteraction(control);
			console.log('deactivate '+control);
		}
	}
}

<commit_msg>clear the selection after removing overlay feature<commit_after>function mapConf(map, ol) {
 usercontrols = [];
 WGL.the_map = map;

    var featureOverlay = new ol.FeatureOverlay({
        style: new ol.style.Style({
            fill: new ol.style.Fill({
                color: 'rgba(255, 255, 255, 0.2)'
            }),
            stroke: new ol.style.Stroke({
                color: '#ffcc33',
                width: 2
            }),
            image: new ol.style.Circle({
                radius: 7,
                fill: new ol.style.Fill({
                    color: '#ffcc33'
                })
            })
        })
    });
    featureOverlay.setMap(map);

 // select interaction working on "singleclick"

    // select interaction working on "click"
    var selectClick = new ol.interaction.Select({
      condition: ol.events.condition.click,
       features: featureOverlay.getFeatures()
    });

	 function deleteFeatures(e){
		var f = selectClick.getFeatures();
		 f.forEach( function(ff){
     	 featureOverlay.removeFeature(ff);
   		})
		selectClick.getFeatures().clear();
	}

    selectClick.on('select', function(e) {
    	 deleteFeatures(e);
    })

 	usercontrols['select'] =  selectClick;

    var modify = new ol.interaction.Modify({
        features: featureOverlay.getFeatures(),

        // the SHIFT key must be pressed to delete vertices, so
        // that new vertices can be drawn at the same position
        // of existing vertices
        deleteCondition: function(event) {
            return ol.events.condition.shiftKeyOnly(event) &&
                ol.events.condition.singleClick(event);
        }

    });

	//usercontrols['modify'] = modify;

    featureOverlay.getFeatures();

    //map.addInteraction(modify);

    var draw; // global so we can remove it lat	 console.log(this);er

        draw = new ol.interaction.Draw({
            features: featureOverlay.getFeatures(),
            type: "Polygon"
        });

        draw.on("drawstart", function(e) {
            e.feature.on('change', function(ff) {
                var res = [];
                var features = ff.target.getGeometry().getCoordinates();
                //for (var i = 0; i < features.length; i++) {
                for (var j = 0; j < features[0].length; j++) {
                    var pp = transform(features[0][j]);
                    res.push(pp);
                }
                //console.log("feature num "+features.length);

                try {
                    var polygons = [];
                    var polid = 0;
                    var ts = new poly2tri.SweepContext(res);
                    ts.triangulate();
                    polygons[polid++] = trianglesToArray(ts.getTriangles());
                    polygons.length = Object.keys(polygons).length;
                    WGL.filterDim('themap','polybrush',polygons);
                } catch (e) {
                    console.log(e);
                }

            }, draw);
        });

	usercontrols['draw'] = draw;

   // addInteraction();

    function transform(p) {
        var tl = getTopLeftTC();

        var v = map.getPixelFromCoordinate(p);
        console.log(v);
        var prop = map.getProperties()
            // var v = map.getViewPortPxFromLonLat( new OpenLayers.LonLat(90,0));
        var v0 = toLevel0(v, tl, prop.view.getZoom());
        return v0;

    }

    function toLevel0(pt, tl, zoom) {
        var p = [];
        var ts = 256;
        var scale = Math.pow(2, zoom);
        p.x = pt[0] / scale + tl.x;
        p.y = pt[1] / scale + tl.y;
        return p;
    }
    var tlwgs = [-20037508.34, 20037508.34];

    function getTopLeftTC() {

        var s = Math.pow(2, map.getView().getZoom());
        var tlpixel = map.getPixelFromCoordinate(tlwgs);
        var res = {
            x: -tlpixel[0] / s,
            y: -tlpixel[1] / s
        }
        return res
    }

    function trianglesToArray(trig) {
        var points = [];
        for (var i in trig) {
            for (var j in trig[i].points_) {
                points.push(trig[i].points_[j].x);
                points.push(trig[i].points_[j].y);
            }
        }
        return points;

    }

}
toggleControl = function(element) {

	for (key in usercontrols) {
		var control = usercontrols[key];

		if (element.value == key && element.checked) {
			 WGL.the_map.addInteraction(control);
			console.log('activate '+control);
		} else {
			 WGL.the_map.removeInteraction(control);
			console.log('deactivate '+control);
		}
	}
}

<|endoftext|>


<commit_before>var pathRoot = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':'+window.location.port : '') + window.location.pathname;
var titleRoot = document.title;
var body = document.body, html = document.documentElement;
var docHeight = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight );
var current = '';
var swapped = false;
var galleriesLoaded = [];
var adsloaded = [];
/* THIS IS CONFIG DATA SPECIFIC TO SITE */
var showAds = true; //show slide-up leaderboards at bottom
var slideAds = 1; //number of times to slide up a leaderboard
var titleFade = true; //whether to fade the Denver Post logo in the top-bar to show the "DP" and a text title
//var pages = ['#titlepage','#part1','#photos','#part2']; //div/section IDs that should trigger a page view and title change
var pages = [];
$('.omnitrig').each(function(i,e) { pages.push('#'+$(e).attr('id')) });
var galleries = [];
$('.centergallery').each(function(i,e) { galleries.push('#'+$(e).attr('id')) }); //div/section IDs of galleries to instantiate (must be a div like #photos and have a child, the gallery itself, with the same ID plus 'gallery' -- i.e. #photosgallery)

function revealSocial(type,link,title,image,desc,twvia,twrel) {
    title = typeof title !== 'undefined' ? title : false;
    image = typeof image !== 'undefined' ? image : false;
    desc = typeof desc !== 'undefined' ? desc : false;
    twvia = typeof twvia !== 'undefined' ? twvia.toString().replace('@','') : false;
    twrel = typeof twrel !== 'undefined' ? twrel.toString().replace('@','') : false;
    //type can be twitter, facebook or gplus
    var srcurl = '';
    if (type == 'twitter') {
        srcurl = 'http://twitter.com/intent/tweet?text=' + encodeURIComponent(title).replace('|','%7c') + '&url=' + link + '&via=' + twvia + '&related=' + twrel;
    } else if (type == 'facebook') {
        srcurl = 'http://www.facebook.com/sharer/sharer.php?s=100&p[url]=' + link + '&p[images][0]=' + image + '&p[title]=' + encodeURIComponent(title).replace('|','%7c') + '&p[summary]=' + encodeURIComponent(desc).replace('|','%7c');
    } else if (type == 'gplus') {
        srcurl = 'https://plus.google.com/share?url=' + link;
    }
    console.log(srcurl);
    if (srcurl.length > 1) {
        window.open(srcurl, type, 'left=60,top=60,width=500,height=500,toolbar=1,resizable=1').focus();
    }
    return false;
}

function load_omniture() {
        var omni = $('#omniture').html();
        $('#omniture').after('
' + omni + '
');
}
function build_url(path) {
        var url = pathRoot + path;
        return url;
}
function rewrite_url(path, new_title) {
        var url = build_url(path);
        current = path;
        document.title = (typeof new_title == 'undefined' || new_title.length < 1 ) ? titleRoot : new_title + ' - ' + titleRoot;
        window.history.replaceState('', new_title, url);
}

$(document).foundation('reveal', {
    animation: 'fade',
    animationspeed: 200
});
function revealCredits() {
    $('#credits').foundation('reveal', 'open');
}
function revealSlides(galleries) {
    for (key in galleries) {
        if (galleriesLoaded.indexOf(galleries[key]) == -1) {
            $(galleries[key]).find('img').unveil();
            $(galleries[key]).slick({
                centerMode: true,
                centerPadding: '15%',
                slidesToShow: 1,
                prevArrow: '<button type="button" class="slick-prev"><</button>',
                nextArrow: '<button type="button" class="slick-next">></button>',
                responsive: [{
                    breakpoint: 800,
                    settings: {
                        arrows: true,
                        centerMode: true,
                        centerPadding: '8%',
                        slidesToShow: 1
                    }
                }]
            });
            galleriesLoaded.push(galleries[key]);
        }
    }
}
function checkHash() {
    if (window.location.hash) {
        revealSlides(galleries);
        var hash = window.location.hash;
        if ($(hash).hasClass('hide')) {
            toggleSidebar(hash,hash + 'link');
        } else {
            scrollDownTo(hash);
        }
    }
}

function scrollDownTo(whereToScroll, scrollOffset) {
    scrollOffset = typeof scrollOffset !== 'undefined' ? scrollOffset : 60;
    if ($(whereToScroll).length) {
        $('html,body').animate({
            scrollTop: ($(whereToScroll).offset().top - scrollOffset)
        }, 300);
    } else {
        var new_url = window.location.href.split('#')[0];
        window.history.replaceState('', document.title, new_url);
    }
}

function toggleSidebar(toShow,toHide) {
    $(toShow).removeClass('hide');
    $(toHide).addClass('hide');
    rewrite_url(toShow);
    scrollDownTo(toShow);
}

function playerCreator(embedId, playerId, divId) {
    divId = typeof divId !== 'undefined' ? divId : false;
    if (divId) {
        $(divId).animate({backgroundColor:'rgba(0,70,70,0.3)',paddingLeft:'.5em',paddingRight:'.5em'}, 350).delay(2000).animate({backgroundColor:'transparent',paddingLeft:'0',paddingRight:'0'},1000);
    }
    OO.Player.create(embedId, playerId, {'autoplay':true});
}

function playerScroller(embedId, playerId, divId) {
    scrollDownTo(('#' + embedId),100);
    playerCreator(embedId, playerId, divId);
}
function getNodePosition(node) {
    var eTop = $(node).offset().top;
    return Math.abs(eTop - $(window).scrollTop());
}
function isVisible(element) {
    var vidTop = $(element).offset().top;
    var vidBot = $(element).offset().top + $(element).height();
    var fromTop = $(window).scrollTop() + $(element).height() / 2;
    if ( fromTop > vidTop && fromTop < vidBot ) {
        return true;
    } else {
        return false;
    }
}

function isElementInViewport(el) {
    el = el.toString().replace('#','');
    if (document.getElementById(el) != null) {
        var rect = document.getElementById(el).getBoundingClientRect();
        var half = window.innerHeight / 2;
        var whole = window.innerHeight;
        return ( (rect.top > 0 && rect.top < half) || (rect.bottom < whole && rect.bottom > half) || (rect.top < 0 && rect.bottom > whole) );
    } else {
        return;
    }
}

$('.top-top').click(function(evt) {
    $('.toggle-topbar').click();
});

$('.vid-embed').on("mouseenter", function() {
    $(this).find('.playicon').fadeTo(300, 0);
    $(this).find('.playtext').fadeTo(300, 1);
});
$('.vid-embed').on("mouseleave", function() {
    $(this).find('.playicon').fadeTo(300, 1);
    $(this).find('.playtext').fadeTo(300, 0);
});

function fadeNavBar(reverse) {
    if (reverse) {
        $('#name1').animate({opacity:1},500);
        $('#name2').animate({opacity:0},500);
        titleFade = true;
    } else {
        $('#name1').animate({opacity:0},500);
        $('#name2').animate({opacity:1},500);
        titleFade = false;
    }
}

function checkFade() {
    if ( !($(window).scrollTop() < window.innerHeight) && titleFade ) {
        fadeNavBar(false);
    } else if ( ($(window).scrollTop() < window.innerHeight) && !titleFade) {
        fadeNavBar(true);
    }
}

function hideAdManual() {
    $('#adwrapper').fadeOut(300);
    $('#adwrapper a.boxclose').css('display', 'none');
    $('#footer-bar').delay(150).animate({marginBottom:'0'},300);
    $('#adframewrapper').html('');
    swapped = false;
}

$(document).keyup(function(e) {
    if (swapped && e.keyCode == 27) {
        hideAdManual();
    }
});

function getAdSize() {
    if ( $(window).width() >= 740 ) {
        var adSizes = ['ad=medium','728','90'];
        return adSizes;
    } else {
        return false;
    }
    /* else if ( $(window).width() >= 300 && $(window).width() < 740 ) {
        var adSizes = ['ad=small','300','50'];
        return adSizes;
    }*/
}

function showAd() {
    var adSize = getAdSize();
    if (adSize) {
        $('#adframewrapper').html('');
        $('#adwrapper').fadeIn(400);
        $('a.boxclose').fadeIn(400);
        var adH = $('#adwrapper').height();
        $('#footer-bar').css('margin-bottom',adH);
        swapped = true;
    }
}

function swapAd() {
    if (swapped) {
        hideAdManual();
    }
    if (!swapped) {
        showAd();
    }
}

function getAdTimes(numAds) {
    var adReturns = [];
    var chunkHeight = docHeight / numAds + 1;
    var chunkHalf = chunkHeight / 2;
    for (i=1;i<=numAds;i++) {
        adReturns.push( Math.round( chunkHalf + (chunkHeight * i) ) );
    }
    return adReturns;
}

function checkAdPos() {
    if (showAds) {
        var topNow = $(window).scrollTop();
        if (!swapped) {
            var adTimes = getAdTimes(slideAds);
            for (var i = 0; i < adTimes.length; i++) {
                if (!adsloaded[i] && topNow > adTimes[i] && topNow < (typeof adTimes[(i+1)] !== 'undefined' ? adTimes[(i+1)] : docHeight)) {
                    swapAd();
                    adsloaded[i] = true;
                    break;
                }
            }
        }
    }
}

function checkPageState(pages) {
    for (key in pages) {
        if ($(window).scrollTop() < 100) {
            rewrite_url('','');
            break;
        }
        var currentpage = pages[key];
        var next = (pages[parseInt(key) + 1]) ? pages[parseInt(key) + 1] : currentpage;
        var prev = (pages[parseInt(key) - 1]) ? pages[parseInt(key) - 1] : currentpage;
        if (isElementInViewport(currentpage) && currentpage != current) {
            var triggerDiv = $(currentpage);
            rewrite_url(currentpage.toString(),$(triggerDiv).data('omniTitle'));
            if ($(triggerDiv).hasClass('omnitrig')) {
                load_omniture();
                $(triggerDiv).removeClass('omnitrig');
            }
        }
    }
}

$('.chart-late').find('img').unveil(300);

$(document).ready(function() {
    checkHash();
    checkAdPos();
});

var didScroll = false;
$(window).scroll(function() {
    didScroll = true;
});
setInterval(function() {
    if (didScroll) {
        checkFade();
        checkPageState(pages);
        revealSlides(galleries);
        checkAdPos();
    }
},250);<commit_msg>Fruther work on ad timing functions<commit_after>var pathRoot = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':'+window.location.port : '') + window.location.pathname;
var titleRoot = document.title;
var body = document.body, html = document.documentElement;
var docHeight = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight );
var current = '';
var swapped = false;
var galleriesLoaded = [];
var adsloaded = [];
/* THIS IS CONFIG DATA SPECIFIC TO SITE */
var showAds = true; //show slide-up leaderboards at bottom
var slideAds = 2; //number of times to slide up a leaderboard
var titleFade = true; //whether to fade the Denver Post logo in the top-bar to show the "DP" and a text title
//var pages = ['#titlepage','#part1','#photos','#part2']; //div/section IDs that should trigger a page view and title change
var pages = [];
$('.omnitrig').each(function(i,e) { pages.push('#'+$(e).attr('id')) });
var galleries = [];
$('.centergallery').each(function(i,e) { galleries.push('#'+$(e).attr('id')) }); //div/section IDs of galleries to instantiate (must be a div like #photos and have a child, the gallery itself, with the same ID plus 'gallery' -- i.e. #photosgallery)

function revealSocial(type,link,title,image,desc,twvia,twrel) {
    title = typeof title !== 'undefined' ? title : false;
    image = typeof image !== 'undefined' ? image : false;
    desc = typeof desc !== 'undefined' ? desc : false;
    twvia = typeof twvia !== 'undefined' ? twvia.toString().replace('@','') : false;
    twrel = typeof twrel !== 'undefined' ? twrel.toString().replace('@','') : false;
    //type can be twitter, facebook or gplus
    var srcurl = '';
    if (type == 'twitter') {
        srcurl = 'http://twitter.com/intent/tweet?text=' + encodeURIComponent(title).replace('|','%7c') + '&url=' + link + '&via=' + twvia + '&related=' + twrel;
    } else if (type == 'facebook') {
        srcurl = 'http://www.facebook.com/sharer/sharer.php?s=100&p[url]=' + link + '&p[images][0]=' + image + '&p[title]=' + encodeURIComponent(title).replace('|','%7c') + '&p[summary]=' + encodeURIComponent(desc).replace('|','%7c');
    } else if (type == 'gplus') {
        srcurl = 'https://plus.google.com/share?url=' + link;
    }
    console.log(srcurl);
    if (srcurl.length > 1) {
        window.open(srcurl, type, 'left=60,top=60,width=500,height=500,toolbar=1,resizable=1').focus();
    }
    return false;
}

function load_omniture() {
        var omni = $('#omniture').html();
        $('#omniture').after('
' + omni + '
');
}
function build_url(path) {
        var url = pathRoot + path;
        return url;
}
function rewrite_url(path, new_title) {
        var url = build_url(path);
        current = path;
        document.title = (typeof new_title == 'undefined' || new_title.length < 1 ) ? titleRoot : new_title + ' - ' + titleRoot;
        window.history.replaceState('', new_title, url);
}

$(document).foundation('reveal', {
    animation: 'fade',
    animationspeed: 200
});
function revealCredits() {
    $('#credits').foundation('reveal', 'open');
}
function revealSlides(galleries) {
    for (key in galleries) {
        if (galleriesLoaded.indexOf(galleries[key]) == -1) {
            $(galleries[key]).find('img').unveil();
            $(galleries[key]).slick({
                centerMode: true,
                centerPadding: '15%',
                slidesToShow: 1,
                prevArrow: '<button type="button" class="slick-prev"><</button>',
                nextArrow: '<button type="button" class="slick-next">></button>',
                responsive: [{
                    breakpoint: 800,
                    settings: {
                        arrows: true,
                        centerMode: true,
                        centerPadding: '8%',
                        slidesToShow: 1
                    }
                }]
            });
            galleriesLoaded.push(galleries[key]);
        }
    }
}
function checkHash() {
    if (window.location.hash) {
        revealSlides(galleries);
        var hash = window.location.hash;
        if ($(hash).hasClass('hide')) {
            toggleSidebar(hash,hash + 'link');
        } else {
            scrollDownTo(hash);
        }
    }
}

function scrollDownTo(whereToScroll, scrollOffset) {
    scrollOffset = typeof scrollOffset !== 'undefined' ? scrollOffset : 60;
    if ($(whereToScroll).length) {
        $('html,body').animate({
            scrollTop: ($(whereToScroll).offset().top - scrollOffset)
        }, 300);
    } else {
        var new_url = window.location.href.split('#')[0];
        window.history.replaceState('', document.title, new_url);
    }
}

function toggleSidebar(toShow,toHide) {
    $(toShow).removeClass('hide');
    $(toHide).addClass('hide');
    rewrite_url(toShow);
    scrollDownTo(toShow);
}

function playerCreator(embedId, playerId, divId) {
    divId = typeof divId !== 'undefined' ? divId : false;
    if (divId) {
        $(divId).animate({backgroundColor:'rgba(0,70,70,0.3)',paddingLeft:'.5em',paddingRight:'.5em'}, 350).delay(2000).animate({backgroundColor:'transparent',paddingLeft:'0',paddingRight:'0'},1000);
    }
    OO.Player.create(embedId, playerId, {'autoplay':true});
}

function playerScroller(embedId, playerId, divId) {
    scrollDownTo(('#' + embedId),100);
    playerCreator(embedId, playerId, divId);
}
function getNodePosition(node) {
    var eTop = $(node).offset().top;
    return Math.abs(eTop - $(window).scrollTop());
}
function isVisible(element) {
    var vidTop = $(element).offset().top;
    var vidBot = $(element).offset().top + $(element).height();
    var fromTop = $(window).scrollTop() + $(element).height() / 2;
    if ( fromTop > vidTop && fromTop < vidBot ) {
        return true;
    } else {
        return false;
    }
}

function isElementInViewport(el) {
    el = el.toString().replace('#','');
    if (document.getElementById(el) != null) {
        var rect = document.getElementById(el).getBoundingClientRect();
        var half = window.innerHeight / 2;
        var whole = window.innerHeight;
        return ( (rect.top > 0 && rect.top < half) || (rect.bottom < whole && rect.bottom > half) || (rect.top < 0 && rect.bottom > whole) );
    } else {
        return;
    }
}

$('.top-top').click(function(evt) {
    $('.toggle-topbar').click();
});

$('.vid-embed').on("mouseenter", function() {
    $(this).find('.playicon').fadeTo(300, 0);
    $(this).find('.playtext').fadeTo(300, 1);
});
$('.vid-embed').on("mouseleave", function() {
    $(this).find('.playicon').fadeTo(300, 1);
    $(this).find('.playtext').fadeTo(300, 0);
});

function fadeNavBar(reverse) {
    if (reverse) {
        $('#name1').animate({opacity:1},500);
        $('#name2').animate({opacity:0},500);
        titleFade = true;
    } else {
        $('#name1').animate({opacity:0},500);
        $('#name2').animate({opacity:1},500);
        titleFade = false;
    }
}

function checkFade() {
    if ( !($(window).scrollTop() < window.innerHeight) && titleFade ) {
        fadeNavBar(false);
    } else if ( ($(window).scrollTop() < window.innerHeight) && !titleFade) {
        fadeNavBar(true);
    }
}

function hideAdManual() {
    $('#adwrapper').fadeOut(300);
    $('#adwrapper a.boxclose').css('display', 'none');
    $('#footer-bar').delay(150).animate({marginBottom:'0'},300);
    $('#adframewrapper').html('');
    swapped = false;
}

$(document).keyup(function(e) {
    if (swapped && e.keyCode == 27) {
        hideAdManual();
    }
});

function getAdSize() {
    if ( $(window).width() >= 740 ) {
        var adSizes = ['ad=medium','728','90'];
        return adSizes;
    } else {
        return false;
    }
    /* else if ( $(window).width() >= 300 && $(window).width() < 740 ) {
        var adSizes = ['ad=small','300','50'];
        return adSizes;
    }*/
}

function showAd() {
    var adSize = getAdSize();
    if (adSize) {
        $('#adframewrapper').html('');
        $('#adwrapper').fadeIn(400);
        $('a.boxclose').fadeIn(400);
        var adH = $('#adwrapper').height();
        $('#footer-bar').css('margin-bottom',adH);
        swapped = true;
    }
}

function swapAd() {
    if (swapped) {
        hideAdManual();
    }
    if (!swapped) {
        showAd();
    }
}

function getAdTimes(numAds) {
    var adReturns = [];
    var chunkHeight = docHeight / (numAds + 1);
    var chunkHalf = chunkHeight / 2;
    for (i=1;i<=numAds;i++) {
        adReturns.push( Math.round( chunkHalf + (chunkHeight * i) ) );
    }
    return adReturns;
}

function checkAdPos() {
    if (showAds) {
        var topNow = $(window).scrollTop();
        if (!swapped) {
            var adTimes = getAdTimes(slideAds);
            for (var i = 0; i < adTimes.length; i++) {
                if (!adsloaded[i] && topNow > adTimes[i] && topNow < (typeof adTimes[(i+1)] !== 'undefined' ? adTimes[(i+1)] : docHeight)) {
                    swapAd();
                    adsloaded[i] = true;
                    break;
                }
            }
        }
    }
}

function checkPageState(pages) {
    for (key in pages) {
        if ($(window).scrollTop() < 100) {
            rewrite_url('','');
            break;
        }
        var currentpage = pages[key];
        var next = (pages[parseInt(key) + 1]) ? pages[parseInt(key) + 1] : currentpage;
        var prev = (pages[parseInt(key) - 1]) ? pages[parseInt(key) - 1] : currentpage;
        if (isElementInViewport(currentpage) && currentpage != current) {
            var triggerDiv = $(currentpage);
            rewrite_url(currentpage.toString(),$(triggerDiv).data('omniTitle'));
            if ($(triggerDiv).hasClass('omnitrig')) {
                load_omniture();
                $(triggerDiv).removeClass('omnitrig');
            }
        }
    }
}

$('.chart-late').find('img').unveil(300);

$(document).ready(function() {
    checkHash();
    checkAdPos();
});

var didScroll = false;
$(window).scroll(function() {
    didScroll = true;
});
setInterval(function() {
    if (didScroll) {
        checkFade();
        checkPageState(pages);
        revealSlides(galleries);
        checkAdPos();
    }
},250);<|endoftext|>


<commit_before>pontoEmbarque = "";
// Iniciando o mapa
var map = L.map('map', {
    zoomControl: false
}).setView([-21.786, -46.566], 15);

L.control.zoom({
    position: 'bottomright'
}).addTo(map);

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
}).addTo(map);

var helloPopup = L.popup().setContent('Hello World!');

L.easyButton({
    id: 'id-for-the-button', // an id for the generated button
    position: 'bottomright', // inherited from L.Control -- the corner it goes in
    type: 'replace', // set to animate when you're comfy with css
    leafletClasses: true, // use leaflet classes to style the button?
    states: [{ // specify different icons and responses for your button
        stateName: 'get-center',
        onClick: function(button, map) {
            alert('Map is centered at: ' + map.getCenter().toString());
        },
        title: 'show me the middle',
        icon: 'fa-crosshairs'
    }]
}).addTo(map);

// Criando camada para desenhar no mapa
var markers = new L.FeatureGroup();

// Generator que desenha no mapa e html
var Generator = {};

var listaRotas = [];

/* Metodos da classe Generator */

// Draws a stop on the map, with the position and agency name.
Generator.drawAgencyStop = function (data) {

    obj = JSON.parse(data);

    L.marker([37.972117, -122.032526], {
            icon: agencyMarker
        }).addTo(map)
        .bindPopup(Generator.drawAgencyPopup(obj.agency_name, obj.agency_url, obj.agency_timezone, obj.agency_lang))
        .openPopup();

    map.setView(new L.LatLng(37.972117, -122.032526), 10);
};

// Draws a popup on the stop, with the agency's information.
Generator.drawAgencyPopup = function(agency_name, agency_url, agency_timezone, agency_lang) {
    var html = "";

    html += "
 " + agency_name + "
" +
        "
Visit Agency!
" +
        "
" + agency_timezone + " - " + agency_lang + "

";

    return html;

};

// Generates the HTML code a list of routes
Generator.drawRoutesList = function(data) {

    obj = JSON.parse(data);

    for (var x = 0; x < obj.length; x++) {

        var route_name = obj[x].route_short_name + ": " + obj[x].route_long_name;

        $("#routes").append("<option value='" + obj[x].route_id + "'>" + route_name + "</option>");

        // Coloca as rotas em uma lista, para ser usada no typeahead
        listaRotas.push(route_name);

        //if ((route_name.search("Metr") > 0) || (route_name.search("metr") != -1)){
        //console.log("é metro ->" + route_name);
        //}
    }

};

// Draws a line between the points of shape
Generator.drawShapes = function(data) {

    obj = JSON.parse(data);

    var latlngs = Array();

    for (var y = 0; y < obj[0].length; y++) {
        var marker = L.marker([obj[0][y].shape_pt_lat, obj[0][y].shape_pt_lon], {
            icon: greenIcon
        });
        //markers.addLayer(marker);
        latlngs.push(marker.getLatLng());
    }

    //map.addLayer(markers);

    // create a polyline from an arrays of LatLng points
    var polyline = L.polyline(latlngs, {
        color: '#3498db'
    }).addTo(map);
    markers.addLayer(polyline);
    map.addLayer(markers);
    // zoom the map to the polyline
    map.fitBounds(polyline.getBounds());
    map.setZoom(10);
};

Generator.drawStopsNear = function(data) {

    obj = JSON.parse(data);
    /*
    for (var y = 0; y < 1; y++) {
      var marker = L.marker([obj[y].stop_lat, obj[y].stop_lon], {icon: redMarker}).bindPopup(Generator.drawStopsPopup(obj[y].stop_id, obj[y].stop_name, obj[y].stop_desc));
      markers.addLayer(marker);

    }

    map.addLayer(markers);
    */
    pontoEmbarque = obj[0].stop_name;
    settings.boarding_stop = obj[0].stop_name;
    boarding_stop_id = obj[0].stop_id;

    var url = "http://127.0.0.1:8000/api/routesbystop?agency_id=SPTRANS&stop_id=" + obj[0].stop_id;
    console.log(url);
    getApi(url, test);
};

function test(data) {
    obj = JSON.parse(data);
    console.log(obj);
    //var url = "http://127.0.0.1:8124/api/shapes?agency_key=county-connection&route_id=" + obj[0].route_id + "&direction_id=0";
    //get(url, "shapes");
    url = "http://127.0.0.1:8000/api/stops?agency_key=SPTRANS&route_id=" + obj[0].route_id + "&direction_id=0";
    console.log(url);
    //get(url, "stops");
    getApi(url, Generator.drawStops);
}

// Draw stops on map
Generator.drawStops = function(data) {

    var marker;
    var stop_name;
    var stop_id;
    var boarding_stop;
    var landing_stop;

    obj = JSON.parse(data);

    for (var y = 0; y < obj.length; y++) {
      stop_name = obj[y].stop_name;
      boarding_stop = settings.boarding_stop;

      //console.log("Nome do stop atual: " + stop_name);
      console.log("Nome do boarding stop: " + boarding_stop);
      if (stop_name !== boarding_stop){
        marker = L.marker([obj[y].stop_lat, obj[y].stop_lon], {
            icon: redMarker
        }).bindPopup(Generator.drawStopsPopup(obj[y].stop_id, obj[y].stop_name, obj[y].stop_desc));
      } else {
        console.log("FOI IGUAL");
        marker = L.marker([obj[y].stop_lat, obj[y].stop_lon], {
            icon: boardingMarker
        }).bindPopup(Generator.drawStopsPopup(obj[y].stop_id, obj[y].stop_name, obj[y].stop_desc));
        $("#melhoresLinhas").html(boarding_stop);
      }

      markers.addLayer(marker);

    }

    map.addLayer(markers);

};

// Draws the pop-up stopping points on the map
Generator.drawStopsPopup = function(stop_id, stop_name, stops_desc) {
    var html = "";

    html += "
" +
        "
" + stop_name + "
" +
        "
" + stops_desc + "

";

    return html;

};

Generator.print = function() {
  console.log("Print");
};
<commit_msg>Check if shape points exists<commit_after>pontoEmbarque = "";
// Iniciando o mapa
var map = L.map('map', {
    zoomControl: false
}).setView([-21.786, -46.566], 15);

L.control.zoom({
    position: 'bottomright'
}).addTo(map);

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
}).addTo(map);

var helloPopup = L.popup().setContent('Hello World!');

L.easyButton({
    id: 'id-for-the-button', // an id for the generated button
    position: 'bottomright', // inherited from L.Control -- the corner it goes in
    type: 'replace', // set to animate when you're comfy with css
    leafletClasses: true, // use leaflet classes to style the button?
    states: [{ // specify different icons and responses for your button
        stateName: 'get-center',
        onClick: function(button, map) {
            alert('Map is centered at: ' + map.getCenter().toString());
        },
        title: 'show me the middle',
        icon: 'fa-crosshairs'
    }]
}).addTo(map);

// Criando camada para desenhar no mapa
var markers = new L.FeatureGroup();

// Generator que desenha no mapa e html
var Generator = {};

var listaRotas = [];

/* Metodos da classe Generator */

// Draws a stop on the map, with the position and agency name.
Generator.drawAgencyStop = function (data) {

    obj = JSON.parse(data);

    L.marker([37.972117, -122.032526], {
            icon: agencyMarker
        }).addTo(map)
        .bindPopup(Generator.drawAgencyPopup(obj.agency_name, obj.agency_url, obj.agency_timezone, obj.agency_lang))
        .openPopup();

    map.setView(new L.LatLng(37.972117, -122.032526), 10);
};

// Draws a popup on the stop, with the agency's information.
Generator.drawAgencyPopup = function(agency_name, agency_url, agency_timezone, agency_lang) {
    var html = "";

    html += "
 " + agency_name + "
" +
        "
Visit Agency!
" +
        "
" + agency_timezone + " - " + agency_lang + "

";

    return html;

};

// Generates the HTML code a list of routes
Generator.drawRoutesList = function(data) {

    obj = JSON.parse(data);

    for (var x = 0; x < obj.length; x++) {

        var route_name = obj[x].route_short_name + ": " + obj[x].route_long_name;

        $("#routes").append("<option value='" + obj[x].route_id + "'>" + route_name + "</option>");

        // Coloca as rotas em uma lista, para ser usada no typeahead
        listaRotas.push(route_name);

        //if ((route_name.search("Metr") > 0) || (route_name.search("metr") != -1)){
        //console.log("é metro ->" + route_name);
        //}
    }

};

// Draws a line between the points of shape
Generator.drawShapes = function(data) {

    var obj = JSON.parse(data);

    // Check if shape points exists
    if(!(obj[0] === undefined || obj[0] === null)){
      var latlngs = Array();

      for (var y = 0; y < obj[0].length; y++) {
          var marker = L.marker([obj[0][y].shape_pt_lat, obj[0][y].shape_pt_lon], {
              icon: greenIcon
          });
          //markers.addLayer(marker);
          latlngs.push(marker.getLatLng());
      }

      //map.addLayer(markers);

      // create a polyline from an arrays of LatLng points
      var polyline = L.polyline(latlngs, {
          color: '#3498db'
      }).addTo(map);
      markers.addLayer(polyline);
      map.addLayer(markers);
      // zoom the map to the polyline
      map.fitBounds(polyline.getBounds());
      map.setZoom(10);

    }
};

Generator.drawStopsNear = function(data) {

    obj = JSON.parse(data);
    /*
    for (var y = 0; y < 1; y++) {
      var marker = L.marker([obj[y].stop_lat, obj[y].stop_lon], {icon: redMarker}).bindPopup(Generator.drawStopsPopup(obj[y].stop_id, obj[y].stop_name, obj[y].stop_desc));
      markers.addLayer(marker);

    }

    map.addLayer(markers);
    */
    pontoEmbarque = obj[0].stop_name;
    settings.boarding_stop = obj[0].stop_name;
    boarding_stop_id = obj[0].stop_id;

    var url = "http://127.0.0.1:8000/api/routesbystop?agency_id=SPTRANS&stop_id=" + obj[0].stop_id;
    console.log(url);
    getApi(url, test);
};

function test(data) {
    obj = JSON.parse(data);
    console.log(obj);
    //var url = "http://127.0.0.1:8124/api/shapes?agency_key=county-connection&route_id=" + obj[0].route_id + "&direction_id=0";
    //get(url, "shapes");
    url = "http://127.0.0.1:8000/api/stops?agency_key=SPTRANS&route_id=" + obj[0].route_id + "&direction_id=0";
    console.log(url);
    //get(url, "stops");
    getApi(url, Generator.drawStops);
}

// Draw stops on map
Generator.drawStops = function(data) {

    var marker;
    var stop_name;
    var stop_id;
    var boarding_stop;
    var landing_stop;

    obj = JSON.parse(data);

    for (var y = 0; y < obj.length; y++) {
      stop_name = obj[y].stop_name;
      boarding_stop = settings.boarding_stop;

      //console.log("Nome do stop atual: " + stop_name);
      //console.log("Nome do boarding stop: " + boarding_stop);
      if (stop_name !== boarding_stop){
        marker = L.marker([obj[y].stop_lat, obj[y].stop_lon], {
            icon: redMarker
        }).bindPopup(Generator.drawStopsPopup(obj[y].stop_id, obj[y].stop_name, obj[y].stop_desc));
      } else {
        console.log("FOI IGUAL");
        marker = L.marker([obj[y].stop_lat, obj[y].stop_lon], {
            icon: boardingMarker
        }).bindPopup(Generator.drawStopsPopup(obj[y].stop_id, obj[y].stop_name, obj[y].stop_desc));
        $("#melhoresLinhas").html(boarding_stop);
      }

      markers.addLayer(marker);

    }

    map.addLayer(markers);

};

// Draws the pop-up stopping points on the map
Generator.drawStopsPopup = function(stop_id, stop_name, stops_desc) {
    var html = "";

    html += "
" +
        "
" + stop_name + "
" +
        "
" + stops_desc + "

";

    return html;

};

Generator.print = function() {
  console.log("Print");
};
<|endoftext|>