<commit_before>function Board(canvas) {
    this.images = {};

    this.canvas = canvas;
    this.context = this.canvas.getContext('2d');
    this.drawing = new Drawing(this.context);

    this.board_data = null;
    this.rows = 0;
    this.columns = 0;
    this.height = 0;
    this.width = 0;
    this.viewPortCoord = [0, 0];
    this.viewPortSize = [canvas.width, canvas.height];
    this.zoom = 1;

    this.hovered_cell = null;

    this.dragging = false;

    // Used in events
    var self = this;

    $(this.canvas).mousemove(function(eventObject) {
        var $this = $(this);
        var offset = $this.offset();
        var x = eventObject.pageX - offset.left;
        var y = eventObject.pageY - offset.top;

        var tileX = Math.floor((x + (self.viewPortCoord[0] * self.zoom)) / (self.drawing.cellWidth * self.zoom));
        var tileY = Math.floor((y + (self.viewPortCoord[1] * self.zoom)) / (self.drawing.cellHeight * self.zoom));

        self.cellHover(tileX, tileY);
    });

    $(this.canvas).mousedown(function(eventObject) {
        this.dragging = true;
    });

    this.setZoom = function(val) {
        this.zoom = val;
        this.viewPortSize = [this.canvas.width * val, this.canvas.height * val];
        var newVpx = Math.min(this.width - this.viewPortSize[0], this.viewPortCoord[0]);
        var newVpy = Math.min(this.height - this.viewPortSize[1], this.viewPortCoord[1]);
        this.viewPortCoord = [Math.max(0, newVpx), Math.max(0, newVpy)];
    };

    this.refresh = function(data) {

        if (!data) {
            return;
        }

        this.board_data = data;
        var self = this;

        this.prepareImages(data.board_images, function(args) { self.update(); });
    };

    this.renderBoardBackground = function() {
        var data = this.board_data;
        var drawing = this.drawing;

        drawing.colorBackground(this.columns, this.rows, "black");

        for (var x = 0; x < data.board_pieces.length; x++) {
            var p = data.board_pieces[x];
            drawing.drawTile(p.left, p.top, p.width, p.height, this.images[p.image]);
        }
    };

    this.renderBoardGrid = function() {
        this.drawing.drawGrid(this.rows, this.columns);
    };

    this.update = function() {
        var context = this.context;
        var drawing = this.drawing;
        var data = this.board_data;

        this.rows = data.board_extents[1];
        this.columns = data.board_extents[0];

        this.width = drawing.gridWidth(this.columns) * this.zoom;
        this.height = drawing.gridHeight(this.rows) * this.zoom;

        context.save();
        context.translate(-1 * this.viewPortCoord[0], -1 * this.viewPortCoord[1]);
        context.scale(this.zoom, this.zoom);

        drawing.clear(this.columns, this.rows);

        this.renderBoardBackground();

        if (this.hovered_cell) {
            this.drawing.colorCell(this.hovered_cell[0], this.hovered_cell[1], "rgba(0, 204, 0, 0.75)");
        }

        context.restore();
    };

    this.cellHover = function(x, y) {
        if (this.hovered_cell && this.hovered_cell[0] == x && this.hovered_cell[1] == y)
            return;

        this.hovered_cell = [x, y];

//        this.context.save();
//        this.context.scale(this.zoom, this.zoom);
//
//        this.drawing.colorCell(x, y, "rgba(0, 204, 0, 0.75)");
//
//        if (this.hovered_cell) {
//            this.drawing.drawCellsFromCanvas(this.hovered_cell[0], this.hovered_cell[1], 1, 1, this.boardCanvas);
//        }
//
//        this.hovered_cell = [x, y];
//
//        this.context.restore();
    };

    this.boardPieceAt = function(x, y) {
        var data = this.board_data;
        for (var i = 0; x < data.board_pieces.length; i++) {
            var p = data.board_pieces[i];
            if (p.left <= x && p.right >= x && p.top <= y && p.bottom >= y) {
                return p;
            }
        }
        return null;
    };

    this.prepareImages = function(imgs, callback) {
        "use strict";
        var loaded = 0;
        var images = [];
        imgs = Object.prototype.toString.apply( imgs ) === '[object Array]' ? imgs : [imgs];
        var inc = function() {
            loaded += 1;
            if ( loaded === imgs.length && callback ) {
                callback( images );
            }
        };
        for ( var i = 0; i < imgs.length; i++ ) {
            if (!this.images[imgs[i]]) {
                images[i] = new Image();
                this.images[imgs[i]] = images[i];
                images[i].onabort = inc;
                images[i].onerror = inc;
                images[i].onload = inc;
                images[i].src = ROOT_URL + "assets/" + imgs[i];
            }
        }
    };
};

function BoardEvents(board) {

}<commit_msg>small change<commit_after>function Board(canvas) {
    this.images = {};

    this.canvas = canvas;
    this.context = this.canvas.getContext('2d');
    this.drawing = new Drawing(this.context);

    this.board_data = null;
    this.rows = 0;
    this.columns = 0;
    this.height = 0;
    this.width = 0;
    this.viewPortCoord = [0, 0];
    this.viewPortSize = [canvas.width, canvas.height];
    this.zoom = 1;

    this.hovered_cell = null;

    this.dragging = false;
    this.dragOrigin = null;

    // Used in events
    var self = this;

    $(this.canvas).mousemove(function(eventObject) {
        var $this = $(this);
        var offset = $this.offset();
        var x = eventObject.pageX - offset.left;
        var y = eventObject.pageY - offset.top;

        var tileX = Math.floor((x + (self.viewPortCoord[0] * self.zoom)) / (self.drawing.cellWidth * self.zoom));
        var tileY = Math.floor((y + (self.viewPortCoord[1] * self.zoom)) / (self.drawing.cellHeight * self.zoom));

        self.cellHover(tileX, tileY);

        if (this.dragging) {

        }
    });

    $(this.canvas).mousedown(function(eventObject) {
        this.dragging = true;
    });

    this.setZoom = function(val) {
        this.zoom = val;
        this.viewPortSize = [this.canvas.width * val, this.canvas.height * val];
        var newVpx = Math.min(this.width - this.viewPortSize[0], this.viewPortCoord[0]);
        var newVpy = Math.min(this.height - this.viewPortSize[1], this.viewPortCoord[1]);
        this.viewPortCoord = [Math.max(0, newVpx), Math.max(0, newVpy)];
    };

    this.refresh = function(data) {

        if (!data) {
            return;
        }

        this.board_data = data;
        var self = this;

        this.prepareImages(data.board_images, function(args) { self.update(); });
    };

    this.renderBoardBackground = function() {
        var data = this.board_data;
        var drawing = this.drawing;

        drawing.colorBackground(this.columns, this.rows, "black");

        for (var x = 0; x < data.board_pieces.length; x++) {
            var p = data.board_pieces[x];
            drawing.drawTile(p.left, p.top, p.width, p.height, this.images[p.image]);
        }
    };

    this.renderBoardGrid = function() {
        this.drawing.drawGrid(this.rows, this.columns);
    };

    this.update = function() {
        var context = this.context;
        var drawing = this.drawing;
        var data = this.board_data;

        this.rows = data.board_extents[1];
        this.columns = data.board_extents[0];

        this.width = drawing.gridWidth(this.columns) * this.zoom;
        this.height = drawing.gridHeight(this.rows) * this.zoom;

        context.save();
        context.translate(-1 * this.viewPortCoord[0], -1 * this.viewPortCoord[1]);
        context.scale(this.zoom, this.zoom);

        drawing.clear(this.columns, this.rows);

        this.renderBoardBackground();

        if (this.hovered_cell) {
            this.drawing.colorCell(this.hovered_cell[0], this.hovered_cell[1], "rgba(0, 204, 0, 0.75)");
        }

        context.restore();
    };

    this.cellHover = function(x, y) {
        if (this.hovered_cell && this.hovered_cell[0] == x && this.hovered_cell[1] == y)
            return;

        this.hovered_cell = [x, y];

//        this.context.save();
//        this.context.scale(this.zoom, this.zoom);
//
//        this.drawing.colorCell(x, y, "rgba(0, 204, 0, 0.75)");
//
//        if (this.hovered_cell) {
//            this.drawing.drawCellsFromCanvas(this.hovered_cell[0], this.hovered_cell[1], 1, 1, this.boardCanvas);
//        }
//
//        this.hovered_cell = [x, y];
//
//        this.context.restore();
    };

    this.boardPieceAt = function(x, y) {
        var data = this.board_data;
        for (var i = 0; x < data.board_pieces.length; i++) {
            var p = data.board_pieces[i];
            if (p.left <= x && p.right >= x && p.top <= y && p.bottom >= y) {
                return p;
            }
        }
        return null;
    };

    this.prepareImages = function(imgs, callback) {
        "use strict";
        var loaded = 0;
        var images = [];
        imgs = Object.prototype.toString.apply( imgs ) === '[object Array]' ? imgs : [imgs];
        var inc = function() {
            loaded += 1;
            if ( loaded === imgs.length && callback ) {
                callback( images );
            }
        };
        for ( var i = 0; i < imgs.length; i++ ) {
            if (!this.images[imgs[i]]) {
                images[i] = new Image();
                this.images[imgs[i]] = images[i];
                images[i].onabort = inc;
                images[i].onerror = inc;
                images[i].onload = inc;
                images[i].src = ROOT_URL + "assets/" + imgs[i];
            }
        }
    };
};

function BoardEvents(board) {

}<|endoftext|>


<commit_before>var selected_projects = [];

