<commit_before>/**
 * Created by Spinpoo on 2015-02-20.
 */
var socket = io();
var operationId;
var oldText;
var saved = false;

$(document).ready(function() {
  // Load comments
  operationId = $('#opName').attr('data-operationId');
  var rows = $('.check-js');

  // Set the color of the comment button depending on if there is a comment.
  rows.each(function(index, row) {
    var comment = $('#checkComment' + row.id);
    var commentButton = $('#commentButton' + row.id);
    changeCommentButton(comment, commentButton);
  });

  // Add click events to table rows in the checklist
  var container = $('.container');
  container.on("click", '.check-js', checkjs);

  // If the actual checkbox is clicked we will get a double-click effect. So we compensate for that here.
  /*
  container.on("click", '.checkbox-js', function() {
    this.checked = !this.checked;
  });
  */

  // TODO: Comment this
  var processContent = $('.process-content');
  processContent.on("click", '.cancelComment', cancelComment);
  processContent.on("click", '.saveComment', saveComment);
  processContent.on("click", '.showComment', showComment);

  // TODO: Comment this
  var articleTable = $('.articleTable tbody');
  articleTable.on("click", '.article-remove', removeArticle);
  articleTable.on("click", '.minus-field', minusOne);
  articleTable.on("click", '.plus-field', plusOne);

  // Load templates and compile them.
  var unCompiledArticle = $('#article-template').html();
  var articleTemplate = Handlebars.compile(unCompiledArticle);
  var unCompiledComment = $('#comment-template').html();
  var commentTemplate = Handlebars.compile(unCompiledComment);

  // Checks if all boxes are checked.
  checkBoxes();

  // Listen to sockets (backend sockets in lib/checklist.js)
  socket.on('saveComment', saveCommentSocket);

  socket.on('removeCheckArticleUpdate', removeCheckArticleUpdate);

  socket.on('getCheckboxes', getCheckboxes);

  socket.on('newArticleUpdate', newArticleUpdate.bind(undefined, articleTemplate, commentTemplate));

  socket.on('articleAmountUpdate', function(amount, articleID) {
    var amountHtml = $('#amount'+articleID);
    var uneditableAmountHtml = $('#uneditableAmount'+articleID);
    amountHtml.find('.amount-field').text(amount);
    uneditableAmountHtml.find('.uneditable-amount').text(amount);
  });

  // Show saved text when the database has successfully stored the comment.
  socket.on('saved', function(id) {
    $('#commentSaved' + id).show();
  });

  // Runs after socket has been started. Get all checkbox statuses from db.
  socket.on('connect', function() {
    socket.emit('operationOpen', operationId);
  });

  socket.on('checkboxClick', function(checkObject) {
    var tableRow = $('#' + checkObject.id);
    updateTableRow(tableRow, checkObject.isChecked, false);
    checkBoxes();
  });

  socket.on('kartotekUpdate', function(checkObject) {
    var tableRow = $('#' + checkObject.id);
    updateTextInTableRow(tableRow, checkObject);
  });

});

// Definition of the minus button that appears when a checklist is edited
var minusOne = function() {
  var operationID = $(this).parent().parent().attr("data-operationId");
  var checkArticleID = $(this).parent().parent().attr('id');
  var amountField = $(this).parent().find('.amount-field');
  var oldAmount = parseInt(amountField.text());
  var newAmount = oldAmount-1;
  if (newAmount > 0) {
    $(amountField).text(newAmount);
    socket.emit('amountChange', checkArticleID, operationID, newAmount);
  }
};

// Definition of the plus button that appears when a checklist is edited.
var plusOne = function() {
  var operationID = $(this).parent().parent().attr("data-operationId");
  var checkArticleID = $(this).parent().parent().attr('id');
  var amountField = $(this).parent().find('.amount-field');
  var oldAmount = parseInt(amountField.text());
  var newAmount = oldAmount+1;
  if (newAmount > 0) {
    $(amountField).text(newAmount);
    socket.emit('amountChange', checkArticleID, operationID, newAmount);
  }
};

// Throw away texted comment if cancel button is clicked.
var cancelComment = function() {
  if (!saved) {
    var id = $(this).data('id');
    var checkComment = $('#checkComment' + id);
    checkComment.val(oldText);
  } else {
    saved = false;
  }
};

// When a checkable row is clicked, check the row and emit to socket.io
var checkjs = function(e) {
  var targetClassName = e.target.className.split(" ")[0];
  var targetTagName = e.target.tagName;
  if (!(targetTagName == 'BUTTON' || targetTagName == 'IMG' || targetClassName == 'amount' ||
        targetClassName == 'article-remove' || targetClassName == 'cross' || $('#editChecklist').is(":visible"))) {
    if (!$(this).prop('disabled')) {
      var checkbox = $(this).find('.checkbox-js');
      var preparation = $(this).hasClass("process-content-item") ? true : false;

      checkbox.toggleClass('glyphicon-ok');

      // Function in checkEffect.js
      changeTableGraphics($(this), checkbox.checked, preparation);
      var checkObject = {
        preparation: $(this).data('preparation'),
        operation: operationId, id: $(this).attr('id'),
        check: checkbox.hasClass('glyphicon-ok')
      };

      socket.emit('checkboxClick', checkObject);

      checkBoxes();

    }
  }
};

var checkBoxes = function() {
  var done = true;
  $('.checkbox-js').each(function(i, box) {
    if (!$(box).hasClass('glyphicon-ok')) {
      done = false;
      return false;
    }
  });
  if (done) {
    $('#btn-done').addClass('btn-done');
  } else {
    $('#btn-done').removeClass('btn-done');
  }
};

// Save the comment locally and emit to back-end to save in database.
var saveComment = function() {
  var id = $(this).data('id');
  var checkComment = $('#checkComment' + id);
  var commentButton = $('#commentButton' + id);

  if (checkComment.val() == "") {
    checkComment.val("-");
  }

  var commentObject = {operation: operationId, id: id, comment: checkComment.val()};

  socket.emit('saveComment', commentObject);
  changeCommentButton(checkComment, commentButton);

  checkComment.attr('disabled', true);
  $(this).attr('disabled', true);
  saved = true;
};

// Hide the "Saved" text, enable the comment field and save the old text if the user presses cancel.
var showComment = function() {
  var id = $(this).data('id');
  var checkComment = $("#checkComment" + id);

  $('#commentSaved' + id).hide();
  checkComment.attr('disabled', false);
  oldText = checkComment.val();
  $('#saveComment' + id).attr('disabled', false);
};

var removeArticle = function() {
  var checkArticleID = $(this).parent().parent().attr('id');
  var operationID = $(this).parent().parent().attr("data-operationId");

  var confirmed = confirm("Är du säker på att du vill ta bort artikeln?");
  if (confirmed) {
    socket.emit('removeCheckArticle', checkArticleID, operationID);
  } else {
    return false;
  }
};

// set checked status and update row color.
var updateTableRow = function(tableRow, isChecked, isTemplate) {
  var checkbox = tableRow.find('.checkbox-js');
  isChecked ? checkbox.addClass('glyphicon-ok') : checkbox.removeClass('glyphicon-ok');
  var preparation = tableRow.hasClass("process-content-item") ? true : false;
  if (isTemplate) {
    checkbox.prop('disabled', true);
    tableRow.prop('disabled', true);
  }

  // Function in checkEffect.js
  changeTableGraphics(tableRow, isChecked, preparation);
};

