<commit_before>function Groundstation() {
  this.channels = new Channels();
  this.channels.url = '/channels';

  this.active_grefs = new Grefs();

  this.username = localStorage.getItem("airship.committer") || "Anonymous Coward";

  this.renderers = {};
  this.validators = {};
}
function init_airship(groundstation) {
  _.each(groundstation.channels.models, function(channel) {
    new ChannelTab({
      model: channel,
      id: channel.attributes["name"]
    });
  });
  rendered_gref_content = new RenderedGref({
    model: rendered_gref
  });
  // Wire up user switching
  // TODO Currently not stored because I haven't decided where it should live. PRobably git-config(5)

  $("#current-user-name").html(groundstation.username);
  $("#current-user-name").on('click', function() {
    var username = prompt("Username for committing:");
    if (username !== null) {
      groundstation.username = username;
      $("#current-user-name").html(groundstation.username);
      try {
        localStorage.setItem("airship.committer", username);
      } catch (e) {
        console.log("Not setting committer name in localStorage");
      }
    }
  });
  var new_gref = {
    title: $("#new-gref-title").text(),
    body: $("#new-gref-body")[0].value,
    name: $("#new-gref-name").text()
  };
  var new_gref_validator = groundstation.validators.gref(new_gref.name, new_gref.title, new_gref.body);

  $("#new-gref").on('click', function() {
    $("#new-gref-title").text(new_gref.title);
    $("#new-gref-body")[0].value = new_gref.body;
    $("#new-gref-name").text(new_gref.name);
    var modal = $("#new-gref-modal");
    modal.modal();
  });
  $("#new-gref-cancel").on('click', function() {
    $("#new-gref-modal").modal('hide');
  });
  $("#new-gref-create").on('click', function() {
    var title = $("#new-gref-title").text(),
        body = $("#new-gref-body")[0].value,
        name = $("#new-gref-name").text(),
        protocol = $("#new-gref-protocol").text();

    if (new_gref_validator(name, title, body)) {
      $.ajax({
        type: "PUT",
        url: groundstation.active_grefs.url,
        data: {
          title: title,
          body: body,
          name: name,
          protocol: protocol,

          user: groundstation.username

        },
        success: function(data, st, xhr) {
          $("#new-gref-modal").modal('hide');
          groundstation.active_grefs.redraw();
        }
      });
    } else {
      // TODO Actually give the user something to go with
      alert("Validation failed!");
    }
  });
}

var Channel = Backbone.Model.extend();
var Channels = Backbone.Collection.extend({
  model: Channel
});

var Gref = Backbone.Model.extend();
var Grefs = Backbone.Collection.extend({
  model: Gref
});

var GrefMenuItem = Backbone.View.extend({
  tagName: "li",
  className: "gref",

  template: '{{identifier}}',

  getUrl: function() {
    return "/gref/" + this.model.attributes["channel"] + "/" + this.model.attributes["identifier"];
  },

  render: function() {
    this.$el.html(this.template.replace("{{identifier}}", this.model.attributes["identifier"]));
    return this;
  },

  select: function() {
    var active_el = this.el;
    $(this.el.parentElement.children).removeClass("active");
    rendered_gref.url = this.getUrl();
    rendered_gref.fetch({
      success: function(model, response, options) {
        $(active_el).addClass("active");
        rendered_gref_content.render();
      }
    });
  },

  events: {
    "click .select":  "select"
  },

  install: function() {
    $('#current-grefs')[0].appendChild(this.el);
  },

  initialize: function() {
    this.listenTo(this.model, "change", this.render);
    this.render();
    this.install();
  }
});

var visible_grefs = [];
var ChannelTab = Backbone.View.extend({

  tagName: "li",

  className: "",

  template: '{{name}}',

  render: function() {
    this.$el.html(this.template.replace("{{name}}", this.model.attributes["name"]));
    return this;
  },

  select: function() {
    var self = this;
    var current_grefs = $("#current-grefs")[0];
    groundstation.active_grefs.url = '/grefs/' + this.model.attributes["name"];
    groundstation.active_grefs.redraw = function() {
      groundstation.active_grefs.fetch({
        success: function(collection, response, options) {
          $("#active-channel").html(self.model.attributes["name"]);
          $("#gref-container").show();
          _.each(visible_grefs, function(el) { el.remove(); });
          _.each(collection.models, function(gref) {
            visible_grefs.push(new GrefMenuItem({
              model: gref
            }));
          });
        }
      });
    };
    groundstation.active_grefs.redraw();
  },

  events: {
    "click .select":          "select"
  },

  install: function() {
    $('#channels-content')[0].appendChild(this.el);
  },

  initialize: function() {
    this.listenTo(this.model, "change", this.render);
    this.render();
    this.install();
  }

});

function buildCommentBox(div, model) {
  var row, input, span, submit;

  row = document.createElement("div");
  row.className = "input-group";

  input = document.createElement("textarea");
  input.setAttribute('rows', 7);
  input.contentEditable = true;
  input.id = "new-comment-body";

  span = document.createElement("span");
  span.className = "input-group-btn";

  submit = document.createElement("button");
  submit.className = "btn";
  submit.id = "new-comment-submit";
  $(submit).text("Submit");
  span.appendChild(submit);

  row.appendChild(input);
  row.appendChild(span);

  $(submit).on('click', function(ev) {
    $.ajax({
        type: "POST",
        url: model.url,
        data: {
            body: input.value,
            parents: JSON.stringify(model.attributes["tips"]),
            user: groundstation.username

        },
        success: function(data, st, xhr) {
            rendered_gref.fetch();
            console.log("Successfully updated groundstation");
        }
    });
    console.log("Sending new comment to groundstation");
  });

  div.appendChild(row);
}

var RenderedGref = Backbone.View.extend({

  tagName: "div",
  className: "",

  render: function() {
    var self = this;
    var content = this.model.attributes["content"];
    var root = this.model.attributes["root"];
    var renderer = null;

    $(this.$el).children().remove();
    $("#gref-graph").children().remove();

    renderer = (function() {
      for (var renderer in groundstation.renderers) {
        if (groundstation.renderers.hasOwnProperty(renderer)) {
          if (root.protocol.search(renderer) === 0)
            return groundstation.renderers[renderer];
        }
      }
    })();
    if (renderer === null) {
      console.log("Unhandled protocol: " + root.protocol);
      return this;
    }

    // Stick the root object in the DOM to make parent linking sane.
    (function() {
      var el = document.createElement("div");
      el.setAttribute("id", root.hash);
      self.el.appendChild(el);
    })();

    _.each(content, function(item) {
      var el = renderer(item);
      if (el) {
        el.setAttribute("id", item.hash);
        var signature = self.model.attributes.signatures[item.hash];
        if (signature !== undefined) {
          if (signature === false) {
            el.setAttribute("data-invalid-signature", "true");
          } else {
            el.setAttribute("data-signature", signature);
          }
        }
        self.el.appendChild(el);
      }
    });
    buildCommentBox(self.el, self.model);

    var graph = $("#gref-graph");
    var width  = graph.width(),
        height = 500;

    var force = d3.layout.force()
      .charge(-120)
      .size([width, height])
      .linkDistance(30);

    var svg = d3.select("#gref-graph").append("svg")
      .attr("width", width)
      .attr("height", height);;

    var data = this.model.attributes;
    var nodes = data.content;
    data.root.parents = [];
    data.root.fixed = true;
    data.root.x = width / 2;
    data.root.y = 10;
    nodes.push(data.root);

    var hash_to_node = {};
    nodes.forEach(function(node) {
      hash_to_node[node.hash] = node;
    });

    var links = [];
    nodes.forEach(function(node) {
      node.parents.forEach(function(parent) {
        links.push({source: node, target: hash_to_node[parent]});
      });
    });

    var tip_node, tip_length = data.tips.length;
    for(var i = 0; i < tip_length; i++) {
      tip_node = hash_to_node[data.tips[i]];
      tip_node.y = height - 10;
      tip_node.x = (width / (tip_length + 1)) * (i + 1);
      tip_node.fixed = true;
    };

    force.nodes(nodes)
      .links(links)
      .start();

    var link = svg.selectAll(".link")
      .data(links)
      .enter().append("line")
      .attr("class", "link");

    function hilight(id) {
      hash_to_node[id].parents.forEach(function(par) {
        hilight(par);
      });
      $(document.getElementById(id)).addClass("selected");
    }

    var node = svg.selectAll(".node")
      .data(nodes)
      .enter().append("circle")
      .attr("class", "node")
      .attr("r", 5)
      .call(force.drag)
      .on('click', function(node) {
        $(".gref-taggable").removeClass("selected");
        hilight(node.hash);
      });

    force.on("tick", function() {
      link.attr("x1", function(d) { return d.source.x; })
      .attr("y1", function(d) { return d.source.y; })
      .attr("x2", function(d) { return d.target.x; })
      .attr("y2", function(d) { return d.target.y; });

      node.attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; });

    });

    return this;
  },

  install: function() {
    $("#gref-content")[0].appendChild(this.el);
  },

  initialize: function() {
    this.listenTo(this.model, "change", this.render);
    this.install();
  }
});
var rendered_gref = new Gref();
var rendered_gref_content;
<commit_msg>Show the hilighted node in the graph<commit_after>function Groundstation() {
  this.channels = new Channels();
  this.channels.url = '/channels';

  this.active_grefs = new Grefs();

  this.username = localStorage.getItem("airship.committer") || "Anonymous Coward";

  this.renderers = {};
  this.validators = {};
}
function init_airship(groundstation) {
  _.each(groundstation.channels.models, function(channel) {
    new ChannelTab({
      model: channel,
      id: channel.attributes["name"]
    });
  });
  rendered_gref_content = new RenderedGref({
    model: rendered_gref
  });
  // Wire up user switching
  // TODO Currently not stored because I haven't decided where it should live. PRobably git-config(5)

  $("#current-user-name").html(groundstation.username);
  $("#current-user-name").on('click', function() {
    var username = prompt("Username for committing:");
    if (username !== null) {
      groundstation.username = username;
      $("#current-user-name").html(groundstation.username);
      try {
        localStorage.setItem("airship.committer", username);
      } catch (e) {
        console.log("Not setting committer name in localStorage");
      }
    }
  });
  var new_gref = {
    title: $("#new-gref-title").text(),
    body: $("#new-gref-body")[0].value,
    name: $("#new-gref-name").text()
  };
  var new_gref_validator = groundstation.validators.gref(new_gref.name, new_gref.title, new_gref.body);

  $("#new-gref").on('click', function() {
    $("#new-gref-title").text(new_gref.title);
    $("#new-gref-body")[0].value = new_gref.body;
    $("#new-gref-name").text(new_gref.name);
    var modal = $("#new-gref-modal");
    modal.modal();
  });
  $("#new-gref-cancel").on('click', function() {
    $("#new-gref-modal").modal('hide');
  });
  $("#new-gref-create").on('click', function() {
    var title = $("#new-gref-title").text(),
        body = $("#new-gref-body")[0].value,
        name = $("#new-gref-name").text(),
        protocol = $("#new-gref-protocol").text();

    if (new_gref_validator(name, title, body)) {
      $.ajax({
        type: "PUT",
        url: groundstation.active_grefs.url,
        data: {
          title: title,
          body: body,
          name: name,
          protocol: protocol,

          user: groundstation.username

        },
        success: function(data, st, xhr) {
          $("#new-gref-modal").modal('hide');
          groundstation.active_grefs.redraw();
        }
      });
    } else {
      // TODO Actually give the user something to go with
      alert("Validation failed!");
    }
  });
}