$(document).ready(function() {

window.addEventListener("load", function(event) {
  console.log("page loaded!");
  var state = history.state;
  console.log("state");
  console.log(state);
    if (state) {
    selected_projects = state["selected_projects"];
    for (i = 0; i < selected_projects.length; i++) {
      selectProject(selected_projects[i]);

      // @TODO: may want to re-visit to see why once I move the following to toggleProject, first page behaves super weird
      selectedCheckBox = ("permit_selected_").concat(selected_projects[i]).replace("-", "_");
      document.getElementById(selectedCheckBox).checked = true;
      alert("finish popstate");
    }
  }
});
$("#new_permit_submit").click(function(e){
    alert("before preventing default");
     e.preventDefault();
     alert("before saving projects");
     saveProjects();
     alert("before submiting");
     $('#new_permit').submit();
 });
// $("#new_permit").submit(function(e) {
//   e.preventDefault();
//   //alert("about to submit");
//   saveProjects();
//   //return true;
//   $(this).trigger('submit');
// });

  // trigger when user clicks any of the "select a project" buttons
  $ (".project").each(function(i) {

    // just focus on the button the user clicked
    $(this).click(function() {

      // get the id of the clicked button button, which will tell us what kind of project the user picked
      clickedButton = $(this).attr("id");

      // add in selected_projects array
      proj_index = selected_projects.indexOf(clickedButton);
      if (proj_index == -1) {
        // add item to array
        selected_projects.push(clickedButton);
        selectProject(clickedButton);
      } else {
        // remove item from array
        selected_projects.splice(proj_index, 1);
        unselectProject(clickedButton);
      }

      console.log(selected_projects);

    });
  });
});

$(document).on("pagecreate",function(){
  console.log("pagecreate event fired!");
});

window.addEventListener('hashchange', function()  {
  console.log('hashchange fired');
});

window.onpopstate = function (e) {
 alert("in onpopstate");
  // if (e.state) {
  //   if (e.state.type == 'product-detail' && $('.product-container').length == 1) {
  //     updateProductDetail(e.state.html);
  //   }
  //   else {
  //     location.reload();
  //   }
  // }
};
window.addEventListener('popstate', function(event) {
  alert("in popstate event");
  console.log("poping state triggered");
  console.log(event.state);
  if (event.state) {
    selected_projects = event.state["selected_projects"];
    for (i = 0; i < selected_projects.length; i++) {
      selectProject(selected_projects[i]);

      // @TODO: may want to re-visit to see why once I move the following to toggleProject, first page behaves super weird
      selectedCheckBox = ("permit_selected_").concat(selected_projects[i]).replace("-", "_");
      document.getElementById(selectedCheckBox).checked = true;
      alert("finish popstate");
    }
  }
});

function selectProject(project)
{
  toggleProject(project, true);
}

function unselectProject(project)
{
  toggleProject(project, false);
}

function toggleProject(project, toggle)
{
  // grab the class for the clickedButton, so we can add the success class and change its color
  clickedButtonClass = (".pick-").concat(project);
  // give the clicked button the success class, so it will change color
  $(clickedButtonClass).toggleClass("btn-success", toggle);

  // turn the id we got from clickedButton into a class, so we can show the correct "Your Project" sidebar icon
  chosenProject = (".").concat(project);
  // show the correct "Your Project" icon in sidebar
  $(chosenProject).toggleClass("displayed", toggle);
}

function blah()
{
  console.log("floor has been clicked!");
}
function saveProjects()
{
  //alert("saving projects");
  //debugger
  console.log("pushing states");
  var stateObj = {};
  stateObj.selected_projects = selected_projects;
  history.pushState(stateObj, "Homebase", document.URL);
  console.log(stateObj);
}
 // $('#new_permit').click(function(e){
 //     e.preventDefault();
 //     //do ur stuff.
 //     $('#formId').submit();
 // });

<commit_msg>Add more debugging alerts<commit_after>var selected_projects = [];

$(document).ready(function() {

window.addEventListener("load", function(event) {
  console.log("page loaded!");
  var state = history.state;
  console.log("state");
  console.log(state);
    if (state) {
    selected_projects = state["selected_projects"];
    for (i = 0; i < selected_projects.length; i++) {
      selectProject(selected_projects[i]);

      // @TODO: may want to re-visit to see why once I move the following to toggleProject, first page behaves super weird
      selectedCheckBox = ("permit_selected_").concat(selected_projects[i]).replace("-", "_");
      document.getElementById(selectedCheckBox).checked = true;
      alert("finish popstate in load");
    }
  }
});
$("#new_permit_submit").click(function(e){
    alert("before preventing default");
     e.preventDefault();
     alert("before saving projects");
     saveProjects();
     alert("before submiting");
     $('#new_permit').submit();
 });
// $("#new_permit").submit(function(e) {
//   e.preventDefault();
//   //alert("about to submit");
//   saveProjects();
//   //return true;
//   $(this).trigger('submit');
// });

  // trigger when user clicks any of the "select a project" buttons
  $ (".project").each(function(i) {

    // just focus on the button the user clicked
    $(this).click(function() {

      // get the id of the clicked button button, which will tell us what kind of project the user picked
      clickedButton = $(this).attr("id");

      // add in selected_projects array
      proj_index = selected_projects.indexOf(clickedButton);
      if (proj_index == -1) {
        // add item to array
        selected_projects.push(clickedButton);
        selectProject(clickedButton);
      } else {
        // remove item from array
        selected_projects.splice(proj_index, 1);
        unselectProject(clickedButton);
      }

      console.log(selected_projects);

    });
  });
});

$(document).on("pagecreate",function(){
  console.log("pagecreate event fired!");
});

window.addEventListener('hashchange', function()  {
  console.log('hashchange fired');
});

window.onpopstate = function (e) {
 alert("in onpopstate");
  // if (e.state) {
  //   if (e.state.type == 'product-detail' && $('.product-container').length == 1) {
  //     updateProductDetail(e.state.html);
  //   }
  //   else {
  //     location.reload();
  //   }
  // }
};
window.addEventListener('popstate', function(event) {
  alert("in popstate event");
  console.log("poping state triggered");
  console.log(event.state);
  if (event.state) {
    selected_projects = event.state["selected_projects"];
    for (i = 0; i < selected_projects.length; i++) {
      selectProject(selected_projects[i]);

      // @TODO: may want to re-visit to see why once I move the following to toggleProject, first page behaves super weird
      selectedCheckBox = ("permit_selected_").concat(selected_projects[i]).replace("-", "_");
      document.getElementById(selectedCheckBox).checked = true;
      alert("finish popstate in listener");
    }
  }
});

function selectProject(project)
{
  toggleProject(project, true);
}

function unselectProject(project)
{
  toggleProject(project, false);
}

function toggleProject(project, toggle)
{
  // grab the class for the clickedButton, so we can add the success class and change its color
  clickedButtonClass = (".pick-").concat(project);
  // give the clicked button the success class, so it will change color
  $(clickedButtonClass).toggleClass("btn-success", toggle);

  // turn the id we got from clickedButton into a class, so we can show the correct "Your Project" sidebar icon
  chosenProject = (".").concat(project);
  // show the correct "Your Project" icon in sidebar
  $(chosenProject).toggleClass("displayed", toggle);
}

function blah()
{
  console.log("floor has been clicked!");
}
function saveProjects()
{
  //alert("saving projects");
  //debugger
  console.log("pushing states");
  var stateObj = {};
  stateObj.selected_projects = selected_projects;
  history.pushState(stateObj, "Homebase", document.URL);
  console.log(stateObj);
}
 // $('#new_permit').click(function(e){
 //     e.preventDefault();
 //     //do ur stuff.
 //     $('#formId').submit();
 // });

<|endoftext|>


<commit_before>var ProjectEdit = {};
(function (o) {
  var trackerInterval;
  var trackerIntervalActive = false;
  var clearTrackerSetupValidations = function (result) {
    $('.success, .failure, .unconfigured', '#tracker_setup').addClass('hide');
  };

  var showAuthTokenError = function () {
    $('#project_tracker_auth_token_status .failure').removeClass('hide');
    $('#tracker_status .failure').removeClass('hide').text("Error in auth token");
  };

  var showProjectIdError = function () {
    $('#project_tracker_project_id_status .failure').removeClass('hide');
    $('#tracker_status .failure').removeClass('hide').text("Error in project ID");
  };

  var showTrackerSuccess = function () {
    $('#project_tracker_project_id_status .success').removeClass('hide');
    $('#project_tracker_auth_token_status .success').removeClass('hide');
    $('#tracker_status .success').removeClass('hide');
  }

  var showGenericError = function () {
    $('#tracker_status .failure').removeClass('hide').text("Error");
  }

  o.validateTrackerSetup = function () {
    var authToken = $('input#project_tracker_auth_token').val();
    var projectId = $('input#project_tracker_project_id').val();

    clearTrackerSetupValidations();

    if (authToken === '' && projectId === '') {
      $('#tracker_status .unconfigured').removeClass('hide');

    } else if (authToken === '') {
      showAuthTokenError();
      return false;

    } else if (projectId === '') {
      showProjectIdError();
      return false;

    } else {
      $('#tracker_status .pending').removeClass('hide');
      $.ajax({
        url: "/projects/validate_tracker_project",
        type: "post",
        data: {
          id: document.location.pathname.split("/")[2],
          auth_token: authToken,
          project_id: projectId
        },
        success: function(data, status, result) {
          if (result.status == 202) {
            if (trackerIntervalActive === false) {
              trackerInterval = window.setInterval(o.validateTrackerSetup, 1000);
              trackerIntervalActive = true;
            }
          }
          else if (result.status == 200) {
            $('#tracker_status .pending').addClass('hide');
            window.clearInterval(trackerInterval);
            trackerIntervalActive = false;
            showTrackerSuccess();
          }
        },
        error: function(result) {
          $('#tracker_status .pending').addClass('hide');
          window.clearInterval(trackerInterval);
          trackerIntervalActive = false;
          if (result.status == 401) {
            showAuthTokenError();
          } else if (result.status == 404) {
            showProjectIdError();
          } else {
            showGenericError();
          }
        }
      });
    }
  };

  o.handleProjectTypeChange = function () {
    var $container = $('#field_container');

    var $disabled_fieldsets = $('fieldset:not(#' + $(this).val() + ')', $container);
    $disabled_fieldsets.addClass('hide');
    $(':input', $disabled_fieldsets).attr('disabled', true);

    var $enabled_fieldset = $('#' + $(this).val());
    $enabled_fieldset.removeClass('hide');
    $(':input', $enabled_fieldset).attr('disabled', false);

    var $auth_fields = $('.auth_field');
    if ( $(this).val() == "TravisProject" || $(this).val() == "SemaphoreProject") {
      $auth_fields.addClass('hide');
    }
    else {
      $auth_fields.removeClass('hide');
    };
  };

  var showBuildStatusSuccess = function () {
    $('#build_status .success').removeClass('hide');
  }

  o.validateFeedUrl = function () {
    $('.success, .failure, .unconfigured', '#polling').addClass('hide');

    if ($('#project_type').val() === "") {
      $('#build_status .unconfigured').removeClass('hide');
      return;
    }

    var $inputs = $('#polling :input:not(.hide):not(.optional):enabled');
    if ($inputs.is('[value=""]')) {
      if ($inputs.is('[value!=""]')) {
        // TODO: This should probably show something like 'Some fields are
        // missing' rather than an error
        $('#polling .failure').removeClass('hide');
      } else {
        $('#polling .unconfigured').removeClass('hide');
      }
      return;
    }

    $('#polling .pending').removeClass('hide');
    $.ajax({
      url: "/projects/validate_build_info",
      type: "post",
      data: $('form').serialize(),
      success: function (result) {
        if (result.status) {
          $('#polling .pending').addClass('hide');
          showBuildStatusSuccess();
        }
        else {
          $('#polling .pending').addClass('hide');
          $('#polling .failure').removeClass('hide').attr("title",result.error_type + ": '" + result.error_text + "'");
        }
      },
      error: function (result) {
        $('#polling .pending').addClass('hide');
        $('#polling .failure').removeClass('hide').attr("title","Server Error");
      }
    });
  };

  var handleParameterChange = function (event) {
    if (o.validateTrackerSetup() === false) {
      event.stopPropagation();
      event.preventDefault();
    }
  };

  o.toggleWebhooks = function () {
    if ($('input#project_webhooks_enabled_true:checked').length > 0) {
      $('fieldset#webhooks').removeClass('hide');
      $('fieldset#polling').addClass('hide');
    }
    else if ($('input#project_webhooks_enabled_false:checked').length > 0) {
      $('fieldset#webhooks').addClass('hide');
      $('fieldset#polling').removeClass('hide');
    }
  };

  var showPasswordField = function () {
    $('#new_password').removeClass('hide');
    $('#change_password').addClass('hide');
    $('#new_password input').focus();
    $('#password_changed').val('true');
    return false;
  };

  o.init = function () {
    $('#project_tracker_auth_token, #project_tracker_project_id, input[type=submit]')
    .change(handleParameterChange);
    $('#project_type').change(o.handleProjectTypeChange);
    $('#polling :input').change(o.validateFeedUrl);
    $('input[name="project[webhooks_enabled]"]').change(o.toggleWebhooks);
    $('#polling input.refresh').click(o.validateFeedUrl);
    $('#change_password a').click(showPasswordField);

    if ($('input[name="project[webhooks_enabled]"]').length > 0) { o.toggleWebhooks(); }

    var $project_online = $('#project_online');
    if ($project_online.length !== 0) {
      if ($project_online.val() === "1") {
        showBuildStatusSuccess();
      } else {
        $('#polling .failure').removeClass('hide');
      }
    }

    var $tracker_online = $('#project_tracker_online');
    if ($tracker_online.length !== 0) {
      if ($tracker_online.val() === "1") {
        showTrackerSuccess();
      } else {
        o.validateTrackerSetup();
      }
    }
  };
})(ProjectEdit);