var updateTextInTableRow = function(tableRow, checkObject) {
  var kartotekArticle = checkObject.kartotekArticle;

  tableRow.find('.name').eq(0).html('
'+checkObject.name+'
');
  tableRow.find('.storage').eq(0).html(kartotekArticle.storage);
  tableRow.find('.section').eq(0).html(kartotekArticle.section);
  tableRow.find('.shelf').eq(0).html(kartotekArticle.shelf);
  tableRow.find('.tray').eq(0).html(kartotekArticle.tray);
};

var saveCommentSocket = function (commentObject) {
  var comment = $('#checkComment' + commentObject.id);
  var commentButton = $('#commentButton' + commentObject.id);
  comment.val(commentObject.comment);
  changeCommentButton(comment, commentButton);
};

var removeCheckArticleUpdate = function(checkArticleID) {
  var row = $('#'+checkArticleID);
  row.remove();
};

var getCheckboxes = function(checkboxesAndTemplate) {
  var checkboxes = checkboxesAndTemplate.checkboxes;
  var isTemplate = checkboxesAndTemplate.template;
  for (var index in checkboxes) {
    var checkbox = checkboxes[index];
    var tableRow = $('#' + checkbox._id);
    var isChecked = checkbox.checked;

    // var isDisabled = checkbox.attr("disabled");
    updateTableRow(tableRow, isChecked, isTemplate);
  }
};

var newArticleUpdate = function(articleTemplate, commentTemplate, checkArticle, kartotekArticle, operationID) {

  var inserted = false;
  var lastindex = $('.articleTable > tbody > tr').length;
  $('.articleTable > tbody > tr').each(function (index) {
    var articleName = $(this).find(".name").text();
    if (compareString(checkArticle.name, articleName)<1) {
      $('.articleTable > tbody > tr').eq( index ).before($(articleTemplate({
        kartotek : kartotekArticle, name : checkArticle.name, operation: operationID,
        _id : checkArticle._id, amount : 1
      })));
      $(commentTemplate({ kartotek: kartotekArticle, _id: checkArticle._id, comment: '' })).appendTo('#contentchecklist');
      inserted = true;
      return false;
    }
  });
  if (!inserted) {
    $('.articleTable > tbody > tr').eq( lastindex-1 ).after($(articleTemplate({
      kartotek : kartotekArticle, name : checkArticle.name, operation: operationID,
      _id : checkArticle._id, amount : 1
    })));

    $(commentTemplate({ kartotek: kartotekArticle, _id: checkArticle._id, comment: '' })).appendTo('#contentchecklist');
  }

  // TODO: refactor this later because ugly
  if ($('#editChecklistButton').text()=="Klar") {
    $('.centered-remove').show();
    $('.amountColumn').show();
    $('.uneditableAmountColumn').hide();
    $('.checkbox-js').hide();
  }
};

var compareString = function(a, b){
  var A = a.toLowerCase();
  var B = b.toLowerCase();
  if (A  B){
    return  1;
  }else{
    return 0;
  }
};
<commit_msg>An unnecessary function removed<commit_after>/**
 * Created by Spinpoo on 2015-02-20.
 */
var socket = io();
var operationId;
var oldText;
var saved = false;

$(document).ready(function() {
  // Load comments
  operationId = $('#opName').attr('data-operationId');
  var rows = $('.check-js');

  // Set the color of the comment button depending on if there is a comment.
  rows.each(function(index, row) {
    var comment = $('#checkComment' + row.id);
    var commentButton = $('#commentButton' + row.id);
    changeCommentButton(comment, commentButton);
  });

  // Add click events to table rows in the checklist
  var container = $('.container');
  container.on("click", '.check-js', checkjs);

  // TODO: Comment this
  var processContent = $('.process-content');
  processContent.on("click", '.cancelComment', cancelComment);
  processContent.on("click", '.saveComment', saveComment);
  processContent.on("click", '.showComment', showComment);

  // TODO: Comment this
  var articleTable = $('.articleTable tbody');
  articleTable.on("click", '.article-remove', removeArticle);
  articleTable.on("click", '.minus-field', minusOne);
  articleTable.on("click", '.plus-field', plusOne);

  // Load templates and compile them.
  var unCompiledArticle = $('#article-template').html();
  var articleTemplate = Handlebars.compile(unCompiledArticle);
  var unCompiledComment = $('#comment-template').html();
  var commentTemplate = Handlebars.compile(unCompiledComment);

  // Checks if all boxes are checked.
  checkBoxes();

  // Listen to sockets (backend sockets in lib/checklist.js)
  socket.on('saveComment', saveCommentSocket);

  socket.on('removeCheckArticleUpdate', removeCheckArticleUpdate);

  socket.on('getCheckboxes', getCheckboxes);

  socket.on('newArticleUpdate', newArticleUpdate.bind(undefined, articleTemplate, commentTemplate));

  socket.on('articleAmountUpdate', function(amount, articleID) {
    var amountHtml = $('#amount'+articleID);
    var uneditableAmountHtml = $('#uneditableAmount'+articleID);
    amountHtml.find('.amount-field').text(amount);
    uneditableAmountHtml.find('.uneditable-amount').text(amount);
  });

  // Show saved text when the database has successfully stored the comment.
  socket.on('saved', function(id) {
    $('#commentSaved' + id).show();
  });

  // Runs after socket has been started. Get all checkbox statuses from db.
  socket.on('connect', function() {
    socket.emit('operationOpen', operationId);
  });

  socket.on('checkboxClick', function(checkObject) {
    var tableRow = $('#' + checkObject.id);
    updateTableRow(tableRow, checkObject.isChecked, false);
    checkBoxes();
  });

  socket.on('kartotekUpdate', function(checkObject) {
    var tableRow = $('#' + checkObject.id);
    updateTextInTableRow(tableRow, checkObject);
  });

});

// Definition of the minus button that appears when a checklist is edited
var minusOne = function() {
  var operationID = $(this).parent().parent().attr("data-operationId");
  var checkArticleID = $(this).parent().parent().attr('id');
  var amountField = $(this).parent().find('.amount-field');
  var oldAmount = parseInt(amountField.text());
  var newAmount = oldAmount-1;
  if (newAmount > 0) {
    $(amountField).text(newAmount);
    socket.emit('amountChange', checkArticleID, operationID, newAmount);
  }
};

// Definition of the plus button that appears when a checklist is edited.
var plusOne = function() {
  var operationID = $(this).parent().parent().attr("data-operationId");
  var checkArticleID = $(this).parent().parent().attr('id');
  var amountField = $(this).parent().find('.amount-field');
  var oldAmount = parseInt(amountField.text());
  var newAmount = oldAmount+1;
  if (newAmount > 0) {
    $(amountField).text(newAmount);
    socket.emit('amountChange', checkArticleID, operationID, newAmount);
  }
};

// Throw away texted comment if cancel button is clicked.
var cancelComment = function() {
  if (!saved) {
    var id = $(this).data('id');
    var checkComment = $('#checkComment' + id);
    checkComment.val(oldText);
  } else {
    saved = false;
  }
};

// When a checkable row is clicked, check the row and emit to socket.io
var checkjs = function(e) {
  var targetClassName = e.target.className.split(" ")[0];
  var targetTagName = e.target.tagName;
  if (!(targetTagName == 'BUTTON' || targetTagName == 'IMG' || targetClassName == 'amount' ||
        targetClassName == 'article-remove' || targetClassName == 'cross' || $('#editChecklist').is(":visible"))) {
    if (!$(this).prop('disabled')) {
      var checkbox = $(this).find('.checkbox-js');
      var preparation = $(this).hasClass("process-content-item") ? true : false;

      checkbox.toggleClass('glyphicon-ok');

      // Function in checkEffect.js
      changeTableGraphics($(this), checkbox.checked, preparation);
      var checkObject = {
        preparation: $(this).data('preparation'),
        operation: operationId, id: $(this).attr('id'),
        check: checkbox.hasClass('glyphicon-ok')
      };

      socket.emit('checkboxClick', checkObject);

      checkBoxes();

    }
  }
};

var checkBoxes = function() {
  var done = true;
  $('.checkbox-js').each(function(i, box) {
    if (!$(box).hasClass('glyphicon-ok')) {
      done = false;
      return false;
    }
  });
  if (done) {
    $('#btn-done').addClass('btn-done');
  } else {
    $('#btn-done').removeClass('btn-done');
  }
};

// Save the comment locally and emit to back-end to save in database.
var saveComment = function() {
  var id = $(this).data('id');
  var checkComment = $('#checkComment' + id);
  var commentButton = $('#commentButton' + id);

  if (checkComment.val() == "") {
    checkComment.val("-");
  }

  var commentObject = {operation: operationId, id: id, comment: checkComment.val()};

  socket.emit('saveComment', commentObject);
  changeCommentButton(checkComment, commentButton);

  checkComment.attr('disabled', true);
  $(this).attr('disabled', true);
  saved = true;
};

// Hide the "Saved" text, enable the comment field and save the old text if the user presses cancel.
var showComment = function() {
  var id = $(this).data('id');
  var checkComment = $("#checkComment" + id);

  $('#commentSaved' + id).hide();
  checkComment.attr('disabled', false);
  oldText = checkComment.val();
  $('#saveComment' + id).attr('disabled', false);
};

var removeArticle = function() {
  var checkArticleID = $(this).parent().parent().attr('id');
  var operationID = $(this).parent().parent().attr("data-operationId");

  var confirmed = confirm("Är du säker på att du vill ta bort artikeln?");
  if (confirmed) {
    socket.emit('removeCheckArticle', checkArticleID, operationID);
  } else {
    return false;
  }
};

// set checked status and update row color.
var updateTableRow = function(tableRow, isChecked, isTemplate) {
  var checkbox = tableRow.find('.checkbox-js');
  isChecked ? checkbox.addClass('glyphicon-ok') : checkbox.removeClass('glyphicon-ok');
  var preparation = tableRow.hasClass("process-content-item") ? true : false;
  if (isTemplate) {
    checkbox.prop('disabled', true);
    tableRow.prop('disabled', true);
  }

  // Function in checkEffect.js
  changeTableGraphics(tableRow, isChecked, preparation);
};

var updateTextInTableRow = function(tableRow, checkObject) {
  var kartotekArticle = checkObject.kartotekArticle;

  tableRow.find('.name').eq(0).html('
'+checkObject.name+'
');
  tableRow.find('.storage').eq(0).html(kartotekArticle.storage);
  tableRow.find('.section').eq(0).html(kartotekArticle.section);
  tableRow.find('.shelf').eq(0).html(kartotekArticle.shelf);
  tableRow.find('.tray').eq(0).html(kartotekArticle.tray);
};

var saveCommentSocket = function (commentObject) {
  var comment = $('#checkComment' + commentObject.id);
  var commentButton = $('#commentButton' + commentObject.id);
  comment.val(commentObject.comment);
  changeCommentButton(comment, commentButton);
};

var removeCheckArticleUpdate = function(checkArticleID) {
  var row = $('#'+checkArticleID);
  row.remove();
};

var getCheckboxes = function(checkboxesAndTemplate) {
  var checkboxes = checkboxesAndTemplate.checkboxes;
  var isTemplate = checkboxesAndTemplate.template;
  for (var index in checkboxes) {
    var checkbox = checkboxes[index];
    var tableRow = $('#' + checkbox._id);
    var isChecked = checkbox.checked;

    // var isDisabled = checkbox.attr("disabled");
    updateTableRow(tableRow, isChecked, isTemplate);
  }
};

var newArticleUpdate = function(articleTemplate, commentTemplate, checkArticle, kartotekArticle, operationID) {

  var inserted = false;
  var lastindex = $('.articleTable > tbody > tr').length;
  $('.articleTable > tbody > tr').each(function (index) {
    var articleName = $(this).find(".name").text();
    if (compareString(checkArticle.name, articleName)<1) {
      $('.articleTable > tbody > tr').eq( index ).before($(articleTemplate({
        kartotek : kartotekArticle, name : checkArticle.name, operation: operationID,
        _id : checkArticle._id, amount : 1
      })));
      $(commentTemplate({ kartotek: kartotekArticle, _id: checkArticle._id, comment: '' })).appendTo('#contentchecklist');
      inserted = true;
      return false;
    }
  });
  if (!inserted) {
    $('.articleTable > tbody > tr').eq( lastindex-1 ).after($(articleTemplate({
      kartotek : kartotekArticle, name : checkArticle.name, operation: operationID,
      _id : checkArticle._id, amount : 1
    })));

    $(commentTemplate({ kartotek: kartotekArticle, _id: checkArticle._id, comment: '' })).appendTo('#contentchecklist');
  }

  // TODO: refactor this later because ugly
  if ($('#editChecklistButton').text()=="Klar") {
    $('.centered-remove').show();
    $('.amountColumn').show();
    $('.uneditableAmountColumn').hide();
    $('.checkbox-js').hide();
  }
};

var compareString = function(a, b){
  var A = a.toLowerCase();
  var B = b.toLowerCase();
  if (A  B){
    return  1;
  }else{
    return 0;
  }
};
<|endoftext|>


<commit_before>'use strict';

var $ = window.$;

$(document).ready(function() {

    $('.cv-viewer').click(function() {
        /// need to write file before iframe injection

        var candidateName = $(this).data('candidate-name');
        var cvid = $(this).data('cvid');
        var vid = $(this).data('vid');
        var agencyEmail = $(this).data('agency-email');
        var agencyId = $(this).data('agency-id');
        var jobTitle = $(this).data('job-title');
        var cvUrl = $(this).data('url');
        var msDocumentTypes = ['doc', 'docx'];

        const ext = cvUrl.substr(cvUrl.lastIndexOf('.')+1);

        // FLOW: checkIfFileNameAlreadyDownloaded
        // If downloaded - open in iframe
        // If not downloaded - downloadFile

        isFileAlreadyDownloaded(cvUrl, (filePath) => {
          if (filePath !== 'notFound') {
            console.log('FILE FOUND');
            openViewer(filePath);
            // checkFileExtension(fileName, () => {
            //
            // })
          } else {
            console.log('NOT FOUND :\'\()');
            downloadFile(cvUrl, (filePath) => {

            })
          }
        });

    });
});

var isFileAlreadyDownloaded = (cvUrl, callback) => {
//AJAX request to do fs.readdirSync --> check if file already exists
  $.ajax({
      url: '/client/file-exists',
      data: {
          cvUrl: cvUrl,
      },
      async: true,
      success: function(response) {
        console.log('!!!!!', response);
        callback(response);
      }
  });
}

var downloadFile = (filePath, callback) => {
}

var openViewer = (filePath) => {
  var src = "/public/assets/ViewerJS/#../Downloads/" + filePath;
  $('iframe').attr('src', src);
  $('.ui.basic.doc-viewer.modal').modal('show');
}

var rejectApplication = () => {
  $('.first.modal.reject-modal').modal('show');

  var $inputs = $('input[name=rejection-reason]');
  $('input[name=rejection-reason]').change(function() {
      if (this.checked) $inputs.not(this).prop('checked', !this.checked);
  });

  $('.confirm-rejection-button').click(function() {
      $('.first.modal.reject').modal('hide');
      $('.second.modal.reject-modal').modal('show', '.first.modal .button');
      $('.second.coupled.modal.accept-modal').modal('hide');

      var reason = $('input[name="rejection-reason"]:checked').val();

      $.ajax({
          url: '/client/job/reject',
          data: {
              candidateName: candidateName,
              cvid: cvid,
              vid: vid,
              email: agencyEmail,
              reason: reason
          },
          async: true,
          success: function(res) {
              if (res) {
                  var element = document.getElementById(cvid);
                  element.remove();
                  $('.ui.basic.doc-viewer.modal').modal('hide');

                  if ($('.listView').length === 0) {
                      $('.message').html('There are no candidates yet!');
                  }
              }
          }
      });
  });
}
<commit_msg>committing before battery dies (again)<commit_after>'use strict';

var $ = window.$;

$(document).ready(function() {

    $('.cv-viewer').click(function() {
        /// need to write file before iframe injection

        var candidateName = $(this).data('candidate-name');
        var cvid = $(this).data('cvid');
        var vid = $(this).data('vid');
        var agencyEmail = $(this).data('agency-email');
        var agencyId = $(this).data('agency-id');
        var jobTitle = $(this).data('job-title');
        var cvUrl = $(this).data('url');
        var msDocumentTypes = ['doc', 'docx'];

        const ext = cvUrl.substr(cvUrl.lastIndexOf('.')+1);

        // FLOW: checkIfFileNameAlreadyDownloaded
        // If downloaded - open in iframe
        // If not downloaded - downloadFile

        isFileAlreadyDownloaded(cvUrl, (filePath) => {
          if (filePath !== 'notFound') {
            console.log('FILE FOUND');
            openViewer(filePath);
            // checkFileExtension(fileName, () => {
            //
            // })
          } else {
            console.log('NOT FOUND :\'\()');
            downloadFile(cvUrl, (filePath) => {

            })
          }
        });

    });
});

var isFileAlreadyDownloaded = (cvUrl, callback) => {
//AJAX request to do fs.readdirSync --> check if file already exists
  $.ajax({
      url: '/client/file-exists',
      data: {
          cvUrl: cvUrl,
      },
      async: true,
      success: function(response) {
        console.log('!!!!!', response);
        callback(response);
      }
  });
}

var downloadFile = (filePath, callback) => {
}

var openViewer = (filePath) => {
  var src = "/public/assets/ViewerJS/#../Downloads/" + filePath;
  $('iframe').attr('src', src);
  $('.ui.basic.doc-viewer.modal').modal('show');
  $('.reject').click(rejectApplication());
}

var rejectApplication = () => {
  $('.first.modal.reject-modal').modal('show');

  var $inputs = $('input[name=rejection-reason]');
  $('input[name=rejection-reason]').change(function() {
      if (this.checked) $inputs.not(this).prop('checked', !this.checked);
  });

  $('.confirm-rejection-button').click(function() {
      $('.first.modal.reject').modal('hide');
      $('.second.modal.reject-modal').modal('show', '.first.modal .button');
      $('.second.coupled.modal.accept-modal').modal('hide');

      var reason = $('input[name="rejection-reason"]:checked').val();

      $.ajax({
          url: '/client/job/reject',
          data: {
              candidateName: candidateName,
              cvid: cvid,
              vid: vid,
              email: agencyEmail,
              reason: reason
          },
          async: true,
          success: function(res) {
              if (res) {
                  var element = document.getElementById(cvid);
                  element.remove();
                  $('.ui.basic.doc-viewer.modal').modal('hide');

                  if ($('.listView').length === 0) {
                      $('.message').html('There are no candidates yet!');
                  }
              }
          }
      });
  });
}

var acceptApplication = () => {

}
<|endoftext|>


<commit_before>function split( val ) {
	return val.split( /,\s*/ );
}

function extractLast( term ) {
	return split( term ).pop();
}

$( document ).ready(function() {
	var groups = $('.tokenfield').attr('data-groups').split(',');
	$('.tokenfield').tokenfield({
		autocomplete: {
			source: function( request, response ) {
				// delegate back to autocomplete, but extract the last term
				response( $.ui.autocomplete.filter(
					groups, extractLast( request.term )));
			},
			focus: function() {
				// prevent value inserted on focus
				return false;
			},
			select: function( event, ui ) {
				var terms = split( this.value );
				// remove the current input
				terms.pop();
				// add the selected item
				terms.push( ui.item.value );
				// add placeholder to get the comma-and-space at the end
				terms.push( "" );
				this.value = terms.join( ", " );
				return false;
			},
			delay: 100
		},
		showAutocompleteOnFocus: true
	});
});
<commit_msg>Add check if tokenfield exists<commit_after>function split( val ) {
	return val.split( /,\s*/ );
}

function extractLast( term ) {
	return split( term ).pop();
}

$( document ).ready(function() {
    if ($('.tokenfield').length) {
        var groups = $('.tokenfield').attr('data-groups').split(',');
        $('.tokenfield').tokenfield({
            autocomplete: {
                source: function( request, response ) {
                    // delegate back to autocomplete, but extract the last term
                    response( $.ui.autocomplete.filter(
                        groups, extractLast( request.term )));
                },
                focus: function() {
                    // prevent value inserted on focus
                    return false;
                },
                select: function( event, ui ) {
                    var terms = split( this.value );
                    // remove the current input
                    terms.pop();
                    // add the selected item
                    terms.push( ui.item.value );
                    // add placeholder to get the comma-and-space at the end
                    terms.push( "" );
                    this.value = terms.join( ", " );
                    return false;
                },
                delay: 100
            },
            showAutocompleteOnFocus: true
        });
    }
});
<|endoftext|>


<commit_before>function resizeNarrative() {
    $('#map,#narrative,#story,#map,body,html,#loadingDiv').css({
        'height': $(window).height()-54
    });
}
resizeNarrative();

function resetLoadingLocation() {
    $("#loading").css("left", ($("#mapDiv").width() - $("#narrative").width()) / 2);
}
resetLoadingLocation();

var resizeTimeout = -1;

$(window).resize(function() {
    clearTimeout(resizeTimeout);
    resizeTimeout = setTimeout(resizeNarrative, 500);
});

var map, layer, symbol, infoTemplate, query, featureLayer;
var visible = [];
var firstSet = true;
var oldLayer = 0;

require([
    "esri/Color",
    "esri/map",
    "esri/geometry/Extent",
    "esri/dijit/Scalebar",
    "esri/layers/FeatureLayer",
    "esri/layers/LayerDrawingOptions",
    "esri/renderers/DotDensityRenderer",
    "esri/renderers/ScaleDependentRenderer",
    "esri/InfoTemplate",
    "esri/layers/ArcGISTiledMapServiceLayer",
    "esri/tasks/query"
], function(Color, Map, Extent, Scalebar, FeatureLayer, LayerDrawingOptions, DotDensityRenderer, ScaleDependentRenderer, InfoTemplate, ArcGISTiledMapServiceLayer, Query) {
    console.log($("#loading").css('left'));
    map = new Map("mapDiv", {
        //center: [-100.425, 47],
        //zoom: 8,
        extent: new Extent({"xmin":-663458,"ymin":924230,"xmax":0,"ymax":1336294,"spatialReference":{"wkid":102003}}),
        maxScale: 1000000,
        minScale: 5000000
        //basemap: "topo"
    });

    // add the basemap
    /*
    var streets = new ArcGISTiledMapServiceLayer("http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer", {
        opacity: 0.0,
        showAttribution: false
    });
    map.addLayer(streets);
    */

    layer = new esri.layers.ArcGISDynamicMapServiceLayer(mapUrl);
    //layer.setDisableClientCaching(true);

    var featureLayer = new FeatureLayer("http://undgeography.und.edu/geographyund/rest/services/ND125/WebMapND125/MapServer/" + getCurrentLayer(), {
          outFields: ["*"]
    });
    console.log(featureLayer);

    // create our slider
    layer.on("load", function(e) {
        values = [];
        for(i=1886; i<=2015; i++) {
        //$.each(startYears, function(index, value) {
            //console.log(index);
            //console.log(layer.layerInfos[value]);
            values.push(i);
        //});
        }
        console.log(values);

        min = values[0];
        max = values[values.length-1];
        difference = (max - min);
        range = {
            'min': min,
            'max': max
        };

        $.each(values, function(index, value) {
            range['' + (100 - ((max - value) / difference * 100.0)) + '%'] = value;
        });
        console.log(range);

        $("#toggleSlider").noUiSlider({
            start: values[0],
            range: range,
            snap: true
        });

        $('#toggleSlider').noUiSlider_pips({
            mode: 'values',
            density: 10,
            values: values,
            stepped: true
        });

        // create a function for when the slider value is set
        $('#toggleSlider').on('set', function() {
            if (!firstSet) {
                map.graphics.clear();
            } else {
                firstSet = false;
            }
            map.infoWindow.hide();
            map.infoWindow.clearFeatures();
            showLoading();

            // prepare our layers for filtering
            currentLayers = [];
            $.each(backgroundLayers, function(index, value) {
                currentLayers.push(value);
            });

            // find the index of this layer
            //currentLayers.push(getCurrentLayer());

            // show the visible layers
            layer.setVisibleLayers(currentLayers);

            // see if we should scroll to a new layer
            /*
            for (var iYear = 0; iYear < startYears.length; ++iYear) {
                if (startYears[iYear] <= $(this).val()) {
                    if (endYears[iYear] > $(this).val() && iYear != oldLayer) {
                        // jump to new content
                        oldLayer = iYear;
                        console.log("Offset: " + $('#title' + iYear).offset().top + $("#story:not(:animated)").scrollTop() - 54);
                        $('#story').animate({
                            scrollTop: $('#title' + iYear).offset().top + $("#story:not(:animated)").scrollTop() - 54
                        }, 'slow');
                        break;
                    }
                }
            }
            */
            oldYear = $(this).val();

            // remove all styling from legendDiv
            $("#legendDiv").attr("style", "");

            // FILTER WITH
            var iYear = Math.floor($(this).val());
            var query = new Query();
            query.where = "BUILT_YR <= " + iYear + " and ABAND_YR > " + iYear;
            query.returnGeometry = true;

            console.log(iYear);
            console.log(query);

            featureLayer.queryFeatures(query, function(featureSet) {
                //remove all graphics on the maps graphics layer
                map.graphics.clear();
                console.log(featureSet);

                //QueryTask returns a featureSet.  Loop through features in the featureSet and add them to the map.
                dojo.forEach(featureSet.features, function(feature) {
                    // add the features
                    var graphic = feature;
                    graphic.setSymbol(symbol);

                    //Add graphic to the map graphics layer.
                    map.graphics.add(graphic);
                });

                map.graphics.redraw();
            });

            // update the renderer
            /*
            var field = "Y" + Math.floor($(this).val());
            featureLayer.setInfoTemplate(new InfoTemplate("${NAME}, ND", "Railroads: ${" + field + ":NumberFormat}"));

            console.log(field);
            console.log(featureLayer);

            var renderer = new ScaleDependentRenderer({
                rendererInfos: [{
                    renderer: new DotDensityRenderer({
                      fields: [{
                        name: field,
                        color: new Color("#CC8800")
                      }],
                      dotValue: 200,
                      dotSize: 1
                    }),
                    maxScale: 2600000,
                    minScale: 6000000
                }, {
                    renderer: new DotDensityRenderer({
                      fields: [{
                        name: field,
                        color: new Color("#CC8800")
                      }],
                      dotValue: 100,
                      dotSize: 1
                    }),
                    maxScale: 1100000,
                    minScale: 2600000
                }, {
                    renderer: new DotDensityRenderer({
                      fields: [{
                        name: field,
                        color: new Color("#CC8800")
                      }],
                      dotValue: 50,
                      dotSize: 1
                    }),
                    maxScale: 0,
                    minScale: 1100000
                }]
            });

            featureLayer.setRenderer(renderer);
            */

            featureLayer.refresh();
        });

        // set as the current layer
        oldLayer = 0;
        $('#toggleSlider').val(min);

        //layer.setScaleRange(0, 0);
        layer.setVisibility(true);
    });

    // hide the loading icon when the dynamic layer finishes updating
    layer.on("update-end", hideLoading);

    // add the layer to the map
    map.addLayer(layer);
    map.addLayers([featureLayer]);

    // show the scalebar
    var scalebar = new Scalebar({
        map: map,
        scalebarUnit: "dual"
    });

    /*
    var legend = new Legend({
        map: map
    }, "legendDiv");
    legend.startup();
    */
});

function getCurrentLayer() {
    // find the index of this layer
    return 34;
}

function ToggleLayer(id) {
    map.graphics.clear();
    map.infoWindow.hide();
    map.infoWindow.clearFeatures();

    showLoading();
}

function hideLoading() {
    $("#loadingDiv").hide();
    $("#togglableLayers").removeAttr('disabled');
}

function showLoading() {
    $("#loadingDiv").show();
    $("#togglableLayers").attr('disabled', 'disabled');
}

$('#slider').click(function() {
    if ($(this).hasClass('expanded')) {
        $('#story').fadeOut(function() {
            $('#narrative').animate({width: 45});
            $('#mapWrapper').animate({right: 45}, function() {
                map.resize(true);
                map.reposition(true);
            });
            $('#slider').removeClass('expanded').find('i').removeClass('glyphicon-chevron-right').addClass('glyphicon-chevron-left');
            resetLoadingLocation();
        });
    }
    else {
        $('#narrative').animate({width: 460}, function() {
            $('#slider').addClass('expanded').find('i').addClass('glyphicon-chevron-right').removeClass('glyphicon-chevron-left');
            $('#story').fadeIn();
            $('#mapWrapper').animate({right: 460}, function() {
                map.resize(true);
                map.reposition(true);
            });
            resetLoadingLocation();
        });
    }
});

$(function() {
    $('[data-toggle="tooltip"]').tooltip();
});
<commit_msg>Changes to Railroad<commit_after>function resizeNarrative() {
    $('#map,#narrative,#story,#map,body,html,#loadingDiv').css({
        'height': $(window).height()-54
    });
}
resizeNarrative();

function resetLoadingLocation() {
    $("#loading").css("left", ($("#mapDiv").width() - $("#narrative").width()) / 2);
}
resetLoadingLocation();

var resizeTimeout = -1;

$(window).resize(function() {
    clearTimeout(resizeTimeout);
    resizeTimeout = setTimeout(resizeNarrative, 500);
});

var map, layer, symbol, infoTemplate, query, featureLayer;
var visible = [];
var firstSet = true;
var oldLayer = 0;

require([
    "esri/Color",
    "esri/map",
    "esri/geometry/Extent",
    "esri/dijit/Scalebar",
    "esri/layers/FeatureLayer",
    "esri/layers/LayerDrawingOptions",
    "esri/renderers/DotDensityRenderer",
    "esri/renderers/ScaleDependentRenderer",
    "esri/InfoTemplate",
    "esri/layers/ArcGISTiledMapServiceLayer",
    "esri/tasks/query"
], function(Color, Map, Extent, Scalebar, FeatureLayer, LayerDrawingOptions, DotDensityRenderer, ScaleDependentRenderer, InfoTemplate, ArcGISTiledMapServiceLayer, Query) {
    console.log($("#loading").css('left'));
    map = new Map("mapDiv", {
        //center: [-100.425, 47],
        //zoom: 8,
        extent: new Extent({"xmin":-663458,"ymin":924230,"xmax":0,"ymax":1336294,"spatialReference":{"wkid":102003}}),
        maxScale: 1000000,
        minScale: 5000000
        //basemap: "topo"
    });

    // add the basemap
    /*
    var streets = new ArcGISTiledMapServiceLayer("http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer", {
        opacity: 0.0,
        showAttribution: false
    });
    map.addLayer(streets);
    */

    layer = new esri.layers.ArcGISDynamicMapServiceLayer(mapUrl);
    //layer.setDisableClientCaching(true);

    var featureLayer = new FeatureLayer("http://undgeography.und.edu/geographyund/rest/services/ND125/WebMapND125/MapServer/" + getCurrentLayer(), {
          outFields: ["*"]
    });
    console.log(featureLayer);

    // create our slider
    layer.on("load", function(e) {
        values = [];
        for(i=1886; i<=2015; i++) {
        //$.each(startYears, function(index, value) {
            //console.log(index);
            //console.log(layer.layerInfos[value]);
             if (i == 1886) {
             values.push(i);
             }
             if (i % 5 == 0) {
                values.push(i);
             }
        //});
        }
        console.log(values);

        min = values[0];
        max = values[values.length-1];
        difference = (max - min);
        range = {
            'min': min,
            'max': max
        };

        $.each(values, function(index, value) {
            range['' + (100 - ((max - value) / difference * 100.0)) + '%'] = value;
        });
        console.log(range);

        $("#toggleSlider").noUiSlider({
            start: values[0],
            range: range,
            snap: true
        });

        $('#toggleSlider').noUiSlider_pips({
            mode: 'values',
            density: 10,
            values: values,
            stepped: true
        });

        // create a function for when the slider value is set
        $('#toggleSlider').on('set', function() {
            if (!firstSet) {
                map.graphics.clear();
            } else {
                firstSet = false;
            }
            map.infoWindow.hide();
            map.infoWindow.clearFeatures();
            showLoading();

            // prepare our layers for filtering
            currentLayers = [];
            $.each(backgroundLayers, function(index, value) {
                currentLayers.push(value);
            });

            // find the index of this layer
            //currentLayers.push(getCurrentLayer());

            // show the visible layers
            layer.setVisibleLayers(currentLayers);

            // see if we should scroll to a new layer
            /*
            for (var iYear = 0; iYear < startYears.length; ++iYear) {
                if (startYears[iYear] <= $(this).val()) {
                    if (endYears[iYear] > $(this).val() && iYear != oldLayer) {
                        // jump to new content
                        oldLayer = iYear;
                        console.log("Offset: " + $('#title' + iYear).offset().top + $("#story:not(:animated)").scrollTop() - 54);
                        $('#story').animate({
                            scrollTop: $('#title' + iYear).offset().top + $("#story:not(:animated)").scrollTop() - 54
                        }, 'slow');
                        break;
                    }
                }
            }
            */
            oldYear = $(this).val();

            // remove all styling from legendDiv
            $("#legendDiv").attr("style", "");

            // FILTER WITH
            var iYear = Math.floor($(this).val());
            var query = new Query();
            query.where = "BUILT_YR <= " + iYear + " and ABAND_YR > " + iYear;
            query.returnGeometry = true;

            console.log(iYear);
            console.log(query);

            featureLayer.queryFeatures(query, function(featureSet) {
                //remove all graphics on the maps graphics layer
                map.graphics.clear();
                console.log(featureSet);

                //QueryTask returns a featureSet.  Loop through features in the featureSet and add them to the map.
                dojo.forEach(featureSet.features, function(feature) {
                    // add the features
                    var graphic = feature;
                    graphic.setSymbol(symbol);

                    //Add graphic to the map graphics layer.
                    map.graphics.add(graphic);
                });

                map.graphics.redraw();
            });

            // update the renderer
            /*
            var field = "Y" + Math.floor($(this).val());
            featureLayer.setInfoTemplate(new InfoTemplate("${NAME}, ND", "Railroads: ${" + field + ":NumberFormat}"));

            console.log(field);
            console.log(featureLayer);

            var renderer = new ScaleDependentRenderer({
                rendererInfos: [{
                    renderer: new DotDensityRenderer({
                      fields: [{
                        name: field,
                        color: new Color("#CC8800")
                      }],
                      dotValue: 200,
                      dotSize: 1
                    }),
                    maxScale: 2600000,
                    minScale: 6000000
                }, {
                    renderer: new DotDensityRenderer({
                      fields: [{
                        name: field,
                        color: new Color("#CC8800")
                      }],
                      dotValue: 100,
                      dotSize: 1
                    }),
                    maxScale: 1100000,
                    minScale: 2600000
                }, {
                    renderer: new DotDensityRenderer({
                      fields: [{
                        name: field,
                        color: new Color("#CC8800")
                      }],
                      dotValue: 50,
                      dotSize: 1
                    }),
                    maxScale: 0,
                    minScale: 1100000
                }]
            });

            featureLayer.setRenderer(renderer);
            */

            featureLayer.refresh();
        });

        // set as the current layer
        oldLayer = 0;
        $('#toggleSlider').val(min);

        //layer.setScaleRange(0, 0);
        layer.setVisibility(true);
    });

    // hide the loading icon when the dynamic layer finishes updating
    layer.on("update-end", hideLoading);

    // add the layer to the map
    map.addLayer(layer);
    map.addLayers([featureLayer]);

    // show the scalebar
    var scalebar = new Scalebar({
        map: map,
        scalebarUnit: "dual"
    });

    /*
    var legend = new Legend({
        map: map
    }, "legendDiv");
    legend.startup();
    */
});

function getCurrentLayer() {
    // find the index of this layer
    return 34;
}

function ToggleLayer(id) {
    map.graphics.clear();
    map.infoWindow.hide();
    map.infoWindow.clearFeatures();

    showLoading();
}

function hideLoading() {
    $("#loadingDiv").hide();
    $("#togglableLayers").removeAttr('disabled');
}

function showLoading() {
    $("#loadingDiv").show();
    $("#togglableLayers").attr('disabled', 'disabled');
}

$('#slider').click(function() {
    if ($(this).hasClass('expanded')) {
        $('#story').fadeOut(function() {
            $('#narrative').animate({width: 45});
            $('#mapWrapper').animate({right: 45}, function() {
                map.resize(true);
                map.reposition(true);
            });
            $('#slider').removeClass('expanded').find('i').removeClass('glyphicon-chevron-right').addClass('glyphicon-chevron-left');
            resetLoadingLocation();
        });
    }
    else {
        $('#narrative').animate({width: 460}, function() {
            $('#slider').addClass('expanded').find('i').addClass('glyphicon-chevron-right').removeClass('glyphicon-chevron-left');
            $('#story').fadeIn();
            $('#mapWrapper').animate({right: 460}, function() {
                map.resize(true);
                map.reposition(true);
            });
            resetLoadingLocation();
        });
    }
});

$(function() {
    $('[data-toggle="tooltip"]').tooltip();
});
<|endoftext|>


<commit_before>import 'handlebars-runtime';

import {Object as YObject, config} from 'yui';
import {Base} from 'base-build';
import {Router} from 'router';
import {PjaxBase} from 'pjax-base';
import {View} from 'view';

import GridModel from './models/grid';
import InputView from './views/input';
import OutputView from './views/output';
import DownloadView from './views/download';

var Handlebars = config.global.Handlebars,
    StartRouter = Base.create('start-router', Router, PjaxBase);

var gridModel = new GridModel(app.start.options);

var inputView = new InputView({
    defaultMQs: app.start.defaults.mediaQueries,
    model     : gridModel,
    container : '.grid-input',
    template  : Handlebars.template(app.templates.start.rows)
});

var outputView = new OutputView({
    pure             : app.pure,
    model            : gridModel,
    container        : '.grid-output',
    cssTemplate      : Handlebars.template(app.templates.start.css),
    cssOldIETemplate : Handlebars.template(app.templates.start['css-old-ie']),
    htmlTemplate     : Handlebars.template(app.templates.start.html)
});

var downloadView = new DownloadView({
    urlTemplate  : 'download?{query}',
    trackTemplate: 'return Pure.trackDownload.call(this, \'start\', \'{label}\');',
    container    : '.grid-output-download',
    model        : gridModel
});

var router = new StartRouter({
    root        : '/start/',
    linkSelector: '.grid-input a'
});

gridModel.on('update', function (e) {
    // Avoid caring about changes made to the model in the route handler.
    if (e.originEvent.src !== 'url') {
        router.save('/?' + this.toString());
    }
});

router.route('/', function (req) {
    var query = req.query;

    var attrs = {
        cols        : query.cols,
        prefix      : query.prefix,
        mediaQueries: []
    };

    delete query.cols;
    delete query.prefix;

    YObject.each(query, function (val, key) {
        attrs.mediaQueries.push({
            id: key,
            mq: val
        });
    });

    gridModel.setAttrs(attrs, {src: 'url'});

    // Render ASAP since it doesn't depend on output.
    inputView.render();

    // Fetch CSS, then render the output view.
    gridModel.load({silent: true}, function () {
        outputView.render();
        downloadView.set('query', query).render();
    });
});

inputView.attachEvents();
outputView.attachEvents();
router.upgrade();

// Force-dispatch for non-HTML5 browsers because the query params might be in
// the hash-fragment of the URL.
if (!router.get('html5')) {
    router.dispatch();
}
<commit_msg>Fix Starter Kit download button<commit_after>import 'handlebars-runtime';

import {Object as YObject, config} from 'yui';
import {Base} from 'base-build';
import {Router} from 'router';
import {PjaxBase} from 'pjax-base';
import {View} from 'view';

import GridModel from './models/grid';
import InputView from './views/input';
import OutputView from './views/output';
import DownloadView from './views/download';

var Handlebars = config.global.Handlebars,
    StartRouter = Base.create('start-router', Router, PjaxBase);

var gridModel = new GridModel(app.start.options);

var inputView = new InputView({
    defaultMQs: app.start.defaults.mediaQueries,
    model     : gridModel,
    container : '.grid-input',
    template  : Handlebars.template(app.templates.start.rows)
});

var outputView = new OutputView({
    pure             : app.pure,
    model            : gridModel,
    container        : '.grid-output',
    cssTemplate      : Handlebars.template(app.templates.start.css),
    cssOldIETemplate : Handlebars.template(app.templates.start['css-old-ie']),
    htmlTemplate     : Handlebars.template(app.templates.start.html)
});

var downloadView = new DownloadView({
    urlTemplate  : 'download?{query}',
    trackTemplate: 'return Pure.trackDownload.call(this, \'start\', \'{label}\');',
    container    : '.grid-output-download',
    model        : gridModel
});

var router = new StartRouter({
    root        : '/start/',
    linkSelector: '.grid-input a'
});

gridModel.on('update', function (e) {
    // Avoid caring about changes made to the model in the route handler.
    if (e.originEvent.src !== 'url') {
        router.save('/?' + this.toString());
    }
});

function getGridModelUpdates(query) {
    query = Y.merge(query);

    var attrs = {
        cols        : query.cols,
        prefix      : query.prefix,
        mediaQueries: []
    };

    delete query.cols;
    delete query.prefix;

    YObject.each(query, function (val, key) {
        attrs.mediaQueries.push({
            id: key,
            mq: val
        });
    });

    return attrs;
}

router.route('/', function (req) {
    var query = req.query;

    gridModel.setAttrs(getGridModelUpdates(query), {src: 'url'});

    // Render ASAP since it doesn't depend on output.
    inputView.render();

    // Fetch CSS, then render the output view.
    gridModel.load({silent: true}, function () {
        outputView.render();
        downloadView.set('query', query).render();
    });
});

inputView.attachEvents();
outputView.attachEvents();
router.upgrade();

// Force-dispatch for non-HTML5 browsers because the query params might be in
// the hash-fragment of the URL.
if (!router.get('html5')) {
    router.dispatch();
}
<|endoftext|>


<commit_before>export const CustomEvent = global.CustomEvent || (() => {
  const DEFAULT_PARAMS = {bubbles: false, cancelable: false, detail: undefined}

  function _CustomEvent (_event, _params) {
    const params = {...DEFAULT_PARAMS, ..._params}
    const event = document.createEvent(`CustomEvent`)

    event.initCustomEvent(_event, params.bubbles, params.cancelable, params.detail)
    return event
  }

  return _CustomEvent
})()
<commit_msg>Fix CustomEvent to import global/document<commit_after>import document from 'global/document'

export const CustomEvent = global.CustomEvent || (() => {
  const DEFAULT_PARAMS = {bubbles: false, cancelable: false, detail: undefined}

  function _CustomEvent (_event, _params) {
    const params = {...DEFAULT_PARAMS, ..._params}
    const event = document.createEvent(`CustomEvent`)

    event.initCustomEvent(_event, params.bubbles, params.cancelable, params.detail)
    return event
  }

  return _CustomEvent
})()
<|endoftext|>


<commit_before>var turkic_timeaccepted = (new Date()).getTime();

function mturk_parameters()
{
    var retval = new Object();
    retval.action = "http://www.mturk.com/mturk/externalSubmit";
    retval

    if (window.location.href.indexOf("?") == -1)
    {
        retval.assignmentid = null;
        retval.hitid = null;
        retval.workerid = null;
        return retval;
    }

    var params = window.location.href.split("?")[1].split("&");

    for (var i in params)
    {
        var sp = params[i].split("=");
        if (sp.length <= 1)
        {
            continue;
        }
        var result = sp[1].split("#")[0];

        if (sp[0] == "assignmentId")
        {
            retval.assignmentid = result;
        }
        else if (sp[0] == "hitId")
        {
            retval.hitid = result;
        }
        else if (sp[0] == "workerId")
        {
            retval.workerid = result;
        }
        else if (sp[0] == "turkSubmitTo")
        {
            retval.action = decodeURIComponent(result) +
                "/mturk/externalSubmit";
        }
        else
        {
            retval[sp[0]] = result;
        }
    }

    return retval;
}

function mturk_isassigned()
{
    var params = mturk_parameters();
    return params.assignmentid && params.assignmentid != "ASSIGNMENT_ID_NOT_AVAILABLE" && params.hitid && params.workerid;
}

function mturk_submit(callback)
{
    if (!mturk_isassigned())
    {
        alert("Please accept task before submitting.");
        return;
    }

    console.log("Preparing work for submission");

    var params = mturk_parameters();
    var now = (new Date()).getTime();

    $("body").append('<form method="get" id="turkic_mturk">' +
        '<input type="hidden" name="assignmentId" value="">' +
        '<input type="hidden" name="data" value="" />' +
        '</form>');

    $("#turkic_mturk input").val(params.assignmentid);
    $("#turkic_mturk").attr("action", params.action);

    // function that must be called to formally complete transaction
    function redirect()
    {
        server_request("turkic_markcomplete", [params.hitid, params.assignmentid, params.workerid], function() {
            $("#turkic_mturk").submit();
        });
    }

    var donateyes = $("#turkic_donate_yes").attr("checked") ? 1 : 0;
    server_request("turkic_savejobstats", [params.hitid, turkic_timeaccepted, now, donateyes], function() {
        callback(redirect);
    });
}

function mturk_acceptfirst()
{
    var af = $('

').prependTo("body")
    af.html("Remember to accept the task before working!");
}

function mturk_showstatistics()
{
    var stc = $('

');
    st = stc.children("#turkic_workerstatscontent");

    server_workerstats(function(data) {
        st.html("");

        var reward = $('

');
        var amount = Math.round(data["reward"] * 100);
        var bonus = Math.round(data["bonus"] * 100);

        var rewardstr = '
' + amount + ' ¢
 pay';
        if (bonus > 0)
        {
            rewardstr += ' +
' + bonus + ' ¢
 bonus';
        }

        reward.html('Reward: ' + rewardstr);
        st.append(reward);

        if (!data["newuser"])
        {
            st.append("Your record:");

            var subm = $('

');
            var submn = $('

');
            submn.html(data["numsubmitted"]);
            submn.appendTo(subm);
            subm.append(" submitted");
            subm.appendTo(st);

            var accp = $('

');
            var accpn = $('

');
            accpn.html(data["numaccepted"]);
            accpn.appendTo(accp);
            accp.append(" accepted");
            accp.appendTo(st);

            var rejt = $('

');
            var rejtn = $('

');
            rejtn.html(data["numrejected"]);
            rejtn.appendTo(rejt);
            rejt.append(" rejected");
            rejt.appendTo(st);
        }
        else
        {
            st.append("Welcome new user! Please take a minute to read the instructions.");
        }
        stc.prependTo("body");

        if (bonus > 0)
        {
            mturk_showdonate(amount, bonus);
        }
    });
}

function mturk_showdonate(reward, bonus)
{
    if ($("#turkic_donation").size())
    {
        $("#turkic_donation").show();
        $("#turkic_overlay").show();
        return;
    }

    $('

').appendTo("body");

    var str = '
Do you want to help end world hunger?
';
    str += '
We are offering our users the chance to work on behalf of a charity. When your HIT is accepted, we will pay you both your standard compensation as well as a bonus. If you choose, we can donate your bonus to charity instead.
';
    str += '
For this HIT, you will receive ' + reward + '¢ with an additional ' + bonus + '¢ bonus. If you opt to donate, your HIT will be accepted and you will receive ' + reward + '¢, but we will donate your bonus to charity.
';
    str += '
We urge you to consider donating. All proceeds will go UNICEF to fight world hunger. If every worker donates, we can collectively donate hundreds of thousands of dollars. Your actions can have an impact — all you must do is donate.
';
    str += '
';
    str += '';
    str += "Can we donate your bonus to fight world hunger?
";
    str += '<input type="radio" id="turkic_donate_yes" name="turkic_donate_option">';
    str += 'Yes, donate this bonus to UNICEF on my behalf.
';
    str += '<input type="radio" id="turkic_donate_no" name="turkic_donate_option">';
    str += 'No, I want to keep this bonus for myself.
';
    //str += '
<input type="checkbox" id="turkic_donate_notagain"> Do not show again
';
    str += '<input type="button" id="turkic_donate_close" value="Continue">';
    str += '
';
    var donation = $('

').appendTo("body");
    donation.append(str);

    var previous = document.cookie.match("(^|;) ?" + "turkic_donate" + "=([^;]*)(;|$)");
    if (previous)
    {
        if (previous[2] == 1)
        {
            $("#turkic_donate_yes").attr("checked", true);
        }
        else
        {
            $("#turkic_donate_no").attr("checked", true);
        }
    }

    $("#turkic_donate_close").click(function() {
        var donateyes = $("#turkic_donate_yes").attr("checked");
        var donateno  = $("#turkic_donate_no").attr("checked");

        if (!donateyes && !donateno)
        {
            window.alert("Please choose your donation option.");
            return;
        }

        document.cookie = "turkic_donate=" + (donateyes ? 1 : 0);

        // we need to reset the timestamp because the task doesnt start until they continue
        turkic_timeaccepted = (new Date()).getTime();

        $("#turkic_overlay").hide();
        donation.hide();
    });
}

function server_geturl(action, parameters)
{
    var url = "server/" + action;
    for (var x in parameters)
    {
        url += "/" + parameters[x];
    }
    return url;
}

function server_request(action, parameters, callback)
{
    var url = server_geturl(action, parameters);
    console.log("Server request: " + url);
    $.ajax({
        url: url,
        dataType: "json",
        success: function(data) {
            callback(data);
        },
        error: function(xhr, textstatus) {
            console.log(xhr.responseText);
            death("Server Error");
        }
    });
}

function server_post(action, parameters, data, callback)
{
    var url = server_geturl(action, parameters);
    console.log("Server post: " + url);
    $.ajax({
        url: url,
        dataType: "json",
        type: "POST",
        data: data,
        success: function(data) {
            callback(data);
        },
        error: function(xhr, textstatus) {
            console.log(xhr.responseText);
            death("Server Error");
        }
    });
}

var server_workerstats_data = null;
function server_workerstats(callback)
{
    if (server_workerstats_data == null)
    {
        var params = mturk_parameters();
        if (params.workerid)
        {
            server_request("turkic_getworkerstats",
                [params.hitid, params.workerid],
                function (data) {
                    server_workerstats_data = data;
                    callback(data);
                });
        }
    }
    else
    {
        callback(server_workerstats_data);
    }
}

function death(message)
{
    document.write("" + message);
}

if (!console)
{
    var console = new Object();
    console.log = function() {};
}
<commit_msg>some animation<commit_after>var turkic_timeaccepted = (new Date()).getTime();

function mturk_parameters()
{
    var retval = new Object();
    retval.action = "http://www.mturk.com/mturk/externalSubmit";
    retval

    if (window.location.href.indexOf("?") == -1)
    {
        retval.assignmentid = null;
        retval.hitid = null;
        retval.workerid = null;
        return retval;
    }

    var params = window.location.href.split("?")[1].split("&");

    for (var i in params)
    {
        var sp = params[i].split("=");
        if (sp.length <= 1)
        {
            continue;
        }
        var result = sp[1].split("#")[0];

        if (sp[0] == "assignmentId")
        {
            retval.assignmentid = result;
        }
        else if (sp[0] == "hitId")
        {
            retval.hitid = result;
        }
        else if (sp[0] == "workerId")
        {
            retval.workerid = result;
        }
        else if (sp[0] == "turkSubmitTo")
        {
            retval.action = decodeURIComponent(result) +
                "/mturk/externalSubmit";
        }
        else
        {
            retval[sp[0]] = result;
        }
    }

    return retval;
}

function mturk_isassigned()
{
    var params = mturk_parameters();
    return params.assignmentid && params.assignmentid != "ASSIGNMENT_ID_NOT_AVAILABLE" && params.hitid && params.workerid;
}

function mturk_submit(callback)
{
    if (!mturk_isassigned())
    {
        alert("Please accept task before submitting.");
        return;
    }

    console.log("Preparing work for submission");

    var params = mturk_parameters();
    var now = (new Date()).getTime();

    $("body").append('<form method="get" id="turkic_mturk">' +
        '<input type="hidden" name="assignmentId" value="">' +
        '<input type="hidden" name="data" value="" />' +
        '</form>');

    $("#turkic_mturk input").val(params.assignmentid);
    $("#turkic_mturk").attr("action", params.action);

    // function that must be called to formally complete transaction
    function redirect()
    {
        server_request("turkic_markcomplete", [params.hitid, params.assignmentid, params.workerid], function() {
            $("#turkic_mturk").submit();
        });
    }

    var donateyes = $("#turkic_donate_yes").attr("checked") ? 1 : 0;
    server_request("turkic_savejobstats", [params.hitid, turkic_timeaccepted, now, donateyes], function() {
        callback(redirect);
    });
}

function mturk_acceptfirst()
{
    var af = $('

').prependTo("body")
    af.html("Remember to accept the task before working!");
}

function mturk_showstatistics()
{
    var stc = $('

');
    st = stc.children("#turkic_workerstatscontent");

    server_workerstats(function(data) {
        st.html("");

        var reward = $('

');
        var amount = Math.round(data["reward"] * 100);
        var bonus = Math.round(data["bonus"] * 100);

        var rewardstr = '
' + amount + ' ¢
 pay';
        if (bonus > 0)
        {
            rewardstr += ' +
' + bonus + ' ¢
 bonus';
        }

        reward.html('Reward: ' + rewardstr);
        st.append(reward);

        if (!data["newuser"])
        {
            st.append("Your record:");

            var subm = $('

');
            var submn = $('

');
            submn.html(data["numsubmitted"]);
            submn.appendTo(subm);
            subm.append(" submitted");
            subm.appendTo(st);

            var accp = $('

');
            var accpn = $('

');
            accpn.html(data["numaccepted"]);
            accpn.appendTo(accp);
            accp.append(" accepted");
            accp.appendTo(st);

            var rejt = $('

');
            var rejtn = $('

');
            rejtn.html(data["numrejected"]);
            rejtn.appendTo(rejt);
            rejt.append(" rejected");
            rejt.appendTo(st);
        }
        else
        {
            st.append("Welcome new user! Please take a minute to read the instructions.");
        }
        stc.prependTo("body");

        if (bonus > 0)
        {
            mturk_showdonate(amount, bonus);
        }
    });
}

function mturk_showdonate(reward, bonus)
{
    if ($("#turkic_donation").size())
    {
        $("#turkic_donation").show();
        $("#turkic_overlay").show();
        return;
    }

    $('

').appendTo("body");

    var str = '
Do you want to help end world hunger?
';
    str += '
We are offering our users the chance to work on behalf of a charity. When your HIT is accepted, we will pay you both your standard compensation as well as a bonus. If you choose, we can donate your bonus to charity instead.
';
    str += '
For this HIT, you will receive ' + reward + '¢ with an additional ' + bonus + '¢ bonus. If you opt to donate, your HIT will be accepted and you will receive ' + reward + '¢, but we will donate your bonus to charity.
';
    str += '
We urge you to consider donating. All proceeds will go UNICEF to fight world hunger. If every worker donates, we can collectively donate hundreds of thousands of dollars. Your actions can have an impact — all you must do is donate.
';
    str += '
';
    str += '';
    str += "Can we donate your bonus to fight world hunger?
";
    str += '<input type="radio" id="turkic_donate_yes" name="turkic_donate_option">';
    str += 'Yes, donate this bonus to UNICEF on my behalf.
';
    str += '<input type="radio" id="turkic_donate_no" name="turkic_donate_option">';
    str += 'No, I want to keep this bonus for myself.
';
    //str += '
<input type="checkbox" id="turkic_donate_notagain"> Do not show again
';
    str += '<input type="button" id="turkic_donate_close" value="Continue">';
    str += '
';
    var donation = $('

').appendTo("body");
    donation.append(str);

    var previous = document.cookie.match("(^|;) ?" + "turkic_donate" + "=([^;]*)(;|$)");
    if (previous)
    {
        if (previous[2] == 1)
        {
            $("#turkic_donate_yes").attr("checked", true);
        }
        else
        {
            $("#turkic_donate_no").attr("checked", true);
        }
    }

    $("#turkic_donate_close").click(function() {
        var donateyes = $("#turkic_donate_yes").attr("checked");
        var donateno  = $("#turkic_donate_no").attr("checked");

        if (!donateyes && !donateno)
        {
            window.alert("Please choose your donation option.");
            return;
        }

        document.cookie = "turkic_donate=" + (donateyes ? 1 : 0);

        // we need to reset the timestamp because the task doesnt start until they continue
        turkic_timeaccepted = (new Date()).getTime();

        $("#turkic_overlay").fadeOut();
        donation.slideUp();
    });
}

function server_geturl(action, parameters)
{
    var url = "server/" + action;
    for (var x in parameters)
    {
        url += "/" + parameters[x];
    }
    return url;
}

function server_request(action, parameters, callback)
{
    var url = server_geturl(action, parameters);
    console.log("Server request: " + url);
    $.ajax({
        url: url,
        dataType: "json",
        success: function(data) {
            callback(data);
        },
        error: function(xhr, textstatus) {
            console.log(xhr.responseText);
            death("Server Error");
        }
    });
}

function server_post(action, parameters, data, callback)
{
    var url = server_geturl(action, parameters);
    console.log("Server post: " + url);
    $.ajax({
        url: url,
        dataType: "json",
        type: "POST",
        data: data,
        success: function(data) {
            callback(data);
        },
        error: function(xhr, textstatus) {
            console.log(xhr.responseText);
            death("Server Error");
        }
    });
}

var server_workerstats_data = null;
function server_workerstats(callback)
{
    if (server_workerstats_data == null)
    {
        var params = mturk_parameters();
        if (params.workerid)
        {
            server_request("turkic_getworkerstats",
                [params.hitid, params.workerid],
                function (data) {
                    server_workerstats_data = data;
                    callback(data);
                });
        }
    }
    else
    {
        callback(server_workerstats_data);
    }
}

function death(message)
{
    document.write("" + message);
}

if (!console)
{
    var console = new Object();
    console.log = function() {};
}
<|endoftext|>


<commit_before>// ==UserScript==
// @name          Steezy Pibb
// @namespace     http://www.geocities.com/ian3n
// @description   Makes Pibb+Fluid one hell of a steez
// @author        Ian Collins
// @homepage      http://www.geocities.com/ian3n
// @include       *pibb.com*
// ==/UserScript==

var Pibb = function(spec) {
	var spec = spec || {}
	var that = {}

	// public
	that.blah = function() {
		window.console.log(spec['hello'])
	}

	// private
	var self = {
		doc  						: function() { return window.frames[0].document },
		message_window 	: function() { return self.doc().getElementsByClassName('EntriesView-Entries')[0] },
		message_input		: function() { return self.doc().getElementsByClassName('gwt-TextBox EntriesView-textbox')[0] },
		footer					: function() { return self.doc().getElementsByClassName('Footer')[0] },

		period 							: 1000,
		new_class 					: 'NewEntry',
		my_bg_color 				: '#eee',
		important_bg_color 	: '#FFC670',

		// input_cookie 				: new Cookie('test'),

		// tabz : self.doc().getElementsByClassName('ChannelTabBar')[0].childNodes[0].getElementsByTagName('li'),
		// tab : function(num) {
		// 	return self.tabz[num]
		// },

		new_messages : [],
		check_for_new_messages : function(){
			if (self.message_window()){
				var elems = self.get_new_message_elems()

				if (elems.length < self.new_messages.length)
					self.new_messages = []

				for (var i = self.new_messages.length; i < elems.length; i++)
					if (elems[i]) self.handle_new_message(elems[i])
			}
			window.setTimeout(self.check_for_new_messages, self.period)
		},
		get_new_message_elems : function(){
			var elems = self.message_window().getElementsByClassName(self.new_class)
			var lame = []

			for (var i=0; i < elems.length; i++)
				if (elems[i] && elems[i].className && elems[i].className.match(self.new_class)) lame.push(elems[i])

			return lame
		},
		handle_new_message: function(elem) {
			var message = new Message(elem)

			// if message was written by current user
			if (self.get_aliases().some(function(a){ return message.author.toLowerCase() == a.toLowerCase() })){
				self.mark_all_read()
				message.mark_read(self.new_class)
				message.by_current_user = true
				message.elem.style['background-color'] = self.my_bg_color
				return
			}

			// if message has one of the words from the alias input in it
			if (self.get_aliases().some(function(a){ return (a.length > 0) && (message.body.match(new RegExp('\\b(' + a + ')\\b','i'))) })) {
				self.new_message_growl_alert(message)
				message.elem.style['background-color'] = self.important_bg_color
			}

			self.new_messages.push(message)
			self.set_dock_alert(self.new_messages.length)
		},

		new_message_growl_alert : function(message){
			window.fluid.showGrowlNotification({
		    title				: message.author + " said",
		    description	: message.body,
		    priority		: 1,
		    sticky			: true,
				icon				: message.icon
			})
		},
		set_dock_alert : function(to){
			window.fluid.dockBadge = to
		},

		setup_message_window_events: function(){
			if (self.message_window()) self.message_window().addEventListener('click', self.message_window_clicked)
			window.setTimeout(self.setup_message_window_events, self.period)
		},
		message_window_clicked : function(){
			self.message_input().focus()
			self.mark_all_read()
		},
		mark_all_read : function() {
			self.new_messages.forEach(function(nm){ nm.mark_read(self.new_class) })
			self.new_messages = []
			self.set_dock_alert('')
		},

		insert_aliases_input: function(){
			if (!self.doc().getElementsByClassName('steezy-input')[0]){
				self.aliases_input = document.createElement("input")
				self.aliases_input.className = "steezy-input"
				self.aliases_input.style.float = "left"

 				self.aliases_input_cookie = new Cookie('aliases_input_value', 'good')
				self.aliases_input.value = self.aliases_input_cookie.get_value()

				self.footer().appendChild(self.aliases_input)
			}

			window.setTimeout(self.insert_aliases_input, self.period)
		},
		get_aliases: function(){
			if (self.aliases_input)
				return self.aliases_input.value.split(',')
		}
	};

	// initialize
	self.check_for_new_messages()
	self.setup_message_window_events()
	self.insert_aliases_input()

	return that
};

var Message = function(elem){
	this.elem				= elem
	this.body 			= this.elem.childNodes[0].innerHTML
	this.author 		= this.elem.parentNode.parentNode.getElementsByClassName('Metadata')[0].getElementsByTagName('h3')[0].getElementsByClassName('Name')[0].innerHTML
	this.icon				= this.elem.parentNode.parentNode.getElementsByClassName('UserThumb')[0]
	this.by_current_user = false
	this.mark_read 	= function(class_name) {
											this.elem.className = this.elem.className.replace(class_name,'')
											// elem.remove_class(class_name)
										}
	return this
}

var Cookie = function(key, value) {
	this.key = key

	this.set_value = function(val) {
		document.cookie = this.key + '=' + val
		return this
	}
	this.get_value = function() {
		var the_match = document.cookie.match(this.key + "=([^;]+)")
		if (the_match && the_match.length > 1) return the_match[1]
		else return null
	}
	this.clear = function(){
		return this.set_value('')
	}

	if (value) this.set_value(value)

	return this
}

// only create pibb instance for second frame(set) (they all run this script)
if (window.loaded_once){
	var the_pibb = Pibb()
	window.loaded_once = false
}else
	window.loaded_once = true

///////////////////////////////////////////////////////////////////////////////
// Native Extensions

// Element.prototype.remove_class = function(class_name) {
// 	window.console.log('this: '+this)
// 	this.className = this.className.replace(class_name,'')
// 	return this
// }<commit_msg>cookie in self decl<commit_after>// ==UserScript==
// @name          Steezy Pibb
// @namespace     http://www.geocities.com/ian3n
// @description   Makes Pibb+Fluid one hell of a steez
// @author        Ian Collins
// @homepage      http://www.geocities.com/ian3n
// @include       *pibb.com*
// ==/UserScript==

var Pibb = function(spec) {
	var spec = spec || {}
	var that = {}

	// public
	that.blah = function() {
		window.console.log(spec['hello'])
	}

	// private
	var self = {
		doc  						: function() { return window.frames[0].document },
		message_window 	: function() { return self.doc().getElementsByClassName('EntriesView-Entries')[0] },
		message_input		: function() { return self.doc().getElementsByClassName('gwt-TextBox EntriesView-textbox')[0] },
		footer					: function() { return self.doc().getElementsByClassName('Footer')[0] },

		period 							: 1000,
		new_class 					: 'NewEntry',
		my_bg_color 				: '#eee',
		important_bg_color 	: '#FFC670',

		aliases_input_cookie : new Cookie('aliases_input_value'),

		// tabz : self.doc().getElementsByClassName('ChannelTabBar')[0].childNodes[0].getElementsByTagName('li'),
		// tab : function(num) {
		// 	return self.tabz[num]
		// },

		new_messages : [],
		check_for_new_messages : function(){
			if (self.message_window()){
				var elems = self.get_new_message_elems()

				if (elems.length < self.new_messages.length)
					self.new_messages = []

				for (var i = self.new_messages.length; i < elems.length; i++)
					if (elems[i]) self.handle_new_message(elems[i])
			}
			window.setTimeout(self.check_for_new_messages, self.period)
		},
		get_new_message_elems : function(){
			var elems = self.message_window().getElementsByClassName(self.new_class)
			var lame = []

			for (var i=0; i < elems.length; i++)
				if (elems[i] && elems[i].className && elems[i].className.match(self.new_class)) lame.push(elems[i])

			return lame
		},
		handle_new_message: function(elem) {
			var message = new Message(elem)

			// if message was written by current user
			if (self.get_aliases().some(function(a){ return message.author.toLowerCase() == a.toLowerCase() })){
				self.mark_all_read()
				message.mark_read(self.new_class)
				message.by_current_user = true
				message.elem.style['background-color'] = self.my_bg_color
				return
			}

			// if message has one of the words from the alias input in it
			if (self.get_aliases().some(function(a){ return (a.length > 0) && (message.body.match(new RegExp('\\b(' + a + ')\\b','i'))) })) {
				self.new_message_growl_alert(message)
				message.elem.style['background-color'] = self.important_bg_color
			}

			self.new_messages.push(message)
			self.set_dock_alert(self.new_messages.length)
		},

		new_message_growl_alert : function(message){
			window.fluid.showGrowlNotification({
		    title				: message.author + " said",
		    description	: message.body,
		    priority		: 1,
		    sticky			: true,
				icon				: message.icon
			})
		},
		set_dock_alert : function(to){
			window.fluid.dockBadge = to
		},

		setup_message_window_events: function(){
			if (self.message_window()) self.message_window().addEventListener('click', self.message_window_clicked)
			window.setTimeout(self.setup_message_window_events, self.period)
		},
		message_window_clicked : function(){
			self.message_input().focus()
			self.mark_all_read()
		},
		mark_all_read : function() {
			self.new_messages.forEach(function(nm){ nm.mark_read(self.new_class) })
			self.new_messages = []
			self.set_dock_alert('')
		},

		insert_aliases_input: function(){
			if (!self.doc().getElementsByClassName('steezy-input')[0]){
				self.aliases_input = document.createElement("input")
				self.aliases_input.className = "steezy-input"
				self.aliases_input.style.float = "left"

				self.aliases_input.value = self.aliases_input_cookie.get_value()

				self.footer().appendChild(self.aliases_input)
			}

			window.setTimeout(self.insert_aliases_input, self.period)
		},
		get_aliases: function(){
			if (self.aliases_input)
				return self.aliases_input.value.split(',')
		}
	};

	// initialize
	self.check_for_new_messages()
	self.setup_message_window_events()
	self.insert_aliases_input()

	return that
};

var Message = function(elem){
	this.elem				= elem
	this.body 			= this.elem.childNodes[0].innerHTML
	this.author 		= this.elem.parentNode.parentNode.getElementsByClassName('Metadata')[0].getElementsByTagName('h3')[0].getElementsByClassName('Name')[0].innerHTML
	this.icon				= this.elem.parentNode.parentNode.getElementsByClassName('UserThumb')[0]
	this.by_current_user = false
	this.mark_read 	= function(class_name) {
											this.elem.className = this.elem.className.replace(class_name,'')
											// elem.remove_class(class_name)
										}
	return this
}

var Cookie = function(key, value) {
	this.key = key

	this.set_value = function(val) {
		document.cookie = this.key + '=' + val
		return this
	}
	this.get_value = function() {
		var the_match = document.cookie.match(this.key + "=([^;]+)")
		if (the_match && the_match.length > 1) return the_match[1]
		else return null
	}
	this.clear = function(){
		return this.set_value('')
	}

	if (value) this.set_value(value)

	return this
}

// only create pibb instance for second frame(set) (they all run this script)
if (window.loaded_once){
	var the_pibb = Pibb()
	window.loaded_once = false
}else
	window.loaded_once = true

///////////////////////////////////////////////////////////////////////////////
// Native Extensions

// Element.prototype.remove_class = function(class_name) {
// 	window.console.log('this: '+this)
// 	this.className = this.className.replace(class_name,'')
// 	return this
// }<|endoftext|>