<commit_before>//
// Author:: Adam Jacob (<adam@opscode.com>)
// Author:: AJ Christensen (<aj@junglist.gen.nz>)
// Copyright:: Copyright (c) 2008 Opscode, Inc.
// License:: Apache License, Version 2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

$(document).ready(function(){

  var buildHiddenFormFromDragDrop = function(form, runListSet) {
    runListSet.each(function(i, envRunListUl) {
      runListItemList = $(envRunListUl).find('li.runListItem')
      if(runListItemList.length == 0){
        activeRunListUl = envRunListUl.getAttribute("class").split(" ").indexOf('active')
        if(activeRunListUl >= 0){
          form.append('<input type="hidden" name="env_run_lists[' + envRunListUl.id + ']"/>');
        }
      }
      else{
        runListItemList.each(function(i, field) {
          form.append('<input type="hidden" name="env_run_lists[' + envRunListUl.id + '][]" value="' + field.id + '"/>');
        });
      }
    });
  };

  var buildHiddenFormFromJSONEditor = function(form) {
    form.append('<input type="hidden" id="default_attributes" name="default_attributes"/>');
    $('input#default_attributes').attr('value', BCJTEP.save('json["defaults"]'));
    form.append('<input type="hidden" id="override_attributes" name="override_attributes"/>');
    $('input#override_attributes').attr('value', BCJTEP.save('json["overrides"]'));
  };

  $('a#debugFormBuild').click(function(event) {buildHiddenFormFromDragDrop(event)});

  $('form.roleForm').submit(function(event) {
    buildHiddenFormFromDragDrop($(this), $('ul.runListItemList'));
    buildHiddenFormFromJSONEditor($(this));
  });

  $('form#edit_environment, form#create_environment').submit(function(event) {
    buildHiddenFormFromJSONEditor($(this));
  });

  $('form#edit_node, form#create_node').submit(function(event) {
    var form = $(this);
    var to_node = $('ul#for_node').sortable('toArray');
    if (form.attr('id') == 'edit_node') {
      form.append('<input type="hidden" name="_method" value="put">');
    }
    form.append($('input#node_name')).css('display', 'none');
    form.append('<input type="hidden" id="attributes" name="attributes"/>');
    $('input#attributes').attr('value', BCJTEP.save());
    jQuery.each(to_node, function(i, field) {
      form.append('<input type="hidden" name="for_node[]" value="' + field + '"/>');
    });
  });

  $('form#edit_databag_item, form#create_databag_item').submit(function(event) {
    var form = $(this);
    if (form.attr('id') == 'edit_databag_item') {
      form.append('<input type="hidden" name="_method" value="put">');
    }
    form.append('<input type="hidden" id="json_data" name="json_data"/>');
    form.append($('input#json_data').attr('value', BCJTEP.save()));
  });

  $('form#edit_databag, form#create_databag').submit(function(event) {
    var form = $(this);
    if (form.attr('id') == 'edit_databag') {
      form.append('<input type="hidden" name="_method" value="put">');
    }
    form.append($('input#databag_name')).css('display', 'none');
  });

  $('form#edit_client, form#create_client').submit(function(event) {
    var form = $(this);
    if (form.attr('id') == 'edit_client') {
      form.append('<input type="hidden" name="_method" value="put">');
    }
    form.append($('input#client_name')).css('display', 'none');
    form.append($('input#client_admin')).css('display', 'none');
    form.append($('input#client_private_key')).css('display', 'none');
    form.append($('input#regen_private_key')).css('display', 'none');

  });

  $('form#edit_user, form#login').submit(function(event) {
    var form = $(this);
    if (form.attr('id') == 'edit_user') {
      form.append('<input type="hidden" name="_method" value="put">');
      form.append($('input#user_new_password')).css('display', 'none');
      form.append($('input#user_admin')).css('display', 'none');
      form.append($('input#user_confirm_new_password')).css('display', 'none');
      form.append($('input#openid')).css('display', 'none');
    }
    if (form.attr('id') == 'login') {
      form.append($('input#user_name')).css('display', 'none');
      form.append($('input#password')).css('display', 'none');
    }
  });

  // livequery hidden form for link_to ajax magic
  $(document.body).delegate('a[method]', 'click', function(e){
    var $this = $(this);
    var message = $this.attr('confirm'), method  = $this.attr('method');

    if (!method && !message) return;

    if (message && !confirm(message)) {
      event.preventDefault();
      return;
    }

    if (method === 'post' || method === 'put' || method === 'delete') {
      event.preventDefault();
      var form = $("<form/>").attr('method', 'post').attr('action', this.href).attr('style', 'display: none');
      if (method !== "post") {
          form.append($('<input type="hidden" name="_method"/>').attr('value', method));
        }
        form.insertAfter(this).submit();
      }
    });
  });

  // accordion for the cookbooks show view
  $('.accordion .head').click(function() {
    $(this).next().toggle('slow');
    return false;
  }).next().hide();

  // global facebox callback
  $('a[rel*=facebox]').facebox();

  var enableDragDropBehavior = function() {
    $('.connectedSortable').sortable({
      placeholder: 'ui-state-highlight',
      connectWith: $('.connectedSortable')
    }).disableSelection();
  };

  var disableDragDropBehavior = function() {
    $('.connectedSortable').sortable("destroy");
  };

  enableDragDropBehavior();

  // The table tree!
  $('table.tree').treeTable({ expandable: true });
  $('span.expander').click(function() { $('tr#' + $(this).attr('toggle')).toggleBranch(); });

  // Tooltips
  $("div.tooltip").tooltip({
      position: ['center', 'right'],
      offset: [-5, 10],
      effect: 'toggle',
      opacity: 0.7
  });

  // Show the sidebars if they have text in them!
  var sidebar_block_notice_children = $("#sidebar_block_notice").children().length;
  var sidebar_block_children = $("#sidebar_block").children().length;

  if (sidebar_block_notice_children > 0) {
    $("#sidebar_block_notice").fadeIn();
  }

  if (sidebar_block_children > 0) {
    $("#sidebar_block").fadeIn();
  }

  // Run list editor with per-env run lists for roles

  var populateAvailableRecipesForEnv = function(currentEnvironment, callback) {
    $.getJSON('/environments/' + currentEnvironment + '/recipes', function(data) {
      $('div#available_recipes_container .spinner').hide();
      for (var i=0; i < data['recipes'].length; i++) {
        var recipe = data['recipes'][i];
        $('ul.availableRecipes').append('
' +  recipe + '
');
      }
    });
    if (callback) { callback(); }
  };

  var depopulateAvailableRecipesForEnv = function() {
    $('ul.availableRecipes li').remove();
    $('div#available_recipes_container .spinner').show();
  };

  // If the attribute 'data-initial-env' exists on this element, use it to load
  // the recipes for that environment via ajax.
  var initialEnvironment = $('div#environmentRunListSelector').data('initial-env');
  if (initialEnvironment) {
    populateAvailableRecipesForEnv(initialEnvironment);
  }

  var resetAvailableRoleList = function() {
    $('ul#availableRoles li').remove();
    var allRoles = $('ul#availableRoles').data('role-list');
    for (var i=0; i < allRoles.length; i++) {
      var role = allRoles[i];
      $('ul#availableRoles').append('
' + role + '
');
    }

  };

  var clearRunListFor = function(environment) {
    $('ul.runListItemList#' + environment).children().remove();
  };

  var removeEnvironmentFromCloneControls = function(environment) {
    $('select.environmentToClone option[value="' + environment + '"]').remove();
  };

  var addEnvironmentToCloneControls = function(environment) {
    $('select.environmentToClone').append('<option value="' + environment + '">' + environment + '</option>');
  };

  var deleteEnvRunList = function(environment) {
    clearRunListFor(environment);
    $('ul.runListItemList#' + environment).removeClass('active').addClass('inactive');
    $('div.emptyRunListControlsContainer#' + environment).removeClass('inactive').addClass('active');
    $('div.runListAdditionalControls#' + environment + " a").remove();
    removeEnvironmentFromCloneControls(environment);
  };

  var createRunListDeleteLinkFor = function(environment) {
    // remove any existing link
    $('a.deleteEnvRunList#' + environment).remove();
    var containerDiv = $('div.runListAdditionalControls#' + environment);
    var link = 'Remove environment specific run list for ' + environment + '';
    containerDiv.append(link);
    containerDiv.find('a').click(function(j) {deleteEnvRunList(environment);});
  };

  $('a.createEmptyRunListControl').each(function(i) {
    var environment = $(this).attr('id');
    $(this).click(function(event) {
      $('div.emptyRunListControlsContainer#' + environment).removeClass('active').addClass('inactive');
      var runListContainerForEnv = $('div.runListContainer#' + environment + 'RunListContainer');
      $('ul.runListItemList#' + environment).removeClass('inactive').addClass('active');
      // remove all previous drag/drop events/behavior/whatever, then re-add it for the new run list container
      disableDragDropBehavior();
      enableDragDropBehavior();
      createRunListDeleteLinkFor(environment);
      addEnvironmentToCloneControls(environment);
    });
  });

  var setActiveRunListLabelFor = function(environment) {
    var labelElement = $('span#selectedRunListEditorLabel');
    if (environment === '_default') {
      labelElement.html('Default Run List');
    }
    else {
      labelElement.html('Run List for ' + environment);
    }
  };

  $('a.deleteEnvRunList').each(function(i) {
   var environment = $(this).attr('id');
   $(this).click(function(j) {deleteEnvRunList(environment);});
  });

  $('select#activeEnvironment').change(function() {
    // set the active run list editor
    var newActiveEnvironment = $(this).val();
    if (newActiveEnvironment !== 'noop') {
      $('div.runListWithControlsContainer.active').removeClass('active').addClass('inactive');
      $('div.runListWithControlsContainer#' + newActiveEnvironment).addClass('active', 10000).removeClass('inactive');
      setActiveRunListLabelFor(newActiveEnvironment);
      depopulateAvailableRecipesForEnv();
      var selector = $(this);
      populateAvailableRecipesForEnv(newActiveEnvironment, function() { selector.val('noop');});
      resetAvailableRoleList();
    }
  });

  $('select.environmentToClone').change(function() {
    var environmentToClone = $(this).val();
    var targetEnvironment = $(this).attr('id');
    var targetRunList = $('ul.runListItemList#' + targetEnvironment);
    clearRunListFor(targetEnvironment); // be sure we start with a clean slate
    $('ul.runListItemList#' + environmentToClone).children().clone().appendTo(targetRunList);
    $('ul.runListItemList#' + targetEnvironment).removeClass('inactive').addClass('active');
    $('div.emptyRunListControlsContainer#' + targetEnvironment).removeClass('active').addClass('inactive');
    createRunListDeleteLinkFor(targetEnvironment);
    addEnvironmentToCloneControls(targetEnvironment);
  });

  $('select#nodeEnvironment').change(function() {
    // set the active run list editor
    var newNodeEnvironment = $(this).val();
    depopulateAvailableRecipesForEnv();
    populateAvailableRecipesForEnv(newNodeEnvironment);
  });

});
<commit_msg>bugfixes ans jslinting<commit_after>//
// Author:: Adam Jacob (<adam@opscode.com>)
// Author:: AJ Christensen (<aj@junglist.gen.nz>)
// Copyright:: Copyright (c) 2008 Opscode, Inc.
// License:: Apache License, Version 2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