var Channel = Backbone.Model.extend();
var Channels = Backbone.Collection.extend({
  model: Channel
});

var Gref = Backbone.Model.extend();
var Grefs = Backbone.Collection.extend({
  model: Gref
});

var GrefMenuItem = Backbone.View.extend({
  tagName: "li",
  className: "gref",

  template: '{{identifier}}',

  getUrl: function() {
    return "/gref/" + this.model.attributes["channel"] + "/" + this.model.attributes["identifier"];
  },

  render: function() {
    this.$el.html(this.template.replace("{{identifier}}", this.model.attributes["identifier"]));
    return this;
  },

  select: function() {
    var active_el = this.el;
    $(this.el.parentElement.children).removeClass("active");
    rendered_gref.url = this.getUrl();
    rendered_gref.fetch({
      success: function(model, response, options) {
        $(active_el).addClass("active");
        rendered_gref_content.render();
      }
    });
  },

  events: {
    "click .select":  "select"
  },

  install: function() {
    $('#current-grefs')[0].appendChild(this.el);
  },

  initialize: function() {
    this.listenTo(this.model, "change", this.render);
    this.render();
    this.install();
  }
});

var visible_grefs = [];
var ChannelTab = Backbone.View.extend({

  tagName: "li",

  className: "",

  template: '{{name}}',

  render: function() {
    this.$el.html(this.template.replace("{{name}}", this.model.attributes["name"]));
    return this;
  },

  select: function() {
    var self = this;
    var current_grefs = $("#current-grefs")[0];
    groundstation.active_grefs.url = '/grefs/' + this.model.attributes["name"];
    groundstation.active_grefs.redraw = function() {
      groundstation.active_grefs.fetch({
        success: function(collection, response, options) {
          $("#active-channel").html(self.model.attributes["name"]);
          $("#gref-container").show();
          _.each(visible_grefs, function(el) { el.remove(); });
          _.each(collection.models, function(gref) {
            visible_grefs.push(new GrefMenuItem({
              model: gref
            }));
          });
        }
      });
    };
    groundstation.active_grefs.redraw();
  },

  events: {
    "click .select":          "select"
  },

  install: function() {
    $('#channels-content')[0].appendChild(this.el);
  },

  initialize: function() {
    this.listenTo(this.model, "change", this.render);
    this.render();
    this.install();
  }

});

function buildCommentBox(div, model) {
  var row, input, span, submit;

  row = document.createElement("div");
  row.className = "input-group";

  input = document.createElement("textarea");
  input.setAttribute('rows', 7);
  input.contentEditable = true;
  input.id = "new-comment-body";

  span = document.createElement("span");
  span.className = "input-group-btn";

  submit = document.createElement("button");
  submit.className = "btn";
  submit.id = "new-comment-submit";
  $(submit).text("Submit");
  span.appendChild(submit);

  row.appendChild(input);
  row.appendChild(span);

  $(submit).on('click', function(ev) {
    $.ajax({
        type: "POST",
        url: model.url,
        data: {
            body: input.value,
            parents: JSON.stringify(model.attributes["tips"]),
            user: groundstation.username

        },
        success: function(data, st, xhr) {
            rendered_gref.fetch();
            console.log("Successfully updated groundstation");
        }
    });
    console.log("Sending new comment to groundstation");
  });

  div.appendChild(row);
}

var RenderedGref = Backbone.View.extend({

  tagName: "div",
  className: "",

  render: function() {
    var self = this;
    var content = this.model.attributes["content"];
    var root = this.model.attributes["root"];
    var renderer = null;

    $(this.$el).children().remove();
    $("#gref-graph").children().remove();

    renderer = (function() {
      for (var renderer in groundstation.renderers) {
        if (groundstation.renderers.hasOwnProperty(renderer)) {
          if (root.protocol.search(renderer) === 0)
            return groundstation.renderers[renderer];
        }
      }
    })();
    if (renderer === null) {
      console.log("Unhandled protocol: " + root.protocol);
      return this;
    }

    // Stick the root object in the DOM to make parent linking sane.
    (function() {
      var el = document.createElement("div");
      el.setAttribute("id", root.hash);
      self.el.appendChild(el);
    })();

    _.each(content, function(item) {
      var el = renderer(item);
      if (el) {
        el.setAttribute("id", item.hash);
        var signature = self.model.attributes.signatures[item.hash];
        if (signature !== undefined) {
          if (signature === false) {
            el.setAttribute("data-invalid-signature", "true");
          } else {
            el.setAttribute("data-signature", signature);
          }
        }
        self.el.appendChild(el);
      }
    });
    buildCommentBox(self.el, self.model);

    var graph = $("#gref-graph");
    var width  = graph.width(),
        height = 500;

    var force = d3.layout.force()
      .charge(-120)
      .size([width, height])
      .linkDistance(30);

    var svg = d3.select("#gref-graph").append("svg")
      .attr("width", width)
      .attr("height", height);;

    var data = this.model.attributes;
    var nodes = data.content;
    data.root.parents = [];
    data.root.fixed = true;
    data.root.x = width / 2;
    data.root.y = 10;
    nodes.push(data.root);

    var hash_to_node = {};
    nodes.forEach(function(node) {
      hash_to_node[node.hash] = node;
    });

    var links = [];
    nodes.forEach(function(node) {
      node.parents.forEach(function(parent) {
        links.push({source: node, target: hash_to_node[parent]});
      });
    });

    var tip_node, tip_length = data.tips.length;
    for(var i = 0; i < tip_length; i++) {
      tip_node = hash_to_node[data.tips[i]];
      tip_node.y = height - 10;
      tip_node.x = (width / (tip_length + 1)) * (i + 1);
      tip_node.fixed = true;
    };

    force.nodes(nodes)
      .links(links)
      .start();

    var link = svg.selectAll(".link")
      .data(links)
      .enter().append("line")
      .attr("class", "link");

    function hilight(id) {
      hash_to_node[id].parents.forEach(function(par) {
        hilight(par);
      });
      $(document.getElementById(id)).addClass("selected");
    }

    var last_node = null;
    var node = svg.selectAll(".node")
      .data(nodes)
      .enter().append("circle")
      .attr("class", "node")
      .attr("r", 5)
      .call(force.drag)
      .on('click', function(node) {
        if (last_node !== null)
          d3.select(last_node).attr('r', 5);

        d3.select(this).attr('r', 10);
        last_node = this;

        $(".gref-taggable").removeClass("selected");
        hilight(node.hash);
      });

    force.on("tick", function() {
      link.attr("x1", function(d) { return d.source.x; })
      .attr("y1", function(d) { return d.source.y; })
      .attr("x2", function(d) { return d.target.x; })
      .attr("y2", function(d) { return d.target.y; });

      node.attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; });

    });

    return this;
  },

  install: function() {
    $("#gref-content")[0].appendChild(this.el);
  },

  initialize: function() {
    this.listenTo(this.model, "change", this.render);
    this.install();
  }
});
var rendered_gref = new Gref();
var rendered_gref_content;
<|endoftext|>


<commit_before>"use strict";

// ---------------------------------------------------------------------------

const okcoinusd = require ('./okcoinusd.js');

// ---------------------------------------------------------------------------

module.exports = class okex extends okcoinusd {

    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'okex',
            'name': 'OKEX',
            'countries': [ 'CN', 'US' ],
            'hasCORS': false,
            'hasFutureMarkets': true,
            'hasFetchTickers': true,
            'has': {
                'fetchTickers': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/32552768-0d6dd3c6-c4a6-11e7-90f8-c043b64756a7.jpg',
                'api': {
                    'web': 'https://www.okex.com/v2',
                    'public': 'https://www.okex.com/api',
                    'private': 'https://www.okex.com/api',
                },
                'www': 'https://www.okex.com',
                'doc': 'https://www.okex.com/rest_getStarted.html',
                'fees': 'https://www.okex.com/fees.html',
            },
        });
    }

    parseTickers (tickers, timestamp, symbols) {
        if (!tickers || (tickers.length < 1)) {
            return {};
        }
        let tickers_result = {};
        for (let i = 0; i < tickers.length; i++) {
            let market = undefined;
            if ('symbol' in tickers[i]) {
                if (tickers[i]['symbol'] in this.markets_by_id) {
                    market = this.markets_by_id[tickers[i]['symbol']];
                }
            }
            let ticker = this.extend (tickers[i], { 'timestamp': timestamp });
            tickers_result[market['symbol']] = this.parseTicker (ticker, market);
        }
        return tickers_result;
    }

    async fetchTickers (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        let method = 'publicGetTickers';
        let request = {};
        let response = await this[method] (this.extend (request, params));
        let timestamp = parseInt (response['date']) * 1000;
        return this.parseTickers (response['tickers'], timestamp, symbols);
    }
}
<commit_msg>python transpile fix<commit_after>"use strict";

// ---------------------------------------------------------------------------

const okcoinusd = require ('./okcoinusd.js');

// ---------------------------------------------------------------------------

module.exports = class okex extends okcoinusd {

    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'okex',
            'name': 'OKEX',
            'countries': [ 'CN', 'US' ],
            'hasCORS': false,
            'hasFutureMarkets': true,
            'hasFetchTickers': true,
            'has': {
                'fetchTickers': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/32552768-0d6dd3c6-c4a6-11e7-90f8-c043b64756a7.jpg',
                'api': {
                    'web': 'https://www.okex.com/v2',
                    'public': 'https://www.okex.com/api',
                    'private': 'https://www.okex.com/api',
                },
                'www': 'https://www.okex.com',
                'doc': 'https://www.okex.com/rest_getStarted.html',
                'fees': 'https://www.okex.com/fees.html',
            },
        });
    }

    parseTickers (tickers, timestamp, symbols) {
        const tickersLength = tickers.length;
        if (!tickers || (tickersLength < 1)) {
            return {};
        }
        let tickers_result = {};
        for (let i = 0; i < tickersLength; i++) {
            let market = undefined;
            if ('symbol' in tickers[i]) {
                if (tickers[i]['symbol'] in this.markets_by_id) {
                    market = this.markets_by_id[tickers[i]['symbol']];
                }
            }
            let ticker = this.extend (tickers[i], { 'timestamp': timestamp });
            tickers_result[market['symbol']] = this.parseTicker (ticker, market);
        }
        return tickers_result;
    }

    async fetchTickers (symbols = undefined, params = {}) {
        await this.loadMarkets ();
        let method = 'publicGetTickers';
        let request = {};
        let response = await this[method] (this.extend (request, params));
        let timestamp = parseInt (response['date']) * 1000;
        return this.parseTickers (response['tickers'], timestamp, symbols);
    }
}
<|endoftext|>


