<commit_before>window.Bloob= {};

var includePath = "../../Bloob/lib/"; // include path relative to scarlet.js

var basicPath = includePath + "basic/";
var physicsPath = includePath + "physics/";
var logicPath = includePath + "logic/";
var scenesPath = includePath + "scenes/";
var gamePath = includePath + "game/";

Scarlet
	// basic
	.include(basicPath + "libraryextensions")
	.include(basicPath + "utils")
	.include(basicPath + "loader")
	.include(basicPath + "gui")
	.include(basicPath + "camera")
	.include(basicPath + "interactionhandler")
	.include(basicPath + "interactionhandlerbuilder")

	// physics
	.include(physicsPath + "jellyphysics")

	.include(physicsPath + "queue")

	.include(physicsPath + "bitmask")

	.include(physicsPath + "internalspring")

	.include(physicsPath + "jellyprerequisites")
	.include(physicsPath + "vector2")
	.include(physicsPath + "pointmass")
	.include(physicsPath + "aabb") // needs vector2
	.include(physicsPath + "vectortools") // needs vector2, jellyprerequisites
	.include(physicsPath + "closedshape") // needs VectorTools, JellyPrerequisites, Vector2

	.include(physicsPath + "body") // needs VectorTools, JellyPrerequisites, Vector2, ClosedShape, Bitmask, AABB, PointMass
	.include(physicsPath + "bodycollisioninfo") // vector2
	.include(physicsPath + "materialmanager")
	.include(physicsPath + "world")
	.include(physicsPath + "springbody") // Body, InternalSpring, World, VectorTools
	.include(physicsPath + "pressurebody") // springbody

	.include(physicsPath + "ray") // vector, ...
	.include(physicsPath + "bodyfactory") // provides chainable interface for creation of bodies
	.include(physicsPath + "particle") //
	.include(physicsPath + "particlecannon") //

	.include(physicsPath + "joints/distancejoint") //
	.include(physicsPath + "joints/pinjoint") //
	.include(physicsPath + "joints/interpolationjoint") //

	.include(physicsPath + "springbuilder") // springbody

	.include(physicsPath + "debugdraw")

	.include(physicsPath + "contactmanager")

	// basic canvas
	.include(basicPath + "canvas")
	// basic for map
	.include(basicPath + "converter")
	.include(basicPath + "map")
	// basic for builder
	.include(basicPath + "shapebuilder")
	.include(basicPath + "bodybuilder")
	.include(basicPath + "mapbuilder")

	// logic
	.include(logicPath + "logic")
	.include(logicPath + "entity")

	// TODO: move mouse to top after refactoring
	.include(basicPath + "mouse")
	// scenes
	.include(scenesPath + "scene")
	.include(scenesPath + "mapscene")
	.include(scenesPath + "titlescene")
	.include(scenesPath + "transition")

	// game
	.include(gamePath + "loop")
	.include(gamePath + "config")
	.include(gamePath + "game")
	.include(gamePath + "main");
	;
<commit_msg>include EditorScene<commit_after>window.Bloob= {};

var includePath = "../../Bloob/lib/"; // include path relative to scarlet.js

var basicPath = includePath + "basic/";
var physicsPath = includePath + "physics/";
var logicPath = includePath + "logic/";
var scenesPath = includePath + "scenes/";
var gamePath = includePath + "game/";

Scarlet
	// basic
	.include(basicPath + "libraryextensions")
	.include(basicPath + "utils")
	.include(basicPath + "loader")
	.include(basicPath + "gui")
	.include(basicPath + "camera")
	.include(basicPath + "interactionhandler")
	.include(basicPath + "interactionhandlerbuilder")

	// physics
	.include(physicsPath + "jellyphysics")

	.include(physicsPath + "queue")

	.include(physicsPath + "bitmask")

	.include(physicsPath + "internalspring")

	.include(physicsPath + "jellyprerequisites")
	.include(physicsPath + "vector2")
	.include(physicsPath + "pointmass")
	.include(physicsPath + "aabb") // needs vector2
	.include(physicsPath + "vectortools") // needs vector2, jellyprerequisites
	.include(physicsPath + "closedshape") // needs VectorTools, JellyPrerequisites, Vector2

	.include(physicsPath + "body") // needs VectorTools, JellyPrerequisites, Vector2, ClosedShape, Bitmask, AABB, PointMass
	.include(physicsPath + "bodycollisioninfo") // vector2
	.include(physicsPath + "materialmanager")
	.include(physicsPath + "world")
	.include(physicsPath + "springbody") // Body, InternalSpring, World, VectorTools
	.include(physicsPath + "pressurebody") // springbody

	.include(physicsPath + "ray") // vector, ...
	.include(physicsPath + "bodyfactory") // provides chainable interface for creation of bodies
	.include(physicsPath + "particle") //
	.include(physicsPath + "particlecannon") //

	.include(physicsPath + "joints/distancejoint") //
	.include(physicsPath + "joints/pinjoint") //
	.include(physicsPath + "joints/interpolationjoint") //

	.include(physicsPath + "springbuilder") // springbody

	.include(physicsPath + "debugdraw")

	.include(physicsPath + "contactmanager")

	// basic canvas
	.include(basicPath + "canvas")
	// basic for map
	.include(basicPath + "converter")
	.include(basicPath + "map")
	// basic for builder
	.include(basicPath + "shapebuilder")
	.include(basicPath + "bodybuilder")
	.include(basicPath + "mapbuilder")

	// logic
	.include(logicPath + "logic")
	.include(logicPath + "entity")

	// TODO: move mouse to top after refactoring
	.include(basicPath + "mouse")
	// scenes
	.include(scenesPath + "scene")
	.include(scenesPath + "mapscene")
	.include(scenesPath + "editorscene")
	.include(scenesPath + "titlescene")
	.include(scenesPath + "transition")

	// game
	.include(gamePath + "loop")
	.include(gamePath + "config")
	.include(gamePath + "game")
	.include(gamePath + "main");
	;
<|endoftext|>


<commit_before>const Player = require('./player');
const Meteor = require('./meteor');
const Bullet = require('./bullet');

function Board(width, height) {
  this.width = width || 1250;
  this.height = height || 600;
  this.meteors = [];
  this.players = [];
  this.bullets = [];
}

Board.prototype.addPlayer = function() {
  return new Player(this);
}

Board.prototype.addMeteor = function() {
  return new Meteor(this);
}

Board.prototype.addBullet = function() {
  return new Bullet(this);
}

Board.prototype.checkBulletMeteorCollisions = function() {
  var bullets = this.bullets
  var meteors = this.meteors
  this.meteors.forEach(function(meteor, index) {
    for(var i = 0; i < bullets.length; i++)
      if(meteor.collisionWith(bullets[i].range())){
        bullets.splice(i, 1);
        meteors.splice(index, 1);
      };
  });
};

Board.prototype.checkPlayerMeteorCollisions = function() {
  var players = this.players[0]
  var meteors = this.meteors
  this.meteors.forEach(function(meteor, index) {
    if(meteor.collisionWith(players[0].range())){
      players.splice(0, 1);
      meteors.splice(index, 1);
    };
  });
};

Board.prototype.checkCollision = function() {
  var board = this;
  board.meteors.forEach(function(element, index) {
    if(element.impactCoordinates.y >= board.height - (board.players[0].size.height + 2)
      && element.impactCoordinates.xmin < board.players[0].impactCoordinates.xmin
      && element.impactCoordinates.xmax > board.players[0].impactCoordinates.xmax) {
      board.meteors.splice(index, 1);
    } else if(element.impactCoordinates.y >= board.height - (board.players[0].size.height + 2)
      && element.impactCoordinates.xmin < board.players[0].impactCoordinates.xmax
      && element.impactCoordinates.xmin > board.players[0].impactCoordinates.xmin) {
        board.meteors.splice(index, 1);
    } else if(element.impactCoordinates.y >= board.height - (board.players[0].size.height + 2)
      && element.impactCoordinates.xmax < board.players[0].impactCoordinates.xmax
      && element.impactCoordinates.xmax > board.players[0].impactCoordinates.xmin) {
        board.meteors.splice(index, 1);
    }
  });
}

module.exports = Board;
<commit_msg>removes ugly collision function<commit_after>const Player = require('./player');
const Meteor = require('./meteor');
const Bullet = require('./bullet');

function Board(width, height) {
  this.width = width || 1250;
  this.height = height || 600;
  this.meteors = [];
  this.players = [];
  this.bullets = [];
}

Board.prototype.addPlayer = function() {
  return new Player(this);
}

Board.prototype.addMeteor = function() {
  return new Meteor(this);
}

Board.prototype.addBullet = function() {
  return new Bullet(this);
}

Board.prototype.checkBulletMeteorCollisions = function() {
  var bullets = this.bullets
  var meteors = this.meteors
  this.meteors.forEach(function(meteor, index) {
    for(var i = 0; i < bullets.length; i++)
      if(meteor.collisionWith(bullets[i].range())){
        bullets.splice(i, 1);
        meteors.splice(index, 1);
      };
  });
};

Board.prototype.checkPlayerMeteorCollisions = function() {
  var players = this.players[0]
  var meteors = this.meteors
  this.meteors.forEach(function(meteor, index) {
    if(meteor.collisionWith(players[0].range())){
      players.splice(0, 1);
      meteors.splice(index, 1);
    };
  });
};

module.exports = Board;
<|endoftext|>


<commit_before>// -------------------------
//  Task edit
// -------------------------

/* Load a task into the edit panel by ajax */
function loadTask(id) {
	jQuery("#task").fadeOut();
	jQuery.get("/tasks/edit/" + id + "?format=js", {}, function(data) {
		jQuery("#task").html(data);
		jQuery("#task").fadeIn('slow');
		init_task_form();
  });
}

// refresh the milestones select menu for all milestones from project pid, setting the selected milestone to mid
// also old /milestones/get_milestones returns line of javasript code `jQuery('#add_milestone').[show()|hide]`
// new /milestones/get_milestones returns flag add_milestone_visible
function refreshMilestones(pid, mid) {
  jQuery.getJSON("/milestones/get_milestones", {project_id: pid},
    function(data) {
      var milestoneSelect = jQuery('#task_milestone_id').get(0);
      rebuildSelect(milestoneSelect, data.options);
      milestoneSelect.options[mid].selected = true;
      if (data.add_milestone_visible){
        jQuery('#add_milestone').show();
      } else{
        jQuery('#add_milestone').hide();
      }
  });
}

/* TASK OWNER METHODS */
function removeTaskUser(sender) {
    sender = jQuery(sender);
    sender.parent(".watcher").remove();
    highlightWatchers();
}

function toggleTaskIcon(sender) {
    var div = jQuery(sender).parents(".watcher");

    var input = div.find("input.assigned");
    var icon = div.find(".icon.assigned");

    if (input.attr("disabled")) {
        div.addClass("is_assigned");
        input.attr("disabled", false);
    }
    else {
        input.attr("disabled", true);
        div.removeClass("is_assigned");
    }
}

/*
  Adds the selected user to the current tasks list of users
*/
function addUserToTask(event, ui) {
    var userId = ui.item.id;
    var taskId = jQuery("#task_id").val();
    var url = tasks_path('add_notification');
    var params = { user_id : userId, id : taskId };
    addUser(url, params);
    jQuery(this).val("");
    return false;

}

/*
  Adds any users setup as auto add to the current task.
*/
function addAutoAddUsersToTask(clientId, taskId, projectId) {
    var url = tasks_path("add_users_for_client");
    var params = { client_id : clientId, id : taskId, project_id : projectId };
    addUser(url, params);
}