<commit_msg>removed errant semicolon that JSHint didn't like '<commit_after>var ProjectEdit = {};
(function (o) {
  var trackerInterval;
  var trackerIntervalActive = false;
  var clearTrackerSetupValidations = function (result) {
    $('.success, .failure, .unconfigured', '#tracker_setup').addClass('hide');
  };

  var showAuthTokenError = function () {
    $('#project_tracker_auth_token_status .failure').removeClass('hide');
    $('#tracker_status .failure').removeClass('hide').text("Error in auth token");
  };

  var showProjectIdError = function () {
    $('#project_tracker_project_id_status .failure').removeClass('hide');
    $('#tracker_status .failure').removeClass('hide').text("Error in project ID");
  };

  var showTrackerSuccess = function () {
    $('#project_tracker_project_id_status .success').removeClass('hide');
    $('#project_tracker_auth_token_status .success').removeClass('hide');
    $('#tracker_status .success').removeClass('hide');
  }

  var showGenericError = function () {
    $('#tracker_status .failure').removeClass('hide').text("Error");
  }

  o.validateTrackerSetup = function () {
    var authToken = $('input#project_tracker_auth_token').val();
    var projectId = $('input#project_tracker_project_id').val();

    clearTrackerSetupValidations();

    if (authToken === '' && projectId === '') {
      $('#tracker_status .unconfigured').removeClass('hide');

    } else if (authToken === '') {
      showAuthTokenError();
      return false;

    } else if (projectId === '') {
      showProjectIdError();
      return false;

    } else {
      $('#tracker_status .pending').removeClass('hide');
      $.ajax({
        url: "/projects/validate_tracker_project",
        type: "post",
        data: {
          id: document.location.pathname.split("/")[2],
          auth_token: authToken,
          project_id: projectId
        },
        success: function(data, status, result) {
          if (result.status == 202) {
            if (trackerIntervalActive === false) {
              trackerInterval = window.setInterval(o.validateTrackerSetup, 1000);
              trackerIntervalActive = true;
            }
          }
          else if (result.status == 200) {
            $('#tracker_status .pending').addClass('hide');
            window.clearInterval(trackerInterval);
            trackerIntervalActive = false;
            showTrackerSuccess();
          }
        },
        error: function(result) {
          $('#tracker_status .pending').addClass('hide');
          window.clearInterval(trackerInterval);
          trackerIntervalActive = false;
          if (result.status == 401) {
            showAuthTokenError();
          } else if (result.status == 404) {
            showProjectIdError();
          } else {
            showGenericError();
          }
        }
      });
    }
  };

  o.handleProjectTypeChange = function () {
    var $container = $('#field_container');

    var $disabled_fieldsets = $('fieldset:not(#' + $(this).val() + ')', $container);
    $disabled_fieldsets.addClass('hide');
    $(':input', $disabled_fieldsets).attr('disabled', true);

    var $enabled_fieldset = $('#' + $(this).val());
    $enabled_fieldset.removeClass('hide');
    $(':input', $enabled_fieldset).attr('disabled', false);

    var $auth_fields = $('.auth_field');
    if ( $(this).val() == "TravisProject" || $(this).val() == "SemaphoreProject") {
      $auth_fields.addClass('hide');
    }
    else {
      $auth_fields.removeClass('hide');
    }
  };

  var showBuildStatusSuccess = function () {
    $('#build_status .success').removeClass('hide');
  }

  o.validateFeedUrl = function () {
    $('.success, .failure, .unconfigured', '#polling').addClass('hide');

    if ($('#project_type').val() === "") {
      $('#build_status .unconfigured').removeClass('hide');
      return;
    }

    var $inputs = $('#polling :input:not(.hide):not(.optional):enabled');
    if ($inputs.is('[value=""]')) {
      if ($inputs.is('[value!=""]')) {
        // TODO: This should probably show something like 'Some fields are
        // missing' rather than an error
        $('#polling .failure').removeClass('hide');
      } else {
        $('#polling .unconfigured').removeClass('hide');
      }
      return;
    }

    $('#polling .pending').removeClass('hide');
    $.ajax({
      url: "/projects/validate_build_info",
      type: "post",
      data: $('form').serialize(),
      success: function (result) {
        if (result.status) {
          $('#polling .pending').addClass('hide');
          showBuildStatusSuccess();
        }
        else {
          $('#polling .pending').addClass('hide');
          $('#polling .failure').removeClass('hide').attr("title",result.error_type + ": '" + result.error_text + "'");
        }
      },
      error: function (result) {
        $('#polling .pending').addClass('hide');
        $('#polling .failure').removeClass('hide').attr("title","Server Error");
      }
    });
  };

  var handleParameterChange = function (event) {
    if (o.validateTrackerSetup() === false) {
      event.stopPropagation();
      event.preventDefault();
    }
  };

  o.toggleWebhooks = function () {
    if ($('input#project_webhooks_enabled_true:checked').length > 0) {
      $('fieldset#webhooks').removeClass('hide');
      $('fieldset#polling').addClass('hide');
    }
    else if ($('input#project_webhooks_enabled_false:checked').length > 0) {
      $('fieldset#webhooks').addClass('hide');
      $('fieldset#polling').removeClass('hide');
    }
  };

  var showPasswordField = function () {
    $('#new_password').removeClass('hide');
    $('#change_password').addClass('hide');
    $('#new_password input').focus();
    $('#password_changed').val('true');
    return false;
  };

  o.init = function () {
    $('#project_tracker_auth_token, #project_tracker_project_id, input[type=submit]')
    .change(handleParameterChange);
    $('#project_type').change(o.handleProjectTypeChange);
    $('#polling :input').change(o.validateFeedUrl);
    $('input[name="project[webhooks_enabled]"]').change(o.toggleWebhooks);
    $('#polling input.refresh').click(o.validateFeedUrl);
    $('#change_password a').click(showPasswordField);

    if ($('input[name="project[webhooks_enabled]"]').length > 0) { o.toggleWebhooks(); }

    var $project_online = $('#project_online');
    if ($project_online.length !== 0) {
      if ($project_online.val() === "1") {
        showBuildStatusSuccess();
      } else {
        $('#polling .failure').removeClass('hide');
      }
    }

    var $tracker_online = $('#project_tracker_online');
    if ($tracker_online.length !== 0) {
      if ($tracker_online.val() === "1") {
        showTrackerSuccess();
      } else {
        o.validateTrackerSetup();
      }
    }
  };
})(ProjectEdit);

<|endoftext|>


<commit_before>$(document).ready(function(){
  $('#purchaseitemquantity').change(function(){
    var $price = parseInt($('#dealprice').text()) * parseInt($('#purchaseitemquantity').val());
    debugger
    $price = $price.toString();
    $('#purchaseitemprice').html($price);
  })
})<commit_msg>remove debugger<commit_after>$(document).ready(function(){
  $('#purchaseitemquantity').change(function(){
    var $price = parseInt($('#dealprice').text()) * parseInt($('#purchaseitemquantity').val());
    $price = $price.toString();
    $('#purchaseitemprice').html($price);
  })
})<|endoftext|>