<commit_before>var MyGame = MyGame || {};

MyGame.LEVEL_COUNT = 2; // the game has 2 levels, for now

MyGame.Play = function () {};

MyGame.Play.prototype = {
  preload: function () {
  },

  create: function () {
    var me = this;

    me.loadLevel();

    me.input.onDown.add(me.playerJump, me);
    me.cursors = me.input.keyboard.createCursorKeys();
  },

  loadLevel: function() {
    var me = this;

    me.level = parseInt(localStorage.level) || 1;
    if (me.level < 1 || me.level > MyGame.LEVEL_COUNT) me.level = 1;

    me.createBackground();
    me.createGameMap();
    me.createEnemies();
    me.createStartAndCheckPoint();
    me.createPlayer();
    me.createHUD();
    me.createSound();

    me.time.events.loop(Phaser.Timer.SECOND, me.updateHUD, me);
  },

  stopTimer: function() {
    this.time.events.removeAll();
  },

  createSound: function() {
    var me = this;

    if (!me.s_music) me.s_music = me.add.audio('music');
    me.s_music.play('', 0, 0.3, true);

    if (!me.s_hit) me.s_hit = me.add.audio('hit');
    if (!me.s_jump) me.s_jump = me.add.audio('jump');
    if (!me.s_completed) me.s_completed = me.add.audio('completed');
  },

  createHUD: function() {
    var me = this;

    // lives
    if (me.lives) me.lives.destroy();
    me.lives = me.add.image(50, 50, 'texture-atlas', 'hud_p2');
    me.lives.anchor.set(0.5);
    me.lives.fixedToCamera = true;

    if (me.livesLabel) me.livesLabel.destroy();
    me.livesLabel = me.add.bitmapText(me.lives.x + me.lives.width + 12, me.lives.y, 'myfont', ' x ' + me.player.health, 35);
    me.livesLabel.anchor.set(0.5);
    me.livesLabel.fixedToCamera = true;

    // current meters
    if (me.metersLabel) me.metersLabel.destroy();
    me.metersLabel = me.add.bitmapText(Math.round(me.game.width/2), me.lives.y, 'myfont', (me.level - 1) * 10 + 'm', 40);
    me.metersLabel.anchor.set(0.5);
    me.metersLabel.fixedToCamera = true;
  },

  loseOneLife: function() {
    var me = this;

    me.player.health--;
    if (me.player.health <= 0) {
      me.s_music.pause();
      me.stopTimer();
      me.state.start('YouLose');
    } else {
      me.livesLabel.text = ' x ' + me.player.health;
    }
  },

  createBackground: function() {
    var me = this;

    if (me.bg) me.bg.destroy();
    me.bg = me.add.image(0, 0, 'background');
  },

  createPlayer: function() {
    var me = this;

    if (me.player) me.player.destroy();

    me.player = me.add.sprite(60, 150, 'texture-atlas', 'alienBlue_walk2');
    me.player.anchor.setTo(0.5, 0.5);
    me.player.animations.add('walking', ['alienBlue_walk1', 'alienBlue_walk2'], 5, true);

    me.physics.arcade.enable(me.player);
    me.player.body.gravity.y = 1000;
    me.camera.follow(me.player);
    me.player.health = 3;
  },

  initPlayer: function() {
    var me = this;

    me.player.animations.stop();
    me.player.x = 60;
    me.player.y = 150;
    me.player.body.velocity.x = 0;
    me.player.body.velocity.y = 0;

    me.player.body.blocked.down = false;
    me.player.alive = true;
  },

  createStartAndCheckPoint: function() {
    var me = this;

    if (me.startAndCheckPoint) me.startAndCheckPoint.destroy();

    me.startAndCheckPoint = me.game.add.group();
    me.map.createFromObjects('ObjectLayer', 'startpoint', 'texture-atlas', 'signRight', true, false, me.startAndCheckPoint);
    me.map.createFromObjects('ObjectLayer', 'checkpoint', 'texture-atlas', 'sign', true, false, me.startAndCheckPoint);

    var pos = me.startAndCheckPoint.getAt(0).position;
    me.add.bitmapText(pos.x, pos.y + 12, 'myfont', (me.level - 1) * 10 + 'm', 24);

    pos = me.startAndCheckPoint.getAt(1).position;
    me.add.bitmapText(pos.x, pos.y + 12, 'myfont', me.level * 10 + 'm', 24);
  },

  createEnemies: function() {
    var me = this;

    if (me.enemyGruop) me.enemyGruop.destroy();

    // create our enemies, put them in a group
    me.enemyGroup = me.game.add.group();
    me.enemyGroup.enableBody = true;
    me.map.createFromObjects('ObjectLayer', 'box', 'texture-atlas', 'blockerMad', true, false, me.enemyGroup);
  },

  createGameMap: function() {
    var me = this;

    if (me.groundLayer) me.groundLayer.destroy();
    if (me.backgroundLayer) me.backgroundLayer.destroy();
    if (me.map) me.map.destroy();

    me.map = me.add.tilemap('level' + me.level);
    me.map.addTilesetImage('mytileset', 'tiles');

    me.backgroundLayer = me.map.createLayer('BackgroundLayer');
    me.groundLayer = me.map.createLayer('GroundLayer');
    me.map.setCollisionBetween(1, 35, true, 'GroundLayer');

    me.groundLayer.resizeWorld();
  },

  playerJump: function(point, isDoubleTap) {
    var me = this;

    if (me.player.body.blocked.down) {
      this.s_jump.play('', 0, 1);
      me.player.animations.stop();
      me.player.frameName = 'alienBlue_walk2';
      me.player.body.velocity.y = -550;
    }
  },

  playerHit: function(player, enemy) {
    player.alive = false;
    this.s_hit.play('', 0, 1);

    this.loseOneLife();
    this.initPlayer();
  },

  levelCompleted: function() {
    var me = this;

    me.s_music.pause();
    me.s_completed.play();

    var nextLevel = me.level + 1;
    if (nextLevel > MyGame.LEVEL_COUNT) {
      localStorage.level = 1;
      me.stopTimer();
      me.state.start('YouWin');
    } else {
      localStorage.level = nextLevel;
      me.loadLevel();
    }
  },

  updateHUD: function() {
    var me = this;

    // meters
    me.metersLabel.text = (me.level - 1) * 10 + Math.round(me.player.x * 10 / me.world.width) + 'm';
  },

  update: function() {
    var me = this;

    if (me.player && me.player.alive) {
      me.physics.arcade.collide(me.player, me.groundLayer);
      me.physics.arcade.overlap(me.player, me.enemyGroup, me.playerHit, null, me);

      if (me.player.body.blocked.down) {
        me.player.body.velocity.x = 250;
        me.player.animations.play('walking');
      }

      if (me.cursors.up.isDown && me.player.body.blocked.down) {
        me.playerJump();
      }

      if (me.player.x > me.world.width) me.levelCompleted();
    }
  },

  render: function() {
    this.game.debug.text(this.game.time.fps || '--', 2, 14, "#00ff00");
  }
};
<commit_msg>better way to handle up key<commit_after>var MyGame = MyGame || {};

MyGame.LEVEL_COUNT = 2; // the game has 2 levels, for now

MyGame.Play = function () {};