function addUser(url, params){
    jQuery.get(url, params, function(data) {
        jQuery("#task_notify").append(data);
        highlightWatchers();
    });
}
/*
  Adds the selected customer to the current task list of clients
*/
function addCustomerToTask(event, ui) {
    var clientId = ui.item.id;
    var taskId = jQuery("#task_id").val();

    var url = tasks_path("add_client");
    var params = { client_id : clientId, id : taskId };
    jQuery.get(url, params, function(data) {
                jQuery("#task_customers").append(data);
    });

    addAutoAddUsersToTask(clientId, taskId);
    jQuery(this).val("");
    return false;
}
/*Adds the selected customer to the new project*/
function addCustomerToProject(event, ui){
    jQuery('#project_customer_id').val(ui.item.id);
}
/*
  If this task has no linked clients yet, link the one that
  project belongs to and update the display.
*/
function addClientLinkForTask(projectId) {
    var customers = jQuery("#task_customers").text();

    if (jQuery.trim(customers) == "") {
        var url = tasks_path("add_client_for_project");
        var params = { project_id : projectId };
        jQuery.get(url, params, function(data) {
            jQuery("#task_customers").html(data);
        });
    }
}

// TODOS

/*
Toggles the todo display or edit fields
*/
function toggleTodoEdit(sender) {
    var todo = jQuery(sender).parents(".todo");
    var display = todo.find(".display");
    var edit = todo.find(".edit");

    display.toggle();
    edit.toggle();
}

/*
Adds listeners to handle users pressing enter in the todo
edit field
*/
function addTodoKeyListener(todoId, taskId) {
  var todo = jQuery("#todos-" + todoId);
  var input = todo.find(".edit input");

  input.keypress(function(key) {
    if (key.keyCode == 13) {
      jQuery(".todo-container").load("/todos/update/" + todoId,  {
        "_method": "PUT",
        task_id: taskId,
        "todo[name]": input.val()
      });

      key.stopPropagation();
      return false;
    }
  });
  initSortableForTodos();
}

/*
Adds listeners to handle users pressing enter in the todo
create field
*/
function addNewTodoKeyListener(taskId) {
  var todo = jQuery("#new-todos");
  var input = todo.find(".edit input");

  input.keypress(function(key) {
    if (key.keyCode == 13) {
      jQuery.ajax({
        url: '/todos/create?task_id='+ taskId + '&todo[name]=' + input.val(),
        type: 'POST',
        dataType: 'json',
        success:function(response) {
          jQuery('.todo-container').html(response.todos_html);
          jQuery('#todo-status-' + response.task_dom_id).html(response.todos_status);
          initSortableForTodos();
        },
        beforeSend:function() { showProgress(); },
        complete:function() { hideProgress(); }
      });
      key.stopPropagation();
      return false;
    }
  });
}

/*
 Add function to handle open/close task
 For New Task
*/

function todoOpenCloseCheckForUncreatedTask(done, sender) {
  if (jQuery(sender).siblings(".edit").is(':visible')){
    var todoName = jQuery(sender).siblings(".edit").children('input').val();
  } else {
    var todoName = jQuery(sender).siblings(".display").text();
  }
  jQuery.ajax({
    url: '/todos/toggle_done_for_uncreated_task/' + done + '?name=' + todoName,
    dataType: 'html',
    success:function(response) {
      jQuery(sender).parent().replaceWith(response);
    },
    beforeSend: function(){ showProgress(); },
    complete: function(){ hideProgress(); },
    error:function (xhr, thrownError) {
      alert("Invalid request");
    }
  });
}

/*
  Add function to handle new todo
  For new Task
*/

function new_task_form() {
    var todo = jQuery("#todos-clone").children("li:last-child");
    var display = todo.find(".display");
    var edit = todo.find(".edit");

    display.toggle();
    edit.toggle();
}

function addNewTodoKeyListenerForUncreatedTask(sender, button) {
     if (button == "edit") {
       var li_element = jQuery(sender).parent().parent();
       var input = jQuery(sender).parent().siblings(".edit").children("input");
     } else if (button == "new") {
       var li_element = jQuery("#todos-clone").children("li:last-child");
       var input = li_element.children("span.edit").children("input");
     }

    input.keypress(function(key) {
        if (key.keyCode == 13) {
            li_element.children(".display").show();
            li_element.children(".display").text(input.val());
            li_element.children(".edit").children("input").val(input.val());
            li_element.children(".edit").hide();

            key.stopPropagation();
            return false;
        }
    });
}

function init_task_form() {
    jQuery('#task_status').change(function() {
      if( jQuery('#task_status').val() == "5" ) {
        jQuery('#defer_options').show();
      } else {
        jQuery('#defer_options').hide();
      }
      return false;
    });
    jQuery('#comment').focus();

    attach_behaviour_to_project_select();
    jQuery("div.log_history").tabs();
    jQuery('.autogrow').autogrow();
    jQuery('#comment').keyup(function() {
        highlightWatchers();
    });
    jQuery(function() {
        jQuery('#search_filter').catcomplete({
              source: '/task_filters/search',
              select: addSearchFilter,
              delay: 800,
              minLength: 3
        });
    });
    autocomplete('#task_customer_name_auto_complete', '/tasks/auto_complete_for_customer_name', addCustomerToTask);
    autocomplete('#dependencies_input', '/tasks/auto_complete_for_dependency_targets', addDependencyToTask);
    autocomplete('#resource_name_auto_complete', '/tasks/auto_complete_for_resource_name/customer_id='+ jQuery('#resource_name_auto_complete').attr('data-customer-id'), addResourceToTask);
    autocomplete('#user_name_auto_complete', '/tasks/auto_complete_for_user_name', addUserToTask);
    autocomplete_multiple_remote('#task_set_tags', '/tags/auto_complete_for_tags' );

    initSortableForTodos();

    jQuery('#snippet').click(function() {
      jQuery(this).children('ul').slideToggle();
    });

    jQuery('#snippet ul li').hover(function() {
      jQuery(this).toggleClass('ui-state-hover');
    });

    jQuery('#snippet ul li').click(function() {
      var id = jQuery(this).attr('id');
      id = id.split('-')[1];
      jQuery.ajax({ url: '/pages/snippet/'+id, type:'GET', success: function(data) {
        jQuery('#comment').val(jQuery('#comment').val() + '\n' + data);
      } });
    });

    jQuery('#add_milestone img').click(add_milestone_popup);
    jQuery('#task_project_id').change(function() {
      jQuery("#milestone_project_id").val(jQuery('#task_project_id').val());
    });

    jQuery('div.file_thumbnail a').slimbox();
    jQuery(".datefield").datepicker({ constrainInput: false, dateFormat: userDateFormat});
    updateTooltips();
}

function delete_todo_callback() {
  jQuery(".delete_todo").bind("ajax:success", function(data, status, xhr) {
    jQuery(this).parent().remove();
  });
}
// this variable is used to cache the last state so we don't run
// all of highlightWatchers() on every keystroke
var task_comment_empty = null;

function remove_file_attachment(file_id, message) {
  var answer = confirm(message);
  if (answer){
    jQuery.ajax({
      url: '/project_files/destroy_file/'+ file_id,
      dataType: 'json',
      success:function(response) {
        if (response.status == 'success') {
           var div=jQuery('#projectfiles-' + file_id);
           div.fadeOut('slow');
           div.html('<input type="hidden" name="delete_files[]" value="' + div.attr('id').split('-')[1] + '">');
        } else {
          flash_message(response.message);
        }
      },
      beforeSend: function(){ showProgress(); },
      complete: function(){ hideProgress(); },
      error:function (xhr, thrownError) {
        alert("Error : " + thrownError);
      }
    });
  }
}

function highlightWatchers() {
	var comment_val = jQuery('#comment').val();

  if (comment_val !== task_comment_empty) {
	  if (comment_val == '') {
	    jQuery('.watcher').removeClass('will_notify');
	    jQuery('#notify_users').html('');
	  } else {
	    if (jQuery('#accessLevel_container div').hasClass('private')) {
	      jQuery('.watcher').removeClass('will_notify');
	      jQuery('.watcher.access_level_2').addClass('will_notify');
	    } else {
	      jQuery('.watcher').addClass('will_notify');
	    }
	    var watcher = "Notify: ";
	    jQuery('div.watcher.will_notify a.username span').each(function() {
	      watcher = watcher + jQuery(this).html() + ", ";
	    });
	    jQuery('#notify_users').html(watcher.substring(0,watcher.length-2));
	  }
	  task_comment_empty = (comment_val == '');
  }
}

function add_milestone_popup() {
  if (jQuery("#task_project_id").val() == "") {
    alert("Please select project before adding milestone !!")
  } else {
    jQuery("#milestone_name").val(" ");
    jQuery("#milestone_due_at").val(" ");
    jQuery("#milestone_user_id").val(" ");
    jQuery("#milestone_description").val(" ");
    var popup = jQuery("span#ui_popup_dialog").dialog({
        autoOpen: false,
	    title: 'New Milestone',
        width: 370,
        draggable: true
	});
	popup.dialog('open');
        // refresh milestone and destroy dialog after a successful milestone addition
        jQuery('#add_milestone_form').bind("ajax:success", function(event, json, xhr) {
             authorize_ajax_form_callback(jQuery.parseJSON(json));
             var project_id = jQuery.parseJSON(json).project_id;
             var milestone_id = jQuery.parseJSON(json).milestone_id;
             parent.refreshMilestones(project_id, milestone_id);
             jQuery('span#ui_popup_dialog').dialog('destroy');
        });
	return false;
  }
}

function toogleDone(sender) {
  var todoId = jQuery(sender).parent().attr("id").split("-")[1];
  var taskId = jQuery("#task_id").val();
  jQuery.ajax({
    url: '/todos/' + todoId + '/toggle_done/' + '?task_id=' + taskId + '&format=json',
    dataType: 'json',
    success:function(response) {
      jQuery('.todo-container').html(response.todos_html);
      jQuery('#todo-status-' + response.task_dom_id).html(response.todos_status);
    },
    beforeSend:function() { showProgress(); },
    complete:function() { hideProgress(); }
  });
}

function deleteTodo(todoId, taskId) {
  jQuery.ajax({
    url: '/todos/' + todoId + '?task_id=' + taskId,
    dataType: 'json',
    type: 'delete',
    success:function(response) {
      jQuery('#todo-status-' + response.task_dom_id).html(response.todos_status);
      jQuery('#todos-' + todoId).remove();
    },
    beforeSend:function() { showProgress(); },
    complete:function() { hideProgress(); }
  });
}

function initSortableForTodos() {
  jQuery('.task-todo').sortable({update: function(event,ui){
    var todos= new Array();
    jQuery.each(jQuery('.task-todo li'),
      function(index, element){
        var position = jQuery('input#todo_position', element);
        position.val(index+1);
        todos[index]= {id: jQuery('input#todo_id', element).val(), position: index+1} ;
      });
      jQuery.ajax({ url: '/todos/reorder', data: {task_id: jQuery('input#task_id').val(), todos: todos }, type: 'POST' });
    }
  });
}
<commit_msg>When for task was selected projects without a any milestone, and when was created a new milestone with green plus(a first for this projects), was an error: milestoneSelect.options[mid] is undefined. If the projects have not less than one milestone, an error occurs but not shown. Function refreshMilestones takes two parameters: pid- prоject's id in the system, mid- index in milestone's select list. But mid must be id too. I fixed this error.<commit_after>// -------------------------
//  Task edit
// -------------------------