<commit_before>// Object
Object.prototype.blank = function(){
  if(this === null) return true;

  for(var prop in this){
    if(this.hasOwnProperty(prop)){
      return false;
    }
  }

  return true;
};

// String

String.prototype.trim = function(){
  return $.trim(this);
};

String.prototype.blank = function(){
  return this.trim() == '';
};

// Array

Array.prototype.compact = function(){
  for(var i=0; i<this.length; i++){
    if(this[i] == undefined || this[i].blank()){
      this.splice(i, 1);
    }
  }
  return this;
};

Array.prototype.includes = function(what){
  if(typeof what == 'object'){
    var re = new RegExp(what);
    for(var i=0; i<this.length; i++){
      if(re.test(this[i].toString())){
        return true;
      }
    }
  }else{
    for(var i=0; i<this.length; i++){
      if(this[i] == what){
        return true;
      }
    }
  }
  return false;
};

Array.prototype.flatten = function(){
  var b = Array.prototype.concat.apply([], this);
  if(b.length != this.length){
    b = b.flatten();
  };

  return b;
};

Array.prototype.blank = function(){
  return this.compact().length == 0;
};

// Boolean

Boolean.prototype.blank = function(){
  return this === false;
};

// Number

Number.prototype.blank = function(){
  return this <= 0;
};<commit_msg>Fixes array compact issue with zero index<commit_after>// Object
Object.prototype.blank = function(){
  if(this === null) return true;

  for(var prop in this){
    if(this.hasOwnProperty(prop)){
      return false;
    }
  }

  return true;
};

// String

String.prototype.trim = function(){
  return $.trim(this);
};

String.prototype.blank = function(){
  return this.trim() == '';
};

// Array

Array.prototype.compact = function(){
  // Because JS is often dumb, prepend an item that we'll remove later
  // http://stackoverflow.com/questions/33136894/array-splice-does-not-remove-element-at-zero-index-when-the-indexed-variable-i
  this.unshift(null);
  for(var i=1; i<this.length; i++){
    if(this[i] == undefined || this[i].blank()){
      this.splice(i, 1);
    }
  }
  // Ignore the item we prepended, return the rest of the array
  return this.slice(1);
};

Array.prototype.includes = function(what){
  if(typeof what == 'object'){
    var re = new RegExp(what);
    for(var i=0; i<this.length; i++){
      if(re.test(this[i].toString())){
        return true;
      }
    }
  }else{
    for(var i=0; i<this.length; i++){
      if(this[i] == what){
        return true;
      }
    }
  }
  return false;
};

Array.prototype.flatten = function(){
  var b = Array.prototype.concat.apply([], this);
  if(b.length != this.length){
    b = b.flatten();
  };

  return b;
};

Array.prototype.blank = function(){
  return this.compact().length == 0;
};

// Boolean

Boolean.prototype.blank = function(){
  return this === false;
};

// Number

Number.prototype.blank = function(){
  return this <= 0;
};<|endoftext|>


<commit_before>var fs = require('fs')
var touch = require('touch')

module.exports = SeqFile

function SeqFile(file, opts) {
  if (!file)
    throw new TypeError('need to specify a file')

  opts = opts || {}

  this.file = file
  this.saving = false
  this.seq = 0
  this.frequency = opts.frequency || 1
}

SeqFile.prototype.read = function(cb) {
  var _this = this

  touch(this.file, function() {
    fs.readFile(_this.file, 'ascii', _this.onRead.bind(_this, cb))
  });
}

SeqFile.prototype.readSync = function() {
  var er, data
  try {
    data = fs.readFileSync(this.file, 'ascii')
  } catch (e) {
    er = e
  }
  return this.onRead(null, er, data)
}

SeqFile.prototype.save = function(n) {
  if (n && n > this.seq)
    this.seq = n

   // only save occasionally to cut down on I/O.
  if ((n || 0) % this.frequency !== 0) return

  if (!this.saving) {
    this.saving = true
    var t = this.file + '.TMP'
    var data = this.seq + '\n'
    fs.writeFile(t, data, this.onSave.bind(this))
  }
}

SeqFile.prototype.onSave = function(er) {
  var cb = this.onFinish.bind(this)
  if (!er)
    fs.rename(this.file + '.TMP', this.file, cb)
  else
    fs.unlink(this.file + '.TMP', cb)
}

SeqFile.prototype.onFinish = function() {
  this.saving = false
}

SeqFile.prototype.onRead = function(cb, er, data) {
  if (er && er.code === 'ENOENT')
    data = 0;
  else if (er) {
    if (cb)
      return cb(er)
    else
      throw er
  }

  if (data === undefined)
    data = null

  if (!+data && +data !== 0)
    return cb(new Error('invalid data in seqFile'))

  data = +data
  if (!er && data > this.seq)
    this.seq = data

  if (cb)
    cb(er, data)
  else if (er)
    throw er
  else
    return data
}
<commit_msg>make sure sync also runs touch.<commit_after>var fs = require('fs')
var touch = require('touch')

module.exports = SeqFile

function SeqFile(file, opts) {
  if (!file)
    throw new TypeError('need to specify a file')

  opts = opts || {}

  this.file = file
  this.saving = false
  this.seq = 0
  this.frequency = opts.frequency || 1
}

SeqFile.prototype.read = function(cb) {
  var _this = this

  touch(this.file, function() {
    fs.readFile(_this.file, 'ascii', _this.onRead.bind(_this, cb))
  });
}

SeqFile.prototype.readSync = function() {
  var er, data
  try {
    touch.sync(this.file)
    data = fs.readFileSync(this.file, 'ascii')
  } catch (e) {
    er = e
  }
  return this.onRead(null, er, data)
}

SeqFile.prototype.save = function(n) {
  if (n && n > this.seq)
    this.seq = n

   // only save occasionally to cut down on I/O.
  if ((n || 0) % this.frequency !== 0) return

  if (!this.saving) {
    this.saving = true
    var t = this.file + '.TMP'
    var data = this.seq + '\n'
    fs.writeFile(t, data, this.onSave.bind(this))
  }
}

SeqFile.prototype.onSave = function(er) {
  var cb = this.onFinish.bind(this)
  if (!er)
    fs.rename(this.file + '.TMP', this.file, cb)
  else
    fs.unlink(this.file + '.TMP', cb)
}

SeqFile.prototype.onFinish = function() {
  this.saving = false
}

SeqFile.prototype.onRead = function(cb, er, data) {
  if (er && er.code === 'ENOENT')
    data = 0;
  else if (er) {
    if (cb)
      return cb(er)
    else
      throw er
  }

  if (data === undefined)
    data = null

  if (!+data && +data !== 0)
    return cb(new Error('invalid data in seqFile'))

  data = +data
  if (!er && data > this.seq)
    this.seq = data

  if (cb)
    cb(er, data)
  else if (er)
    throw er
  else
    return data
}
<|endoftext|>


<commit_before>angular.module('myApp')

.service('amazonApi',
  function($q, user) {
    var amazonAuthenticated = false
    var bucketName = 'upload-form'
    var roleArn = 'arn:aws:iam::901881000271:role/uploader'
    var topicArn = 'arn:aws:sns:eu-west-1:901881000271:upload-form'
    var snsRegion = 'eu-west-1'
    var s3
    var sns

    return {
      authenticate: function() {
        var credentials = $q.defer()

        if (user.isAuthenticated()) {
          if (!amazonAuthenticated) {
            AWS.config.credentials = new AWS.WebIdentityCredentials({
              RoleArn: roleArn,
              WebIdentityToken: user.get().idToken
            })

            s3 = new AWS.S3({ params: { Bucket: bucketName } })
            sns = new AWS.SNS({ region: snsRegion })
            amazonAuthenticated = true
          }

          credentials.resolve(AWS.config.credentials)
        } else {
          credentials.reject({ errorMessage: 'User not authenticated.' })
          amazonAuthenticated = false

          user.redirect()
        }

        return credentials.promise
      },

      listObjects: function(options) {
        var files = $q.defer()

        this.authenticate().then(function() {
          s3.listObjects(options, function(error, data) {
            files.resolve({
              error: error,
              data: data
            })
          })
        })

        return files.promise
      },

      uploadFile: function(options) {
        var fileUploadResponse = $q.defer()

        this.authenticate().then(function() {
          options = options || {}
          options.Bucket = bucketName

          s3.putObject(options)
            .on('httpUploadProgress', function(uploadProgress) {
              fileUploadResponse.notify({
                loaded: uploadProgress.loaded,
                total: uploadProgress.total
              })
            })
            .on('complete', function() {
              fileUploadResponse.resolve(true)
            })
            .on('error', function() {
              fileUploadResponse.resolve(false)
              console.log(arguments)
            })
            .send()
        })

        return fileUploadResponse.promise
      },

      getSignedUrl: function(key) {
        return s3.getSignedUrl('getObject', {
          Bucket: bucketName,
          Key: key,
          Expires: 78892300 // 25 years in seconds
        })
      },

      sendNotification: function(message) {
        var messageStatus = $q.defer()

        this.authenticate().then(function() {
          sns.publish({
            TopicArn: topicArn,
            Subject: message.subject,
            Message: message.body,
          }, function(error, data) {
            if (error !== null) {
              messageStatus.resolve(false)
            } else {
              messageStatus.resolve(true)
            }
          })
        })

        return messageStatus.promise
      }
    }
  }
)

.service('user',
  function($state, $q) {
    var user = {}
    var credentials

    return {
      redirect: function() {
        if (this.isAuthenticated()) {
          $state.go('uploadForm')
        } else {
          $state.go('requireLogin')
        }
      },

      isAuthenticated: function() {
        var currentTime = parseInt(new Date().valueOf() / 1000)
        credentials = credentials || (localStorage['credentials'] && JSON.parse(localStorage['credentials']))

        if (credentials && credentials.expires_at > currentTime) {
          this.setCredentials(credentials)
          return true
        } else {
          return false
        }
      },

      setCredentials: function(newCredentials) {
        angular.extend(user, {
          accessToken: newCredentials.access_token,
          idToken: newCredentials.id_token
        })

        credentials = newCredentials
        gapi.auth.setToken(credentials)
        localStorage['credentials'] = JSON.stringify(credentials)
      },

      get: function() {
        return user
      },

      populateInfo: function() {
        var userInfo = $q.defer()

        gapi.client.oauth2.userinfo.get().execute(function(freshUserInfo) {
          angular.extend(user, {
            name: {
              display: freshUserInfo.name,
              familyName: freshUserInfo.family_name,
              givenName: freshUserInfo.given_name
            },
            domain: freshUserInfo.hd,
            email: freshUserInfo.email,
            gender: freshUserInfo.gender,
            id: freshUserInfo.id,
            image: freshUserInfo.picture,
            googlePlusUrl: freshUserInfo.link
          })

          userInfo.resolve(user)
        })

        return userInfo.promise
      }
    }
  }
)