$(document).ready(function(){

  var buildHiddenFormFromDragDrop = function(form, runListSet) {
    runListSet.each(function(i, envRunListUl) {
      runListItemList = $(envRunListUl).find('li.runListItem')
      if(runListItemList.length == 0){
        activeRunListUl = envRunListUl.getAttribute("class").split(" ").indexOf('active')
        if(activeRunListUl >= 0){
          form.append('<input type="hidden" name="env_run_lists[' + envRunListUl.id + ']"/>');
        }
      }
      else{
        runListItemList.each(function(i, field) {
          form.append('<input type="hidden" name="env_run_lists[' + envRunListUl.id + '][]" value="' + field.id + '"/>');
        });
      }
    });
  };

  var buildHiddenFormFromJSONEditor = function(form) {
    form.append('<input type="hidden" id="default_attributes" name="default_attributes"/>');
    $('input#default_attributes').attr('value', BCJTEP.save('json["defaults"]'));
    form.append('<input type="hidden" id="override_attributes" name="override_attributes"/>');
    $('input#override_attributes').attr('value', BCJTEP.save('json["overrides"]'));
  };

  $('a#debugFormBuild').click(function(event) {buildHiddenFormFromDragDrop(event)});

  $('form.roleForm').submit(function(event) {
    buildHiddenFormFromDragDrop($(this), $('ul.runListItemList'));
    buildHiddenFormFromJSONEditor($(this));
  });

  $('form#edit_environment, form#create_environment').submit(function(event) {
    buildHiddenFormFromJSONEditor($(this));
  });

  $('form#edit_node, form#create_node').submit(function(event) {
    var form = $(this);
    var to_node = $('ul#for_node').sortable('toArray');
    if (form.attr('id') === 'edit_node') {
      form.append('<input type="hidden" name="_method" value="put">');
    }
    form.append($('input#node_name')).css('display', 'none');
    form.append('<input type="hidden" id="attributes" name="attributes"/>');
    $('input#attributes').attr('value', BCJTEP.save());
    jQuery.each(to_node, function(i, field) {
      form.append('<input type="hidden" name="for_node[]" value="' + field + '"/>');
    });
  });

  $('form#edit_databag_item, form#create_databag_item').submit(function(event) {
    var form = $(this);
    if (form.attr('id') === 'edit_databag_item') {
      form.append('<input type="hidden" name="_method" value="put">');
    }
    form.append('<input type="hidden" id="json_data" name="json_data"/>');
    form.append($('input#json_data').attr('value', BCJTEP.save()));
  });

  $('form#edit_databag, form#create_databag').submit(function(event) {
    var form = $(this);
    if (form.attr('id') === 'edit_databag') {
      form.append('<input type="hidden" name="_method" value="put">');
    }
    form.append($('input#databag_name')).css('display', 'none');
  });

  $('form#edit_client, form#create_client').submit(function(event) {
    var form = $(this);
    if (form.attr('id') === 'edit_client') {
      form.append('<input type="hidden" name="_method" value="put">');
    }
    form.append($('input#client_name')).css('display', 'none');
    form.append($('input#client_admin')).css('display', 'none');
    form.append($('input#client_private_key')).css('display', 'none');
    form.append($('input#regen_private_key')).css('display', 'none');

  });

  $('form#edit_user, form#login').submit(function(event) {
    var form = $(this);
    if (form.attr('id') === 'edit_user') {
      form.append('<input type="hidden" name="_method" value="put">');
      form.append($('input#user_new_password')).css('display', 'none');
      form.append($('input#user_admin')).css('display', 'none');
      form.append($('input#user_confirm_new_password')).css('display', 'none');
      form.append($('input#openid')).css('display', 'none');
    }
    if (form.attr('id') === 'login') {
      form.append($('input#user_name')).css('display', 'none');
      form.append($('input#password')).css('display', 'none');
    }
  });

  // livequery hidden form for link_to ajax magic
  $(document.body).delegate('a[method]', 'click', function(e){
    var $this = $(this);
    var message = $this.attr('confirm'), method = $this.attr('method');

    if (!method && !message) {
      return;
    }

    if (message && !confirm(message)) {
      event.preventDefault();
      return;
    }

    if (method === 'post' || method === 'put' || method === 'delete') {
      event.preventDefault();
      var form = $("<form/>").attr('method', 'post').attr('action', this.href).attr('style', 'display: none');
      if (method !== "post") {
          form.append($('<input type="hidden" name="_method"/>').attr('value', method));
        }
        form.insertAfter(this).submit();
      }
  });

  // accordion for the cookbooks show view
  $('.accordion .head').click(function() {
    $(this).next().toggle('slow');
    return false;
  }).next().hide();

  // global facebox callback
  $('a[rel*=facebox]').facebox();

  var enableDragDropBehavior = function() {
    $('.connectedSortable').sortable({
      placeholder: 'ui-state-highlight',
      connectWith: $('.connectedSortable')
    }).disableSelection();
  };

  var disableDragDropBehavior = function() {
    $('.connectedSortable').sortable("destroy");
  };

  enableDragDropBehavior();

  // The table tree!
  $('table.tree').treeTable({ expandable: true });
  $('span.expander').click(function() { $('tr#' + $(this).attr('toggle')).toggleBranch(); });

  // Tooltips
  $("div.tooltip").tooltip({
      position: ['center', 'right'],
      offset: [-5, 10],
      effect: 'toggle',
      opacity: 0.7
  });

  // Show the sidebars if they have text in them!
  var sidebar_block_notice_children = $("#sidebar_block_notice").children().length;
  var sidebar_block_children = $("#sidebar_block").children().length;

  if (sidebar_block_notice_children > 0) {
    $("#sidebar_block_notice").fadeIn();
  }

  if (sidebar_block_children > 0) {
    $("#sidebar_block").fadeIn();
  }

  // Run list editor with per-env run lists for roles

  var populateAvailableRecipesForEnv = function(currentEnvironment, callback) {
    $.getJSON('/environments/' + currentEnvironment + '/recipes', function(data) {
      $('div#available_recipes_container .spinner').hide();
      for (var i=0; i < data['recipes'].length; i++) {
        var recipe = data['recipes'][i];
        $('ul.availableRecipes').append('
' +  recipe + '
');
      }
    });
    if (callback) { callback(); }
  };

  var depopulateAvailableRecipesForEnv = function() {
    $('ul.availableRecipes li').remove();
    $('div#available_recipes_container .spinner').show();
  };

  // If the attribute 'data-initial-env' exists on this element, use it to load
  // the recipes for that environment via ajax.
  var initialEnvironment = $('div#environmentRunListSelector').data('initial-env');
  if (initialEnvironment) {
    populateAvailableRecipesForEnv(initialEnvironment);
  }

  var resetAvailableRoleList = function() {
    $('ul#availableRoles li').remove();
    var allRoles = $('ul#availableRoles').data('role-list');
    for (var i=0; i < allRoles.length; i++) {
      var role = allRoles[i];
      $('ul#availableRoles').append('
' + role + '
');
    }

  };

  var clearRunListFor = function(environment) {
    $('ul.runListItemList#' + environment).children().remove();
  };

  var removeEnvironmentFromCloneControls = function(environment) {
    $('select.environmentToClone option[value="' + environment + '"]').remove();
  };

  var addEnvironmentToCloneControls = function(environment) {
    $('select.environmentToClone').append('<option value="' + environment + '">' + environment + '</option>');
  };

  var deleteEnvRunList = function(environment) {
    clearRunListFor(environment);
    $('ul.runListItemList#' + environment).removeClass('active').addClass('inactive');
    $('div.emptyRunListControlsContainer#' + environment).removeClass('inactive').addClass('active');
    $('div.runListAdditionalControls#' + environment + " a").remove();
    removeEnvironmentFromCloneControls(environment);
  };

  var createRunListDeleteLinkFor = function(environment) {
    // remove any existing link
    $('a.deleteEnvRunList#' + environment).remove();
    var containerDiv = $('div.runListAdditionalControls#' + environment);
    var link = 'Remove environment specific run list for ' + environment + '';
    containerDiv.append(link);
    containerDiv.find('a').click(function(j) {deleteEnvRunList(environment);});
  };

  $('a.createEmptyRunListControl').each(function(i) {
    var environment = $(this).attr('id');
    $(this).click(function(event) {
      $('div.emptyRunListControlsContainer#' + environment).removeClass('active').addClass('inactive');
      var runListContainerForEnv = $('div.runListContainer#' + environment + 'RunListContainer');
      $('ul.runListItemList#' + environment).removeClass('inactive').addClass('active');
      // remove all previous drag/drop events/behavior/whatever, then re-add it for the new run list container
      disableDragDropBehavior();
      enableDragDropBehavior();
      createRunListDeleteLinkFor(environment);
      addEnvironmentToCloneControls(environment);
    });
  });

  var setActiveRunListLabelFor = function(environment) {
    var labelElement = $('span#selectedRunListEditorLabel');
    if (environment === '_default') {
      labelElement.html('Default Run List');
    }
    else {
      labelElement.html('Run List for ' + environment);
    }
  };

  $('a.deleteEnvRunList').each(function(i) {
   var environment = $(this).attr('id');
   $(this).click(function(j) {deleteEnvRunList(environment);});
  });

  $('select#activeEnvironment').change(function() {
    // set the active run list editor
    var newActiveEnvironment = $(this).val();
    if (newActiveEnvironment !== 'noop') {
      $('div.runListWithControlsContainer.active').removeClass('active').addClass('inactive');
      $('div.runListWithControlsContainer#' + newActiveEnvironment).addClass('active', 10000).removeClass('inactive');
      setActiveRunListLabelFor(newActiveEnvironment);
      depopulateAvailableRecipesForEnv();
      var selector = $(this);
      populateAvailableRecipesForEnv(newActiveEnvironment, function() { selector.val('noop');});
      resetAvailableRoleList();
    }
  });

  $('select.environmentToClone').change(function() {
    var environmentToClone = $(this).val();
    var targetEnvironment = $(this).attr('id');
    var targetRunList = $('ul.runListItemList#' + targetEnvironment);
    clearRunListFor(targetEnvironment); // be sure we start with a clean slate
    $('ul.runListItemList#' + environmentToClone).children().clone().appendTo(targetRunList);
    $('ul.runListItemList#' + targetEnvironment).removeClass('inactive').addClass('active');
    $('div.emptyRunListControlsContainer#' + targetEnvironment).removeClass('active').addClass('inactive');
    createRunListDeleteLinkFor(targetEnvironment);
    addEnvironmentToCloneControls(targetEnvironment);
  });

  $('select#nodeEnvironment').change(function() {
    // set the active run list editor
    var newNodeEnvironment = $(this).val();
    depopulateAvailableRecipesForEnv();
    populateAvailableRecipesForEnv(newNodeEnvironment);
  });

});
<|endoftext|>


<commit_before>FACING = ["up", "left", "down", "right"];

function DrawnRobot(){
  imgElement = document.getElementById('robot-icon');
  this.body = new fabric.Image(imgElement, {
    left: 200,
    top: 390,
    fill: '#006569',
    width: 20,
    height: 20,
    originX: 'center',
    originY: 'center',
    selectable: false,
    crashed: false
  });
  this.facing =  FACING[0];
  this.canvas = new fabric.Canvas('myCanvas');
  this.queuedInstructions = [];
}

DrawnRobot.prototype.doTheseFrames = function(instructionsArr){
  this.queuedInstructions = instructionsArr;
};

DrawnRobot.prototype.getNextInstruction = function(){
  var robot = this;
  if(robot.queuedInstructions.length > 0){
    console.log("Number of instructions left: " + robot.queuedInstructions.length);
    eval(robot.queuedInstructions.shift());
  }else{
      $(".game-console-button").show();
      $(".hint-link").show();
      $(".challenge-navigation a").show();
  }

};

DrawnRobot.prototype.setFacingRight = function(){
  facingIndex = FACING.indexOf(this.facing);
  facingIndex -= 1;
  if (facingIndex === -1) {
      facingIndex = 3;
  }
  this.facing = FACING[facingIndex];
};

DrawnRobot.prototype.setFacingLeft = function(){
  facingIndex = FACING.indexOf(this.facing);
  facingIndex += 1;
  if (facingIndex === 4) {
      facingIndex = 0;
  }
  this.facing = FACING[facingIndex];
  console.log(this.facing);
};

DrawnRobot.prototype.turnLeft = function(){
  var canvas = this.canvas;
  var robot = this;
  robot.setFacingLeft();
  canvasData = {
    duration: 1500,
    onChange: canvas.renderAll.bind(canvas),
    onComplete: function(){
      robot.getNextInstruction();
    }
  };
  this.body.animate('angle', '-=90', canvasData);
};

DrawnRobot.prototype.turnRight = function(){
  var robot = this;
  var canvas = this.canvas;
  robot.setFacingRight();
  canvasData = {
    duration: 1500,
    onChange: canvas.renderAll.bind(canvas),
    onComplete: function(){
      robot.getNextInstruction();
    }
  };
  this.body.animate('angle', '+=90', canvasData);
  // console.log(this.facing);
};

DrawnRobot.prototype.upInSmoke = function(){
  var robot = this;
  var smokeTop = robot.body.top;
  var smokeSide = robot.body.left;
  robot.canvas.remove(robot.body);
  imgElement = document.getElementById('cloud');
  smoke = new fabric.Image(imgElement, {
    left: smokeSide,
    top: smokeTop,
    fill: '#006569',
    width: 20,
    height: 20,
    originX: 'center',
    originY: 'center',
    selectable: false,
    evented: false
  });
  robot.canvas.add(smoke);
  robot.crashed = true;
};

DrawnRobot.prototype.moveForward = function(amt){
  if(typeof amt === 'undefined' || typeof amt === 'string') amt = 1;
  var distance, line, robot, canvas, canvasData;
  robot = this;
  canvas = robot.canvas;
  canvasData = {
    onChange: function(){
      if (robot.body.top >= 400){
        robot.upInSmoke();
      }else if(robot.body.top <= 0){
        robot.upInSmoke();
      }else if(robot.body.left >= 400){
        robot.upInSmoke();
      }else if(robot.body.left <= 0){
        robot.upInSmoke();
      }
    canvas.renderAll.bind(canvas);
  },
  abort: function(){
    return robot.crashed;
  },
  duration: 1500,
  onComplete: function(){
      robot.getNextInstruction();
    }
  };

  canvasLineData = { onChange: canvas.renderAll.bind(canvas),
    duration: 1500,
     onComplete: function(){
    }
  };
  distance = amt * 50;
  line = robot.lineTrail();
  canvas.add(line);
  canvas.sendToBack(line);
  if (robot.facing === "up") {
    robot.body.animate('top', '-=' + distance.toString(), canvasData);
    line.animate('height', '-=' + distance.toString(), canvasLineData);
  } else if (robot.facing === "left") {
      robot.body.animate('left', '-=' + distance.toString(), canvasData);
      line.animate('width', '-=' + distance.toString(), canvasLineData);
  } else if (robot.facing === "down") {
      robot.body.animate('top', '+=' + distance.toString(), canvasData);
      line.animate('height', '+=' + distance.toString(), canvasLineData);
  } else {
      robot.body.animate('left', '+=' + distance.toString(), canvasData);
      line.animate('width', '+=' + distance.toString(), canvasLineData);
  }
};

DrawnRobot.prototype.lineTrail = function() {
    var line = new fabric.Line([ this.body.left - 3, this.body.top -3, this.body.left -3, this.body.top - 3], {
      stroke: '#006569',
      strokeWidth: 5,
      strokeDashArray: [5, 5],
      selectable: false,
      lockMovementY: true,
      lockMovementX: true
  });
  return line;
};

// DrawnRobot.prototype.turnAround = function(){
//   var canvas = this.canvas;
//   var robot = this;

//   this.body.animate('angle', '-=180', {
//     onChange: canvas.renderAll.bind(canvas),
//     duration: 1000,
//     onComplete: function() { robot.getNextInstruction(); }
//   });

//   facingIndex = FACING.indexOf(this.facing);

//   facingIndex += 2;
//     if (facingIndex === 4) {
//       facingIndex = 0;
//   } else if (facingIndex === 5) {
//       facingIndex = 1;
//   } else {
//     return facingIndex;
//   }
//   this.facing = FACING[facingIndex];
//   console.log(this.facing);
// };

<commit_msg>animation now stops upon collision<commit_after>FACING = ["up", "left", "down", "right"];

function DrawnRobot(){
  imgElement = document.getElementById('robot-icon');
  this.body = new fabric.Image(imgElement, {
    left: 200,
    top: 390,
    fill: '#006569',
    width: 20,
    height: 20,
    originX: 'center',
    originY: 'center',
    selectable: false,
    crashed: false
  });
  this.facing =  FACING[0];
  this.canvas = new fabric.Canvas('myCanvas');
  this.queuedInstructions = [];
}

DrawnRobot.prototype.doTheseFrames = function(instructionsArr){
  this.queuedInstructions = instructionsArr;
};

DrawnRobot.prototype.getNextInstruction = function(){
  var robot = this;
  if(robot.queuedInstructions.length > 0){
    console.log("Number of instructions left: " + robot.queuedInstructions.length);
    eval(robot.queuedInstructions.shift());
  }else{
      $(".game-console-button").show();
      $(".hint-link").show();
      $(".challenge-navigation a").show();
  }

};

DrawnRobot.prototype.setFacingRight = function(){
  facingIndex = FACING.indexOf(this.facing);
  facingIndex -= 1;
  if (facingIndex === -1) {
      facingIndex = 3;
  }
  this.facing = FACING[facingIndex];
};

DrawnRobot.prototype.setFacingLeft = function(){
  facingIndex = FACING.indexOf(this.facing);
  facingIndex += 1;
  if (facingIndex === 4) {
      facingIndex = 0;
  }
  this.facing = FACING[facingIndex];
  console.log(this.facing);
};

DrawnRobot.prototype.turnLeft = function(){
  var canvas = this.canvas;
  var robot = this;
  robot.setFacingLeft();
  canvasData = {
    duration: 1500,
    onChange: canvas.renderAll.bind(canvas),
    onComplete: function(){
      robot.getNextInstruction();
    }
  };
  this.body.animate('angle', '-=90', canvasData);
};

DrawnRobot.prototype.turnRight = function(){
  var robot = this;
  var canvas = this.canvas;
  robot.setFacingRight();
  canvasData = {
    duration: 1500,
    onChange: canvas.renderAll.bind(canvas),
    onComplete: function(){
      robot.getNextInstruction();
    }
  };
  this.body.animate('angle', '+=90', canvasData);
  // console.log(this.facing);
};

DrawnRobot.prototype.upInSmoke = function(){
  var robot = this;
  var smokeTop = robot.body.top;
  var smokeSide = robot.body.left;
  robot.canvas.remove(robot.body);
  imgElement = document.getElementById('cloud');
  smoke = new fabric.Image(imgElement, {
    left: smokeSide,
    top: smokeTop,
    fill: '#006569',
    width: 20,
    height: 20,
    originX: 'center',
    originY: 'center',
    selectable: false,
    evented: false
  });
  robot.canvas.add(smoke);
  robot.crashed = true;
  alert("Try Again!")
};

DrawnRobot.prototype.moveForward = function(amt){
  if(typeof amt === 'undefined' || typeof amt === 'string') amt = 1;
  var distance, line, robot, canvas, canvasData;
  robot = this;
  canvas = robot.canvas;
  canvasData = {
    onChange: function(){
      if (robot.body.top >= 400){
        robot.upInSmoke();
      }else if(robot.body.top <= 0){
        robot.upInSmoke();
      }else if(robot.body.left >= 400){
        robot.upInSmoke();
      }else if(robot.body.left <= 0){
        robot.upInSmoke();
      }
    canvas.renderAll.bind(canvas);
  },
  abort: function(){
    return robot.crashed;
  },
  duration: 1500,
  onComplete: function(){
      robot.getNextInstruction();
    }
  };

  canvasLineData = { onChange: canvas.renderAll.bind(canvas),
    duration: 1500,
     onComplete: function(){
    }
  };
  distance = amt * 50;
  line = robot.lineTrail();
  canvas.add(line);
  canvas.sendToBack(line);
  if (robot.facing === "up") {
    robot.body.animate('top', '-=' + distance.toString(), canvasData);
    line.animate('height', '-=' + distance.toString(), canvasLineData);
  } else if (robot.facing === "left") {
      robot.body.animate('left', '-=' + distance.toString(), canvasData);
      line.animate('width', '-=' + distance.toString(), canvasLineData);
  } else if (robot.facing === "down") {
      robot.body.animate('top', '+=' + distance.toString(), canvasData);
      line.animate('height', '+=' + distance.toString(), canvasLineData);
  } else {
      robot.body.animate('left', '+=' + distance.toString(), canvasData);
      line.animate('width', '+=' + distance.toString(), canvasLineData);
  }
};

DrawnRobot.prototype.lineTrail = function() {
    var line = new fabric.Line([ this.body.left - 3, this.body.top -3, this.body.left -3, this.body.top - 3], {
      stroke: '#006569',
      strokeWidth: 5,
      strokeDashArray: [5, 5],
      selectable: false,
      lockMovementY: true,
      lockMovementX: true
  });
  return line;
};

// DrawnRobot.prototype.turnAround = function(){
//   var canvas = this.canvas;
//   var robot = this;

//   this.body.animate('angle', '-=180', {
//     onChange: canvas.renderAll.bind(canvas),
//     duration: 1000,
//     onComplete: function() { robot.getNextInstruction(); }
//   });

//   facingIndex = FACING.indexOf(this.facing);

//   facingIndex += 2;
//     if (facingIndex === 4) {
//       facingIndex = 0;
//   } else if (facingIndex === 5) {
//       facingIndex = 1;
//   } else {
//     return facingIndex;
//   }
//   this.facing = FACING[facingIndex];
//   console.log(this.facing);
// };

<|endoftext|>


<commit_before>import EventType from '../../../../../src/ol/pointer/EventType.js';
import Map from '../../../../../src/ol/Map.js';
import MousePosition from '../../../../../src/ol/control/MousePosition.js';
import View from '../../../../../src/ol/View.js';

describe('ol/control/MousePosition', function () {
  describe('constructor', function () {
    it('can be constructed without arguments', function () {
      const instance = new MousePosition();
      expect(instance).to.be.an(MousePosition);
      expect(instance.element.className).to.be('ol-mouse-position');
    });

    it('creates the element with the provided class name', function () {
      const className = 'foobar';
      const instance = new MousePosition({
        className: className,
      });
      expect(instance.element.className).to.be(className);
    });
  });

  describe('configuration options', function () {
    let target, map;
    const width = 360;
    const height = 180;

    beforeEach(function () {
      target = document.createElement('div');
      const style = target.style;
      style.position = 'absolute';
      style.left = '-1000px';
      style.top = '-1000px';
      style.width = width + 'px';
      style.height = height + 'px';

      document.body.appendChild(target);
      map = new Map({
        target: target,
        controls: [],
        view: new View({
          projection: 'EPSG:4326',
          center: [0, 0],
          resolution: 1,
        }),
      });
    });
    afterEach(function () {
      map.dispose();
      document.body.removeChild(target);
    });

    function simulateEvent(type, x, y) {
      const viewport = map.getViewport();
      // calculated in case body has top < 0 (test runner with small window)
      const position = viewport.getBoundingClientRect();
      const evt = new PointerEvent(type, {
        clientX: position.left + x + width / 2,
        clientY: position.top + y + height / 2,
      });
      document.querySelector('div.ol-viewport').dispatchEvent(evt);
    }

    describe('undefinedHTML', function () {
      it('renders undefinedHTML when mouse moves out', function () {
        const ctrl = new MousePosition({
          undefinedHTML: 'some text',
        });
        ctrl.setMap(map);
        map.renderSync();

        const element = document.querySelector(
          '.ol-mouse-position',
          map.getTarget()
        );

        simulateEvent(EventType.POINTEROUT, width + 1, height + 1);
        expect(element.innerHTML).to.be('some text');

        simulateEvent(EventType.POINTERMOVE, 20, 30);
        expect(element.innerHTML).to.be('20,-30');

        simulateEvent(EventType.POINTEROUT, width + 1, height + 1);
        expect(element.innerHTML).to.be('some text');
      });

      it('clears the mouse position by default when the mouse moves outside the viewport', function () {
        const ctrl = new MousePosition();
        ctrl.setMap(map);
        map.renderSync();

        const element = document.querySelector(
          '.ol-mouse-position',
          map.getTarget()
        );

        simulateEvent(EventType.POINTEROUT, width + 1, height + 1);
        expect(element.innerHTML).to.be(' ');

        target.dispatchEvent(new PointerEvent('pointermove'));
        simulateEvent(EventType.POINTERMOVE, 20, 30);
        expect(element.innerHTML).to.be('20,-30');

        simulateEvent(EventType.POINTEROUT, width + 1, height + 1);
        expect(element.innerHTML).to.be(' ');
      });

      it('retains the mouse position when undefinedHTML is falsey and mouse moves outside the viewport', function () {
        const ctrl = new MousePosition({
          undefinedHTML: '',
        });
        ctrl.setMap(map);
        map.renderSync();

        const element = document.querySelector(
          '.ol-mouse-position',
          map.getTarget()
        );

        simulateEvent(EventType.POINTEROUT, width + 1, height + 1);
        expect(element.innerHTML).to.be('');

        target.dispatchEvent(new PointerEvent('pointermove'));
        simulateEvent(EventType.POINTERMOVE, 20, 30);
        expect(element.innerHTML).to.be('20,-30');

        simulateEvent(EventType.POINTEROUT, width + 1, height + 1);
        expect(element.innerHTML).to.be('20,-30');
      });
    });
  });
});
<commit_msg>Test empty string rendering for mouse control<commit_after>import EventType from '../../../../../src/ol/pointer/EventType.js';
import Map from '../../../../../src/ol/Map.js';
import MousePosition from '../../../../../src/ol/control/MousePosition.js';
import View from '../../../../../src/ol/View.js';

describe('ol/control/MousePosition', function () {
  describe('constructor', function () {
    it('can be constructed without arguments', function () {
      const instance = new MousePosition();
      expect(instance).to.be.an(MousePosition);
      expect(instance.element.className).to.be('ol-mouse-position');
    });

    it('creates the element with the provided class name', function () {
      const className = 'foobar';
      const instance = new MousePosition({
        className: className,
      });
      expect(instance.element.className).to.be(className);
    });
  });

  describe('configuration options', function () {
    let target, map;
    const width = 360;
    const height = 180;

    beforeEach(function () {
      target = document.createElement('div');
      const style = target.style;
      style.position = 'absolute';
      style.left = '-1000px';
      style.top = '-1000px';
      style.width = width + 'px';
      style.height = height + 'px';

      document.body.appendChild(target);
      map = new Map({
        target: target,
        controls: [],
        view: new View({
          projection: 'EPSG:4326',
          center: [0, 0],
          resolution: 1,
        }),
      });
    });
    afterEach(function () {
      map.dispose();
      document.body.removeChild(target);
    });

    function simulateEvent(type, x, y) {
      const viewport = map.getViewport();
      // calculated in case body has top < 0 (test runner with small window)
      const position = viewport.getBoundingClientRect();
      const evt = new PointerEvent(type, {
        clientX: position.left + x + width / 2,
        clientY: position.top + y + height / 2,
      });
      document.querySelector('div.ol-viewport').dispatchEvent(evt);
    }

    describe('undefinedHTML', function () {
      it('renders undefinedHTML when mouse moves out', function () {
        const ctrl = new MousePosition({
          undefinedHTML: 'some text',
        });
        ctrl.setMap(map);
        map.renderSync();

        const element = document.querySelector(
          '.ol-mouse-position',
          map.getTarget()
        );

        simulateEvent(EventType.POINTEROUT, width + 1, height + 1);
        expect(element.innerHTML).to.be('some text');

        simulateEvent(EventType.POINTERMOVE, 20, 30);
        expect(element.innerHTML).to.be('20,-30');

        simulateEvent(EventType.POINTEROUT, width + 1, height + 1);
        expect(element.innerHTML).to.be('some text');
      });

      it('clears the mouse position by default when the mouse moves outside the viewport', function () {
        const ctrl = new MousePosition();
        ctrl.setMap(map);
        map.renderSync();

        const element = document.querySelector(
          '.ol-mouse-position',
          map.getTarget()
        );

        simulateEvent(EventType.POINTEROUT, width + 1, height + 1);
        expect(element.innerHTML).to.be(' ');

        target.dispatchEvent(new PointerEvent('pointermove'));
        simulateEvent(EventType.POINTERMOVE, 20, 30);
        expect(element.innerHTML).to.be('20,-30');

        simulateEvent(EventType.POINTEROUT, width + 1, height + 1);
        expect(element.innerHTML).to.be(' ');
      });

      it('retains the mouse position when undefinedHTML is false and mouse moves outside the viewport', function () {
        const ctrl = new MousePosition({
          undefinedHTML: false,
        });
        ctrl.setMap(map);
        map.renderSync();

        const element = document.querySelector(
          '.ol-mouse-position',
          map.getTarget()
        );

        simulateEvent(EventType.POINTEROUT, width + 1, height + 1);
        expect(element.innerHTML).to.be('');

        target.dispatchEvent(new PointerEvent('pointermove'));
        simulateEvent(EventType.POINTERMOVE, 20, 30);
        expect(element.innerHTML).to.be('20,-30');

        simulateEvent(EventType.POINTEROUT, width + 1, height + 1);
        expect(element.innerHTML).to.be('20,-30');
      });

      it('renders an empty string if undefinedHTML is an empty string and mouse moves outside the viewport', function () {
        const ctrl = new MousePosition({
          undefinedHTML: '',
        });
        ctrl.setMap(map);
        map.renderSync();

        const element = document.querySelector(
          '.ol-mouse-position',
          map.getTarget()
        );

        simulateEvent(EventType.POINTEROUT, width + 1, height + 1);
        expect(element.innerHTML).to.be('');

        target.dispatchEvent(new PointerEvent('pointermove'));
        simulateEvent(EventType.POINTERMOVE, 20, 30);
        expect(element.innerHTML).to.be('20,-30');

        simulateEvent(EventType.POINTEROUT, width + 1, height + 1);
        expect(element.innerHTML).to.be('');
      });
    });
  });
});
<|endoftext|>


<commit_before>
/* TODO: This is only part of the original template JS */

/* -------------------- Check Browser --------------------- */

function browser() {

  //var isOpera = !!(window.opera && window.opera.version);  // Opera 8.0+
  //var isFirefox = testCSS('MozBoxSizing');                 // FF 0.8+
  var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
      // At least Safari 3+: "[object HTMLElementConstructor]"
  var isChrome = !isSafari && testCSS('WebkitTransform');  // Chrome 1+
  //var isIE = /*@cc_on!@*/false || testCSS('msTransform');  // At least IE6

  function testCSS(prop) {
      return prop in document.documentElement.style;
  }

  if (isSafari || isChrome) {

    return true;

  } else {

    return false;

  }

}

/* -------------------- Search --------------------- */

jQuery(document).ready(function($){

  $('.search > :input').on('keyup',function(){

    $(this).attr('class', 'activeSearch');

    var count;
    var timeToEnd = 1000;

    $(':input').keydown(function(){

      clearTimeout(count);

      count = setTimeout(endCount, timeToEnd);

    });

  });

  function endCount(){

    $('.search > :input').attr('class','search-form');

  }

});

/* -------------------- Buttons 3D Style --------------------- */

jQuery(document).ready(function($){

  $(':button').each(function(){

    if($(this).hasClass('btn-tabula')) {

      $(this).wrap('
');

      var inner = $(this).html();

      if(browser()) {

        $(this).html('' + inner + '');

      }

    }

  });

  $('a').each(function(){

    if($(this).hasClass('btnOverlay')) {

      $(this).wrap('
');

      var inner = $(this).html();

      if(browser()) {

        $(this).html('' + inner + '');

      }

    }

  });

});

/* ------------------ Back To Top ------------------- */
jQuery(document).ready(function($){

  jQuery('#under-footer-back-to-top a').click(function(){
    jQuery('html, body').animate({scrollTop:0}, 300);
    return false;
  });

});

/* ------------------ Tooltips ----------------- */

jQuery(document).ready(function($) {

    $('.tooltips').tooltip({
      selector: "a[rel=tooltip]"
    })

});

/* -------------------- Isotope --------------------- */

jQuery(document).ready(function () {

  $('#wall').imagesLoaded(function() {

    var $container = $('#wall');
      $select = $('#filters select');

    // initialize Isotope
    $container.isotope({
    // options...
    resizable: false, // disable normal resizing
    // set columnWidth to a percentage of container width
      masonry: { columnWidth: $container.width() / 12 }
    });

    // update columnWidth on window resize
    $(window).smartresize(function(){

      $container.isotope({
      // update columnWidth to a percentage of container width
        masonry: { columnWidth: $container.width() / 12 }
      });
    });

    $container.isotope({
      itemSelector : '.item'
    });

    $select.change(function() {

      var filters = $(this).val();

        $container.isotope({
          filter: filters
        });

      });

      var $optionSets = $('#filters .option-set'),
        $optionLinks = $optionSets.find('a');

        $optionLinks.click(function(){

        var $this = $(this);
        // don't proceed if already selected
        if ( $this.hasClass('selected') ) {
            return false;
        }
      var $optionSet = $this.parents('.option-set');
      $optionSet.find('.selected').removeClass('selected');
      $this.addClass('selected');

      // make option object dynamically, i.e. { filter: '.my-filter-class' }
      var options = {},
        key = $optionSet.attr('data-option-key'),
        value = $this.attr('data-option-value');
      // parse 'false' as false boolean
      value = value === 'false' ? false : value;
      options[ key ] = value;
      if ( key === 'layoutMode' && typeof changeLayoutMode === 'function' ) {
        // changes in layout modes need extra logic
        changeLayoutMode( $this, options )
      } else {
        // otherwise, apply new options
        $container.isotope( options );
      }

      return false;

      });

  });

});

/* ------------------ Tabs ----------------- */

function AutomaticTabsWidhtReset() {

  $('.nav-tabs').find('li').each(function(){

    $(this).find('a').css('width', 'auto');

  });

}

function AutomaticTabsWidht() {

  var containerWidth = $('.tab-content').width();

  var tabsNavWidth = 0;

  $('.nav-tabs').find('li').each(function(){

    var liWidth = $(this).outerWidth();

    tabsNavWidth = tabsNavWidth + liWidth;

  });

  if(tabsNavWidth > containerWidth) {

    var elements = $(".nav-tabs li").size();

    var newWidth = containerWidth / elements - 15;

    $('.nav-tabs').find('li').each(function(){

      $(this).find('a').css('width', newWidth);

    });

  }

}

jQuery(document).ready(function($) {

  $('#myTab a').click(function (e) {
    e.preventDefault();
    $(this).tab('show');
  })

});

/* -------------------- Width Functions --------------------- */

jQuery(document).ready(function($){

  widthFunctions();

});

$(window).bind("resize", widthFunctions);

function widthFunctions(e) {

  AutomaticTabsWidhtReset();
  AutomaticTabsWidht();

  var winHeight = $(window).height();
  var winWidth = $(window).width();

  if (winWidth < 980 && winWidth > 767) {

    if($("#wall").width()) {

      if($(".item").hasClass("span3")) {

        $(".item").removeClass("span3");
        $(".item").addClass("span4");

      }

    }

    if($(".lr-page").hasClass("span4 offset4")) {

      $(".lr-page").removeClass("span4 offset4");
      $(".lr-page").addClass("span6 offset3");

      $("#page-title").removeClass("span4 offset4");
      $("#page-title").addClass("span6 offset3");
    }

  } else {

    if($("#wall").width()) {

      if($(".item").hasClass("span4")) {

        $(".item").removeClass("span4");
        $(".item").addClass("span3");

      }

    }

    if($(".lr-page").hasClass("span6 offset3")) {

      $(".lr-page").removeClass("span6 offset3");
      $(".lr-page").addClass("span4 offset4");

      $("#page-title").removeClass("span6 offset3");
      $("#page-title").addClass("span4 offset4");
    }

  }

}<commit_msg>Try to fix overlapping images in Firefox<commit_after>
/* TODO: This is only part of the original template JS */

/* -------------------- Check Browser --------------------- */

function browser() {

  //var isOpera = !!(window.opera && window.opera.version);  // Opera 8.0+
  //var isFirefox = testCSS('MozBoxSizing');                 // FF 0.8+
  var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
      // At least Safari 3+: "[object HTMLElementConstructor]"
  var isChrome = !isSafari && testCSS('WebkitTransform');  // Chrome 1+
  //var isIE = /*@cc_on!@*/false || testCSS('msTransform');  // At least IE6

  function testCSS(prop) {
      return prop in document.documentElement.style;
  }

  if (isSafari || isChrome) {

    return true;

  } else {

    return false;

  }

}

/* -------------------- Search --------------------- */

jQuery(document).ready(function($){

  $('.search > :input').on('keyup',function(){

    $(this).attr('class', 'activeSearch');

    var count;
    var timeToEnd = 1000;

    $(':input').keydown(function(){

      clearTimeout(count);

      count = setTimeout(endCount, timeToEnd);

    });

  });

  function endCount(){

    $('.search > :input').attr('class','search-form');

  }

});

/* -------------------- Buttons 3D Style --------------------- */

jQuery(document).ready(function($){

  $(':button').each(function(){

    if($(this).hasClass('btn-tabula')) {

      $(this).wrap('
');

      var inner = $(this).html();

      if(browser()) {

        $(this).html('' + inner + '');

      }

    }

  });

  $('a').each(function(){

    if($(this).hasClass('btnOverlay')) {

      $(this).wrap('
');

      var inner = $(this).html();

      if(browser()) {

        $(this).html('' + inner + '');

      }

    }

  });

});

/* ------------------ Back To Top ------------------- */
jQuery(document).ready(function($){

  jQuery('#under-footer-back-to-top a').click(function(){
    jQuery('html, body').animate({scrollTop:0}, 300);
    return false;
  });

});

/* ------------------ Tooltips ----------------- */

jQuery(document).ready(function($) {

    $('.tooltips').tooltip({
      selector: "a[rel=tooltip]"
    })

});

/* -------------------- Isotope --------------------- */
/* dcabo: This was called on ready() in the original template, but images overlapped
          when using Turbolinks (only in Firefox, maybe). See discussion at
          https://github.com/rails/turbolinks/issues/159 */

jQuery(document).load(function () {

  $('#wall').imagesLoaded(function() {

    var $container = $('#wall');
      $select = $('#filters select');

    // initialize Isotope
    $container.isotope({
    // options...
    resizable: false, // disable normal resizing
    // set columnWidth to a percentage of container width
      masonry: { columnWidth: $container.width() / 12 }
    });

    // update columnWidth on window resize
    $(window).smartresize(function(){

      $container.isotope({
      // update columnWidth to a percentage of container width
        masonry: { columnWidth: $container.width() / 12 }
      });
    });

    $container.isotope({
      itemSelector : '.item'
    });

    $select.change(function() {

      var filters = $(this).val();

        $container.isotope({
          filter: filters
        });

      });

      var $optionSets = $('#filters .option-set'),
        $optionLinks = $optionSets.find('a');

        $optionLinks.click(function(){

        var $this = $(this);
        // don't proceed if already selected
        if ( $this.hasClass('selected') ) {
            return false;
        }
      var $optionSet = $this.parents('.option-set');
      $optionSet.find('.selected').removeClass('selected');
      $this.addClass('selected');

      // make option object dynamically, i.e. { filter: '.my-filter-class' }
      var options = {},
        key = $optionSet.attr('data-option-key'),
        value = $this.attr('data-option-value');
      // parse 'false' as false boolean
      value = value === 'false' ? false : value;
      options[ key ] = value;
      if ( key === 'layoutMode' && typeof changeLayoutMode === 'function' ) {
        // changes in layout modes need extra logic
        changeLayoutMode( $this, options )
      } else {
        // otherwise, apply new options
        $container.isotope( options );
      }

      return false;

      });

  });

});

/* ------------------ Tabs ----------------- */

function AutomaticTabsWidhtReset() {

  $('.nav-tabs').find('li').each(function(){

    $(this).find('a').css('width', 'auto');

  });

}

function AutomaticTabsWidht() {

  var containerWidth = $('.tab-content').width();

  var tabsNavWidth = 0;

  $('.nav-tabs').find('li').each(function(){

    var liWidth = $(this).outerWidth();

    tabsNavWidth = tabsNavWidth + liWidth;

  });

  if(tabsNavWidth > containerWidth) {

    var elements = $(".nav-tabs li").size();

    var newWidth = containerWidth / elements - 15;

    $('.nav-tabs').find('li').each(function(){

      $(this).find('a').css('width', newWidth);

    });

  }

}

jQuery(document).ready(function($) {

  $('#myTab a').click(function (e) {
    e.preventDefault();
    $(this).tab('show');
  })

});

/* -------------------- Width Functions --------------------- */

jQuery(document).ready(function($){

  widthFunctions();

});

$(window).bind("resize", widthFunctions);

function widthFunctions(e) {

  AutomaticTabsWidhtReset();
  AutomaticTabsWidht();

  var winHeight = $(window).height();
  var winWidth = $(window).width();

  if (winWidth < 980 && winWidth > 767) {

    if($("#wall").width()) {

      if($(".item").hasClass("span3")) {

        $(".item").removeClass("span3");
        $(".item").addClass("span4");

      }

    }

    if($(".lr-page").hasClass("span4 offset4")) {

      $(".lr-page").removeClass("span4 offset4");
      $(".lr-page").addClass("span6 offset3");

      $("#page-title").removeClass("span4 offset4");
      $("#page-title").addClass("span6 offset3");
    }

  } else {

    if($("#wall").width()) {

      if($(".item").hasClass("span4")) {

        $(".item").removeClass("span4");
        $(".item").addClass("span3");

      }

    }

    if($(".lr-page").hasClass("span6 offset3")) {

      $(".lr-page").removeClass("span6 offset3");
      $(".lr-page").addClass("span4 offset4");

      $("#page-title").removeClass("span6 offset3");
      $("#page-title").addClass("span4 offset4");
    }

  }

}<|endoftext|>


<commit_before>;(function() {

  var btnSelect = document.querySelector('.btn-select');
  var fileInput = document.querySelector('.input-file');
  var form = document.querySelector('.upload-form');
  var btnSubmit = document.querySelector('.btn-submit');
  var namefield = document.querySelector('#name');
  var items = document.querySelectorAll('.js-item');
  var tips = document.querySelectorAll('.js-copy-link');
  // var move = require('move');

  var shouldSubmit = false;

  form.addEventListener('submit', function onFormSubmit(e) {
    if (!shouldSubmit) e.preventDefault();
  });

  btnSelect.addEventListener('click', function onUploadButtonClick(e) {
    fileInput.click();
  });

  btnSubmit.addEventListener('click', function onSubmit(e) {
    shouldSubmit = true;
  });

  fileInput.addEventListener('change', function onChange(e) {
    btnSubmit.removeAttribute('disabled');
    namefield.focus();
  });

  bind(items, delegate);

  $('.js-item').on('click', '.js-remove', onCrossClick);
  $('.js-item').on('click', '.js-edit-button', onEditClick);
  $('.js-item').on('change', '.js-edit-name', onNameChange);
  $('.js-item').on('submit', '.edit-name-form', onNameSubmit);

  // $(document).on('keyup', onKeytype);
  // var searchform = document.querySelector('.search-form');

  // function onKeytype(e) {
  //   console.log('typed');
  //   showNode(searchform);
  //   var input = this.querySelector('.search-form input');
  //   input.focus();
  // }

  function onCrossClick(e) {
    var item = e.delegateTarget;
    var id = item.getAttribute('data-id');

    if (item) {
      deleteItem(id, function() {
        item.parentNode.remove();
      });
    }
  }

  function onEditClick(e) {
    var item = e.delegateTarget;
    var anchor = item.querySelector('.js-item-link');
    var form = item.querySelector('.edit-name-form');
    var button = item.querySelector('.js-edit-button');
    var input = form.querySelector('.js-edit-name');
    var editon = button.classList.contains('active');

    if (editon) {
      showNode(anchor);
      hideNode(form);
      deactivateNode(button);
    } else {
      hideNode(anchor);
      showNode(form);
      activateNode(button);
      input.focus();
    }
  }

  function onNameChange(e) {
    var item = e.delegateTarget;
    var id = item.getAttribute('data-id');
    var button = item.querySelector('.js-edit-button');
    var form = item.querySelector('.edit-name-form');
    var anchor = item.querySelector('.js-item-link');
    var input = item.querySelector('.js-edit-name');
    anchor.innerHTML = input.value;
    deactivateNode(button);
    hideNode(button);
    hideNode(form);
    showNode(anchor);
    saveName(id, input.value, function() { });
  }

  function onNameSubmit(e) {
    e.preventDefault();
  }

  function activateNode(node) {
    node.classList.add('active');
  }

  function deactivateNode(node) {
    node.classList.remove('active');
  }

  function showNode(node) {
    node.classList.remove('hide');
  }

  function hideNode(node) {
    node.classList.add('hide');
  }

  function deleteItem(id, done) {
    $.ajax({
      url: '/v1/items/' + id,
      type: 'delete'
    }).done(function() {
      done();
    }).fail(function(jqXhr, statusText, msg) {
      notify('Failed to delete', jqXhr.responseText);
    }).always(function() {

    });
  }

  function saveName(id, name, done) {
    $.ajax({
      url: '/v1/items/' + id,
      type: 'put',
      data: { name: name }
    }).done(function() {
      // done();
    }).fail(function() {
      notify('Failed to change name', jqXhr.responseText);
    }).always(function() {

    });
  }

  function notify(msgHuman, msgMachine) {
    console.log(msgHuman, ' - ', msgMachine);
  }

  // Show remove
  bind(items, function(e) {
    var remove = this.querySelector('.js-remove');
    var edit = this.querySelector('.js-edit-button');
    showNode(remove);
    showNode(edit);
  }, 'mouseenter');

  // Hide remove
  bind(items, function(e) {
    var remove = this.querySelector('.js-remove');
    var edit = this.querySelector('.js-edit-button');
    hideNode(remove);
    if (!edit.classList.contains('active')) hideNode(edit);
  }, 'mouseleave');

  function bind(els, listener, eventName, capture) {
    eventName = eventName || 'click';
    capture = capture || false;
    for (var i = 0, len = els.length; i < len; ++i) {
      els[i].addEventListener(eventName, listener, capture);
    }
  }

  function delegate(e) {
    var el = e.target;

    // toggleClass(overlay, 'hide');

    if (el.classList.contains('js-cog')) {
      oncogclick(el, this);
    } else if (e.target === '') {

    }
  }

  function oncogclick(el, parent) {
    var overlay = parent.querySelector('.item-overlay');
    overlay.classList.remove('hide');

    setTimeout(function() {
      overlay.style.opacity = '1.0';
    }, 1)

    // move(parent)
    //   .scale(0)
    //   .duration(400)
    //   .end(function() {
    //     parent.parentNode.remove();
    //   });
  }

  function toggleClass(el, className) {
    className = className || '';
    if (el.classList) {
      el.classList.toggle(className);
    } else {
      var classes = el.className.split(' ');
      var existingIndex = classes.indexOf(className);

      if (existingIndex >= 0)
        classes.splice(existingIndex, 1);
      else
        classes.push(className);

      el.className = classes.join(' ');
    }
  }

})(window);<commit_msg>Fix upload button in Chrome Android<commit_after>;(function() {

  var btnSelect = document.querySelector('.btn-select');
  var fileInput = document.querySelector('.input-file');
  var form = document.querySelector('.upload-form');
  var btnSubmit = document.querySelector('.btn-submit');
  var namefield = document.querySelector('#name');
  var items = document.querySelectorAll('.js-item');
  var tips = document.querySelectorAll('.js-copy-link');
  // var move = require('move');

  var shouldSubmit = false;

  form.addEventListener('submit', function onFormSubmit(e) {
    if (!shouldSubmit) e.preventDefault();
  });

  btnSelect.addEventListener('click', function onUploadButtonClick(e) {
    fileInput.click();
  });

  btnSubmit.addEventListener('click', function onSubmit(e) {
    shouldSubmit = true;
  });

  $(fileInput).on('change', function onChange(e) {
    btnSubmit.removeAttribute('disabled');
    namefield.focus();
  });

  bind(items, delegate);

  $('.js-item').on('click', '.js-remove', onCrossClick);
  $('.js-item').on('click', '.js-edit-button', onEditClick);
  $('.js-item').on('change', '.js-edit-name', onNameChange);
  $('.js-item').on('submit', '.edit-name-form', onNameSubmit);

  // $(document).on('keyup', onKeytype);
  // var searchform = document.querySelector('.search-form');

  // function onKeytype(e) {
  //   console.log('typed');
  //   showNode(searchform);
  //   var input = this.querySelector('.search-form input');
  //   input.focus();
  // }

  function onCrossClick(e) {
    var item = e.delegateTarget;
    var id = item.getAttribute('data-id');

    if (item) {
      deleteItem(id, function() {
        item.parentNode.remove();
      });
    }
  }

  function onEditClick(e) {
    var item = e.delegateTarget;
    var anchor = item.querySelector('.js-item-link');
    var form = item.querySelector('.edit-name-form');
    var button = item.querySelector('.js-edit-button');
    var input = form.querySelector('.js-edit-name');
    var editon = button.classList.contains('active');

    if (editon) {
      showNode(anchor);
      hideNode(form);
      deactivateNode(button);
    } else {
      hideNode(anchor);
      showNode(form);
      activateNode(button);
      input.focus();
    }
  }

  function onNameChange(e) {
    var item = e.delegateTarget;
    var id = item.getAttribute('data-id');
    var button = item.querySelector('.js-edit-button');
    var form = item.querySelector('.edit-name-form');
    var anchor = item.querySelector('.js-item-link');
    var input = item.querySelector('.js-edit-name');
    anchor.innerHTML = input.value;
    deactivateNode(button);
    hideNode(button);
    hideNode(form);
    showNode(anchor);
    saveName(id, input.value, function() { });
  }

  function onNameSubmit(e) {
    e.preventDefault();
  }

  function activateNode(node) {
    node.classList.add('active');
  }

  function deactivateNode(node) {
    node.classList.remove('active');
  }

  function showNode(node) {
    node.classList.remove('hide');
  }

  function hideNode(node) {
    node.classList.add('hide');
  }

  function deleteItem(id, done) {
    $.ajax({
      url: '/v1/items/' + id,
      type: 'delete'
    }).done(function() {
      done();
    }).fail(function(jqXhr, statusText, msg) {
      notify('Failed to delete', jqXhr.responseText);
    }).always(function() {

    });
  }

  function saveName(id, name, done) {
    $.ajax({
      url: '/v1/items/' + id,
      type: 'put',
      data: { name: name }
    }).done(function() {
      // done();
    }).fail(function() {
      notify('Failed to change name', jqXhr.responseText);
    }).always(function() {

    });
  }

  function notify(msgHuman, msgMachine) {
    console.log(msgHuman, ' - ', msgMachine);
  }

  // Show remove
  bind(items, function(e) {
    var remove = this.querySelector('.js-remove');
    var edit = this.querySelector('.js-edit-button');
    showNode(remove);
    showNode(edit);
  }, 'mouseenter');

  // Hide remove
  bind(items, function(e) {
    var remove = this.querySelector('.js-remove');
    var edit = this.querySelector('.js-edit-button');
    hideNode(remove);
    if (!edit.classList.contains('active')) hideNode(edit);
  }, 'mouseleave');

  function bind(els, listener, eventName, capture) {
    eventName = eventName || 'click';
    capture = capture || false;
    for (var i = 0, len = els.length; i < len; ++i) {
      els[i].addEventListener(eventName, listener, capture);
    }
  }

  function delegate(e) {
    var el = e.target;

    // toggleClass(overlay, 'hide');

    if (el.classList.contains('js-cog')) {
      oncogclick(el, this);
    } else if (e.target === '') {

    }
  }

  function oncogclick(el, parent) {
    var overlay = parent.querySelector('.item-overlay');
    overlay.classList.remove('hide');

    setTimeout(function() {
      overlay.style.opacity = '1.0';
    }, 1)

    // move(parent)
    //   .scale(0)
    //   .duration(400)
    //   .end(function() {
    //     parent.parentNode.remove();
    //   });
  }

  function toggleClass(el, className) {
    className = className || '';
    if (el.classList) {
      el.classList.toggle(className);
    } else {
      var classes = el.className.split(' ');
      var existingIndex = classes.indexOf(className);

      if (existingIndex >= 0)
        classes.splice(existingIndex, 1);
      else
        classes.push(className);

      el.className = classes.join(' ');
    }
  }

})(window);<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008 Apple Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * @constructor
 * @extends {WebInspector.VBox}
 */
WebInspector.DatabaseTableView = function(database, tableName)
{
    WebInspector.VBox.call(this);

    this.database = database;
    this.tableName = tableName;

    this.element.classList.add("storage-view");
    this.element.classList.add("table");

    this.refreshButton = new WebInspector.StatusBarButton(WebInspector.UIString("Refresh"), "refresh-storage-status-bar-item");
    this.refreshButton.addEventListener("click", this._refreshButtonClicked, this);
}

WebInspector.DatabaseTableView.prototype = {
    wasShown: function()
    {
        this.update();
    },

    get statusBarItems()
    {
        return [this.refreshButton.element];
    },

    /**
     * @param {string} tableName
     * @return {string}
     */
    _escapeTableName: function(tableName)
    {
        return tableName.replace(/\"/g, "\"\"");
    },

    update: function()
    {
        this.database.executeSql("SELECT * FROM \"" + this._escapeTableName(this.tableName) + "\"", this._queryFinished.bind(this), this._queryError.bind(this));
    },

    _queryFinished: function(columnNames, values)
    {
        this.detachChildViews();
        this.element.removeChildren();

        var dataGrid = WebInspector.SortableDataGrid.create(columnNames, values);
        if (!dataGrid) {
            this._emptyView = new WebInspector.EmptyView(WebInspector.UIString("The “%s”\ntable is empty.", this.tableName));
            this._emptyView.show(this.element);
            return;
        }
        dataGrid.show(this.element);
        dataGrid.autoSizeColumns(5);
    },

    _queryError: function(error)
    {
        this.detachChildViews();
        this.element.removeChildren();

        var errorMsgElement = createElement("div");
        errorMsgElement.className = "storage-table-error";
        errorMsgElement.textContent = WebInspector.UIString("An error occurred trying to\nread the “%s” table.", this.tableName);
        this.element.appendChild(errorMsgElement);
    },

    _refreshButtonClicked: function(event)
    {
        this.update();
    },

    __proto__: WebInspector.VBox.prototype
}
<commit_msg>DevTools: WebSQL: show rowid column.<commit_after>/*
 * Copyright (C) 2008 Apple Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * @constructor
 * @extends {WebInspector.VBox}
 */
WebInspector.DatabaseTableView = function(database, tableName)
{
    WebInspector.VBox.call(this);

    this.database = database;
    this.tableName = tableName;

    this.element.classList.add("storage-view");
    this.element.classList.add("table");

    this.refreshButton = new WebInspector.StatusBarButton(WebInspector.UIString("Refresh"), "refresh-storage-status-bar-item");
    this.refreshButton.addEventListener("click", this._refreshButtonClicked, this);
}

WebInspector.DatabaseTableView.prototype = {
    wasShown: function()
    {
        this.update();
    },

    get statusBarItems()
    {
        return [this.refreshButton.element];
    },

    /**
     * @param {string} tableName
     * @return {string}
     */
    _escapeTableName: function(tableName)
    {
        return tableName.replace(/\"/g, "\"\"");
    },

    update: function()
    {
        this.database.executeSql("SELECT rowid, * FROM \"" + this._escapeTableName(this.tableName) + "\"", this._queryFinished.bind(this), this._queryError.bind(this));
    },

    _queryFinished: function(columnNames, values)
    {
        this.detachChildViews();
        this.element.removeChildren();

        var dataGrid = WebInspector.SortableDataGrid.create(columnNames, values);
        if (!dataGrid) {
            this._emptyView = new WebInspector.EmptyView(WebInspector.UIString("The “%s”\ntable is empty.", this.tableName));
            this._emptyView.show(this.element);
            return;
        }
        dataGrid.show(this.element);
        dataGrid.autoSizeColumns(5);
    },

    _queryError: function(error)
    {
        this.detachChildViews();
        this.element.removeChildren();

        var errorMsgElement = createElement("div");
        errorMsgElement.className = "storage-table-error";
        errorMsgElement.textContent = WebInspector.UIString("An error occurred trying to\nread the “%s” table.", this.tableName);
        this.element.appendChild(errorMsgElement);
    },

    _refreshButtonClicked: function(event)
    {
        this.update();
    },

    __proto__: WebInspector.VBox.prototype
}
<|endoftext|>


<commit_before>
var unprocessed_events = {};
unprocessed_events.waiting_for = 0;

// Handle unprocessed events
function handle_unprocessed_events() {

  if (slam.local_event_number == slam.event_number) {
    // Everything is up to date.
    return;
  }

  if (unprocessed_events[slam.local_event_number + 1] !== undefined) {
    // Handle next event.

    var i = slam.local_event_number + 1;

    do_event(unprocessed_events[i]);
    delete (unprocessed_events[i]);
  }
}

function process_subscribers(subscribers) {
    var e = document.getElementById("number_of_subscribers");

    e.innerHTML = "Viewers: " + subscribers.total_subscribers;
}

function process_event(event) {

  try {

    if (event.type == "subscribers") {
        process_subscribers(event)
        return;
    }

    if (event.type == "heads_up") {
      do_heads_up(event);
      return;
    }

    if (event.type == "reload") {
      location.reload(true);
      return;
    }

    if (event.web_sock_id != undefined) {

      try {
        var strings = event.web_sock_id.split(';');
        if (strings.length > 1) {
          event.web_sock_id = strings[0];
          event.confirmation = strings[1];

          collection_of_lights.confirmation_received(event.confirmation);
        }

      }
      catch (e) {
        console.log(e);
      }
    }

  }
  catch(e) {}

  if (event.competition_id != slam.id)
    return;

  slam.event_number = event.event_number;

  if (event.event_number == slam.local_event_number + 1) {
    do_event(event);
  }
  else {

    unprocessed_events[event.event_number] = event;
    event_catch_up(event.event_number - 1);
  }
}

function last_updated(event) {

  var div = document.getElementById("last_updated");

  var date_pat = /(.*)T/;
  var date =  _.last(date_pat.exec(event.datetime));

  var time_pat = /T(\d*):(\d*):(\d*)/;
  var times = time_pat.exec(event.datetime);

  var time = " " + times[1] + ":" + times[2] + ":" + times[3];

  var datetime = date + time;

  div.innerHTML = "
 Last updated: " + datetime + "
";
}

function do_event(event) {

  if (slam.local_event_number + 1 != event.event_number)
    return;

  slam.local_event_number = event.event_number;

  if (event.event != 'signup_poet')
    last_updated(event);

  // I'm making 'new_round' an exceoption to help keep in sync with the server
  if (event.web_sock_id == web_sock_id && event.event != 'new_round') {
    return;
  }

  switch (event.event) {

    case 'new_performance':
      event_new_performance(event);
      break;
    case 'judge':
      event_judge(event);
      break;
    case 'set_time':
      event_set_time(event);
      break;
    case 'set_penalty':
      event_set_penalty(event);
      break;
    case 'signup_poet':
      signup_poet(event.name);
      break;
    case 'remove_performance':
      event_remove_performance(event);
      break;
    case 'new_round':
      event_new_round(event);
      break;
    case 'announcement':
      event_announcement(event);
      break;
    case 'edit_round':
      event_edit_round(event);
      break;
  }

}

function do_heads_up(event) {

  /*
     if (event.web_sock_id == web_sock_id || event.competition_id != slam.id || comm_2[event.performance_id] == undefined) {
     return;
     }
     */

  if (event.web_sock_id == web_sock_id) {
    console.log("bad web_sock_id");
    return;
  }

  if (event.competition_id != slam.id) {

    console.log("wrong competition");
    return
  }

  if (comms_2[event.performance_id] == undefined) {

    console.log("no performance id")
      return;
  }

  switch (event.event) {

    case 'judge':
      event_judge(event);
      break;
    case 'set_time':
      event_set_time(event);
      break;
    case 'set_penalty':
      event_set_penalty(event);
      break;
    case 'focus':
      event_focus(event);
      break;
    case 'blur':
      event_blur(event);
      break;
  }
}

// Send requests to the server up to and including 'event_number'
function event_catch_up(event_number) {

  var event_number_i = Math.max(unprocessed_events.waiting_for, slam.local_number_event_number + 1);
  var event_number_j = event_number;

  unprocessed_events.waiting_for = event_number_j;
  get_event_range_request(event_number_i, event_number_j);
}

function event_new_performance(event) {

  var round = rounds[event.round_number -1];

  var prev_performance_2 = null;

  if (event.previous_performance_id != null) {
    prev_performance_2 = comms_2[event.previous_performance_id].p_div.performance;
  }

  var performance_2 = performance_new(event.poet_name, prev_performance_2, round.time_limit, round.grace_period, slam.num_judges);
  var p_div = p_div_new(performance_2);

  performance_2.performance_id = event.performance_id;

  round.round_js.add_performance(performance_2);

  performance_2.calculate(); // So that it doesn't say Rank is 'Infinity'

  $("#performances_" + round.round_number).append(p_div);
  resize_inputs(p_div.data_columns);
  auto_scroll.scroll_if_on();

  round.names_already_performing.push(performance_2.name);
  invisible_round.notify_rank();

  p_div.comm.performance_id = event.performance_id;

  window.comms_2[event.performance_id] = p_div.comm;

  // Trigger contenders.get_winners() so that the button to add the performer will be removed
  if (round.are_poets_from_previous) {

    var previous_round_index = round.previous_round_number == null ? event.round_number - 2 : round.previous_round_number -1;
    rounds[previous_round_index].round_js.rank();
  }

}

function event_announcement(event) {

  var announcement_recv_id = "announcement_recv_" + event.round_number;
  var announcement_recv = document.getElementById(announcement_recv_id);

  announcement_recv.innerHTML = event.message;
  announcement_recv.style.color = '#5E5C42';
}

function event_focus(event) {

  try {
    var p_div = window.comms_2[event.performance_id].p_div;

    var minutes_i = p_div.indexes['minutes_i'];
    var seconds_i = p_div.indexes['seconds_i'];

    if (event.index == minutes_i || event.index == seconds_i ) {
      p_div.data_columns[minutes_i].style.fontStyle = 'italic';
      p_div.data_columns[seconds_i].style.fontStyle = 'italic';
    }
    else {
      var input = p_div.data_columns[event.index];
      input.style.fontStyle = "italic";
    }
  }
  catch (e) {
    console.log(e);
  }

}

function event_blur(event) {

  try {
    var p_div = window.comms_2[event.performance_id].p_div;

    var minutes_i = p_div.indexes['minutes_i'];
    var seconds_i = p_div.indexes['seconds_i'];

    if (event.index == minutes_i || event.index == seconds_i ) {
      p_div.data_columns[minutes_i].style.fontStyle = 'normal';
      p_div.data_columns[seconds_i].style.fontStyle = 'normal';
    }
    else {
      var input = p_div.data_columns[event.index];
      input.style.fontStyle = "normal";
    }
  }
  catch (e) {
    console.log(e);
  }

}

function event_judge(event) {
  var comm_2 = window.comms_2[event.performance_id];
  var is_this_a_heads_up = event.type == 'heads_up' ? true : false;

  p_div_set_score(comm_2.p_div, parseInt(event.judge_name), event.value, is_this_a_heads_up);
}

function event_set_time(event) {

  var p_div = window.comms_2[event.performance_id].p_div;
  var is_this_a_heads_up = event.type == 'heads_up' ? true : false;
  p_div_set_time(p_div, event.minutes, event.seconds, is_this_a_heads_up);
}

function event_set_penalty(event) {
  var p_div = window.comms_2[event.performance_id].p_div;
  var is_this_a_heads_up = event.type == 'heads_up' ? true : false;
  p_div_set_penalty(p_div, event.penalty, is_this_a_heads_up);

}

function event_remove_performance(event) {

  var comm_2 = window.comms_2[event.performance_id];

  remove_performance(comm_2.p_div);
}

function event_new_round(event) {

  if (rounds.length >= parseInt(event.round.round_number))
    return; // ignore

  var round = event.round;
  create_round_div(round);
}

function event_edit_round(event) {

    function update_round(round, event) {

        var keys = _.keys(event);

        for (var i=0; i<keys.length; i++) {
            round[keys[i]] = event[keys[i]];
        }
    }
    function update_time_limit_and_grace_period_for_performances(round) {

        var performances = round.round_js.performances;

        for (var i=0; i<performances.length; i++) {

            var performance = performances[i];

            performance.time_limit = round.time_limit;
            performance.grace_period = round.grace_period;

            performance.calculate();
        }
    }

    var round = null;

    for (var i=0; i<rounds.length; i++) {
        if (rounds[i].id == event.round_id) {
            round = rounds[i];
            break;
        }
    }

    if (round == null)
        return;

    update_round(round, event);

    //Title
   var e = document.getElementById("round_title_" + round.round_number);
   e.innerHTML = event.title;
   update_time_limit_and_grace_period_for_performances(round);

   // Number of Poets
   round.contenders.get_winners(round.contenders, round);

   // Number of Places

   // Time limit & Grace period
   e = document.getElementById("round_info_" + round.round_number);
   e.innerHTML = generate_round_info_innerHTML(round);

   // Is cumulative

   // Are poets from previous

   // Previous Round Number

}
<commit_msg>experimenting ..show when offline<commit_after>
var unprocessed_events = {};
unprocessed_events.waiting_for = 0;

// Handle unprocessed events
function handle_unprocessed_events() {

  if (slam.local_event_number == slam.event_number) {
    // Everything is up to date.
    return;
  }

  if (unprocessed_events[slam.local_event_number + 1] !== undefined) {
    // Handle next event.

    var i = slam.local_event_number + 1;

    do_event(unprocessed_events[i]);
    delete (unprocessed_events[i]);
  }
}

function process_subscribers(subscribers) {
    var e = document.getElementById("number_of_subscribers");

    e.innerHTML = "Viewers: " + subscribers.total_subscribers;
}

window.onoffline = function() {
	$('#number_of_subscribers').html('Offline');
}

function process_event(event) {

  try {

    if (event.type == "subscribers") {
        process_subscribers(event)
        return;
    }

    if (event.type == "heads_up") {
      do_heads_up(event);
      return;
    }

    if (event.type == "reload") {
      location.reload(true);
      return;
    }

    if (event.web_sock_id != undefined) {

      try {
        var strings = event.web_sock_id.split(';');
        if (strings.length > 1) {
          event.web_sock_id = strings[0];
          event.confirmation = strings[1];

          collection_of_lights.confirmation_received(event.confirmation);
        }

      }
      catch (e) {
        console.log(e);
      }
    }

  }
  catch(e) {}

  if (event.competition_id != slam.id)
    return;

  slam.event_number = event.event_number;

  if (event.event_number == slam.local_event_number + 1) {
    do_event(event);
  }
  else {

    unprocessed_events[event.event_number] = event;
    event_catch_up(event.event_number - 1);
  }
}

function last_updated(event) {

  var div = document.getElementById("last_updated");

  var date_pat = /(.*)T/;
  var date =  _.last(date_pat.exec(event.datetime));

  var time_pat = /T(\d*):(\d*):(\d*)/;
  var times = time_pat.exec(event.datetime);

  var time = " " + times[1] + ":" + times[2] + ":" + times[3];

  var datetime = date + time;

  div.innerHTML = "
 Last updated: " + datetime + "
";
}

function do_event(event) {

  if (slam.local_event_number + 1 != event.event_number)
    return;

  slam.local_event_number = event.event_number;

  if (event.event != 'signup_poet')
    last_updated(event);

  // I'm making 'new_round' an exceoption to help keep in sync with the server
  if (event.web_sock_id == web_sock_id && event.event != 'new_round') {
    return;
  }

  switch (event.event) {

    case 'new_performance':
      event_new_performance(event);
      break;
    case 'judge':
      event_judge(event);
      break;
    case 'set_time':
      event_set_time(event);
      break;
    case 'set_penalty':
      event_set_penalty(event);
      break;
    case 'signup_poet':
      signup_poet(event.name);
      break;
    case 'remove_performance':
      event_remove_performance(event);
      break;
    case 'new_round':
      event_new_round(event);
      break;
    case 'announcement':
      event_announcement(event);
      break;
    case 'edit_round':
      event_edit_round(event);
      break;
  }

}

function do_heads_up(event) {

  /*
     if (event.web_sock_id == web_sock_id || event.competition_id != slam.id || comm_2[event.performance_id] == undefined) {
     return;
     }
     */

  if (event.web_sock_id == web_sock_id) {
    console.log("bad web_sock_id");
    return;
  }

  if (event.competition_id != slam.id) {

    console.log("wrong competition");
    return
  }

  if (comms_2[event.performance_id] == undefined) {

    console.log("no performance id")
      return;
  }

  switch (event.event) {

    case 'judge':
      event_judge(event);
      break;
    case 'set_time':
      event_set_time(event);
      break;
    case 'set_penalty':
      event_set_penalty(event);
      break;
    case 'focus':
      event_focus(event);
      break;
    case 'blur':
      event_blur(event);
      break;
  }
}

// Send requests to the server up to and including 'event_number'
function event_catch_up(event_number) {

  var event_number_i = Math.max(unprocessed_events.waiting_for, slam.local_number_event_number + 1);
  var event_number_j = event_number;

  unprocessed_events.waiting_for = event_number_j;
  get_event_range_request(event_number_i, event_number_j);
}

function event_new_performance(event) {

  var round = rounds[event.round_number -1];

  var prev_performance_2 = null;

  if (event.previous_performance_id != null) {
    prev_performance_2 = comms_2[event.previous_performance_id].p_div.performance;
  }

  var performance_2 = performance_new(event.poet_name, prev_performance_2, round.time_limit, round.grace_period, slam.num_judges);
  var p_div = p_div_new(performance_2);

  performance_2.performance_id = event.performance_id;

  round.round_js.add_performance(performance_2);

  performance_2.calculate(); // So that it doesn't say Rank is 'Infinity'

  $("#performances_" + round.round_number).append(p_div);
  resize_inputs(p_div.data_columns);
  auto_scroll.scroll_if_on();

  round.names_already_performing.push(performance_2.name);
  invisible_round.notify_rank();

  p_div.comm.performance_id = event.performance_id;

  window.comms_2[event.performance_id] = p_div.comm;

  // Trigger contenders.get_winners() so that the button to add the performer will be removed
  if (round.are_poets_from_previous) {

    var previous_round_index = round.previous_round_number == null ? event.round_number - 2 : round.previous_round_number -1;
    rounds[previous_round_index].round_js.rank();
  }

}

function event_announcement(event) {

  var announcement_recv_id = "announcement_recv_" + event.round_number;
  var announcement_recv = document.getElementById(announcement_recv_id);

  announcement_recv.innerHTML = event.message;
  announcement_recv.style.color = '#5E5C42';
}

function event_focus(event) {

  try {
    var p_div = window.comms_2[event.performance_id].p_div;

    var minutes_i = p_div.indexes['minutes_i'];
    var seconds_i = p_div.indexes['seconds_i'];

    if (event.index == minutes_i || event.index == seconds_i ) {
      p_div.data_columns[minutes_i].style.fontStyle = 'italic';
      p_div.data_columns[seconds_i].style.fontStyle = 'italic';
    }
    else {
      var input = p_div.data_columns[event.index];
      input.style.fontStyle = "italic";
    }
  }
  catch (e) {
    console.log(e);
  }

}

function event_blur(event) {

  try {
    var p_div = window.comms_2[event.performance_id].p_div;

    var minutes_i = p_div.indexes['minutes_i'];
    var seconds_i = p_div.indexes['seconds_i'];

    if (event.index == minutes_i || event.index == seconds_i ) {
      p_div.data_columns[minutes_i].style.fontStyle = 'normal';
      p_div.data_columns[seconds_i].style.fontStyle = 'normal';
    }
    else {
      var input = p_div.data_columns[event.index];
      input.style.fontStyle = "normal";
    }
  }
  catch (e) {
    console.log(e);
  }

}

function event_judge(event) {
  var comm_2 = window.comms_2[event.performance_id];
  var is_this_a_heads_up = event.type == 'heads_up' ? true : false;

  p_div_set_score(comm_2.p_div, parseInt(event.judge_name), event.value, is_this_a_heads_up);
}

function event_set_time(event) {

  var p_div = window.comms_2[event.performance_id].p_div;
  var is_this_a_heads_up = event.type == 'heads_up' ? true : false;
  p_div_set_time(p_div, event.minutes, event.seconds, is_this_a_heads_up);
}

function event_set_penalty(event) {
  var p_div = window.comms_2[event.performance_id].p_div;
  var is_this_a_heads_up = event.type == 'heads_up' ? true : false;
  p_div_set_penalty(p_div, event.penalty, is_this_a_heads_up);

}

function event_remove_performance(event) {

  var comm_2 = window.comms_2[event.performance_id];

  remove_performance(comm_2.p_div);
}

function event_new_round(event) {

  if (rounds.length >= parseInt(event.round.round_number))
    return; // ignore

  var round = event.round;
  create_round_div(round);
}

function event_edit_round(event) {

    function update_round(round, event) {

        var keys = _.keys(event);

        for (var i=0; i<keys.length; i++) {
            round[keys[i]] = event[keys[i]];
        }
    }
    function update_time_limit_and_grace_period_for_performances(round) {

        var performances = round.round_js.performances;

        for (var i=0; i<performances.length; i++) {

            var performance = performances[i];

            performance.time_limit = round.time_limit;
            performance.grace_period = round.grace_period;

            performance.calculate();
        }
    }

    var round = null;

    for (var i=0; i<rounds.length; i++) {
        if (rounds[i].id == event.round_id) {
            round = rounds[i];
            break;
        }
    }

    if (round == null)
        return;

    update_round(round, event);

    //Title
   var e = document.getElementById("round_title_" + round.round_number);
   e.innerHTML = event.title;
   update_time_limit_and_grace_period_for_performances(round);

   // Number of Poets
   round.contenders.get_winners(round.contenders, round);

   // Number of Places

   // Time limit & Grace period
   e = document.getElementById("round_info_" + round.round_number);
   e.innerHTML = generate_round_info_innerHTML(round);

   // Is cumulative

   // Are poets from previous

   // Previous Round Number

}
<|endoftext|>