/* Load a task into the edit panel by ajax */
function loadTask(id) {
	jQuery("#task").fadeOut();
	jQuery.get("/tasks/edit/" + id + "?format=js", {}, function(data) {
		jQuery("#task").html(data);
		jQuery("#task").fadeIn('slow');
		init_task_form();
  });
}

// refresh the milestones select menu for all milestones from project pid, setting the selected milestone to mid
// also old /milestones/get_milestones returns line of javasript code `jQuery('#add_milestone').[show()|hide]`
// new /milestones/get_milestones returns flag add_milestone_visible
function refreshMilestones(pid, mid) {
  jQuery.getJSON("/milestones/get_milestones", {project_id: pid},
    function(data) {
      var milestoneSelect = jQuery('#task_milestone_id').get(0);
      rebuildSelect(milestoneSelect, data.options);
      for(i=0;i<milestoneSelect.options.length;i++){
        if (milestoneSelect.options[i].value == mid){
          milestoneSelect.options[i].selected = true;
          break
        }
      }
      if (data.add_milestone_visible){
        jQuery('#add_milestone').show();
      } else{
        jQuery('#add_milestone').hide();
      }
  });
}

/* TASK OWNER METHODS */
function removeTaskUser(sender) {
    sender = jQuery(sender);
    sender.parent(".watcher").remove();
    highlightWatchers();
}

function toggleTaskIcon(sender) {
    var div = jQuery(sender).parents(".watcher");

    var input = div.find("input.assigned");
    var icon = div.find(".icon.assigned");

    if (input.attr("disabled")) {
        div.addClass("is_assigned");
        input.attr("disabled", false);
    }
    else {
        input.attr("disabled", true);
        div.removeClass("is_assigned");
    }
}

/*
  Adds the selected user to the current tasks list of users
*/
function addUserToTask(event, ui) {
    var userId = ui.item.id;
    var taskId = jQuery("#task_id").val();
    var url = tasks_path('add_notification');
    var params = { user_id : userId, id : taskId };
    addUser(url, params);
    jQuery(this).val("");
    return false;

}

/*
  Adds any users setup as auto add to the current task.
*/
function addAutoAddUsersToTask(clientId, taskId, projectId) {
    var url = tasks_path("add_users_for_client");
    var params = { client_id : clientId, id : taskId, project_id : projectId };
    addUser(url, params);
}

function addUser(url, params){
    jQuery.get(url, params, function(data) {
        jQuery("#task_notify").append(data);
        highlightWatchers();
    });
}
/*
  Adds the selected customer to the current task list of clients
*/
function addCustomerToTask(event, ui) {
    var clientId = ui.item.id;
    var taskId = jQuery("#task_id").val();

    var url = tasks_path("add_client");
    var params = { client_id : clientId, id : taskId };
    jQuery.get(url, params, function(data) {
                jQuery("#task_customers").append(data);
    });

    addAutoAddUsersToTask(clientId, taskId);
    jQuery(this).val("");
    return false;
}
/*Adds the selected customer to the new project*/
function addCustomerToProject(event, ui){
    jQuery('#project_customer_id').val(ui.item.id);
}
/*
  If this task has no linked clients yet, link the one that
  project belongs to and update the display.
*/
function addClientLinkForTask(projectId) {
    var customers = jQuery("#task_customers").text();

    if (jQuery.trim(customers) == "") {
        var url = tasks_path("add_client_for_project");
        var params = { project_id : projectId };
        jQuery.get(url, params, function(data) {
            jQuery("#task_customers").html(data);
        });
    }
}

// TODOS

/*
Toggles the todo display or edit fields
*/
function toggleTodoEdit(sender) {
    var todo = jQuery(sender).parents(".todo");
    var display = todo.find(".display");
    var edit = todo.find(".edit");

    display.toggle();
    edit.toggle();
}

/*
Adds listeners to handle users pressing enter in the todo
edit field
*/
function addTodoKeyListener(todoId, taskId) {
  var todo = jQuery("#todos-" + todoId);
  var input = todo.find(".edit input");

  input.keypress(function(key) {
    if (key.keyCode == 13) {
      jQuery(".todo-container").load("/todos/update/" + todoId,  {
        "_method": "PUT",
        task_id: taskId,
        "todo[name]": input.val()
      });

      key.stopPropagation();
      return false;
    }
  });
  initSortableForTodos();
}

/*
Adds listeners to handle users pressing enter in the todo
create field
*/
function addNewTodoKeyListener(taskId) {
  var todo = jQuery("#new-todos");
  var input = todo.find(".edit input");

  input.keypress(function(key) {
    if (key.keyCode == 13) {
      jQuery.ajax({
        url: '/todos/create?task_id='+ taskId + '&todo[name]=' + input.val(),
        type: 'POST',
        dataType: 'json',
        success:function(response) {
          jQuery('.todo-container').html(response.todos_html);
          jQuery('#todo-status-' + response.task_dom_id).html(response.todos_status);
          initSortableForTodos();
        },
        beforeSend:function() { showProgress(); },
        complete:function() { hideProgress(); }
      });
      key.stopPropagation();
      return false;
    }
  });
}

/*
 Add function to handle open/close task
 For New Task
*/

function todoOpenCloseCheckForUncreatedTask(done, sender) {
  if (jQuery(sender).siblings(".edit").is(':visible')){
    var todoName = jQuery(sender).siblings(".edit").children('input').val();
  } else {
    var todoName = jQuery(sender).siblings(".display").text();
  }
  jQuery.ajax({
    url: '/todos/toggle_done_for_uncreated_task/' + done + '?name=' + todoName,
    dataType: 'html',
    success:function(response) {
      jQuery(sender).parent().replaceWith(response);
    },
    beforeSend: function(){ showProgress(); },
    complete: function(){ hideProgress(); },
    error:function (xhr, thrownError) {
      alert("Invalid request");
    }
  });
}

/*
  Add function to handle new todo
  For new Task
*/

function new_task_form() {
    var todo = jQuery("#todos-clone").children("li:last-child");
    var display = todo.find(".display");
    var edit = todo.find(".edit");

    display.toggle();
    edit.toggle();
}

function addNewTodoKeyListenerForUncreatedTask(sender, button) {
     if (button == "edit") {
       var li_element = jQuery(sender).parent().parent();
       var input = jQuery(sender).parent().siblings(".edit").children("input");
     } else if (button == "new") {
       var li_element = jQuery("#todos-clone").children("li:last-child");
       var input = li_element.children("span.edit").children("input");
     }

    input.keypress(function(key) {
        if (key.keyCode == 13) {
            li_element.children(".display").show();
            li_element.children(".display").text(input.val());
            li_element.children(".edit").children("input").val(input.val());
            li_element.children(".edit").hide();

            key.stopPropagation();
            return false;
        }
    });
}

function init_task_form() {
    jQuery('#task_status').change(function() {
      if( jQuery('#task_status').val() == "5" ) {
        jQuery('#defer_options').show();
      } else {
        jQuery('#defer_options').hide();
      }
      return false;
    });
    jQuery('#comment').focus();

    attach_behaviour_to_project_select();
    jQuery("div.log_history").tabs();
    jQuery('.autogrow').autogrow();
    jQuery('#comment').keyup(function() {
        highlightWatchers();
    });
    jQuery(function() {
        jQuery('#search_filter').catcomplete({
              source: '/task_filters/search',
              select: addSearchFilter,
              delay: 800,
              minLength: 3
        });
    });
    autocomplete('#task_customer_name_auto_complete', '/tasks/auto_complete_for_customer_name', addCustomerToTask);
    autocomplete('#dependencies_input', '/tasks/auto_complete_for_dependency_targets', addDependencyToTask);
    autocomplete('#resource_name_auto_complete', '/tasks/auto_complete_for_resource_name/customer_id='+ jQuery('#resource_name_auto_complete').attr('data-customer-id'), addResourceToTask);
    autocomplete('#user_name_auto_complete', '/tasks/auto_complete_for_user_name', addUserToTask);
    autocomplete_multiple_remote('#task_set_tags', '/tags/auto_complete_for_tags' );

    initSortableForTodos();

    jQuery('#snippet').click(function() {
      jQuery(this).children('ul').slideToggle();
    });

    jQuery('#snippet ul li').hover(function() {
      jQuery(this).toggleClass('ui-state-hover');
    });

    jQuery('#snippet ul li').click(function() {
      var id = jQuery(this).attr('id');
      id = id.split('-')[1];
      jQuery.ajax({ url: '/pages/snippet/'+id, type:'GET', success: function(data) {
        jQuery('#comment').val(jQuery('#comment').val() + '\n' + data);
      } });
    });

    jQuery('#add_milestone img').click(add_milestone_popup);
    jQuery('#task_project_id').change(function() {
      jQuery("#milestone_project_id").val(jQuery('#task_project_id').val());
    });

    jQuery('div.file_thumbnail a').slimbox();
    jQuery(".datefield").datepicker({ constrainInput: false, dateFormat: userDateFormat});
    updateTooltips();
}

function delete_todo_callback() {
  jQuery(".delete_todo").bind("ajax:success", function(data, status, xhr) {
    jQuery(this).parent().remove();
  });
}
// this variable is used to cache the last state so we don't run
// all of highlightWatchers() on every keystroke
var task_comment_empty = null;

function remove_file_attachment(file_id, message) {
  var answer = confirm(message);
  if (answer){
    jQuery.ajax({
      url: '/project_files/destroy_file/'+ file_id,
      dataType: 'json',
      success:function(response) {
        if (response.status == 'success') {
           var div=jQuery('#projectfiles-' + file_id);
           div.fadeOut('slow');
           div.html('<input type="hidden" name="delete_files[]" value="' + div.attr('id').split('-')[1] + '">');
        } else {
          flash_message(response.message);
        }
      },
      beforeSend: function(){ showProgress(); },
      complete: function(){ hideProgress(); },
      error:function (xhr, thrownError) {
        alert("Error : " + thrownError);
      }
    });
  }
}

function highlightWatchers() {
	var comment_val = jQuery('#comment').val();

  if (comment_val !== task_comment_empty) {
	  if (comment_val == '') {
	    jQuery('.watcher').removeClass('will_notify');
	    jQuery('#notify_users').html('');
	  } else {
	    if (jQuery('#accessLevel_container div').hasClass('private')) {
	      jQuery('.watcher').removeClass('will_notify');
	      jQuery('.watcher.access_level_2').addClass('will_notify');
	    } else {
	      jQuery('.watcher').addClass('will_notify');
	    }
	    var watcher = "Notify: ";
	    jQuery('div.watcher.will_notify a.username span').each(function() {
	      watcher = watcher + jQuery(this).html() + ", ";
	    });
	    jQuery('#notify_users').html(watcher.substring(0,watcher.length-2));
	  }
	  task_comment_empty = (comment_val == '');
  }
}

function add_milestone_popup() {
  if (jQuery("#task_project_id").val() == "") {
    alert("Please select project before adding milestone !!")
  } else {
    jQuery("#milestone_name").val(" ");
    jQuery("#milestone_due_at").val(" ");
    jQuery("#milestone_user_id").val(" ");
    jQuery("#milestone_description").val(" ");
    var popup = jQuery("span#ui_popup_dialog").dialog({
        autoOpen: false,
	    title: 'New Milestone',
        width: 370,
        draggable: true
	});
	popup.dialog('open');
        // refresh milestone and destroy dialog after a successful milestone addition
        jQuery('#add_milestone_form').bind("ajax:success", function(event, json, xhr) {
             authorize_ajax_form_callback(jQuery.parseJSON(json));
             var project_id = jQuery.parseJSON(json).project_id;
             var milestone_id = jQuery.parseJSON(json).milestone_id;
             parent.refreshMilestones(project_id, milestone_id);
             jQuery('span#ui_popup_dialog').dialog('destroy');
        });
	return false;
  }
}