.service('filesCollection',
  function($q) {
    var files = []
    var supportedTypes = {
      descriptionDocument: ['pdf', 'txt', 'doc', 'docx'],
      image: ['gif', 'jpeg', 'png'],
      video: ['avi', 'mpeg', 'mov', 'mp4', 'ogg', 'm4v', 'webm'],
    }

    return {
      get: function() {
        return files
      },

      add: function(newFiles) {
        var add = $q.defer()

        _.each(newFiles, function(newFile, index) {
          $q.all({
            descriptionDocument: validateExtension(supportedTypes.descriptionDocument, newFile),
            video: validateExtension(supportedTypes.video, newFile),
            hsAndBs: validateImageFile(newFile, [3840, 2160]),
            oneSheet: validateImageFile(newFile, [3072, 4608])
          }).then(function(results) {
            files.push(initFile(newFile, {
              assetType: _.invert(results)['true'] || 'other'
            }))

            if (index === newFiles.length - 1) {
              add.resolve(files)
            }
          })
        })

        return add.promise

        function initFile(newFile, newProperties) {
          return angular.extend(newFile, newProperties)
        }

        function validateExtension(extensions, file) {
          var validateExtensions = $q.defer()

          if (_.any(extensions, function(extension) {
            return file.name.substr(-extension.length) === extension
          })) {
            validateExtensions.resolve(true)
          } else {
            validateExtensions.resolve(false)
          }

          return validateExtensions.promise
        }

        function validateImageFile(file, dimensions) {
          var validateImageFile = $q.defer()
          var fileReader = new FileReader

          if (_.any(supportedTypes.image, function(extension) {
            return file.name.substr(-extension.length) === extension
          })) {
            fileReader.onload = function() {
              var img = new Image

              img.onload = function() {
                if (img.width === dimensions[0] && img.height === dimensions[1]) {
                  validateImageFile.resolve(true)
                } else {
                  validateImageFile.resolve(false)
                }
              }

              img.src = fileReader.result
            }

            fileReader.readAsDataURL(file)
          } else {
            validateImageFile.resolve(false)
          }

          return validateImageFile.promise
        }
      },
    }
  }
)<commit_msg>Bug fix.<commit_after>angular.module('myApp')

.service('amazonApi',
  function($q, user) {
    var amazonAuthenticated = false
    var bucketName = 'upload-form'
    var roleArn = 'arn:aws:iam::901881000271:role/uploader'
    var topicArn = 'arn:aws:sns:eu-west-1:901881000271:upload-form'
    var snsRegion = 'eu-west-1'
    var s3
    var sns

    return {
      authenticate: function() {
        var credentials = $q.defer()

        if (user.isAuthenticated()) {
          if (!amazonAuthenticated) {
            AWS.config.credentials = new AWS.WebIdentityCredentials({
              RoleArn: roleArn,
              WebIdentityToken: user.get().idToken
            })

            s3 = new AWS.S3({ params: { Bucket: bucketName } })
            sns = new AWS.SNS({ region: snsRegion })
            amazonAuthenticated = true
          }

          credentials.resolve(AWS.config.credentials)
        } else {
          credentials.reject({ errorMessage: 'User not authenticated.' })
          amazonAuthenticated = false

          user.redirect()
        }

        return credentials.promise
      },

      listObjects: function(options) {
        var files = $q.defer()

        this.authenticate().then(function() {
          s3.listObjects(options, function(error, data) {
            files.resolve({
              error: error,
              data: data
            })
          })
        })

        return files.promise
      },

      uploadFile: function(options) {
        var fileUploadResponse = $q.defer()

        this.authenticate().then(function() {
          options = options || {}
          options.Bucket = bucketName

          s3.putObject(options)
            .on('httpUploadProgress', function(uploadProgress) {
              fileUploadResponse.notify({
                loaded: uploadProgress.loaded,
                total: uploadProgress.total
              })
            })
            .on('complete', function() {
              fileUploadResponse.resolve(true)
            })
            .on('error', function() {
              fileUploadResponse.resolve(false)
              console.log(arguments)
            })
            .send()
        })

        return fileUploadResponse.promise
      },

      getSignedUrl: function(key) {
        return s3.getSignedUrl('getObject', {
          Bucket: bucketName,
          Key: key,
          Expires: 78892300 // 25 years in seconds
        })
      },

      sendNotification: function(message) {
        var messageStatus = $q.defer()

        this.authenticate().then(function() {
          sns.publish({
            TopicArn: topicArn,
            Subject: message.subject,
            Message: message.body,
          }, function(error, data) {
            if (error !== null) {
              messageStatus.resolve(false)
            } else {
              messageStatus.resolve(true)
            }
          })
        })

        return messageStatus.promise
      }
    }
  }
)

.service('user',
  function($state, $q) {
    var user = {}
    var credentials

    return {
      redirect: function() {
        if (this.isAuthenticated()) {
          $state.go('uploadForm')
        } else {
          $state.go('requireLogin')
        }
      },

      isAuthenticated: function() {
        var currentTime = parseInt(new Date().valueOf() / 1000)
        credentials = credentials || (localStorage['credentials'] && JSON.parse(localStorage['credentials']))

        if (credentials && credentials.expires_at > currentTime && credentials.error.length < 1) {
          this.setCredentials(credentials)
          return true
        } else {
          return false
        }
      },

      setCredentials: function(newCredentials) {
        angular.extend(user, {
          accessToken: newCredentials.access_token,
          idToken: newCredentials.id_token
        })

        credentials = newCredentials
        gapi.auth.setToken(credentials)
        localStorage['credentials'] = JSON.stringify(credentials)
      },

      get: function() {
        return user
      },

      populateInfo: function() {
        var userInfo = $q.defer()

        gapi.client.oauth2.userinfo.get().execute(function(freshUserInfo) {
          angular.extend(user, {
            name: {
              display: freshUserInfo.name,
              familyName: freshUserInfo.family_name,
              givenName: freshUserInfo.given_name
            },
            domain: freshUserInfo.hd,
            email: freshUserInfo.email,
            gender: freshUserInfo.gender,
            id: freshUserInfo.id,
            image: freshUserInfo.picture,
            googlePlusUrl: freshUserInfo.link
          })

          userInfo.resolve(user)
        })

        return userInfo.promise
      }
    }
  }
)

.service('filesCollection',
  function($q) {
    var files = []
    var supportedTypes = {
      descriptionDocument: ['pdf', 'txt', 'doc', 'docx'],
      image: ['gif', 'jpeg', 'png'],
      video: ['avi', 'mpeg', 'mov', 'mp4', 'ogg', 'm4v', 'webm'],
    }

    return {
      get: function() {
        return files
      },

      add: function(newFiles) {
        var add = $q.defer()

        _.each(newFiles, function(newFile, index) {
          $q.all({
            descriptionDocument: validateExtension(supportedTypes.descriptionDocument, newFile),
            video: validateExtension(supportedTypes.video, newFile),
            hsAndBs: validateImageFile(newFile, [3840, 2160]),
            oneSheet: validateImageFile(newFile, [3072, 4608])
          }).then(function(results) {
            files.push(initFile(newFile, {
              assetType: _.invert(results)['true'] || 'other'
            }))

            if (index === newFiles.length - 1) {
              add.resolve(files)
            }
          })
        })

        return add.promise

        function initFile(newFile, newProperties) {
          return angular.extend(newFile, newProperties)
        }

        function validateExtension(extensions, file) {
          var validateExtensions = $q.defer()

          if (_.any(extensions, function(extension) {
            return file.name.substr(-extension.length) === extension
          })) {
            validateExtensions.resolve(true)
          } else {
            validateExtensions.resolve(false)
          }

          return validateExtensions.promise
        }

        function validateImageFile(file, dimensions) {
          var validateImageFile = $q.defer()
          var fileReader = new FileReader

          if (_.any(supportedTypes.image, function(extension) {
            return file.name.substr(-extension.length) === extension
          })) {
            fileReader.onload = function() {
              var img = new Image

              img.onload = function() {
                if (img.width === dimensions[0] && img.height === dimensions[1]) {
                  validateImageFile.resolve(true)
                } else {
                  validateImageFile.resolve(false)
                }
              }

              img.src = fileReader.result
            }

            fileReader.readAsDataURL(file)
          } else {
            validateImageFile.resolve(false)
          }

          return validateImageFile.promise
        }
      },
    }
  }
)<|endoftext|>


<commit_before>function minbet(gs) {
  return gs.current_buy_in - gs.players[in_action][bet] + gs.minimum_raise;
}

var l = console.log;

function checkCard(card) {
        switch (card) {
            case "J" :
                card = 11;
                break;
            case "Q" :
                card = 12;
                break;
            case "K" :
                card = 13;
                break;
            case "A" :
                card = 14;
                break;
            default:
                card = card;
        }
        return card;
    }

function calculateBet(gs) {
    var ours = gs.players[gs.in_action].hole_cards;
    var card1 = checkCard(ours[0]);
    var card2 = checkCard(ours[1]);

    l(card1);
    l(card2);

      if (findPair(game_state)) {
        l("pair");
        return minbet(gs) + 100000;
      } else if (card1 < 2 && card2 < 2) {
        return 10;
      } else if (card1 < 6 && card2 < 6) {
        l("low cards");
        return minbet(gs);
      } else if (card1 < 10 && card2 < 10) {
        l("middle cards");
        return minbet(gs) + 200;
      } else {
        l("high cards");
        return minbet(gs) + 100000;
      }
}