MyGame.Play.prototype = {
  preload: function () {
  },

  create: function () {
    var me = this;

    me.loadLevel();

    me.input.onDown.add(me.playerJump, me);
    me.input.keyboard.addKey(Phaser.KeyCode.UP).onDown.add(me.playerJump, me);
  },

  loadLevel: function() {
    var me = this;

    me.level = parseInt(localStorage.level) || 1;
    if (me.level < 1 || me.level > MyGame.LEVEL_COUNT) me.level = 1;

    me.createBackground();
    me.createGameMap();
    me.createEnemies();
    me.createStartAndCheckPoint();
    me.createPlayer();
    me.createHUD();
    me.createSound();

    me.time.events.loop(Phaser.Timer.SECOND, me.updateHUD, me);
  },

  stopTimer: function() {
    this.time.events.removeAll();
  },

  createSound: function() {
    var me = this;

    if (!me.s_music) me.s_music = me.add.audio('music');
    me.s_music.play('', 0, 0.3, true);

    if (!me.s_hit) me.s_hit = me.add.audio('hit');
    if (!me.s_jump) me.s_jump = me.add.audio('jump');
    if (!me.s_completed) me.s_completed = me.add.audio('completed');
  },

  createHUD: function() {
    var me = this;

    // lives
    if (me.lives) me.lives.destroy();
    me.lives = me.add.image(50, 50, 'texture-atlas', 'hud_p2');
    me.lives.anchor.set(0.5);
    me.lives.fixedToCamera = true;

    if (me.livesLabel) me.livesLabel.destroy();
    me.livesLabel = me.add.bitmapText(me.lives.x + me.lives.width + 12, me.lives.y, 'myfont', ' x ' + me.player.health, 35);
    me.livesLabel.anchor.set(0.5);
    me.livesLabel.fixedToCamera = true;

    // current meters
    if (me.metersLabel) me.metersLabel.destroy();
    me.metersLabel = me.add.bitmapText(Math.round(me.game.width/2), me.lives.y, 'myfont', (me.level - 1) * 10 + 'm', 40);
    me.metersLabel.anchor.set(0.5);
    me.metersLabel.fixedToCamera = true;
  },

  loseOneLife: function() {
    var me = this;

    me.player.health--;
    if (me.player.health <= 0) {
      me.s_music.pause();
      me.stopTimer();
      me.state.start('YouLose');
    } else {
      me.livesLabel.text = ' x ' + me.player.health;
    }
  },

  createBackground: function() {
    var me = this;

    if (me.bg) me.bg.destroy();
    me.bg = me.add.image(0, 0, 'background');
  },

  createPlayer: function() {
    var me = this;

    if (me.player) me.player.destroy();

    me.player = me.add.sprite(60, 150, 'texture-atlas', 'alienBlue_walk2');
    me.player.anchor.setTo(0.5, 0.5);
    me.player.animations.add('walking', ['alienBlue_walk1', 'alienBlue_walk2'], 5, true);

    me.physics.arcade.enable(me.player);
    me.player.body.gravity.y = 1000;
    me.camera.follow(me.player);
    me.player.health = 3;
  },

  initPlayer: function() {
    var me = this;

    me.player.animations.stop();
    me.player.x = 60;
    me.player.y = 150;
    me.player.body.velocity.x = 0;
    me.player.body.velocity.y = 0;

    me.player.body.blocked.down = false;
    me.player.alive = true;
  },

  createStartAndCheckPoint: function() {
    var me = this;

    if (me.startAndCheckPoint) me.startAndCheckPoint.destroy();

    me.startAndCheckPoint = me.game.add.group();
    me.map.createFromObjects('ObjectLayer', 'startpoint', 'texture-atlas', 'signRight', true, false, me.startAndCheckPoint);
    me.map.createFromObjects('ObjectLayer', 'checkpoint', 'texture-atlas', 'sign', true, false, me.startAndCheckPoint);

    var pos = me.startAndCheckPoint.getAt(0).position;
    me.add.bitmapText(pos.x, pos.y + 12, 'myfont', (me.level - 1) * 10 + 'm', 24);

    pos = me.startAndCheckPoint.getAt(1).position;
    me.add.bitmapText(pos.x, pos.y + 12, 'myfont', me.level * 10 + 'm', 24);
  },

  createEnemies: function() {
    var me = this;

    if (me.enemyGruop) me.enemyGruop.destroy();

    // create our enemies, put them in a group
    me.enemyGroup = me.game.add.group();
    me.enemyGroup.enableBody = true;
    me.map.createFromObjects('ObjectLayer', 'box', 'texture-atlas', 'blockerMad', true, false, me.enemyGroup);
  },

  createGameMap: function() {
    var me = this;

    if (me.groundLayer) me.groundLayer.destroy();
    if (me.backgroundLayer) me.backgroundLayer.destroy();
    if (me.map) me.map.destroy();

    me.map = me.add.tilemap('level' + me.level);
    me.map.addTilesetImage('mytileset', 'tiles');

    me.backgroundLayer = me.map.createLayer('BackgroundLayer');
    me.groundLayer = me.map.createLayer('GroundLayer');
    me.map.setCollisionBetween(1, 35, true, 'GroundLayer');

    me.groundLayer.resizeWorld();
  },

  playerJump: function(point, isDoubleTap) {
    var me = this;

    if (me.player.body.blocked.down) {
      this.s_jump.play('', 0, 1);
      me.player.animations.stop();
      me.player.frameName = 'alienBlue_walk2';
      me.player.body.velocity.y = -550;
    }
  },

  playerHit: function(player, enemy) {
    player.alive = false;
    this.s_hit.play('', 0, 1);

    this.loseOneLife();
    this.initPlayer();
  },

  levelCompleted: function() {
    var me = this;

    me.s_music.pause();
    me.s_completed.play();

    var nextLevel = me.level + 1;
    if (nextLevel > MyGame.LEVEL_COUNT) {
      localStorage.level = 1;
      me.stopTimer();
      me.state.start('YouWin');
    } else {
      localStorage.level = nextLevel;
      me.loadLevel();
    }
  },

  updateHUD: function() {
    var me = this;

    // meters
    me.metersLabel.text = (me.level - 1) * 10 + Math.round(me.player.x * 10 / me.world.width) + 'm';
  },

  update: function() {
    var me = this;

    if (me.player && me.player.alive) {
      me.physics.arcade.collide(me.player, me.groundLayer);
      me.physics.arcade.overlap(me.player, me.enemyGroup, me.playerHit, null, me);

      if (me.player.body.blocked.down) {
        me.player.body.velocity.x = 250;
        me.player.animations.play('walking');
      }

      if (me.player.x > me.world.width) me.levelCompleted();
    }
  },

  render: function() {
    this.game.debug.text(this.game.time.fps || '--', 2, 14, "#00ff00");
  }
};
<|endoftext|>


<commit_before>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/* globals */
var player, token; // externally assigned globals
var step = 0, banCooldown = false, timer, timerHandle;

function init() {
    synchronize();
    if (player !== 7)
        connect();
    init_countdown();
}

/* Communications */

function updateUI (response) {
    if (response.connected === true) {
        setStep(step);
        setLoadingAnimation(false);
    }
    if (response.updates === true) {
        for (i = 0; i < response.maps.length; i++)
            applyVisualBan(response.maps[i]);
        step = response.step;
        setStep(step);
    }
    listen();
}

// True if player has the right to execute step
function getCurrentPlayer() {
    switch (step) {
        case 0:
        case 3:
        case 4:
            return 0;
            break;
        case 1:
        case 2:
        case 5:
            return 1;
            break;
        default:
            return 7;
    }
}

function ban(map)
{
    if (banCooldown || getCurrentPlayer() !== player)
        return;

    setLoadingAnimation(true);

    $.ajax({
        url: 'system/ban.php',
        data: {
            token: token,
            map: map,
            step: step
        },
        type: 'GET',
        dataType: 'json'
    })
    .done(function (response) {
        banCooldown = false;
        if (response.success === true) {
            applyVisualBan(map);
            step = response.step;
            setStep(step);
            setLoadingAnimation(false);
        }
    });
    banCooldown = true;
}

function listen()
{
    $.ajax({
        url: 'system/listen.php',
        data: {
            token: token,
            step: step
        },
        type: 'GET',
        dataType: 'json'
    }).done( updateUI );
}

function synchronize()
{
    $.ajax({
        url: 'system/synchronize.php',
        data: {
            token: token
        },
        type: 'GET',
        dataType: 'json'
    }).done( updateUI );
}

function connect()
{
    $.ajax({
        url: 'system/connect.php',
        data: {
            token: token
        },
        type: 'GET',
        dataType: 'json'
    }).done(function (data) {
        if(data !== true)
            alert("Error connecting!");
    });
}

/* Visuals */

function setStep(step) {
    resetCountdown();
    if (step === 6) {
        displayMessage("Bans Finished!");
        clearTimeout(timerHandle);
        $('#timer').text('0.0');
    } else {
        var player2 = getCurrentPlayer();
        if (player2 === player) {
            displayMessage('Your turn [' + (step + 1) + '/6]');
        } else {
            displayMessage('Player ' + (player2 + 1) + "'s turn [" + (step + 1) + '/6]');
        }
    }
}

/* Display */
function displayMessage(message) {
    $('#message').text(message);
}

function setLoadingAnimation(state) {
    if (state) {
        $('#overlay').show();
        displayMessage("loading...");
    } else
        $('#overlay').hide();
}

function countdown() {
    var d = new Date();
    var t = timer - d.getTime();
    var s = Math.floor(t / 1000);
    var s10 = Math.floor(t / 100) % 10;
    $('#timer').text(s + '.' + s10);
}

function init_countdown() {
    var d = new Date();
    timer = d.getTime() + 60000;
    timerHandle = setInterval(countdown, 100);
}

function resetCountdown() {
    var d = new Date();
    timer = d.getTime() + 30500;
}

function applyVisualBan(map) {
    $('#' + map).addClass('banned').off();
}

function removeVisualBan(map) {
    $('#' + map).removeClass('banned').click(ban(map));
}<commit_msg>Reduced unnecessary variables in timer code<commit_after>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/* globals */
var player, token; // externally assigned globals
var step = 0, banCooldown = false;
var timer, timerHandle;

function init() {
    synchronize();
    if (player !== 7)
        connect();
    cd_init();
}

/* Communications */

function updateUI(response) {
    if (response.connected === true) {
        setStep(step);
        setLoadingAnimation(false);
    }
    if (response.updates === true) {
        for (i = 0; i < response.maps.length; i++)
            applyVisualBan(response.maps[i]);
        step = response.step;
        setStep(step);
    }
    listen();
}

// True if player has the right to execute step
function getCurrentPlayer() {
    switch (step) {
        case 0:
        case 3:
        case 4:
            return 0;
            break;
        case 1:
        case 2:
        case 5:
            return 1;
            break;
        default:
            return 7;
    }
}

function ban(map)
{
    if (banCooldown || getCurrentPlayer() !== player)
        return;

    setLoadingAnimation(true);

    $.ajax({
        url: 'system/ban.php',
        data: {
            token: token,
            map: map,
            step: step
        },
        type: 'GET',
        dataType: 'json'
    })
            .done(function (response) {
                banCooldown = false;
                if (response.success === true) {
                    applyVisualBan(map);
                    step = response.step;
                    setStep(step);
                    setLoadingAnimation(false);
                }
            });
    banCooldown = true;
}

function listen()
{
    $.ajax({
        url: 'system/listen.php',
        data: {
            token: token,
            step: step
        },
        type: 'GET',
        dataType: 'json'
    }).done(updateUI);
}

function synchronize()
{
    $.ajax({
        url: 'system/synchronize.php',
        data: {
            token: token
        },
        type: 'GET',
        dataType: 'json'
    }).done(updateUI);
}

function connect()
{
    $.ajax({
        url: 'system/connect.php',
        data: {
            token: token
        },
        type: 'GET',
        dataType: 'json'
    }).done(function (data) {
        if (data !== true)
            alert("Error connecting!");
    });
}

/* Visuals */

function setStep(step) {
    cd_reset();
    if (step === 6) {
        displayMessage("Bans Finished!");
        clearTimeout(timerHandle);
        $('#timer').text('0.0');
    } else {
        var player2 = getCurrentPlayer();
        if (player2 === player) {
            displayMessage('Your turn [' + (step + 1) + '/6]');
        } else {
            displayMessage('Player ' + (player2 + 1) + "'s turn [" + (step + 1) + '/6]');
        }
    }
}

/* Display */
function displayMessage(message) {
    $('#message').text(message);
}

function setLoadingAnimation(state) {
    if (state) {
        $('#overlay').show();
        displayMessage("loading...");
    } else
        $('#overlay').hide();
}

// Draft for potential future adaptation
//function timerFactory() {
//    return {
//        timer: null,
//        handle: null,
//        init: function () {
//            timer = new Date().getTime() + 60000;
//            timerHandle = setInterval(this.tick, 500);
//        },
//        tick: function () {
//            document.getElementById('timer').innerHTML.text(
//                    Math.floor(
//                            (timer - new Date().getTime()) / 1000));
//        },
//        reset: function () {
//            timer = new Date().getTime() + 30500;
//        }
//    };
//}

function cd_tick() {
    document.getElementById('timer').innerHTML = (
                    Math.floor(
                            (timer - new Date().getTime()) / 1000));
}

function cd_init() {
    timer = new Date().getTime() + 60000;
    timerHandle = setInterval(cd_tick, 500);
}

function cd_reset() {
    timer = new Date().getTime() + 30500;
}

function applyVisualBan(map) {
    $('#' + map).addClass('banned').off();
}

function removeVisualBan(map) {
    $('#' + map).removeClass('banned').click(ban(map));
}<|endoftext|>


<commit_before>function setMeter(rating) {
	if(rating>=6) {
		var x=500;
	} else if(rating<=-6) {
		var x=-500;
	} else {
		var x=rating*100;
	}
	var r=$("#meterRed");
	var g=$("#meterGreen");
	g.animate({width: (583+x)}, Math.abs(g.width()-(583+x)));
	r.animate({width: (583-x)}, Math.abs(r.width()-(583-x)));
}