function toogleDone(sender) {
  var todoId = jQuery(sender).parent().attr("id").split("-")[1];
  var taskId = jQuery("#task_id").val();
  jQuery.ajax({
    url: '/todos/' + todoId + '/toggle_done/' + '?task_id=' + taskId + '&format=json',
    dataType: 'json',
    success:function(response) {
      jQuery('.todo-container').html(response.todos_html);
      jQuery('#todo-status-' + response.task_dom_id).html(response.todos_status);
    },
    beforeSend:function() { showProgress(); },
    complete:function() { hideProgress(); }
  });
}

function deleteTodo(todoId, taskId) {
  jQuery.ajax({
    url: '/todos/' + todoId + '?task_id=' + taskId,
    dataType: 'json',
    type: 'delete',
    success:function(response) {
      jQuery('#todo-status-' + response.task_dom_id).html(response.todos_status);
      jQuery('#todos-' + todoId).remove();
    },
    beforeSend:function() { showProgress(); },
    complete:function() { hideProgress(); }
  });
}

function initSortableForTodos() {
  jQuery('.task-todo').sortable({update: function(event,ui){
    var todos= new Array();
    jQuery.each(jQuery('.task-todo li'),
      function(index, element){
        var position = jQuery('input#todo_position', element);
        position.val(index+1);
        todos[index]= {id: jQuery('input#todo_id', element).val(), position: index+1} ;
      });
      jQuery.ajax({ url: '/todos/reorder', data: {task_id: jQuery('input#task_id').val(), todos: todos }, type: 'POST' });
    }
  });
}
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var util = require('util');
var bs2 = require('bs2-programmer');
var nodefn = require('when/node');
var bluebird = require('bluebird');
var Bs2Programmer = bs2.Programmer;
var reemit = require('re-emitter');
var bs2tokenizer = require('pbasic-tokenizer');
var EventEmitter = require('events').EventEmitter;
var Bs2SerialProtocol = require('bs2-serial-protocol');

function internalCompile(source){
  var TModuleRec = bs2tokenizer.compile(source, false);

  var program = {
    data: TModuleRec.PacketBuffer.slice(0, TModuleRec.PacketCount * 18),
    name: TModuleRec.TargetModuleName,
    error: !TModuleRec.Succeeded ? TModuleRec.Error : null,
    raw: TModuleRec
  };

  return program;
}

function generateEmptyPortlist(portList){
  return _.map(portList, function(port){
    return {
      name: null,
      path: port,
      type: 'bs2',
      match: false,
      program: null,
      board: {
        path: port
      }
    };
  });
}

function listPorts(options){
  var reject = _.get(options, 'reject') || [];
  var predicate = reject;
  if(Array.isArray(reject)){
    predicate = function(port){
      return _.some(reject, function(entry){
        if(typeof entry === 'string'){
          return port === entry;
        }
        return entry.test(port);
      });
    };
  }
  return Bs2SerialProtocol.listPorts()
    .then(function(portList){
      return _.reject(portList, predicate);
    });
}

function Board(options){
  if(!options){
    throw new Error('Options error: no options');
  }

  if(!options.path){
    throw new Error('Options error: no path');
  }

  EventEmitter.call(this);

  this._revision = options.revision || 'bs2';
  this._protocol = new Bs2SerialProtocol(options);
  this._programmer = new Bs2Programmer({
    protocol: this._protocol,
    revision: this._revision
  });

  reemit(this._protocol, this, ['terminal', 'transmit', 'open', 'close']);

  var self = this;
  this._programmer.on('bootloadProgress', function(progress){
    self.emit('progress', progress);
  });
}

util.inherits(Board, EventEmitter);

Board.search = function(options, cb){
  var revisions = _.keys(bs2.revisions);
  var result = listPorts(options)
    .then(function(portList){
      return bluebird.reduce(portList, function(boardList, path){

        var protocol = new Bs2SerialProtocol({ path: path });
        return bluebird.reduce(revisions, function(current, rev){
          if(current){
            return current;
          }

          var boardOpts = {
            protocol: protocol,
            revision: rev
          };

          return bs2.identify(boardOpts)
            .then(function(result){
              return _.assign({ path: path, revision: rev }, result);
            })
            .otherwise(function(){
              return null;
            });

        }, null)
        .then(function(board){
          if(board != null){
            var details = {
              name: board.name,
              path: board.path,
              version: board.version,
              board: _.cloneDeep(board),
              match: false,
              program: null
            };
            if(options.source){
              details.program = internalCompile(options.source);
              details.match = details.program.name === board.name;
            }
            boardList.push(details);
          }
          return boardList;
        });
      }, [])
      .then(function(boards){
        var allPorts = generateEmptyPortlist(portList);
        var emptyPorts = _.reject(allPorts, function(ep){
          return _.find(boards, { path: ep.path });
        });
        return boards.concat(emptyPorts);
      });
    });

  return nodefn.bindCallback(result, cb);
};

Board.prototype.bootload = function(program, cb){
  if(typeof program === 'string'){
    program = internalCompile(program);
  }
  if(program && program.error){
    return bluebird.reject(program.error).nodeify(cb);
  }
  if(!program || !program.data){
    return bluebird.reject(new Error('Options error: no program data')).nodeify(cb);
  }

  return this._programmer.bootload(program.data, cb);
};

Board.compile = function(source){
  return internalCompile(source);
};

Board.prototype.isOpen = function(){
  return !!_.get(this, '_protocol._isOpen');
};

Board.prototype.write = function(data, cb){
  if(typeof data === 'number'){
    data = new Buffer([data]);
  }else if(Array.isArray(data) || typeof data === 'string'){
    data = new Buffer(data);
  }
  return this._protocol.write(data, cb);
};

Board.prototype.open = function(cb){
  return this._protocol.open(cb);
};

Board.prototype.close = function(cb){
  return this._protocol.close(cb);
};

Board.getRevisions = function(){
  return bs2.revisions;
};

module.exports = Board;
<commit_msg>Add search status messages<commit_after>'use strict';

var _ = require('lodash');
var util = require('util');
var bs2 = require('bs2-programmer');
var nodefn = require('when/node');
var bluebird = require('bluebird');
var Bs2Programmer = bs2.Programmer;
var reemit = require('re-emitter');
var bs2tokenizer = require('pbasic-tokenizer');
var EventEmitter = require('events').EventEmitter;
var Bs2SerialProtocol = require('bs2-serial-protocol');

function internalCompile(source){
  var TModuleRec = bs2tokenizer.compile(source, false);

  var program = {
    data: TModuleRec.PacketBuffer.slice(0, TModuleRec.PacketCount * 18),
    name: TModuleRec.TargetModuleName,
    error: !TModuleRec.Succeeded ? TModuleRec.Error : null,
    raw: TModuleRec
  };

  return program;
}

function generateEmptyPort(port, err){
  return {
    name: null,
    path: port,
    type: 'bs2',
    match: false,
    program: null,
    displayError: err,
    board: {
      path: port
    }
  };
}

function generateEmptyPortlist(portList){
  return _.map(portList, function(port){
    return {
      name: null,
      path: port,
      type: 'bs2',
      match: false,
      program: null,
      displayError: null,
      board: {
        path: port
      }
    };
  });
}

function listPorts(options){
  var reject = _.get(options, 'reject') || [];
  var predicate = reject;
  if(Array.isArray(reject)){
    predicate = function(port){
      return _.some(reject, function(entry){
        if(typeof entry === 'string'){
          return port === entry;
        }
        return entry.test(port);
      });
    };
  }
  return Bs2SerialProtocol.listPorts()
    .then(function(portList){
      return _.reject(portList, predicate);
    });
}

function Board(options){
  if(!options){
    throw new Error('Options error: no options');
  }

  if(!options.path){
    throw new Error('Options error: no path');
  }

  EventEmitter.call(this);

  this._revision = options.revision || 'bs2';
  this._protocol = new Bs2SerialProtocol(options);
  this._programmer = new Bs2Programmer({
    protocol: this._protocol,
    revision: this._revision
  });

  reemit(this._protocol, this, ['terminal', 'transmit', 'open', 'close']);

  var self = this;
  this._programmer.on('bootloadProgress', function(progress){
    self.emit('progress', progress);
  });
}

util.inherits(Board, EventEmitter);

Board.search = function(options, cb){
  var revisions = _.keys(bs2.revisions);
  var result = listPorts(options)
    .then(function(portList){
      return bluebird.reduce(portList, function(boardList, path){

        var protocol = new Bs2SerialProtocol({ path: path });
        return bluebird.reduce(revisions, function(current, rev){
          if(current.revision){
            return current;
          }

          var boardOpts = {
            protocol: protocol,
            revision: rev
          };

          return bs2.identify(boardOpts)
            .then(function(result){
              return _.assign({ path: path, revision: rev }, result);
            })
            .otherwise(function(err){
              if(err.message === 'Serialport not open.'){
                //workaround for generic browser-serialport errors
                //TODO improve error messages in browser-serialport
                err = new Error('Port could not be opened.');
              }
              return {
                displayError: err.message
              };
            });

        }, {})
        .then(function(board){
          if(board.revision != null){
            var details = {
              name: board.name,
              path: board.path,
              version: board.version,
              board: _.cloneDeep(board),
              match: false,
              program: null
            };
            if(options.source){
              details.program = internalCompile(options.source);
              details.match = details.program.name === board.name;
            }
            boardList.push(details);
          }else{
            boardList.push(generateEmptyPort(path, board.displayError));
          }
          return boardList;
        });
      }, [])
      .then(function(boards){
        return _.sortBy(boards, 'name');
      });
    });

  return nodefn.bindCallback(result, cb);
};

Board.prototype.bootload = function(program, cb){
  if(typeof program === 'string'){
    program = internalCompile(program);
  }
  if(program && program.error){
    return bluebird.reject(program.error).nodeify(cb);
  }
  if(!program || !program.data){
    return bluebird.reject(new Error('Options error: no program data')).nodeify(cb);
  }

  return this._programmer.bootload(program.data, cb);
};

Board.compile = function(source){
  return internalCompile(source);
};

Board.prototype.isOpen = function(){
  return !!_.get(this, '_protocol._isOpen');
};

Board.prototype.write = function(data, cb){
  if(typeof data === 'number'){
    data = new Buffer([data]);
  }else if(Array.isArray(data) || typeof data === 'string'){
    data = new Buffer(data);
  }
  return this._protocol.write(data, cb);
};

Board.prototype.open = function(cb){
  return this._protocol.open(cb);
};

Board.prototype.close = function(cb){
  return this._protocol.close(cb);
};

Board.getRevisions = function(){
  return bs2.revisions;
};

module.exports = Board;
<|endoftext|>