function cardholder(game_state) {
    var ours = game_state.players[game_state.in_action].hole_cards;
    var common = game_state.community_cards;
    var cards = common;
    cards.push(ours[0].rank);
    cards.push(ours[1].rank);
    return cards;
}

function findPair(game_state) {
    var cards = cardholder(game_state);
    cards.sort();
    for (var i in cards) {
        if (i = cards.length) return false;
        if (cards[i] === cards[i+1]) {
            return true;
        }
    }
}

module.exports = {
    checkCard: checkCard,
    calBet: calculateBet,
}
<commit_msg>tt<commit_after>function minbet(gs) {
  return gs.current_buy_in - gs.players[gs.in_action]['bet'] + gs.minimum_raise;
}

var l = console.log;

function checkCard(card) {
        switch (card) {
            case "J" :
                card = 11;
                break;
            case "Q" :
                card = 12;
                break;
            case "K" :
                card = 13;
                break;
            case "A" :
                card = 14;
                break;
            default:
                card = card;
        }
        return card;
    }

function calculateBet(gs) {
    var ours = gs.players[gs.in_action].hole_cards;
    var card1 = checkCard(ours[0]);
    var card2 = checkCard(ours[1]);

    l(card1);
    l(card2);

      if (findPair(game_state)) {
        l("pair");
        return minbet(gs) + 100000;
      } else if (card1 < 2 && card2 < 2) {
        return 10;
      } else if (card1 < 6 && card2 < 6) {
        l("low cards");
        return minbet(gs);
      } else if (card1 < 10 && card2 < 10) {
        l("middle cards");
        return minbet(gs) + 200;
      } else {
        l("high cards");
        return minbet(gs) + 100000;
      }
}

function cardholder(game_state) {
    var ours = game_state.players[game_state.in_action].hole_cards;
    var common = game_state.community_cards;
    var cards = common;
    cards.push(ours[0].rank);
    cards.push(ours[1].rank);
    return cards;
}

function findPair(game_state) {
    var cards = cardholder(game_state);
    cards.sort();
    for (var i in cards) {
        if (i = cards.length) return false;
        if (cards[i] === cards[i+1]) {
            return true;
        }
    }
}

module.exports = {
    checkCard: checkCard,
    calBet: calculateBet,
}
<|endoftext|>


<commit_before>/*
 *	ab.js JavaScript A/B-testing tool v0.2
 *
 *	Copyright 2010, Anders Mattson
 *	Licensed under the MIT or GPL Version 2 licenses.
 *
 */

var AB = window.AB = {
	vary: function(d){
		var j = d.elem || d,
			e = typeof j == "string" ? document.getElementById(j) : j;

		if(!e || e.constructor == Array) {
			for(j in e) {
				if(!d.elem)
					d = {};
				d.elem = e[j];
				arguments[0] = d;
				AB.vary.apply(this, arguments);
			}
			return;
		}

		var o, p, c, h = document.location.href, A = arguments, P = (d.name || 'ab_js'),
			i = (c = document.cookie.match(new RegExp("(?:^|[^a-z0-9_\-]+)" + P + "=([0-9]+)", "i"))) ?
				c[1]*1 :
				(c = h.match(new RegExp("[\&\?]+"+P+"=([0-9]+)", "i"))) ?
				c[1]*1 :
				Math.floor(A.length*Math.random());

		o = i == 0 || i > A.length - 1 ? {} : A[i];

		document.cookie = P + '=' + i + '; path=/';

		if(o.html)
			e.innerHTML = o.html;

		if(o.style)
			for(j in o.style)
				e.style[j] = o.style[j];

		// Last we replace all the links found in the changed document.
		A = e.nodeName == 'A' ? [e] : e.getElementsByTagName('A');

		for(var j in A) {
			h = A[j].href;
			if(h) {
				if(o.href)
					h = o.href[0] == '+' ? h + o.href.substring(1) : o.href;
				else {
					if(h.indexOf('#') > -1) {
						p = h.split("#");
						h = p[0] + ((h.indexOf('?') > -1) ? '&' : '?') + P + '=' + i + '#' + p[1];
					}
					else
						h = h + ((h.indexOf('?') > -1) ? '&' : '?') + P + '=' + i;
				}
				A[j].href = h;
			}
		}
	}
};<commit_msg>Added support for current url validation and variation callbacks.<commit_after>/*
 *	ab.js JavaScript A/B-testing tool v0.3
 *
 *	Copyright 2010, Anders Mattson
 *	Licensed under the MIT or GPL Version 2 licenses.
 *
 *  AB.vary( Settings (Object), Variation #1 (Object) [, Variation #2 (Object) [, ...]] )
 *
 *  AB.vary({
 *  		name: 'unique_query_parameter_name',
 *  		elem: 'id_string_or_DOM_Node',
 *  		url: 'http://validation.url.for/variation'
 *  	},{
 *  		html: 'html_content',
 *  		style: {
 *  			'css-attribute': 'css-attribute-value',
 *  			...
 *  		},
 *  		fn: function(){...},
 *  		href: 'http://variation.url' (starting with a plus appends the string to the urls)
 *  	},{
 *  		...
 *  });
 */

var AB = window.AB = {

	vary: function(d){

		var j = d.elem || d,
			e = typeof j == "string" ? document.getElementById(j) : j;

		// Applying the variation to multiple DOM elements
		if(!e || e.constructor == Array) {

			for(j in e) {
				if(!d.elem)
					d = {};
				d.elem = e[j];
				arguments[0] = d;
				AB.vary.apply(this, arguments);
			}

			return;

		}

		// Check if the variation is for a specific url and if so, check that it matches the current one.
		if(d.url && !AB.compareUrls(d.url, document.location.href))
			return;

		var o, p, c, h = document.location.href, A = arguments, P = (d.name || 'ab_js'),
			i = (c = document.cookie.match(new RegExp("(?:^|[^a-z0-9_\-]+)" + P + "=([0-9]+)", "i"))) ?
				c[1]*1 :
				(c = h.match(new RegExp("[\&\?]+"+P+"=([0-9]+)", "i"))) ?
				c[1]*1 :
				Math.floor(A.length*Math.random());

		o = i == 0 || i > A.length - 1 ? {} : A[i];

		document.cookie = P + '=' + i + '; path=/';

		if(o.html)
			e.innerHTML = o.html;

		if(o.style)
			for(j in o.style)
				e.style[j] = o.style[j];

		// Last we replace all the links found in the changed document fragment.
		A = e.nodeName == 'A' ? [e] : e.getElementsByTagName('A');

		for(var j in A) {
			h = A[j].getAttribute('href');
			if(h) {
				if(o.href)
					h = o.href[0] == '+' ? h + o.href.substring(1) : o.href;
				else {
					if(h.indexOf('#') > -1) {
						p = h.split("#");
						h = p[0] + ((h.indexOf('?') > -1) ? '&' : '?') + P + '=' + i + '#' + p[1];
					}
					else
						h += ((h.indexOf('?') > -1) ? '&' : '?') + P + '=' + i;
				}
				A[j].setAttribute('href', h);
			}
		}

		if(o.fn)
			fn.apply(this, arguments);
	},

	// Checks if two urls points to the same source, regardless of the order between the parameters.
	// The hash tag is ignored.
	compareUrls: function(a, b) {
		var as, bs;
		return a == b || ((as = a.split('#')[0].split('?')).length > 1 ? as[0] + '?' + as[1].split('&').sort().join('&') : as[0]) ==
			   ((bs = b.split('#')[0].split('?')).length > 1 ? bs[0] + '?' + bs[1].split('&').sort().join('&') : bs[0]);
	}
};<|endoftext|>


<commit_before>const ctx = require('axel')
const keypress = require('keypress')

const Player = require('./player')
const Pip = require('./pip')
const { getGameWidth } = require('./utils')

let gameLoop

const p1 = new Player(10, 20, 'down', [0, 255, 0])
const p2 = new Player(getGameWidth() - 10, 20, 'down', [0, 0, 255])
const pip = new Pip()
while (
	(pip.x === p1.x && pip.y === p1.y) ||
	(pip.x === p2.x && pip.y === p2.y)
) {
	pip.moveToRandLocation()
}

function isCollision(a, b) {
	return a.x === b.x && a.y === b.y
}

function checkCollisions() {
	if (isCollision(p1, pip)) {
		p1.setGrow()
	}
	if (isCollision(p2, pip)) {
		p2.setGrow()
	}
}

function move() {
	p1.move()
	p2.move()
}

function draw() {
	// Clear the terminal
	ctx.clear()
	p1.draw()
	p2.draw()
	pip.draw()
	ctx.cursor.restore()
}

function endGame() {
	if (gameLoop) {
		process.stdin.pause()
		clearInterval(gameLoop)
		ctx.cursor.on()
		ctx.cursor.restore()
	}
}

module.exports.start = function() {
	ctx.cursor.off()
	ctx.clear()
	gameLoop = setInterval(() => {
		draw()
		move()
		checkCollisions()
	}, 1000 / 10)
	process.stdin.setRawMode(true)
	keypress(process.stdin)
	process.stdin.resume()
}

module.exports.registerControls = function() {
	process.stdin.on('keypress', function(ch, key) {
		switch (key.name) {
			case 'escape':
			case 'q':
				endGame()
				break
			case 'w':
				if (p1.dir !== 'down') {
					p1.setDir('up')
				}
				break
			case 's':
				if (p1.dir !== 'up') {
					p1.setDir('down')
				}
				break
			case 'a':
				if (p1.dir !== 'right') {
					p1.setDir('left')
				}
				break
			case 'd':
				if (p1.dir !== 'left') {
					p1.setDir('right')
				}
				break
			case 'up':
				if (p2.dir !== 'down') {
					p2.setDir(key.name)
				}
				break
			case 'down':
				if (p2.dir !== 'up') {
					p2.setDir(key.name)
				}
				break
			case 'left':
				if (p2.dir !== 'right') {
					p2.setDir(key.name)
				}
				break
			case 'right':
				if (p2.dir !== 'left') {
					p2.setDir(key.name)
				}
				break
		}
		if (key && key.ctrl && key.name == 'c') {
			endGame()
		}
	})
}
<commit_msg>move pip<commit_after>const ctx = require('axel')
const keypress = require('keypress')