var player;
var firebase = new Firebase('https://adr2370.firebaseio.com/');
var songdb = firebase.child('songs');
var playerdb = firebase.child('playerdb');
var commentdb = firebase.child('comments');
var currentdb = firebase.child('current');
var goingToNext = false;

var songs=new Array();

function startVideo() {
	//youtube video
	currentdb.once('value', function(dataSnapshot) {
		var id=dataSnapshot.child('id').val();
		if(player==null) {
			player=new YT.Player('youtube', {
				height: '390',
				width: '640',
				videoId: id,
				playerVars: { autoplay:1, enablejsapi:1, modestbranding:1, rel:0, showinfo:0, iv_load_policy:3, volume:50 },
				events: {
					'onStateChange': onPlayerStateChange,
					//'onError': onError
				}});
		} else {
			player.loadVideoById(id, 5, "large");
		}
		/*if(player!=null) {
			playerdb.child('volume').once('value', function(dataSnapshot) {
				player.setVolume(dataSnapshot.val());
			});
		} else {
			console.log("SOMETHING WENT WRONG");
		}*/
		$("#visuals canvas").hide();
		$("#"+id).remove();
		songdb.child(id).remove();
		removeA(songs, id);
	});
}

function nextVideo() {
	setMeter(0);
	$("#comments").html("");
	commentdb.remove();
	currentdb.remove();
	if(songs.length>0) {
		songdb.child(songs[0]).once('value', function(dataSnapshot) {
			currentdb.set(dataSnapshot.val());
			currentdb.child('rating').set(0);
			currentdb.child('skip').set(0);
			currentdb.child('play').set(0);
			currentdb.child('pause').set(0);
			currentdb.child('fullScreen').set(0);
			currentdb.child('id').set(songs[0]);
			goingToNext=false;
		});
	} else {
		$("#youtube").replaceWith($('
<\/div>'));
		player=null;
		goingToNext=false;
	}
}

function onPlayerStateChange(event) {
	if(event.data == 0) {
		currentdb.remove();
	}
}

function onError(event) {
	currentdb.remove();
}

currentdb.on('child_changed', function(snapshot, prevChildName) {
	console.log(snapshot.name());
	//CHANGE RATING OR SKIP VIDEO
	if(snapshot.name()=="id") {
		startVideo();
	}
	if(snapshot.name()=="rating") {
		setMeter(snapshot.val());
	} else if(snapshot.name()=="skip"&&snapshot.val()==1) {
		nextVideo();
	} else if(snapshot.name()=="play"&&snapshot.val()==1) {
		currentdb.child('play').set(0);
		player.playVideo();
	} else if(snapshot.name()=="pause"&&snapshot.val()==1) {
		currentdb.child('pause').set(0);
		player.pauseVideo();
	} else if(snapshot.name()=="fullScreen"&&snapshot.val()==1) {
		currentdb.child('fullScreen').set(0);
		window.fullScreen();
	}
});

currentdb.on('child_added', function(snapshot, prevChildName) {
	//ADDED SONG
	console.log(snapshot.name());
	if(snapshot.name()=="id") {
		startVideo();
	}
});

currentdb.on('child_removed', function(snapshot, prevChildName) {
	//ADDED SONG
	if(snapshot.name()=="id") {
		//nextVideo();
	}
});

songdb.on('child_added', function(snapshot, prevChildName) {
	//ADDS SOMETHING TO QUEUE
	//snapshot.name() is youtube id, all else is below
	songs.push(snapshot.name());
	$("#queue").append('
'+snapshot.child('name').val()+'<\/td>'+snapshot.child('length').val()+'<\/td><\/td>'+snapshot.child('numViews').val()+'<\/tr>');
	currentdb.on('value', function(snapshot, prevChildName) {
		if(snapshot.val()==null&&!goingToNext) {
			goingToNext=true;
			nextVideo();
		}
	});
});

songdb.on('child_moved', function(snapshot, prevChildName) {
	//SWITCHES ORDER OF STUFF IN QUEUE
	//prevChildName is the name of the previous one, snapshot.name is the id of the snapshot
	if(prevChildName==null) {
		$("#topQueue").after($("#"+snapshot.name()).remove());
	} else {
		$("#"+prevChildName).after($("#"+snapshot.name()).remove());
	}
});

playerdb.on('child_changed', function(snapshot, prevChildName) {
	player.setVolume(snapshot.val());
});

commentdb.on('child_added', function(snapshot, prevChildName) {
	//COMMENTS ADDED
	//snapshot.val() is each comment
	$("#comments").prepend("
" + snapshot.val()+"<\/p>");
});

function removeA(arr) {
    var what, a = arguments, L = a.length, ax;
    while (L > 1 && arr.length) {
        what = a[--L];
        while ((ax= arr.indexOf(what)) !== -1) {
            arr.splice(ax, 1);
        }
    }
    return arr;
}<commit_msg>Added console logs<commit_after>function setMeter(rating) {
	if(rating>=6) {
		var x=500;
	} else if(rating<=-6) {
		var x=-500;
	} else {
		var x=rating*100;
	}
	var r=$("#meterRed");
	var g=$("#meterGreen");
	g.animate({width: (583+x)}, Math.abs(g.width()-(583+x)));
	r.animate({width: (583-x)}, Math.abs(r.width()-(583-x)));
}

var player;
var firebase = new Firebase('https://adr2370.firebaseio.com/');
var songdb = firebase.child('songs');
var playerdb = firebase.child('playerdb');
var commentdb = firebase.child('comments');
var currentdb = firebase.child('current');
var goingToNext = false;

var songs=new Array();

function startVideo() {
	//youtube video
	console.log("STARTING VIDEO");
	currentdb.once('value', function(dataSnapshot) {
		var id=dataSnapshot.child('id').val();
		console.log(id);
		if(player==null) {
			player=new YT.Player('youtube', {
				height: '390',
				width: '640',
				videoId: id,
				playerVars: { autoplay:1, enablejsapi:1, modestbranding:1, rel:0, showinfo:0, iv_load_policy:3, volume:50 },
				events: {
					'onStateChange': onPlayerStateChange,
					//'onError': onError
				}});
		} else {
			player.loadVideoById(id, 5, "large");
		}
		/*if(player!=null) {
			playerdb.child('volume').once('value', function(dataSnapshot) {
				player.setVolume(dataSnapshot.val());
			});
		} else {
			console.log("SOMETHING WENT WRONG");
		}*/
		$("#visuals canvas").hide();
		$("#"+id).remove();
		songdb.child(id).remove();
		removeA(songs, id);
	});
}

function nextVideo() {
	setMeter(0);
	$("#comments").html("");
	commentdb.remove();
	currentdb.remove();
	if(songs.length>0) {
		songdb.child(songs[0]).once('value', function(dataSnapshot) {
			currentdb.set(dataSnapshot.val());
			currentdb.child('rating').set(0);
			currentdb.child('skip').set(0);
			currentdb.child('play').set(0);
			currentdb.child('pause').set(0);
			currentdb.child('fullScreen').set(0);
			currentdb.child('id').set(songs[0]);
			goingToNext=false;
		});
	} else {
		$("#youtube").replaceWith($('
<\/div>'));
		player=null;
		goingToNext=false;
	}
}

function onPlayerStateChange(event) {
	if(event.data == 0) {
		currentdb.remove();
	}
}

function onError(event) {
	currentdb.remove();
}

currentdb.on('child_changed', function(snapshot, prevChildName) {
	console.log(snapshot.name());
	//CHANGE RATING OR SKIP VIDEO
	if(snapshot.name()=="rating") {
		setMeter(snapshot.val());
	} else if(snapshot.name()=="skip"&&snapshot.val()==1) {
		nextVideo();
	} else if(snapshot.name()=="play"&&snapshot.val()==1) {
		currentdb.child('play').set(0);
		player.playVideo();
	} else if(snapshot.name()=="pause"&&snapshot.val()==1) {
		currentdb.child('pause').set(0);
		player.pauseVideo();
	} else if(snapshot.name()=="fullScreen"&&snapshot.val()==1) {
		currentdb.child('fullScreen').set(0);
		window.fullScreen();
	} else if(snapshot.name()=="id") {
		startVideo();
	}
});

currentdb.on('child_added', function(snapshot, prevChildName) {
	//ADDED SONG
	console.log(snapshot.name());
	if(snapshot.name()=="id") {
		console.log("STARTING");
		startVideo();
	}
});

currentdb.on('child_removed', function(snapshot, prevChildName) {
	//ADDED SONG
	if(snapshot.name()=="id") {
		//nextVideo();
	}
});

songdb.on('child_added', function(snapshot, prevChildName) {
	//ADDS SOMETHING TO QUEUE
	//snapshot.name() is youtube id, all else is below
	songs.push(snapshot.name());
	$("#queue").append('
'+snapshot.child('name').val()+'<\/td>'+snapshot.child('length').val()+'<\/td><\/td>'+snapshot.child('numViews').val()+'<\/tr>');
	currentdb.on('value', function(snapshot, prevChildName) {
		if(snapshot.val()==null&&!goingToNext) {
			goingToNext=true;
			nextVideo();
		}
	});
});

songdb.on('child_moved', function(snapshot, prevChildName) {
	//SWITCHES ORDER OF STUFF IN QUEUE
	//prevChildName is the name of the previous one, snapshot.name is the id of the snapshot
	if(prevChildName==null) {
		$("#topQueue").after($("#"+snapshot.name()).remove());
	} else {
		$("#"+prevChildName).after($("#"+snapshot.name()).remove());
	}
});

playerdb.on('child_changed', function(snapshot, prevChildName) {
	player.setVolume(snapshot.val());
});

commentdb.on('child_added', function(snapshot, prevChildName) {
	//COMMENTS ADDED
	//snapshot.val() is each comment
	$("#comments").prepend("
" + snapshot.val()+"<\/p>");
});

function removeA(arr) {
    var what, a = arguments, L = a.length, ax;
    while (L > 1 && arr.length) {
        what = a[--L];
        while ((ax= arr.indexOf(what)) !== -1) {
            arr.splice(ax, 1);
        }
    }
    return arr;
}<|endoftext|>


<commit_before>var SendPage = new (function () {
  var address, name;

  this.onShowTab = function () {
    var recentSends = blobVault.getRecentSends(),
        isValidAddress = (function () {
          var r = /^r\w{30,35}$/;
          return function (a) { return r.test(a); }
        })();

    function onNewVal() {
      address = $("#SendDestSelect").val() || this.value,
      name = blobVault.addressBook.getName(address) || '';

      $("#AddressDisplayRow").hide();
      $("#SendDestNameRow").hide();
      $("#SendPageButton").attr('disabled', false);

      if (isValidAddress(address)) {
        if (address == this.value) {
          // address in input box
          $("#SendDestNameRow").show();
          $("#SendDestName").val(name);
        } else {
          // name in input box
          $("#AddressDisplayRow").show();
          $("#AddressDisplay").val(address)
        }
      } else {
        $("#SendPageButton").attr('disabled', true);
      }
    }

    $("#SendDest").combobox({
        data: recentSends,
        selected: '',
        button_title: 'Recently used addresses',
        onchange: onNewVal,
        onselect: onNewVal
      }).on('input', onNewVal);

    var select = $("#SendDestSelect");
    select.children("option[value!='']").remove();
    _.each(
      recentSends,
      function (name, addr) {
        select.append(new Option(name, addr));
      }
    );

    $("#SendDest").trigger('input');
  }

  this.send = function () {
    var currency = $("#SendCurrency").val(),
        amount = $("#SendAmount").val() * (currency == 'XNS' ? BALANCE_DISPLAY_DIVISOR : 1);

    name = $("#SendDestName").val() || name;

    if (currency == 'XNS') {
      rpc.send(ncc.masterKey, ncc.accountID, address, String(amount), currency, SendPage.onSendResponse);
    } else {
      rpc.send(ncc.masterKey, ncc.accountID, address, String(amount), currency, ncc.accountID, SendPage.onSendResponse);
    }

    $("#SendPageButton").attr('disabled', true).text("Sending...");
    $("#t-send").find("input, select").attr('disabled', true);
  }

  this.onSendResponse = function (response, success) {
    console.log("Send response:", JSON.stringify(response));

    if (success) {
      if (!ncc.checkError(response)) {
        var toAccount = response.result.dstAccountID,
            curr = $("#SendCurrency").val(),
            sel = $("#SendDestSelect");

        if (name) {
          blobVault.addressBook.setEntry(name, toAccount);
        }

        blobVault.data.recent_sends = _.without(blobVault.data.recent_sends, toAccount);
        blobVault.data.recent_sends.unshift(toAccount);
        blobVault.data.recent_sends.splice(NUM_RECENT_ADDRESSES);

        blobVault.save();
        blobVault.pushToServer();

        sel.find("option[value=" + toAccount + "]").remove();
        sel.prepend(new Option(name || toAccount, toAccount));

        ncc.status( $("#SendAmount").val() + ' ' + curr + ' sent to ' + (name ? name + ' @ ' + toAccount : toAccount) );

        address = '';
        name = '';

        $("#SendDest").val('');
        $("#SendAmount").val('');
        $("#SendDestName").val('');
        $("#SendDestNameRow").hide();
        $("#AddressDisplay").val('');
        $("#AddressDisplayRow").hide();

        $("#SendPageButton").attr('disabled', false).text("Send Money");
        $("#t-send").find("input, select").attr('disabled', false);
      }
    } else {
      ncc.serverDown();
    }
  }

})();

$(document).ready(function () {
  $("#SendCurrency").combobox({ data: ncc.allCurrencyOptions, selected: 'XNS' });
});
<commit_msg>fixed send page form after error occurs<commit_after>var SendPage = new (function () {
  var address, name;

  this.onShowTab = function () {
    var recentSends = blobVault.getRecentSends(),
        isValidAddress = (function () {
          var r = /^r\w{30,35}$/;
          return function (a) { return r.test(a); }
        })();

    function onNewVal() {
      address = $("#SendDestSelect").val() || this.value,
      name = blobVault.addressBook.getName(address) || '';

      $("#AddressDisplayRow").hide();
      $("#SendDestNameRow").hide();
      $("#SendPageButton").attr('disabled', false);

      if (isValidAddress(address)) {
        if (address == this.value) {
          // address in input box
          $("#SendDestNameRow").show();
          $("#SendDestName").val(name);
        } else {
          // name in input box
          $("#AddressDisplayRow").show();
          $("#AddressDisplay").val(address)
        }
      } else {
        $("#SendPageButton").attr('disabled', true);
      }
    }

    $("#SendDest").combobox({
        data: recentSends,
        selected: '',
        button_title: 'Recently used addresses',
        onchange: onNewVal,
        onselect: onNewVal
      }).on('input', onNewVal);

    var select = $("#SendDestSelect");
    select.children("option[value!='']").remove();
    _.each(
      recentSends,
      function (name, addr) {
        select.append(new Option(name, addr));
      }
    );

    $("#SendDest").trigger('input');
  }

  this.send = function () {
    var currency = $("#SendCurrency").val(),
        amount = $("#SendAmount").val() * (currency == 'XNS' ? BALANCE_DISPLAY_DIVISOR : 1);

    name = $("#SendDestName").val() || name;

    if (currency == 'XNS') {
      rpc.send(ncc.masterKey, ncc.accountID, address, String(amount), currency, SendPage.onSendResponse);
    } else {
      rpc.send(ncc.masterKey, ncc.accountID, address, String(amount), currency, ncc.accountID, SendPage.onSendResponse);
    }

    $("#SendPageButton").attr('disabled', true).text("Sending...");
    $("#t-send").find("input, select").attr('disabled', true);
  }

  this.onSendResponse = function (response, success) {
    console.log("Send response:", JSON.stringify(response));

    if (success) {
      if (!ncc.checkError(response)) {
        var toAccount = response.result.dstAccountID,
            curr = $("#SendCurrency").val(),
            sel = $("#SendDestSelect");

        if (name) {
          blobVault.addressBook.setEntry(name, toAccount);
        }

        blobVault.data.recent_sends = _.without(blobVault.data.recent_sends, toAccount);
        blobVault.data.recent_sends.unshift(toAccount);
        blobVault.data.recent_sends.splice(NUM_RECENT_ADDRESSES);

        blobVault.save();
        blobVault.pushToServer();

        sel.find("option[value=" + toAccount + "]").remove();
        sel.prepend(new Option(name || toAccount, toAccount));

        ncc.status( $("#SendAmount").val() + ' ' + curr + ' sent to ' + (name ? name + ' @ ' + toAccount : toAccount) );

        address = '';
        name = '';

        $("#SendDest").val('');
        $("#SendAmount").val('');
        $("#SendDestName").val('');
        $("#SendDestNameRow").hide();
        $("#AddressDisplay").val('');
        $("#AddressDisplayRow").hide();
      }
    } else {
      ncc.serverDown();
    }

    // re-enable form
    $("#SendPageButton").attr('disabled', false).text("Send Money");
    $("#t-send").find("input, select").attr('disabled', false);
  }

})();

$(document).ready(function () {
  $("#SendCurrency").combobox({ data: ncc.allCurrencyOptions, selected: 'XNS' });
});
<|endoftext|>


<commit_before>var map;

$(document).ready(function() {
    $('#map').text('');
    map = L.map('map').setView([47, 8.5], 9);
    L.tileLayer('http://tile.osm.ch/switzerland/{z}/{x}/{y}.png', {
        maxZoom: 20,
        attribution: '© OpenStreetMap contributors'
    }).addTo(map);

    $('.view-selector').click(function() {
        $("body").toggleClass('map-only');
        map.invalidateSize();
    });

    if (location.hash === "#map") {
        $("body").addClass('map-only');
    }
});
<commit_msg>increase max zoom to 21<commit_after>var map;

$(document).ready(function() {
    $('#map').text('');
    map = L.map('map').setView([47, 8.5], 9);
    L.tileLayer('http://tile.osm.ch/switzerland/{z}/{x}/{y}.png', {
        maxZoom: 21,
        attribution: '© OpenStreetMap contributors'
    }).addTo(map);

    $('.view-selector').click(function() {
        $("body").toggleClass('map-only');
        map.invalidateSize();
    });

    if (location.hash === "#map") {
        $("body").addClass('map-only');
    }
});
<|endoftext|>


<commit_before>var activity_chart = dc.pieChart("#activity");
var country_chart = dc.pieChart("#country");
var organisation_chart = dc.rowChart("#organisation");
var region_chart = dc.geoChoroplethChart("#map");

var cf = crossfilter(data);

cf.activity = cf.dimension(function(d){ return d.Activity; });
cf.country = cf.dimension(function(d){ return d.Country; });
cf.organisation = cf.dimension(function(d){ return d.Organisation; });
cf.region = cf.dimension(function(d){ return d.Region; });

var activity = cf.activity.group();
var country = cf.country.group();
var organisation = cf.organisation.group();
var region = cf.region.group();
var all = cf.groupAll();

activity_chart.width(250).height(250)
        .dimension(cf.activity)
        .group(activity)
        .colors(['#ffe082',
                 '#ffd54f',
                 '#ffca28',
                 '#ffc107',
                 '#ffb300',
                 '#ffa000',
                 '#ff8f00',
                 '#ff6f00'
            ])
        .colorDomain([1,8])
        .colorAccessor(function(d, i){return i%7+1;});

country_chart.width(250).height(250)
        .dimension(cf.country)
        .group(country)
        .colors(['#0d5302',
                 '#0a7e07',
                 '#259b24',
                 '#42bd41'
            ])
        .colorDomain([0,4])
        .colorAccessor(function(d, i){return i%4;});

organisation_chart.width(350).height(600)
        .dimension(cf.organisation)
        .group(organisation)
        .elasticX(true)
        .data(function(group) {
            return group.top(20);
        })
        .colors(['#81d4fa',
                 '#4fc3f7',
                 '#29b6f6',
                 '#03a9f4',
                 '#039be5',
                 '#0288d1',
                 '#0277bd',
                 '#01579b'
            ])
        .colorDomain([0,8])
        .colorAccessor(function(d, i){return i%8;});

dc.dataCount("#count-info")
	.dimension(cf)
	.group(all);

region_chart.width(400).height(350)
        .dimension(cf.region)
        .group(region)
        .colors(['#DDDDDD', '#e51c23'])
        .colorDomain([0, 1])
        .colorAccessor(function (d) {
            if(d>0){
                return 1;
            } else {
                return 0;
            }
        })
        .overlayGeoJson(regions.features, "Regions", function (d) {
            return d.properties.NAME_REF;
        })
        .projection(d3.geo.mercator().center([-4,6.5]).scale(2200))
        .title(function(d){
            return d.key;
        });
dc.renderAll();

var projection = d3.geo.mercator()
    .center([-4,6.5])
    .scale(2200);

var path = d3.geo.path()
    .projection(projection);

var g = d3.selectAll("#map").select("svg").append("g");

g.selectAll("path")
    .data(westafrica.features)
    .enter()
    .append("path")
    .attr("d", path)
    .attr("stroke",'#999999')
    .attr("stroke-width",'2px')
    .attr("fill",'none')
    .attr("class","country");

var mapLabels = d3.selectAll("#map").select("svg").append("g");
mapLabels.selectAll('text')
    .data(westafrica.features)
    .enter()
    .append("text")
    .attr("x", function(d,i){
                return path.centroid(d)[0]-20;})
    .attr("y", function(d,i){
                return path.centroid(d)[1];})
    .attr("dy", ".55em")
    .attr("class","maplabel")
    .style("font-size","12px")
    .attr("opacity",0.4)
    .text(function(d,i){
        return d.properties.NAME;
    });

<commit_msg>Trying layout adjustments to fit iframe on hi<commit_after>var activity_chart = dc.pieChart("#activity");
var country_chart = dc.pieChart("#country");
var organisation_chart = dc.rowChart("#organisation");
var region_chart = dc.geoChoroplethChart("#map");

var cf = crossfilter(data);

cf.activity = cf.dimension(function(d){ return d.Activity; });
cf.country = cf.dimension(function(d){ return d.Country; });
cf.organisation = cf.dimension(function(d){ return d.Organisation; });
cf.region = cf.dimension(function(d){ return d.Region; });

var activity = cf.activity.group();
var country = cf.country.group();
var organisation = cf.organisation.group();
var region = cf.region.group();
var all = cf.groupAll();

activity_chart.width(250).height(250)
        .dimension(cf.activity)
        .group(activity)
        .colors(['#ffe082',
                 '#ffd54f',
                 '#ffca28',
                 '#ffc107',
                 '#ffb300',
                 '#ffa000',
                 '#ff8f00',
                 '#ff6f00'
            ])
        .colorDomain([1,8])
        .colorAccessor(function(d, i){return i%7+1;});

country_chart.width(250).height(250)
        .dimension(cf.country)
        .group(country)
        .colors(['#0d5302',
                 '#0a7e07',
                 '#259b24',
                 '#42bd41'
            ])
        .colorDomain([0,4])
        .colorAccessor(function(d, i){return i%4;});

organisation_chart.width(300).height(600)
        .dimension(cf.organisation)
        .group(organisation)
        .elasticX(true)
        .data(function(group) {
            return group.top(20);
        })
        .colors(['#81d4fa',
                 '#4fc3f7',
                 '#29b6f6',
                 '#03a9f4',
                 '#039be5',
                 '#0288d1',
                 '#0277bd',
                 '#01579b'
            ])
        .colorDomain([0,8])
        .colorAccessor(function(d, i){return i%8;});

dc.dataCount("#count-info")
	.dimension(cf)
	.group(all);

region_chart.width(400).height(350)
        .dimension(cf.region)
        .group(region)
        .colors(['#DDDDDD', '#e51c23'])
        .colorDomain([0, 1])
        .colorAccessor(function (d) {
            if(d>0){
                return 1;
            } else {
                return 0;
            }
        })
        .overlayGeoJson(regions.features, "Regions", function (d) {
            return d.properties.NAME_REF;
        })
        .projection(d3.geo.mercator().center([-4,6.5]).scale(2200))
        .title(function(d){
            return d.key;
        });
dc.renderAll();

var projection = d3.geo.mercator()
    .center([-4,6.5])
    .scale(2200);

var path = d3.geo.path()
    .projection(projection);

var g = d3.selectAll("#map").select("svg").append("g");

g.selectAll("path")
    .data(westafrica.features)
    .enter()
    .append("path")
    .attr("d", path)
    .attr("stroke",'#999999')
    .attr("stroke-width",'2px')
    .attr("fill",'none')
    .attr("class","country");

var mapLabels = d3.selectAll("#map").select("svg").append("g");
mapLabels.selectAll('text')
    .data(westafrica.features)
    .enter()
    .append("text")
    .attr("x", function(d,i){
                return path.centroid(d)[0]-20;})
    .attr("y", function(d,i){
                return path.centroid(d)[1];})
    .attr("dy", ".55em")
    .attr("class","maplabel")
    .style("font-size","12px")
    .attr("opacity",0.4)
    .text(function(d,i){
        return d.properties.NAME;
    });

<|endoftext|>


<commit_before>/*function hxlProxyToJSON(input){
    var output = [];
    var keys=[]
    input.forEach(function(e,i){
        if(i==0){
            keys = e;
        } else {
            var row = {};
            e.forEach(function(e2,i2){
                row[keys[i2]] = e2;
            });
            output.push(row);
        }
    });
    return output;
}*/

//function to construct hxlprxy URL

function constructHXLURL(linkList){
    var url = 'http://beta.proxy.hxlstandard.org/data.csv?filter_count=7&url=';
    linkList.forEach(function(l,i){
        if(i==0){
            url+=l+'&format=html';
        }
        if(i==1){
            url+='&filter01=append&append-dataset01-01='+l;
        }
        if(i>1 && 1<10){
            url+='&append-dataset01-0'+i+'='+l;
        }
        if(i>1 && 1<10){
            url+='&append-dataset01-'+i+'='+l;
        }
    });
    url += '&filter02=replace-map&replace-map-url02=https://docs.google.com/spreadsheets/d/12TdWAO9BmavBkGEM-7hPV7IMjN_EOJY_2iGnW_ezjuk/pub?gid=493036357&single=true&output=csv7&filter03=merge&merge-url03=https%3A%2F%2Fdocs.google.com%2Fspreadsheets%2Fd%2F12TdWAO9BmavBkGEM-7hPV7IMjN_EOJY_2iGnW_ezjuk%2Fpub%3Foutput%3Dcsv&merge-tags03=country%2Bcode&merge-keys03=country';
    // &filter03=merge&merge-url03=https%3A%2F%2Fdocs.google.com%2Fspreadsheets%2Fd%2F1S9umNUolP-u_R7FYNOdHZM-g8PUcAC1xq7Y8-48bArg%2Fpub%3Fgid%3D0%26single%3Dtrue%26output%3Dcsv&merge-tags03=meta%2Bid%2Cadm3%2Bcode%2Cindicator%2Bpriority&merge-keys03=adm3%2Bname&filter04=merge&merge-url04=https%3A%2F%2Fdocs.google.com%2Fspreadsheets%2Fd%2F1S9umNUolP-u_R7FYNOdHZM-g8PUcAC1xq7Y8-48bArg%2Fpub%3Fgid%3D1687445680%26single%3Dtrue%26output%3Dcsv&merge-tags04=adm4%2Bcode&merge-keys04=adm3%2Bcode%2Cadm4%2Bname';
    return url;
}

var url = constructHXLURL(sheets);

console.log(url);

var html = 'Download complete data set: Download CSV';

$('#completedownload').html(html);

var hxlProxyURL = url.replace('/data.csv?','/data/edit?');

var html = 'HXL Proxy Editor: Editor';

$('#hxlproxyeditor').html(html);

/*var districtURL = url+'&filter05=count&count-tags05=%23adm3%2Bname%2C%23org%2Bpns%2C%23sector%2C%23indicator%2Bconfirmedvdc&count-aggregate-tag05=&filter06=sort&sort-tags06=%23adm3%2Bname';

var html = 'Download district Overview: Download CSV';

$('#district').html(html);*/

var html = 'Data quality dashboard';

$('#dataquality').html(html);

$('#updatedownloadbutton').click(function(){
    $('#updatedownload').html('Updating');
    $.ajax(url+'&force=1', {
            success: function(data) {
                $('#updatedownload').html('Updated');
            },
            error: function(e,err) {
                $('#updatedownload').html('Bad Update');
            }
    });
});

/*$('#updatedistrictbutton').click(function(){
    $('#updatedistrict').html('Updating...');
    $.ajax(districtURL+'&force=1', {
            success: function(data) {
                $('#updatedistrict').html('Updated');
            },
            error: function(e,err) {
                $('#updatedistrict').html('Bad Update');
            }
    });
});
*/
<commit_msg>removed redundant code<commit_after>//function to construct hxlprxy URL

function constructHXLURL(linkList){
    var url = 'http://beta.proxy.hxlstandard.org/data.csv?filter_count=7&url=';
    linkList.forEach(function(l,i){
        if(i==0){
            url+=l+'&format=html';
        }
        if(i==1){
            url+='&filter01=append&append-dataset01-01='+l;
        }
        if(i>1 && 1<10){
            url+='&append-dataset01-0'+i+'='+l;
        }
        if(i>1 && 1<10){
            url+='&append-dataset01-'+i+'='+l;
        }
    });
    url += '&filter02=replace-map&replace-map-url02=https://docs.google.com/spreadsheets/d/12TdWAO9BmavBkGEM-7hPV7IMjN_EOJY_2iGnW_ezjuk/pub?gid=493036357&single=true&output=csv7&filter03=merge&merge-url03=https%3A%2F%2Fdocs.google.com%2Fspreadsheets%2Fd%2F12TdWAO9BmavBkGEM-7hPV7IMjN_EOJY_2iGnW_ezjuk%2Fpub%3Foutput%3Dcsv&merge-tags03=country%2Bcode&merge-keys03=country';
    return url;
}

var url = constructHXLURL(sheets);

console.log(url);

var html = 'Download complete data set: Download CSV';

$('#completedownload').html(html);

var hxlProxyURL = url.replace('/data.csv?','/data/edit?');

var html = 'HXL Proxy Editor: Editor';

$('#hxlproxyeditor').html(html);

var html = 'Data quality dashboard';

$('#dataquality').html(html);

$('#updatedownloadbutton').click(function(){
    $('#updatedownload').html('Updating');
    $.ajax(url+'&force=1', {
            success: function(data) {
                $('#updatedownload').html('Updated');
            },
            error: function(e,err) {
                $('#updatedownload').html('Bad Update');
            }
    });
});
<|endoftext|>


<commit_before>// get a random integer between a and b
function randint(a, b) {
    return Math.floor(Math.random() * (b - a + 1) + a, 10);
}

$(document).ready(function() {
    // load preferences
    if (!localStorage.pref_range) { localStorage.pref_range = 1; }
    if (!localStorage.pref_hork) { localStorage.pref_hork = "h"; }
    if (!localStorage.pref_direction) { localStorage.pref_direction = "kanalatin"; }

    // init
    on_range_update();
    on_hork_update();
    on_direction_update();
    randomize();

    function randomize() {
        kana_range = localStorage.pref_range * 5;

        id_array = new Array;
        id_pointer = 0;
        for (var array_i = 0, kana_i = 0; kana_i < kana_range; kana_i++) {
            if (hs[kana_i] && hs[kana_i][0] != '(') {
                id_array[array_i++] = kana_i;
            }
        }
        id_array.sort(function() { return 0.5 - Math.random(); });
    }

    var prev_hork;
    function get_next() {
        $("#select button.option.green").addClass("blue");
        $("#select button.option.red").addClass("blue");
        $("#select button.option.green").removeClass("green");
        $("#select button.option.red").removeClass("red");
        $("#next").html("?");
        $("#next").attr("data-state", "ask");

        var kana_id = id_array[id_pointer++];
        if (kana_id === undefined) {
            randomize();
            kana_id = id_array[id_pointer++];
        }

        if (localStorage.pref_hork == "h") {
            hork = "h";
        }
        else if (localStorage.pref_hork == "k") {
            hork = "k";
        }
        else {
            hork = (prev_hork == "h") ? "k" : "h";
            prev_hork = hork;
        }

        if (localStorage.pref_direction == "kanalatin") {
            ch = (hork == "h") ? hs[kana_id] : ks[kana_id];
        }
        else {
            ch = ls[kana_id];
        }
        $("#kana").html(ch);

        // place options
        var which_right = randint(0, 3);
        $("#next").attr("data-right", which_right);
        if (localStorage.pref_direction == "kanalatin") {
            right_ch = ls[kana_id];
        }
        else {
            right_ch = (hork == "h") ? hs[kana_id] : ks[kana_id];
        }
        $($("#select button")[which_right]).html(right_ch);

        var used_id = [kana_id];
        for (var i = 0; i <= 3; i++) {
            if (i == which_right) {
                continue;
            }
            var rand_id = randint(0, kana_range - 1);
            while (used_id.indexOf(rand_id) >= 0 || !ls[rand_id] || ls[rand_id][0] == '(') {
                rand_id = randint(0, kana_range - 1);
            }
            used_id.push(rand_id);
            if (localStorage.pref_direction == "kanalatin") {
                option_ch = ls[rand_id];
            }
            else {
                option_ch = (hork == "h") ? hs[rand_id] : ks[rand_id];
            }
            $($("#select button")[i]).html(option_ch);
        }
    }

    function on_range_update() {
        var range = localStorage.pref_range;
        var range_text = 'あ-' + hs[(range - 1) * 5];
        $("#pref-range-text").html(range_text);
        reset_counter();
        randomize();
        get_next();
    }

    function on_hork_update() {
        var selector_this = "#pref-hork button[data-hork=" + localStorage.pref_hork + "]";
        $("#pref-hork button.active").addClass("not-active").removeClass("active");
        $(selector_this).addClass("active").removeClass("not-active");
        reset_counter();
        randomize();
        get_next();
    }

    function on_direction_update() {
        var selector_this = "#pref-direction button[data-direction=" + localStorage.pref_direction + "]";
        $("#kana").attr("lang", $(selector_this).attr("data-main-display"));

        $("#pref-direction button.active").addClass("not-active").removeClass("active");
        $(selector_this).addClass("active").removeClass("not-active");

        reset_counter();
        randomize();
        get_next();
    }

    function reset_counter() {
        $("#counter-ac").html("0");
        $("#counter-total").html("0");
        $("#counter").hide();
    }

    $("#next").click(function() {
        if ($(this).attr("data-state") == "ask") {
            $("#counter").show();
            $("#counter-total").html(parseInt($("#counter-total").html()) + 1);
            var which_right = $(this).attr("data-right");
            $($("#select button")[which_right]).removeClass("blue");
            $($("#select button")[which_right]).addClass("green");
            $(this).html("→");
            $(this).attr("data-state", "next");
        }
        else if ($(this).attr("data-state") == "next") {
            get_next();
        }
    });

    $(".option").click(function() {
        $("#counter").show();
        if ($("#next").attr("data-state") == "ask") {
            // first click on the option
            $("#counter-total").html(parseInt($("#counter-total").html()) + 1);
        }
        var which_right = $("#next").attr("data-right");
        if ($(this).attr("data-id") == which_right) {
            if ($("#next").attr("data-state") == "ask") {
                // first click on the option
                $("#counter-ac").html(parseInt($("#counter-ac").html()) + 1);
            }
            get_next();
        }
        else {
            $("#next").html("→");
            $("#next").attr("data-state", "next");
            $(this).removeClass("blue");
            $(this).addClass("red");
            $($("#select button")[which_right]).removeClass("blue");
            $($("#select button")[which_right]).addClass("green");
        }
    });

    $("#pref-range-decrease").click(function() {
        if (localStorage.pref_range <= 1) {
            return;
        }
        localStorage.pref_range -= 1;
        on_range_update();
    });
    $("#pref-range-increase").click(function() {
        if (localStorage.pref_range >= total_line) {
            return;
        }
        localStorage.pref_range += 1;
        on_range_update();
    });

    // `hork` means `hiragana or katakana`.
    $("#pref-hork button").click(function() {
        localStorage.pref_hork = $(this).attr("data-hork");
        on_hork_update();
    });

    $("#pref-direction button").click(function() {
        localStorage.pref_direction = $(this).attr("data-direction");
        on_direction_update();
    });

    get_next();
});<commit_msg>Fixed another bug- -.<commit_after>// get a random integer between a and b
function randint(a, b) {
    return Math.floor(Math.random() * (b - a + 1) + a, 10);
}

$(document).ready(function() {
    // load preferences
    if (!localStorage.pref_range) { localStorage.pref_range = 1; }
    if (!localStorage.pref_hork) { localStorage.pref_hork = "h"; }
    if (!localStorage.pref_direction) { localStorage.pref_direction = "kanalatin"; }

    // init
    on_range_update();
    on_hork_update();
    on_direction_update();
    randomize();

    function randomize() {
        kana_range = parseInt(localStorage.pref_range) * 5;

        id_array = new Array;
        id_pointer = 0;
        for (var array_i = 0, kana_i = 0; kana_i < kana_range; kana_i++) {
            if (hs[kana_i] && hs[kana_i][0] != '(') {
                id_array[array_i++] = kana_i;
            }
        }
        id_array.sort(function() { return 0.5 - Math.random(); });
    }

    var prev_hork;
    function get_next() {
        $("#select button.option.green").addClass("blue");
        $("#select button.option.red").addClass("blue");
        $("#select button.option.green").removeClass("green");
        $("#select button.option.red").removeClass("red");
        $("#next").html("?");
        $("#next").attr("data-state", "ask");

        var kana_id = id_array[id_pointer++];
        if (kana_id === undefined) {
            randomize();
            kana_id = id_array[id_pointer++];
        }

        if (localStorage.pref_hork == "h") {
            hork = "h";
        }
        else if (localStorage.pref_hork == "k") {
            hork = "k";
        }
        else {
            hork = (prev_hork == "h") ? "k" : "h";
            prev_hork = hork;
        }

        if (localStorage.pref_direction == "kanalatin") {
            ch = (hork == "h") ? hs[kana_id] : ks[kana_id];
        }
        else {
            ch = ls[kana_id];
        }
        $("#kana").html(ch);

        // place options
        var which_right = randint(0, 3);
        $("#next").attr("data-right", which_right);
        if (localStorage.pref_direction == "kanalatin") {
            right_ch = ls[kana_id];
        }
        else {
            right_ch = (hork == "h") ? hs[kana_id] : ks[kana_id];
        }
        $($("#select button")[which_right]).html(right_ch);

        var used_id = [kana_id];
        for (var i = 0; i <= 3; i++) {
            if (i == which_right) {
                continue;
            }
            var rand_id = randint(0, kana_range - 1);
            while (used_id.indexOf(rand_id) >= 0 || !ls[rand_id] || ls[rand_id][0] == '(') {
                rand_id = randint(0, kana_range - 1);
            }
            used_id.push(rand_id);
            if (localStorage.pref_direction == "kanalatin") {
                option_ch = ls[rand_id];
            }
            else {
                option_ch = (hork == "h") ? hs[rand_id] : ks[rand_id];
            }
            $($("#select button")[i]).html(option_ch);
        }
    }

    function on_range_update() {
        var range = parseInt(localStorage.pref_range);
        var range_text = 'あ-' + hs[(range - 1) * 5];
        $("#pref-range-text").html(range_text);
        reset_counter();
        randomize();
        get_next();
    }

    function on_hork_update() {
        var selector_this = "#pref-hork button[data-hork=" + localStorage.pref_hork + "]";
        $("#pref-hork button.active").addClass("not-active").removeClass("active");
        $(selector_this).addClass("active").removeClass("not-active");
        reset_counter();
        randomize();
        get_next();
    }

    function on_direction_update() {
        var selector_this = "#pref-direction button[data-direction=" + localStorage.pref_direction + "]";
        $("#kana").attr("lang", $(selector_this).attr("data-main-display"));

        $("#pref-direction button.active").addClass("not-active").removeClass("active");
        $(selector_this).addClass("active").removeClass("not-active");

        reset_counter();
        randomize();
        get_next();
    }

    function reset_counter() {
        $("#counter-ac").html("0");
        $("#counter-total").html("0");
        $("#counter").hide();
    }

    $("#next").click(function() {
        if ($(this).attr("data-state") == "ask") {
            $("#counter").show();
            $("#counter-total").html(parseInt($("#counter-total").html()) + 1);
            var which_right = $(this).attr("data-right");
            $($("#select button")[which_right]).removeClass("blue");
            $($("#select button")[which_right]).addClass("green");
            $(this).html("→");
            $(this).attr("data-state", "next");
        }
        else if ($(this).attr("data-state") == "next") {
            get_next();
        }
    });

    $(".option").click(function() {
        $("#counter").show();
        if ($("#next").attr("data-state") == "ask") {
            // first click on the option
            $("#counter-total").html(parseInt($("#counter-total").html()) + 1);
        }
        var which_right = $("#next").attr("data-right");
        if ($(this).attr("data-id") == which_right) {
            if ($("#next").attr("data-state") == "ask") {
                // first click on the option
                $("#counter-ac").html(parseInt($("#counter-ac").html()) + 1);
            }
            get_next();
        }
        else {
            $("#next").html("→");
            $("#next").attr("data-state", "next");
            $(this).removeClass("blue");
            $(this).addClass("red");
            $($("#select button")[which_right]).removeClass("blue");
            $($("#select button")[which_right]).addClass("green");
        }
    });

    $("#pref-range-decrease").click(function() {
        if (parseInt(localStorage.pref_range) <= 1) {
            return;
        }
        localStorage.pref_range = parseInt(localStorage.pref_range) - 1;
        on_range_update();
    });
    $("#pref-range-increase").click(function() {
        if (parseInt(localStorage.pref_range) >= total_line) {
            return;
        }
        localStorage.pref_range = parseInt(localStorage.pref_range) + 1;
        on_range_update();
    });

    // `hork` means `hiragana or katakana`.
    $("#pref-hork button").click(function() {
        localStorage.pref_hork = $(this).attr("data-hork");
        on_hork_update();
    });

    $("#pref-direction button").click(function() {
        localStorage.pref_direction = $(this).attr("data-direction");
        on_direction_update();
    });

    get_next();
});<|endoftext|>


<commit_before>  var tempArray = [];

tempArray.length = 20;
for (var i = 0; i < tempArray.length; i++) {
  tempArray[i] = new Array(8);
}

console.log(tempArray);

var tileArray = new Array(5);

for (i = 0; i < 5; i++) {
  for (j = 0; j < 5; j++) {
    tileArray[i][j] = String(i) + "/" + String(j);
  }
}

<commit_msg>deleted test.js<commit_after><|endoftext|>