<commit_before>$(document).ready(function(){
	tinyMCE.init({
			mode : "exact",
			elements: "blog_editor",
			theme : "advanced",
			plugins : "emotions,spellchecker,advhr,insertdatetime,preview",

			// Theme options - button# indicated the row# only
		theme_advanced_buttons1 : "newdocument,|,bold,italic,underline,|,justifyleft,justifycenter,justifyright,fontsizeselect,formatselect",
		theme_advanced_buttons2 : "cut,copy,paste|,bullist,numlist,|,outdent,indent|,undo,redo,|,link,unlink,anchor,image,|,preview,|,forecolor,backcolor",
		theme_advanced_buttons3 : "insertdate,inserttime,|,spellchecker,|,sub,sup,|,charmap,emotions",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		//theme_advanced_resizing : true //leave this out as there is an intermittent bug.
	});

	$('.comment_set').each(function(index) {
	    if($(this).children().length > 1) {
			$(this).parent().show();
			var show_comments_toggle = $(this).parent().prev().children(".show_post_comments");
			show_comments_toggle.html("hide comments ("+ ($(this).children().length - 1) + ")");
		};
	  });

	$('a').hover(function(){
	  $(this).fadeTo(60, 0.5);
	}, function(){
	  $(this).fadeTo(80, 1);
	});

	$('ul.nav li').hover(function(){
	  $(this).fadeTo(60, 0.5);
	}, function(){
	  $(this).fadeTo(80, 1);
	});

	$('#debug_info').click(function() {
		$('#debug_more').toggle('fast', function() {

		});
	});

  $("label").inFieldLabels();

  $('#flash_notice, #flash_error, #flash_alert').delay(1500).slideUp(130);

  $("#stream li").live('mouseover mouseout',function() {
    $(this).children(".destroy_link").fadeIn(0);
  }, function() {
    $(this).children(".destroy_link").fadeOut(0);
  });

  $(".show_post_comments").live('click', function(event) {
    event.preventDefault();
    if( $(this).hasClass( "visible")) {
      $(this).html($(this).html().replace("hide", "show"));
      $(this).parents("li").children(".comments").fadeOut(100);
    } else {
      $(this).html($(this).html().replace("show", "hide"));
      $(this).parents("li").children(".comments").fadeIn(100);
    }
    $(this).toggleClass( "visible" );
  });

//Called with $(selector).clearForm()
	$.fn.clearForm = function() {
		return this.each(function() {
		var type = this.type, tag = this.tagName.toLowerCase();
		if (tag == 'form')
			return $(':input',this).clearForm();
		if (type == 'text' || type == 'password' || tag == 'textarea')
			this.value = '';
		else if (type == 'checkbox' || type == 'radio')
			this.checked = false;
		else if (tag == 'select')
			this.selectedIndex = -1;
		});
	};
});//end document ready
<commit_msg>hover fix<commit_after>$(document).ready(function(){
	tinyMCE.init({
			mode : "exact",
			elements: "blog_editor",
			theme : "advanced",
			plugins : "emotions,spellchecker,advhr,insertdatetime,preview",

			// Theme options - button# indicated the row# only
		theme_advanced_buttons1 : "newdocument,|,bold,italic,underline,|,justifyleft,justifycenter,justifyright,fontsizeselect,formatselect",
		theme_advanced_buttons2 : "cut,copy,paste|,bullist,numlist,|,outdent,indent|,undo,redo,|,link,unlink,anchor,image,|,preview,|,forecolor,backcolor",
		theme_advanced_buttons3 : "insertdate,inserttime,|,spellchecker,|,sub,sup,|,charmap,emotions",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		//theme_advanced_resizing : true //leave this out as there is an intermittent bug.
	});

	$('.comment_set').each(function(index) {
	    if($(this).children().length > 1) {
			$(this).parent().show();
			var show_comments_toggle = $(this).parent().prev().children(".show_post_comments");
			show_comments_toggle.html("hide comments ("+ ($(this).children().length - 1) + ")");
		};
	  });

	$('a').hover(function(){
	  $(this).fadeTo(60, 0.5);
	}, function(){
	  $(this).fadeTo(80, 1);
	});

	$('ul.nav li').hover(function(){
	  $(this).fadeTo(60, 0.5);
	}, function(){
	  $(this).fadeTo(80, 1);
	});

	$('#debug_info').click(function() {
		$('#debug_more').toggle('fast', function() {

		});
	});

  $("label").inFieldLabels();

  $('#flash_notice, #flash_error, #flash_alert').delay(1500).slideUp(130);

  $("#stream li").live('mouseover',function() {
    $(this).children(".destroy_link").fadeIn(0);
  });

  $("#stream li").live('mouseout',function() {
    $(this).children(".destroy_link").fadeOut(0);
  });

  $(".show_post_comments").live('click', function(event) {
    event.preventDefault();
    if( $(this).hasClass( "visible")) {
      $(this).html($(this).html().replace("hide", "show"));
      $(this).parents("li").children(".comments").fadeOut(100);
    } else {
      $(this).html($(this).html().replace("show", "hide"));
      $(this).parents("li").children(".comments").fadeIn(100);
    }
    $(this).toggleClass( "visible" );
  });

//Called with $(selector).clearForm()
	$.fn.clearForm = function() {
		return this.each(function() {
		var type = this.type, tag = this.tagName.toLowerCase();
		if (tag == 'form')
			return $(':input',this).clearForm();
		if (type == 'text' || type == 'password' || tag == 'textarea')
			this.value = '';
		else if (type == 'checkbox' || type == 'radio')
			this.checked = false;
		else if (tag == 'select')
			this.selectedIndex = -1;
		});
	};
});//end document ready
<|endoftext|>


<commit_before>document.addEventListener('DOMContentLoaded', function () {

	var CELL_SIZE_X = 25;
	var CELL_SIZE_Y = 10;

	var canvas = document.getElementById('sheet');
	canvas.style.border = "black 1px solid";
	var ctx = canvas.getContext('2d');

	var controller = Controller();

	// Clears the Sheet and polls the controller to redraw it.
	var redrawSheet = function () {

		var drawCell = function (coordX,coordY) {
			ctx.fillStyle = "black";
			ctx.fillRect(coordX * CELL_SIZE_X, coordY * CELL_SIZE_Y, CELL_SIZE_X, CELL_SIZE_Y);
		};

		ctx.clearRect(0, 0, canvas.width, canvas.height); //clear the canvas
		ctx.canvas.width = CELL_SIZE_X * controller.dimX;
		ctx.canvas.height = CELL_SIZE_Y * controller.dimY;

		var noteCells = controller.returnNoteCells();
		noteCells.map(function (coords) {
			drawCell(coords[0],coords[1]);
		});
	};

	isDown = false;
	mouseListener = function(evt){
		if (isDown) {
			var mouseCoordsToMouseCoords = function (mouseX,mouseY) {
				var canvasRect = canvas.getBoundingClientRect();

				xCoord = Math.floor((mouseX - canvasRect.left)/CELL_SIZE_X);
				yCoord = Math.floor((mouseY - canvasRect.top)/CELL_SIZE_Y);

				return [xCoord, yCoord];
			}

			cellCoords = mouseCoordsToMouseCoords(evt.clientX,evt.clientY);
			if (evt.button === 0){
				controller.setCell(cellCoords[0], cellCoords[1], true);
			} else if (evt.button === 2) {
				controller.setCell(cellCoords[0], cellCoords[1], false);
			};
		};
	};

	canvas.addEventListener("mousedown", function(evt){
		isDown = true;
		mouseListener(evt);
	});
	canvas.addEventListener("mouseup", function(evt){
		isDown = false;
	});

	// Listens for mouseclick to notify controller
	canvas.addEventListener("mousemove", mouseListener,false);

	//Whenever the Sheet gets updated in the controller/model, redraw it
	controller.addSubscriber(redrawSheet);

	redrawSheet();

});<commit_msg>added colors!<commit_after>document.addEventListener('DOMContentLoaded', function () {

	var CELL_SIZE_X = 25;
	var CELL_SIZE_Y = 10;

	var canvas = document.getElementById('sheet');
	canvas.style.border = "black 1px solid";
	var ctx = canvas.getContext('2d');

	var controller = Controller();

	// Clears the Sheet and polls the controller to redraw it.
	var redrawSheet = function () {
		var colors = {0:"red",1:"blue",2:"green",3:"yellow",4:"purple",5:"brown",6:"magenta",7:"darkblue",8:"orange",9:"olive",10:"maroon",11:"lightblue"}
		var drawCell = function (coordX,coordY) {
			ctx.fillStyle = colors[coordX%12];
			ctx.fillRect(coordX * CELL_SIZE_X, coordY * CELL_SIZE_Y, CELL_SIZE_X, CELL_SIZE_Y);
		};

		ctx.clearRect(0, 0, canvas.width, canvas.height); //clear the canvas
		ctx.canvas.width = CELL_SIZE_X * controller.dimX;
		ctx.canvas.height = CELL_SIZE_Y * controller.dimY;

		var noteCells = controller.returnNoteCells();
		noteCells.map(function (coords) {
			drawCell(coords[0],coords[1]);
		});
	};

	isDown = false;
	mouseListener = function(evt){
		if (isDown) {
			var mouseCoordsToMouseCoords = function (mouseX,mouseY) {
				var canvasRect = canvas.getBoundingClientRect();

				xCoord = Math.floor((mouseX - canvasRect.left)/CELL_SIZE_X);
				yCoord = Math.floor((mouseY - canvasRect.top)/CELL_SIZE_Y);

				return [xCoord, yCoord];
			}

			cellCoords = mouseCoordsToMouseCoords(evt.clientX,evt.clientY);
			if (evt.button === 0){
				controller.setCell(cellCoords[0], cellCoords[1], true);
			} else if (evt.button === 2) {
				controller.setCell(cellCoords[0], cellCoords[1], false);
			};
		};
	};

	canvas.addEventListener("mousedown", function(evt){
		isDown = true;
		mouseListener(evt);
	});
	canvas.addEventListener("mouseup", function(evt){
		isDown = false;
	});

	// Listens for mouseclick to notify controller
	canvas.addEventListener("mousemove", mouseListener,false);

	//Whenever the Sheet gets updated in the controller/model, redraw it
	controller.addSubscriber(redrawSheet);

	redrawSheet();

});<|endoftext|>