const Player = require('./player')
const Pip = require('./pip')
const { getGameWidth } = require('./utils')

let gameLoop

const p1 = new Player(10, 20, 'down', [0, 255, 0])
const p2 = new Player(getGameWidth() - 10, 20, 'down', [0, 0, 255])
const pip = new Pip()

function movePip() {
	while (
		(pip.x === p1.x && pip.y === p1.y) ||
		(pip.x === p2.x && pip.y === p2.y)
	) {
		pip.moveToRandLocation()
	}
}

function isCollision(a, b) {
	return a.x === b.x && a.y === b.y
}

function checkCollisions() {
	if (isCollision(p1, pip)) {
		p1.setGrow()
		movePip()
	}
	if (isCollision(p2, pip)) {
		p2.setGrow()
		movePip()
	}
}

function move() {
	p1.move()
	p2.move()
}

function draw() {
	// Clear the terminal
	ctx.clear()
	p1.draw()
	p2.draw()
	pip.draw()
	ctx.cursor.restore()
}

function endGame() {
	if (gameLoop) {
		process.stdin.pause()
		clearInterval(gameLoop)
		ctx.cursor.on()
		ctx.cursor.restore()
	}
}

module.exports.start = function() {
	ctx.cursor.off()
	ctx.clear()
	movePip()
	gameLoop = setInterval(() => {
		draw()
		move()
		checkCollisions()
	}, 1000 / 10)
	process.stdin.setRawMode(true)
	keypress(process.stdin)
	process.stdin.resume()
}

module.exports.registerControls = function() {
	process.stdin.on('keypress', function(ch, key) {
		switch (key.name) {
			case 'escape':
			case 'q':
				endGame()
				break
			case 'w':
				if (p1.dir !== 'down') {
					p1.setDir('up')
				}
				break
			case 's':
				if (p1.dir !== 'up') {
					p1.setDir('down')
				}
				break
			case 'a':
				if (p1.dir !== 'right') {
					p1.setDir('left')
				}
				break
			case 'd':
				if (p1.dir !== 'left') {
					p1.setDir('right')
				}
				break
			case 'up':
				if (p2.dir !== 'down') {
					p2.setDir(key.name)
				}
				break
			case 'down':
				if (p2.dir !== 'up') {
					p2.setDir(key.name)
				}
				break
			case 'left':
				if (p2.dir !== 'right') {
					p2.setDir(key.name)
				}
				break
			case 'right':
				if (p2.dir !== 'left') {
					p2.setDir(key.name)
				}
				break
		}
		if (key && key.ctrl && key.name == 'c') {
			endGame()
		}
	})
}
<|endoftext|>


<commit_before>var Express = require("express");
var sync = require("../sync");
var Database = require("../database");
var debug = require("debug")("clients:dropbox:routes");
var async = require("async");
var config = require("config");
var crypto = require("crypto");
var Webhook = Express.Router();

// Used for testing purposes only to determine when a sync has finished
// Redlock means we can't reliably determine this just by calling
// Blot.sync();
Webhook.get("/syncs-finished/:blogID", function(req, res) {
  res.send(finishedAllSyncs(req.params.blogID));
});

// This is called by Dropbox to verify
// the webhook is valid.
Webhook.route("/").get(function(req, res, next) {
  if (req.query && req.query.challenge) return res.send(req.query.challenge);

  return next();
});

// We keep a dictionary of synced blogs for testing
// purposes. There isn't an easy way to determine
// after pushing whether or not Blot has completed the
// sync of the blog's folder. This is because I can't
// work out how to do something asynchronous after we've
// accepted a push but before we've sent the response.
var activeSyncs = {};

function started(blogID) {
  if (activeSyncs[blogID] === undefined) activeSyncs[blogID] = 0;
  activeSyncs[blogID]++;
}

function finished(blogID) {
  activeSyncs[blogID]--;
}

function finishedAllSyncs(blogID) {
  return activeSyncs[blogID] === 0;
}

Webhook.route('/').post(function(req, res) {

  if (config.maintenance) return res.sendStatus(503);

  var data = "";
  var accounts = [];
  var signature = req.headers["x-dropbox-signature"];
  var secret;

  if (!!req.query.full_access) {
    secret = config.dropbox.full.secret;
  } else {
    secret = config.dropbox.app.secret;
  }

  var verification = crypto.createHmac("SHA256", secret);

  req.setEncoding("utf8");

  req.on("data", function(chunk) {
    data += chunk;
    verification.update(chunk);
  });

  req.on("end", function() {
    if (signature !== verification.digest("hex")) return res.sendStatus(403);

    try {
      accounts = JSON.parse(data).list_folder.accounts;
    } catch (e) {
      return res.sendStatus(504);
    }

    // Tell Dropbox we retrieved the list of accounts
    res.sendStatus(200);

    // Sync each of the accounts!
    // accounts can be synced in parallel
    async.each(
      accounts,
      function(account_id, next_account) {
        debug("Checking blogs for Dropbox account", account_id);

        Database.listBlogs(account_id, function(err, blogs) {
          if (err) return next_account(err);

          debug("Syncing", blogs.length, "blogs");

          blogs.forEach(function(blog) {
            // Used for testing purposes only
            started(blog.id);
          });

          // blogs can be synced in parallel
          async.each(
            blogs,
            function(blog, next) {
              sync(blog, function(err) {
                if (err) console.log("Blog", blog.id, "Sync error:", err);
                next();
              });
            },
            function() {
              blogs.forEach(function(blog) {
                debug("Finish sync for", blog.id);
                finished(blog.id);
              });
            }
          );
        });

        next_account();

        // Do nothing when all the accounts have synced.
      },
      function() {}
    );
  });
});

module.exports = Webhook;
<commit_msg>Tidied webhook route<commit_after>var Express = require("express");
var sync = require("../sync");
var Database = require("../database");
var debug = require("debug")("clients:dropbox:routes");
var async = require("async");
var config = require("config");
var crypto = require("crypto");
var Webhook = Express.Router();

// Used for testing purposes only to determine when a sync has finished
// Redlock means we can't reliably determine this just by calling sync()
Webhook.get("/syncs-finished/:blogID", function(req, res) {
  res.send(finishedAllSyncs(req.params.blogID));
});

// This is called by Dropbox to verify the webhook exists
Webhook.get("/", function(req, res, next) {
  if (!req.query || !req.query.challenge) return next();
  res.send(req.query.challenge);
});

// We keep a dictionary of synced blogs for testing
// purposes. There isn't an easy way to determine
// after pushing whether or not Blot has completed the
// sync of the blog's folder. This is because I can't
// work out how to do something asynchronous after we've
// accepted a push but before we've sent the response.
var activeSyncs = {};

function started(blogID) {
  if (activeSyncs[blogID] === undefined) activeSyncs[blogID] = 0;
  activeSyncs[blogID]++;
}

function finished(blogID) {
  activeSyncs[blogID]--;
}

function finishedAllSyncs(blogID) {
  return activeSyncs[blogID] === 0;
}

Webhook.route("/").post(function(req, res) {
  if (config.maintenance) return res.sendStatus(503);

  var data = "";
  var accounts = [];
  var signature = req.headers["x-dropbox-signature"];
  var secret;

  if (!!req.query.full_access) {
    secret = config.dropbox.full.secret;
  } else {
    secret = config.dropbox.app.secret;
  }

  var verification = crypto.createHmac("SHA256", secret);

  req.setEncoding("utf8");

  req.on("data", function(chunk) {
    data += chunk;
    verification.update(chunk);
  });

  req.on("end", function() {
    if (signature !== verification.digest("hex")) return res.sendStatus(403);

    try {
      accounts = JSON.parse(data).list_folder.accounts;
    } catch (e) {
      return res.sendStatus(504);
    }

    // Tell Dropbox we retrieved the list of accounts
    res.sendStatus(200);

    // Sync each of the accounts!
    // accounts can be synced in parallel
    async.each(
      accounts,
      function(account_id, next_account) {
        debug("Checking blogs for Dropbox account", account_id);

        Database.listBlogs(account_id, function(err, blogs) {
          if (err) return next_account(err);

          debug("Syncing", blogs.length, "blogs");

          blogs.forEach(function(blog) {
            // Used for testing purposes only
            started(blog.id);
          });

          // blogs can be synced in parallel
          async.each(
            blogs,
            function(blog, next) {
              sync(blog, function(err) {
                if (err) console.log("Blog", blog.id, "Sync error:", err);
                next();
              });
            },
            function() {
              blogs.forEach(function(blog) {
                debug("Finish sync for", blog.id);
                finished(blog.id);
              });
            }
          );
        });

        next_account();

        // Do nothing when all the accounts have synced.
      },
      function() {}
    );
  });
});

module.exports = Webhook;
<|endoftext|>