<commit_before>(function() {
  'use strict';

  angular
    .module('app')
    .controller('MainController', ['$scope','$route','$rootScope','$location','requestService', '$translate',
    function($scope,$route,$rootScope,$location,requestService,$translate) {

      $rootScope.title = 'Leplanner beta';

      //console.log($rootScope.user);
      $scope.logout = function(){
        requestService.get('/user/logout')
          .then(function(data){
            console.log(data);
            $rootScope.user = undefined;
            $location.path('/');
          });
      };

      $scope.navigateToLogin = function($event){
        $event.preventDefault();
        if($location.path().toString() != '/'){
          $rootScope.navigatedToLoginFrom = $location.path();
          $location.path('/login');
        }else{
          // if from home page
          $location.path('/login');
        }

      };

      $scope.searchFromTop = function($event){
        if($location.path() == '/search'){
          $rootScope.top_search_word = $scope.top_search_word;
          $scope.$broadcast ('triggerSearchForm');
        }else{
          if(typeof $event !== 'undefined'){
            $event.preventDefault();
          }
          $rootScope.top_search_word = $scope.top_search_word;
          $location.path('/search');
        }
      };

      //var currentLang = $translate.proposedLanguage() || $translate.use();
      //console.log('language ' + currentLang);

      $scope.changeLanguage = function (langKey) {
        $translate.use(langKey).then(function(data){
            //if user - save preferred language
            if($rootScope.user){
                $scope.setLanguage();
            }else{
                //trigger on language change, change important defaults
                $scope.translateDefaults();
                $route.reload();
            }
        });
      };

      $scope.setLanguage = function(){
          var currentLang = $translate.proposedLanguage() || $translate.use();
          requestService.post('/user/save-language', {lang: currentLang})
            .then(function(data) {

              if(data.success){
                  //console.log(data.success);
                  $rootScope.user.lang = currentLang;
                  $scope.translateDefaults();
                  $route.reload();
              }

              if(data.error){
                //console.log(data);
                console.log('unable to set user lang');
              }
          });
      };

      $rootScope.translateDefaults = function(){
          //translate and store in rootScope
          //translate organization / CO_AUTHORSHIP and DISPLAYS
          //translate dropdown buttons texts
          //translate for confirm dialoge
          $translate([
              'ORGANIZATION.0','ORGANIZATION.1','ORGANIZATION.2','ORGANIZATION.3',
              'CO_AUTHORSHIP.0','CO_AUTHORSHIP.1','CO_AUTHORSHIP.2','CO_AUTHORSHIP.3','CO_AUTHORSHIP.4','CO_AUTHORSHIP.5','CO_AUTHORSHIP.6',
              'DISPLAYS.0','DISPLAYS.1','DISPLAYS.2','DISPLAYS.3','DISPLAYS.4','DISPLAYS.5',

              'INPUT.SUBJECTS', 'INPUT.UNCHECK_ALL', 'INPUT.SEARCH', 'INPUT.LEARNING_OUTCOMES', 'BUTTON.PUBLISHED', 'BUTTON.DRAFT',

              'NOTICE.DELETE_CONFIRM',

              'INPUT.LANGUAGE', 'BUTTON_LANG_LONG_ET', 'BUTTON_LANG_LONG_EN',

              'NOTICE.COPY_CONFIRM'
          ]).then(function (t) {

              $rootScope.translated = {
                  lang: $translate.use(),
                  organization: [t['ORGANIZATION.0'],t['ORGANIZATION.1'],t['ORGANIZATION.2'],t['ORGANIZATION.3']],
                  co_authorship: [t['CO_AUTHORSHIP.0'],t['CO_AUTHORSHIP.1'],t['CO_AUTHORSHIP.2'],t['CO_AUTHORSHIP.3'],t['CO_AUTHORSHIP.4'],t['CO_AUTHORSHIP.5'],t['CO_AUTHORSHIP.6']],
                  displays: [t['DISPLAYS.0'],t['DISPLAYS.1'],t['DISPLAYS.2'],t['DISPLAYS.3'],t['DISPLAYS.4'], t['DISPLAYS.5']],
                  dropdowns: {
                      subjects: t['INPUT.SUBJECTS'],
                      uncheck_all: t['INPUT.UNCHECK_ALL'],
                      search: t['INPUT.SEARCH'],
                      learning_outcomes: t['INPUT.LEARNING_OUTCOMES'],
                      published: t['BUTTON.PUBLISHED'],
                      draft: t['BUTTON.DRAFT'],
                      language: t['INPUT.LANGUAGE'],
                      estonian: t.BUTTON_LANG_LONG_ET,
                      english: t.BUTTON_LANG_LONG_EN,
                  },
                  confirm: t['NOTICE.DELETE_CONFIRM'],
                  copy_confirm: t['NOTICE.COPY_CONFIRM']
              };
              //console.log($rootScope.translated);

          });
      };

      //trigger on main load
      $scope.translateDefaults();

  }]); // MainController end
}());
<commit_msg>added logout and language save routes<commit_after>(function() {
  'use strict';

  angular
    .module('app')
    .controller('MainController', ['$scope','$route','$rootScope','$location','requestService', '$translate',
    function($scope,$route,$rootScope,$location,requestService,$translate) {

      $rootScope.title = 'Leplanner beta';

      //console.log($rootScope.user);
      $scope.logout = function(){

        requestService.post('/users/logout')
          .then(function(data){
            $rootScope.user = undefined;
            $location.path('/');
          })
          .catch(function(error) {
              console.log(error);
              window.alert('unable to logout, refresh the page');
          });
      };

      $scope.navigateToLogin = function($event){
        $event.preventDefault();
        if($location.path().toString() !== '/'){
          $rootScope.navigatedToLoginFrom = $location.path();
          $location.path('/login');
        }else{
          // if from home page
          $location.path('/login');
        }

      };

      $scope.searchFromTop = function($event){
        if($location.path() === '/search'){
          $rootScope.top_search_word = $scope.top_search_word;
          $scope.$broadcast ('triggerSearchForm');
        }else{
          if($event){
            $event.preventDefault();
          }
          $rootScope.top_search_word = $scope.top_search_word;
          $location.path('/search');
        }
      };

      //var currentLang = $translate.proposedLanguage() || $translate.use();
      //console.log('language ' + currentLang);

      $scope.changeLanguage = function (langKey) {
        $translate.use(langKey).then(function(data){
            //if user - save preferred language
            if($rootScope.user){
                $scope.setLanguage();
            }else{
                //trigger on language change, change important defaults
                $scope.translateDefaults();
                $route.reload();
            }
        });
      };

      $scope.setLanguage = function(){

          console.log('saving');

          var currentLang = $translate.proposedLanguage() || $translate.use();
          requestService.post('/users/language', { lang: currentLang })
            .then(function(data) {

              $rootScope.user.lang = currentLang;
              $scope.translateDefaults();
              $route.reload();
          })
          .catch(function (error) {
              console.log(error);
          });
      };

      $rootScope.translateDefaults = function(){
          //translate and store in rootScope
          //translate organization / CO_AUTHORSHIP and DISPLAYS
          //translate dropdown buttons texts
          //translate for confirm dialoge
          $translate([
              'ORGANIZATION.0','ORGANIZATION.1','ORGANIZATION.2','ORGANIZATION.3',
              'CO_AUTHORSHIP.0','CO_AUTHORSHIP.1','CO_AUTHORSHIP.2','CO_AUTHORSHIP.3','CO_AUTHORSHIP.4','CO_AUTHORSHIP.5','CO_AUTHORSHIP.6',
              'DISPLAYS.0','DISPLAYS.1','DISPLAYS.2','DISPLAYS.3','DISPLAYS.4','DISPLAYS.5',

              'INPUT.SUBJECTS', 'INPUT.UNCHECK_ALL', 'INPUT.SEARCH', 'INPUT.LEARNING_OUTCOMES', 'BUTTON.PUBLISHED', 'BUTTON.DRAFT',

              'NOTICE.DELETE_CONFIRM',

              'INPUT.LANGUAGE', 'BUTTON_LANG_LONG_ET', 'BUTTON_LANG_LONG_EN',

              'NOTICE.COPY_CONFIRM'
          ]).then(function (t) {

              $rootScope.translated = {
                  lang: $translate.use(),
                  organization: [t['ORGANIZATION.0'],t['ORGANIZATION.1'],t['ORGANIZATION.2'],t['ORGANIZATION.3']],
                  co_authorship: [t['CO_AUTHORSHIP.0'],t['CO_AUTHORSHIP.1'],t['CO_AUTHORSHIP.2'],t['CO_AUTHORSHIP.3'],t['CO_AUTHORSHIP.4'],t['CO_AUTHORSHIP.5'],t['CO_AUTHORSHIP.6']],
                  displays: [t['DISPLAYS.0'],t['DISPLAYS.1'],t['DISPLAYS.2'],t['DISPLAYS.3'],t['DISPLAYS.4'], t['DISPLAYS.5']],
                  dropdowns: {
                      subjects: t['INPUT.SUBJECTS'],
                      uncheck_all: t['INPUT.UNCHECK_ALL'],
                      search: t['INPUT.SEARCH'],
                      learning_outcomes: t['INPUT.LEARNING_OUTCOMES'],
                      published: t['BUTTON.PUBLISHED'],
                      draft: t['BUTTON.DRAFT'],
                      language: t['INPUT.LANGUAGE'],
                      estonian: t.BUTTON_LANG_LONG_ET,
                      english: t.BUTTON_LANG_LONG_EN,
                  },
                  confirm: t['NOTICE.DELETE_CONFIRM'],
                  copy_confirm: t['NOTICE.COPY_CONFIRM']
              };
              //console.log($rootScope.translated);

          });
      };

      //trigger on main load
      $scope.translateDefaults();

  }]); // MainController end
}());
<|endoftext|>


<commit_before>const editTextarea = {
  init() {
    // get all textarea elements with a maxlength attr
    const textAreaEls = document.querySelectorAll("textarea[data-max-length]");

    if (textAreaEls.length < 1) return;

    textAreaEls.forEach(el => {
      const limit = el.getAttribute("data-max-length");

      // create and insert counter element
      const counterEl = document.createElement("div");
      counterEl.innerText = `${el.innerHTML.length}/${limit}`;
      counterEl.className = "textarea-counter";
      el.insertAdjacentElement("afterend", counterEl);
      this.generateClass(counterEl, el.innerHTML.length, limit);

      // update count on every character change
      el.addEventListener("keyup", e => {
        const count = e.target.value.length;
        counterEl.innerText = `${count}/${limit}`;
        this.generateClass(counterEl, count, limit);
      });
    });
  },
  generateClass(counterEl, count, limit) {
    if (count > limit) {
      counterEl.classList.add("textarea-counter-over-limit");
    } else {
      counterEl.classList.remove("textarea-counter-over-limit");
    }
  }
};

export default editTextarea;
<commit_msg>Put textarea counter class in variable<commit_after>const editTextarea = {
  init() {
    // get all textarea elements with a maxlength attr
    const textAreaEls = document.querySelectorAll("textarea[data-max-length]");

    if (textAreaEls.length < 1) return;

    textAreaEls.forEach(el => {
      const limit = el.getAttribute("data-max-length");

      // create and insert counter element
      const counterEl = document.createElement("div");
      counterEl.innerText = `${el.innerHTML.length}/${limit}`;
      counterEl.className = "textarea-counter";
      el.insertAdjacentElement("afterend", counterEl);
      this.generateClass(counterEl, el.innerHTML.length, limit);

      // update count on every character change
      el.addEventListener("keyup", e => {
        const count = e.target.value.length;
        counterEl.innerText = `${count}/${limit}`;
        this.generateClass(counterEl, count, limit);
      });
    });
  },
  generateClass(counterEl, count, limit) {
    const textareaCounterClass = 'textarea-counter-over-limit';
    if (count > limit) {
      counterEl.classList.add(textareaCounterClass);
    } else {
      counterEl.classList.remove(textareaCounterClass);
    }
  }
};

export default editTextarea;
<|endoftext|>


<commit_before>var Fontomas = (function (_, XMLSerializer, Fontomas) {
  "use strict";

  $.extend(true, Fontomas, {lib: {util: {}}});

  var config = Fontomas.cfg;

  function notify(text, tpl, suppress_dup) {
    var tpl_vars = {
        text: text
      },
      options = config.notify.options;

    if (suppress_dup && (text !== undefined)) {
      if (config.notify.dup[text] !== undefined) {
        console.log("notification suppressed");
        return;
      }

      config.notify.dup[text] = true;
      $.extend(options, {
        close: function () {
          delete config.notify.dup[text];
          console.log("notification can be fired again");
        }
      });
    }

    $(config.id.notification).notify("create", tpl, tpl_vars, options);
  }

  Fontomas.lib.util.notify_alert = function (text, suppress_dup) {
    notify(text,
      config.notify.templates.alert,
      suppress_dup
    );
  };

  Fontomas.lib.util.notify_info = function (text, suppress_dup) {
    notify(text,
      config.notify.templates.info,
      suppress_dup
    );
  };

  // ===============
  // misc functions
  // ===============
  Fontomas.lib.util.outerHtml = function (jquery_object) {
    return $("<div/>").append(jquery_object.clone()).html();
  };

  Fontomas.lib.util.getAllAttrs = function (dom_node) {
    var result = {},
      attrs = dom_node.attributes,
      i, len;

    for (i=0, len=attrs.length; i<len; i++) {
      result[attrs[i].nodeName] = attrs[i].nodeValue;
    }

    return result;
  };

  Fontomas.lib.util.xmlToString = function(xmlDom) {
    // cross-browser
    var result = (typeof XMLSerializer !== "undefined") ?
      (new window.XMLSerializer()).serializeToString(xmlDom) :
      xmlDom.xml;
    //FIXME: quickfix: get rid of unwanted xmlns insertion
    result = result.replace(/ xmlns="http:\/\/www\.w3\.org\/1999\/xhtml"/g,
      "");
    //FIXME: quickfix: remove the extra newlines
    result = result.replace(/>(\s)*<glyph/gm, ">\n<glyph");
    //FIXME: quickfix: & => &
    result = result.replace(/&#x/gm, "&#x");
    return result;
  };

  Fontomas.lib.util.getFileExt = function (filepath) {
    var defaultval = "",
      index;
    if (!_.isString(filepath)) {
      return defaultval;
    }

    index = filepath.lastIndexOf(".");
    if (index === -1) {
      return defaultval;
    } else {
      return filepath.substr(index+1).toLowerCase();
    }
  };

  Fontomas.lib.util.joinList = function (array, delim1, delim2) {
    return array.reduce(function (prev, cur, idx, arr) {
      return arr.length !== idx+1 ?
        prev + delim1 + cur :
        prev + delim2 + cur;
    });
  };

  // trim string at both sides:
  // in:  s="abc{hello}def", begin="c{", end="}"
  // out: "hello"
  Fontomas.lib.util.trimBoth = function (s, begin, end) {
    var idx1 = s.indexOf(begin) + begin.length,
      idx2 = s.lastIndexOf(end);
    if (idx1 < idx2) {
      return s.substr(idx1, idx2 - idx1);
    } else {
      return s;
    }
  };

  Fontomas.lib.util.repeat = function (s, times) {
    /*jshint bitwise:false*/
    if (times < 1) {
      return "";
    }

    var result = "";
    while (times > 0) {
      if (times & 1) {
        result += s;
      }
      times >>= 1;
      s += s;
    }
    return result;
  };

  Fontomas.lib.util.rpad = function (s, len) {
    if (s.length < len) {
      return s + Fontomas.lib.util.repeat(" ", len - s.length);
    } else {
      return s;
    }
  };

  Fontomas.lib.util.lpad = function (s, len) {
    if (s.length < len) {
      return Fontomas.lib.util.repeat(" ", len - s.length) + s;
    } else {
      return s;
    }
  };

  Fontomas.lib.util.base64_encode = function (s) {
    /*jshint bitwise:false*/
    var table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
      result = "",

      chr1, chr2, chr3, enc1, enc2, enc3, enc4,
      i, len;

    for (i=0, len=s.length; i<len; i+=3) {
      chr1 = s.charCodeAt(i);
      chr2 = s.charCodeAt(i+1);
      chr3 = s.charCodeAt(i+2);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
        enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
        enc4 = 64;
      }

      result += table.charAt(enc1) + table.charAt(enc2) +
        table.charAt(enc3) + table.charAt(enc4);
    }

    return result;
  };
}(window._, window.XMLSerializer, Fontomas || {}));
<commit_msg>Refactor utils<commit_after>var Fontomas = (function (_, XMLSerializer, Fontomas) {
  "use strict";

  var exports = {}, config = Fontomas.cfg;

  function notify(tpl, text, suppress_dup) {
    var tpl_vars = {text: text},
        options  = config.notify.options;

    if (suppress_dup && (text !== undefined)) {
      if (config.notify.dup[text] !== undefined) {
        console.log("notification suppressed");
        return;
      }

      config.notify.dup[text] = true;

      $.extend(options, {
        close: function () {
          delete config.notify.dup[text];
          console.log("notification can be fired again");
        }
      });
    }

    $(config.id.notification).notify("create", tpl, tpl_vars, options);
  }

  exports.notify_alert = function (text, suppress_dup) {
    notify(config.notify.templates.alert, text, suppress_dup);
  };

  exports.notify_info = function (text, suppress_dup) {
    notify(config.notify.templates.info, text, suppress_dup);
  };

  // ===============
  // misc functions
  // ===============
  exports.outerHtml = function (jquery_object) {
    return $("<div/>").append(jquery_object.clone()).html();
  };

  exports.getAllAttrs = function (dom_node) {
    var result = {};

    _.each(dom_node.attributes, function (attr) {
      result[attr.nodeName] = attr.nodeValue;
    });

    return result;
  };

  exports.xmlToString = function(xmlDom) {
    var result;

    // cross-browser
    result = ("undefined" === typeof XMLSerializer) ? xmlDom.xml
      : (new window.XMLSerializer()).serializeToString(xmlDom);

    result = result
      //FIXME: quickfix: get rid of unwanted xmlns insertion
      .replace(/ xmlns="http:\/\/www\.w3\.org\/1999\/xhtml"/g, "")
      //FIXME: quickfix: remove the extra newlines
      .replace(/>(\s)*<glyph/gm, ">\n<glyph")
      //FIXME: quickfix: & => &
      .replace(/&#x/gm, "&#x");

    return result;
  };

  exports.getFileExt = function (filepath) {
    var index = String(filepath).lastIndexOf(".");
    return (index === -1) ? "" : filepath.substr(index+1).toLowerCase();
  };

  exports.joinList = function (array, delim1, delim2) {
    return _.reduce(array, function (prev, cur, idx, arr) {
      return prev + ((arr.length !== idx + 1) ? delim1 : delim2) + cur;
    });
  };

  // trim string at both sides:
  // in:  s="abc{hello}def", begin="c{", end="}"
  // out: "hello"
  exports.trimBoth = function (s, begin, end) {
    var idx1 = s.indexOf(begin) + begin.length, idx2 = s.lastIndexOf(end);
    return (idx1 >= idx2) ? s : s.substr(idx1, idx2 - idx1);
  };

  exports.repeat = function (s, times) {
    var result = "";

    while (0 < times) {
      result += s;
      times -= 1;
    }

    return result;
  };

  exports.rpad = function (s, len) {
    return s + exports.repeat(" ", len - s.length);
  };

  exports.lpad = function (s, len) {
    return exports.repeat(" ", len - s.length) + s;
  };

  exports.base64_encode = function (s) {
    /*jshint bitwise:false*/
    var table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
        result = "",
        chr1, chr2, chr3, enc1, enc2, enc3, enc4,
        i, l;

    for (i = 0, l = s.length; i < l; i += 3) {
      chr1 = s.charCodeAt(i);
      chr2 = s.charCodeAt(i+1);
      chr3 = s.charCodeAt(i+2);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
        enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
        enc4 = 64;
      }

      result += table.charAt(enc1) + table.charAt(enc2) + table.charAt(enc3) + table.charAt(enc4);
    }

    return result;
  };

  return $.extend(true, Fontomas, {lib: {util: exports}});
}(window._, window.XMLSerializer, Fontomas || {}));
<|endoftext|>


<commit_before>var exec = require('child_process').exec;
var fs = require('fs');
var path = require('path');

function write(path, contents, callback) {
  fs.writeFile(path, contents, function(err) {
    callback(err);
  })
}

function standalone(req) {
  var scope = this;
  var output = this.output;
  var section = this.section || '1';
  var args = req.args.slice(0);
  var file = path.join(output, path.basename(args[0]) + '.' + section);
  var arg = this.argument || '--help';
  if(!~args.indexOf(arg)) {
    args.push(arg);
  }
  var errstream = this.err === true;
  var cmd = args.join(' ');
  this.log.info('directory %s', output);
  this.log.info('file %s', file);
  exec(cmd, function(err, stdout, stderr) {
    if(err) {
      return scope.raise(err);
    }
    //process.stdout.write(errstream ? stderr : stdout);
    write(file, errstream ? stderr : stdout, function(err) {
      if(err) {
        return scope.raise(err);
      }
      scope.log.info('wrote %s', file);
    });
  })
}

function json(req, callback) {
  var args = req.args.slice(0);
  var arg = this.argument || '--help';
  if(!~args.indexOf(arg)) {
    args.push(arg);
  }
  var errstream = this.err === true;
  var cmd = args.join(' ');
  exec(cmd, function(err, stdout, stderr) {
    callback(err, errstream ? stderr : stdout);
  })
}

function all(req) {
  var scope = this;
  standalone.call(this, req)
  process.env.CLI_TOOLKIT_HELP_STYLE='json';
  json.call(this, req, function(err, document) {
    if(err) {
      return scope.raise(err);
    }
    var doc = null;
    try {
      doc = JSON.parse(document);
    }catch(e) {
      return scope.raise(e);
    }
    console.dir(doc);
  });
}

module.exports = function build(req) {
  process.env.CLI_TOOLKIT_HELP_STYLE='man';
  if(this.standalone) {
    return standalone.call(this, req);
  }
  all.call(this, req);
}
<commit_msg>Test for commands in json output.<commit_after>var exec = require('child_process').exec;
var fs = require('fs');
var path = require('path');

function write(path, contents, callback) {
  fs.writeFile(path, contents, function(err) {
    callback(err);
  })
}

function standalone(req, callback) {
  process.env.CLI_TOOLKIT_HELP_STYLE='man';
  var scope = this;
  var output = this.output;
  var section = this.section || '1';
  var args = req.args.slice(0);
  var file = path.join(output, path.basename(args[0]) + '.' + section);
  var arg = this.argument || '--help';
  if(!~args.indexOf(arg)) {
    args.push(arg);
  }
  var errstream = this.err === true;
  var cmd = args.join(' ');
  this.log.info('directory %s', output);
  this.log.info('file %s', file);
  exec(cmd, function(err, stdout, stderr) {
    if(err) {
      return scope.raise(err);
    }
    //process.stdout.write(errstream ? stderr : stdout);
    write(file, errstream ? stderr : stdout, function(err) {
      if(err) {
        return scope.raise(err);
      }
      scope.log.info('wrote %s', file);
      if(callback) callback();
    });
  })
}

function json(req, callback) {
  var args = req.args.slice(0);
  var arg = this.argument || '--help';
  if(!~args.indexOf(arg)) {
    args.push(arg);
  }
  var errstream = this.err === true;
  var cmd = args.join(' ');
  exec(cmd, function(err, stdout, stderr) {
    callback(err, errstream ? stderr : stdout);
  })
}

function all(req) {
  var scope = this;
  standalone.call(this, req, function() {
    process.env.CLI_TOOLKIT_HELP_STYLE='json';
    json.call(scope, req, function(err, document) {
      if(err) {
        return scope.raise(err);
      }
      var doc = null;
      try {
        doc = JSON.parse(document);
      }catch(e) {
        return scope.raise(e);
      }
      //console.dir(doc);
      var hasCommands = doc.commands
        && Object.keys(doc.commands).length > 0;
      if(hasCommands) {
        console.log('has command pages');
      }
    });
  });
}

module.exports = function build(req) {
  if(this.standalone) {
    return standalone.call(this, req);
  }
  all.call(this, req);
}
<|endoftext|>


<commit_before>'use strict';

var $ = window.$;