<commit_before>(function() {

  // Set up State enum
  var states = [ "Uninitialized",
                 "PlayerSetup",
                 "ShowScenarioChoices",
                 "PreTurn",
                 "MidTurn",
                 "PostTurn",
                 "OpinionPhase",
                 "VotingPhase",
                 "FinalChoice",
                 "GameEnd"
               ];

  var State = {};
  for (var i = 0; i < states.length; i++) {
    var stateName = states[ i ];
    State[ stateName ] = stateName;
  }

  var Game = Backbone.Model.extend({
    type: "Game",

    defaults: {
      "players": [],
      "numberOfTurns": 0,
      "currentTurn": -1,
      "scenario": undefined,
      "cardsOnBoard": [],
      "state": State.Uninitialized
    },

    // Accessors
    currentPlayer: function() {
      var turn = this.get( "currentTurn" );
      var players = this.get( "players" );
      var currentPlayerIndex = turn % players.length;
      return players[ currentPlayerIndex ];
    },

    beginPlayerSetup: function() {
      this.set( "state", Game.State.PlayerSetup );
    },

    finishPlayerSetup: function( numberOfPlayers ) {
      var numberOfTurns = numberOfPlayers * 3; // Decide how we determine this

      var scenario = new Scenario();
      var cardGroups = scenario.generateCardGroups(numberOfPlayers);

      var players = [];
      for (var i = 0; i < numberOfPlayers; i++) {
        var player = new Player({
          identifier: i
        });
        player.addCardsToHand(cardGroups[i]);
        players.push(player);
      }

      this.set({
        numberOfTurns: numberOfTurns,
        players: players,
        scenario: scenario
      });

      // TODO: Set up the scenario and distribute cards to players

      this.set( "state", Game.State.ShowScenarioChoices );
    },

    beginNextTurn: function() {
      var turn = this.get( "currentTurn" ) + 1;
      this.set( "currentTurn", turn );

      if ( turn < this.get( "numberOfTurns" )) {
        this.beginPreTurn();
      } else {
        this.beginOpinionPhase();
      }
    },

    beginPreTurn: function() {
      var currentPlayer = this.currentPlayer();
      console.log( "*** Starting turn:", this.get( "currentTurn" ));
      console.log( "Player", currentPlayer.get( "name" ), "take the screen! Everyone else look away!" );

      this.set( "state", Game.State.PreTurn );
    },

    beginMidTurn: function() {
      // Not sure that we need anything else here
      this.set( "state", Game.State.MidTurn );
    },

    beginPostTurn: function( sharedCard, cardsOnBoard ) {
      var player = this.currentPlayer();
      player.playCardFromHand( sharedCard );
      this.set( "cardsOnBoard", cardsOnBoard );
      this.set( "state", Game.State.PostTurn );
    },

    beginOpinionPhase: function() {
      this.set( "state", Game.State.OpinionPhase );
    },

    beginVotingPhase: function() {
      this.set( "state", Game.State.VotingPhase );
    },

    beginFinalChoice: function() {
      this.set( "state", Game.State.FinalChoice );
    },

    lockInDecision: function( choice ) {
      this.set( "state", Game.State.GameEnd );
    }
  });

  Game.State = State;
  window.Game = Game;
}());
<commit_msg>Remove extraneous console.logs in game.js<commit_after>(function() {

  // Set up State enum
  var states = [ "Uninitialized",
                 "PlayerSetup",
                 "ShowScenarioChoices",
                 "PreTurn",
                 "MidTurn",
                 "PostTurn",
                 "OpinionPhase",
                 "VotingPhase",
                 "FinalChoice",
                 "GameEnd"
               ];

  var State = {};
  for (var i = 0; i < states.length; i++) {
    var stateName = states[ i ];
    State[ stateName ] = stateName;
  }

  var Game = Backbone.Model.extend({
    type: "Game",

    defaults: {
      "players": [],
      "numberOfTurns": 0,
      "currentTurn": -1,
      "scenario": undefined,
      "cardsOnBoard": [],
      "state": State.Uninitialized
    },

    // Accessors
    currentPlayer: function() {
      var turn = this.get( "currentTurn" );
      var players = this.get( "players" );
      var currentPlayerIndex = turn % players.length;
      return players[ currentPlayerIndex ];
    },

    beginPlayerSetup: function() {
      this.set( "state", Game.State.PlayerSetup );
    },

    finishPlayerSetup: function( numberOfPlayers ) {
      var numberOfTurns = numberOfPlayers * 3; // Decide how we determine this

      var scenario = new Scenario();
      var cardGroups = scenario.generateCardGroups(numberOfPlayers);

      var players = [];
      for (var i = 0; i < numberOfPlayers; i++) {
        var player = new Player({
          identifier: i
        });
        player.addCardsToHand(cardGroups[i]);
        players.push(player);
      }

      this.set({
        numberOfTurns: numberOfTurns,
        players: players,
        scenario: scenario
      });

      // TODO: Set up the scenario and distribute cards to players

      this.set( "state", Game.State.ShowScenarioChoices );
    },

    beginNextTurn: function() {
      var turn = this.get( "currentTurn" ) + 1;
      this.set( "currentTurn", turn );

      if ( turn < this.get( "numberOfTurns" )) {
        this.beginPreTurn();
      } else {
        this.beginOpinionPhase();
      }
    },

    beginPreTurn: function() {
      this.set( "state", Game.State.PreTurn );
    },

    beginMidTurn: function() {
      // Not sure that we need anything else here
      this.set( "state", Game.State.MidTurn );
    },

    beginPostTurn: function( sharedCard, cardsOnBoard ) {
      var player = this.currentPlayer();
      player.playCardFromHand( sharedCard );
      this.set( "cardsOnBoard", cardsOnBoard );
      this.set( "state", Game.State.PostTurn );
    },

    beginOpinionPhase: function() {
      this.set( "state", Game.State.OpinionPhase );
    },

    beginVotingPhase: function() {
      this.set( "state", Game.State.VotingPhase );
    },

    beginFinalChoice: function() {
      this.set( "state", Game.State.FinalChoice );
    },

    lockInDecision: function( choice ) {
      this.set( "state", Game.State.GameEnd );
    }
  });

  Game.State = State;
  window.Game = Game;
}());
<|endoftext|>


<commit_before>/* Copyright 2015 Dietrich Epp.

   This file is part of Dash and the Jetpack Space Pirates.  The Dash
   and the Jetpack Space Pirates source code is distributed under the
   terms of the MIT license.  See LICENSE.txt for details. */
'use strict';

var glm = require('gl-matrix');
var vec2 = glm.vec2;

var background = require('./background');
var camera = require('./camera');
var control = require('./control');
var param = require('./param');
var physics = require('./physics');
var player = require('./player');
var sprites = require('./sprites');
var state = require('./state');
var time = require('./time');

/*
 * Main game screen.
 */
function Game() {
	var g = param.Game;

	// Timing manager
	this.time = null;

	// Sprite layer
	this.sprites = new sprites.Sprites();

	// Physics engine
	this.world = physics.createWorld();

	// Occupants
	this.player = new player.Player();
	this.world.addBody(this.player.body);

	var shape;
	this.plane0 = new p2.Body({
		mass: 0,
		position: [0, -16],
	});
	shape = new p2.Plane();
	shape.material = physics.Material.World;
	this.plane0.addShape(shape);
	this.world.addBody(this.plane0);
	this.plane1 = new p2.Body({
		mass: 0,
		position: [0, 16],
		angle: Math.PI,
	});
	shape = new p2.Plane();
	shape.material = physics.Material.World;
	this.plane1.addShape(shape);
	this.world.addBody(this.plane1);

	physics.settle(this.world, 1 / param.Rate, 3.0);

	// Camera
	this.camera = new camera.Camera({
		target: this.player.body,
		targetY: 0,
		leading: g.Leading / g.Speed,
	});

	this._bg = new background.Background(this.camera);
	this._bg.setGrid();
}

/*
 * Initialize the screen.
 */
Game.prototype.init = function(r) {
	this._bg.init(r);
	this.time = new time.Time(this, r.time);
	control.game.enable();
};

/*
 * Destroy the screen
 */
Game.prototype.destroy = function(r) {
	this._bg.destroy(r);
	control.game.disable();
};

/*
 * Render the game screen, updating the game state as necessary.
 */
Game.prototype.render = function(r) {
	var gl = r.gl;
	this.time.update(r.time);
	var frac = this.time.frac;
	this.camera.update(r, frac);
	this._bg.render(r);
	this.sprites.clear();
	this.player.emit(this, frac);
	this.sprites.draw(gl, this.camera.MVP);
};

/*
 * Advance the game by one frame.  Called by the timing manager.
 *
 * dt: The timestep, in s
 */
Game.prototype.step = function(dt) {
	control.game.update();
	this.player.step(this);
	this.world.step(dt);
	this.camera.step();
};

/*
 * Update the uniforms for the background.
 */
Game.prototype._bgUniforms = function(r, p) {
};

// We export through the state module.
state.Game = Game;
<commit_msg>cleaunp: naming conventions<commit_after>/* Copyright 2015 Dietrich Epp.

   This file is part of Dash and the Jetpack Space Pirates.  The Dash
   and the Jetpack Space Pirates source code is distributed under the
   terms of the MIT license.  See LICENSE.txt for details. */
'use strict';

var glm = require('gl-matrix');
var vec2 = glm.vec2;

var background = require('./background');
var camera = require('./camera');
var control = require('./control');
var param = require('./param');
var physics = require('./physics');
var player = require('./player');
var sprites = require('./sprites');
var state = require('./state');
var time = require('./time');

/*
 * Main game screen.
 */
function Game() {
	var g = param.Game;

	// Timing manager
	this.time = null;

	// Sprite layer
	this.sprites = new sprites.Sprites();

	// Physics engine
	this.world = physics.createWorld();

	// Occupants
	this.player = new player.Player();
	this.world.addBody(this.player.body);

	var shape;
	this.plane0 = new p2.Body({
		mass: 0,
		position: [0, -16],
	});
	shape = new p2.Plane();
	shape.material = physics.Material.World;
	this.plane0.addShape(shape);
	this.world.addBody(this.plane0);
	this.plane1 = new p2.Body({
		mass: 0,
		position: [0, 16],
		angle: Math.PI,
	});
	shape = new p2.Plane();
	shape.material = physics.Material.World;
	this.plane1.addShape(shape);
	this.world.addBody(this.plane1);

	physics.settle(this.world, 1 / param.Rate, 3.0);

	// Camera
	this.camera = new camera.Camera({
		target: this.player.body,
		targetY: 0,
		leading: g.Leading / g.Speed,
	});

	this.background = new background.Background(this.camera);
	this.background.setGrid();
}

/*
 * Initialize the screen.
 */
Game.prototype.init = function(r) {
	this.background.init(r);
	this.time = new time.Time(this, r.time);
	control.game.enable();
};

/*
 * Destroy the screen
 */
Game.prototype.destroy = function(r) {
	this.background.destroy(r);
	control.game.disable();
};

/*
 * Render the game screen, updating the game state as necessary.
 */
Game.prototype.render = function(r) {
	var gl = r.gl;
	this.time.update(r.time);
	var frac = this.time.frac;
	this.camera.update(r, frac);
	this.background.render(r);
	this.sprites.clear();
	this.player.emit(this, frac);
	this.sprites.draw(gl, this.camera.MVP);
};

/*
 * Advance the game by one frame.  Called by the timing manager.
 *
 * dt: The timestep, in s
 */
Game.prototype.step = function(dt) {
	control.game.update();
	this.player.step(this);
	this.world.step(dt);
	this.camera.step();
};

// We export through the state module.
state.Game = Game;
<|endoftext|>