(function() {

    var CANDIDATES = {
        init: function() {
            this.fetch();
            this.search();
            this.reset();
            this.interviewRequest()
        },
        queryObject: {
                    jobTitle: $('select[name=jobTitle]').val(),
                    company: $('select[name=company]').val(),
                    jobCategory: $('select[name=jobCategory]').val(),
                    location: $('select[name=location]').val(),
                    salaryMin: $('select[name=salaryMin]').val(),
                    salaryMax: $('select[name=salaryMax]').val(),
                    contractType: $('select[name=contractType]').val()
                },
        fetch: function(query) {
            $.ajax({
                url: '/harnesstalent/results',
                data: query,
                success: function(response) {
                    if(response === false){
                        $('.ui.message').text('There is no talent');
                    }
                    console.log('RESULTS FORM BE', response);
                    var source = $('#candidates-template').html()
                    var template = Handlebars.compile(source);
                    var context = response.array;
                    var userType = response.userType;
                    if(userType === 'admin'){
                        $('.client-menus').remove();
                    }
                    var populatedHTML = template(context);
                    $('#candidates-container').html(populatedHTML);
                    DOCUMENTVIEWER.init();
                    CANDIDATES.interviewRequest();
                }
            });
        },
        search: function() {
            let self =this;
            $('.search').on('click', function() {

                var queryObj = {
                    jobTitle: $('select[name=jobTitle]').val(),
                    company: $('select[name=company]').val(),
                    jobCategory: $('select[name=jobCategory]').val(),
                    location: $('select[name=location]').val(),
                    salaryMin: $('select[name=salaryMin]').val(),
                    salaryMax: $('select[name=salaryMax]').val(),
                    contractType: $('select[name=contractType]').val()
                }
                let query = $.param(queryObj);
                CANDIDATES.fetch(query);
            });
        },
        reset: function(){
             var self = this;
             $('.reset').on('click', function() {
                for(var key in self.queryObject){
                    $('select[name='+key+']').val('All');
                }
                CANDIDATES.fetch();
            });
        },
        interviewRequest: function(){
            let self =this;
            $('.interviewRequest').on('click', function(){
                $('.message').text('');
                let cvid = $(this).data('cvid');
                $('#' + cvid).toggleClass('hide-element');
                $('.ui.message.info').removeClass('.ui.info');
                $('#' + cvid).modal('show');
                $( ".datepicker" ).datepicker({dateFormat: 'DD, d MM, yy'});
                AWS.init();
                self.sendInterviewRequest();
            });
        },
        sendInterviewRequest: function(){
                var self = this;

                $('.button.send-interview').off().on('click', function(e) {
                    e.preventDefault();
                    const cvid = $(this).data('cvid');
                    let form =  document.forms[cvid];
                    let firstTime = form['firstIntTime'].value;
                    let firstDate = form['firstIntDate'].value;
                    let interviewAddress = form['interviewAddress'].value;
                    //let stage = form['stage'].value;
                    let fields = [firstDate, firstTime, interviewAddress];
                    let validated =  self.validate(fields);

                    if ( validated[0] === '' || validated[0] === null ){
                        return  $('.message').addClass('ui info').text('We need the date, time, stage and location of the interview');
                    } else {
                        let formData = $('form[name='+cvid+']').each(function(){ $(this).find(':input');});
                        return  self.sendFormData(formData ,cvid);
                    }
                });
        },
        validate: function(fields){
            var self = this;
            return  fields.filter(self.checkForEmpty);
        },
        checkForEmpty: function(field){
             return field ==''|| field == null;
        },
        sendFormData: function(formData, cvid){
            var data = formData.serialize();
            //console.log('DATA', data);
                $.ajax({
                    type: 'POST',
                    url: '/harnesstalent/interview/proposed',
                    data: data,
                    async: true,
                    success: function(cvid) {
                        if (cvid) {
                            $('.message').addClass('ui info message').text("We\'ve emailed the agent to arrange an interview"); // change to something better...
                            $('#' + cvid).modal('hide');
                            $('button[data-cvid='+cvid+']').text('Requested Interview').addClass('orange');
                            $('form[name='+cvid+']').find("input, textarea").val("");
                        } else {
                            $('#' + cvid).modal('hide');
                            $('.message').innerHTML = 'Sorry, there was an error. Please try again!';
                        }
                    },
                    error: function(res) {
                        console.log("ERROR", res);
                        $('#' + cvid).modal('hide');
                        $('.message').innerHTML = 'Sorry, there was an error. Please try again!';
                    }
            });
        },
        datepicker: function(){
             $( ".datepicker" ).datepicker({dateFormat: 'DD, d MM, yy'});
        }
    };
    CANDIDATES.init();

})();
<commit_msg>request interview orange<commit_after>'use strict';

var $ = window.$;

(function() {

    var CANDIDATES = {
        init: function() {
            this.fetch();
            this.search();
            this.reset();
            this.interviewRequest()
        },
        queryObject: {
                    jobTitle: $('select[name=jobTitle]').val(),
                    company: $('select[name=company]').val(),
                    jobCategory: $('select[name=jobCategory]').val(),
                    location: $('select[name=location]').val(),
                    salaryMin: $('select[name=salaryMin]').val(),
                    salaryMax: $('select[name=salaryMax]').val(),
                    contractType: $('select[name=contractType]').val()
                },
        fetch: function(query) {
            $.ajax({
                url: '/harnesstalent/results',
                data: query,
                success: function(response) {
                    if(response === false){
                        $('.ui.message').text('There is no talent');
                    }
                    console.log('RESULTS FORM BE', response);
                    var source = $('#candidates-template').html()
                    var template = Handlebars.compile(source);
                    var context = response.array;
                    var userType = response.userType;
                    if(userType === 'admin'){
                        $('.client-menus').remove();
                    }
                    var populatedHTML = template(context);
                    $('#candidates-container').html(populatedHTML);
                    DOCUMENTVIEWER.init();
                    CANDIDATES.interviewRequest();
                }
            });
        },
        search: function() {
            let self =this;
            $('.search').on('click', function() {

                var queryObj = {
                    jobTitle: $('select[name=jobTitle]').val(),
                    company: $('select[name=company]').val(),
                    jobCategory: $('select[name=jobCategory]').val(),
                    location: $('select[name=location]').val(),
                    salaryMin: $('select[name=salaryMin]').val(),
                    salaryMax: $('select[name=salaryMax]').val(),
                    contractType: $('select[name=contractType]').val()
                }
                let query = $.param(queryObj);
                CANDIDATES.fetch(query);
            });
        },
        reset: function(){
             var self = this;
             $('.reset').on('click', function() {
                for(var key in self.queryObject){
                    $('select[name='+key+']').val('All');
                }
                CANDIDATES.fetch();
            });
        },
        interviewRequest: function(){
            let self =this;
            $('.interviewRequest').on('click', function(){
                $('.message').text('');
                let cvid = $(this).data('cvid');
                $('#' + cvid).toggleClass('hide-element');
                $('.ui.message.info').removeClass('.ui.info');
                $('#' + cvid).modal('show');
                $( ".datepicker" ).datepicker({dateFormat: 'DD, d MM, yy'});
                AWS.init();
                self.sendInterviewRequest();
            });
        },
        sendInterviewRequest: function(){
                var self = this;

                $('.button.send-interview').off().on('click', function(e) {
                    e.preventDefault();
                    const cvid = $(this).data('cvid');
                    let form =  document.forms[cvid];
                    let firstTime = form['firstIntTime'].value;
                    let firstDate = form['firstIntDate'].value;
                    let interviewAddress = form['interviewAddress'].value;
                    //let stage = form['stage'].value;
                    let fields = [firstDate, firstTime, interviewAddress];
                    let validated =  self.validate(fields);

                    if ( validated[0] === '' || validated[0] === null ){
                        return  $('.message').addClass('ui info').text('We need the date, time, stage and location of the interview');
                    } else {
                        let formData = $('form[name='+cvid+']').each(function(){ $(this).find(':input');});
                        return  self.sendFormData(formData ,cvid);
                    }
                });
        },
        validate: function(fields){
            var self = this;
            return  fields.filter(self.checkForEmpty);
        },
        checkForEmpty: function(field){
             return field ==''|| field == null;
        },
        sendFormData: function(formData, cvid){
            var data = formData.serialize();
            //console.log('DATA', data);
                $.ajax({
                    type: 'POST',
                    url: '/harnesstalent/interview/proposed',
                    data: data,
                    async: true,
                    success: function(cvid) {
                        if (cvid) {
                            $('.message').addClass('ui info message').text("We\'ve emailed the agent to arrange an interview"); // change to something better...
                            $('#' + cvid).modal('hide');
                            $('button[data-cvid='+cvid+'].interviewRequest').text('Requested Interview').addClass('orange');
                            $('form[name='+cvid+']').find("input, textarea").val("");
                        } else {
                            $('#' + cvid).modal('hide');
                            $('.message').innerHTML = 'Sorry, there was an error. Please try again!';
                        }
                    },
                    error: function(res) {
                        console.log("ERROR", res);
                        $('#' + cvid).modal('hide');
                        $('.message').innerHTML = 'Sorry, there was an error. Please try again!';
                    }
            });
        },
        datepicker: function(){
             $( ".datepicker" ).datepicker({dateFormat: 'DD, d MM, yy'});
        }
    };
    CANDIDATES.init();

})();
<|endoftext|>


<commit_before>const path = require('path');
const yaml = require('js-yaml');
const helpers = require('spacedoc-helpers');

/**
 * Create an HTML page out of a documentation object.
 * @param {PageData} data - Page object generated by `Spacedoc.parse()`.
 * @throws Will throw an error if no template was set with `Spacedoc.config()`.
 * @throws Will throw an error if the template encounters an error while rendering.
 * @returns {String} Rendered HTML string.
 */
module.exports = function build(data = {}) {
  // Render a template with the component's data and write it to disk
  let output = '';

  let helper = name => this.adapters[name].template({
    groups: data.docs[name],
    helpers: Object.assign({}, helpers, this.adapters[name].helpers)
  });

  // Extend file data with global data and template locals
  data = Object.assign({}, this.options.data, data, {
    spacedoc: helper
  });

  // Catch template errors, because they won't show up in the Gulp console
  try {
    output = this.template(data);
  }
  catch (e) {
    throw new Error(`Spacedoc.build(): template error - ${e.message}`);
  }

  if (this.options.keepFm) {
    output = `---\n${yaml.safeDump(data._frontMatter)}\n---\n\n${output}` ;
  }

  return output;
}
<commit_msg>Log Pug errors to the console, as the thrown errors get lost in the stream<commit_after>const path = require('path');
const yaml = require('js-yaml');
const helpers = require('spacedoc-helpers');

/**
 * Create an HTML page out of a documentation object.
 * @param {PageData} data - Page object generated by `Spacedoc.parse()`.
 * @throws Will throw an error if no template was set with `Spacedoc.config()`.
 * @throws Will throw an error if the template encounters an error while rendering.
 * @returns {String} Rendered HTML string.
 */
module.exports = function build(data = {}) {
  // Render a template with the component's data and write it to disk
  let output = '';

  const helper = name => this.adapters[name].template({
    groups: data.docs[name],
    helpers: Object.assign({}, helpers, this.adapters[name].helpers)
  });

  // Extend file data with global data and template locals
  data = Object.assign({}, this.options.data, data, {
    spacedoc: helper
  });

  // Catch template errors, because they won't show up in the Gulp console
  try {
    output = this.template(data);
  }
  catch (e) {
    console.warn('Spacedoc.build(): ', e);
  }

  if (this.options.keepFm) {
    output = `---\n${yaml.safeDump(data._frontMatter)}\n---\n\n${output}` ;
  }

  return output;
}
<|endoftext|>