<commit_before>// Main function run on document load
$(function() {

  $(document)
    // Handle form submit by sending message to mbuilder
    .on('submit', 'form', function(evt) {
      evt.preventDefault();
      submitForm();
    })
    // Reload locations on change of password
    .on('change', '#password', function(evt) {
      loadFromMbuilder();
    })
    // or on manual reload
    .on('click', '.reload-dropdown', function(evt) {
      evt.preventDefault();
      loadFromMbuilder();
    })
    // Clear form when clear button is clicked
    .on('click', '#clear', function(evt) {
      evt.preventDefault();
      // Clear form here!
      $('#password').text('');
      $('#location').text('');
      $('#role').text('');
      $('#message').text('');
    });

  // Also try to load if password is filled by browser
  window.setTimeout(function() {
    loadFromMbuilder();
  }, 500);

});

// Submits form by sending message to mBuilder
function submitForm() {
  var password = $('#password').val();
  var data = {
    message: $('#message').val(),
    location: $('#location').val(),
    role: $('#role').val()
    lang:$('#lang').val()
  };

  var url = MBUILDER_URL
    + 'external/application/' + MBUILDER_APP_ID
    + '/trigger/' + MBUILDER_TRIGGER
    + '?' + $.param(data);

  confirmSubmit(data, url, password);
};

// Loads contacts table in mbuilder
function loadFromMbuilder() {
  var password = $('#password').val();
  if (password == '') return;

  var url = MBUILDER_URL + 'api/applications/' + MBUILDER_APP_ID + '/tables/' + MBUILDER_CONTACTS_TABLE;
  $.ajax({
    url: url,
    type: "GET",
    dataType: 'json',
    headers: {
      "Authorization": "Basic " + btoa(USERNAME + ":" + password)
    },
    success: function(contacts) {
      extractAndLoad(contacts, 'Location', $('#location'));
      extractAndLoad(contacts, 'Role', $('#role'));
      extractAndLoad(contacts, 'Language', $('#lang'));
    }
  });
};

function extractAndLoad(contacts, field, dropdown) {
  var items = _.pluck(contacts, field).sort();
  items = _.uniq(items, true);
  dropdown.empty();
  _.each(items, function(item) {
    $('<option>' + item + '</option>').appendTo(dropdown);
  });
};

// Confirmation before submitting the message
function confirmSubmit(data,url,password){
  $("#response-message").text('Are you sure you want to send the message?');
  $("#dialog-confirm").dialog({
    resizable: false,
    height:180,
    modal: true,
    buttons: {
      "Ok": function() {
        ajaxSubmit(data,url,password);
      },
      "Cancel":function(){
        $(this).dialog("close");
      }
    }
  });
}

//Ajax submit
function ajaxSubmit(data,url,password) {
  $.ajax({
    url: url,
    type: "POST",
    dataType: 'json',
    contentType: 'text/plain',
    content: '',
    xhrFields: {
      withCredentials: false
    },
    headers: {
      "Authorization": "Basic " + btoa(USERNAME + ":" + password)
    },
    success: function(data) {
      //$('#message').val('');
      $('#response-message').text(data.length+" messages have been sent sucessfully!");
      $("#dialog-confirm").dialog({
        resizable: false,
        height:180,
        modal: true,
        buttons: {
          "Ok": function() {
            $(this).dialog("close");
          }
        }
      });
    },
    error: function(err) {
      console.log(err);
      $('#response-message').text('Submit failed. Your password/username is incorrect.');
      $("#dialog-confirm").dialog({
        resizable: false,
        height:180,
        modal: true,
        buttons: {
          "Ok": function() {
            $(this).dialog("close");
          }
        }
      });
    }
  });
};

<commit_msg>commit<commit_after>// Main function run on document load
$(function() {

  $(document)
    // Handle form submit by sending message to mbuilder
    .on('submit', 'form', function(evt) {
      evt.preventDefault();
      submitForm();
    })
    // Reload locations on change of password
    .on('change', '#password', function(evt) {
      loadFromMbuilder();
    })
    // or on manual reload
    .on('click', '.reload-dropdown', function(evt) {
      evt.preventDefault();
      loadFromMbuilder();
    })
    // Clear form when clear button is clicked
    .on('click', '#clear', function(evt) {
      evt.preventDefault();
      // Clear form here!
      $('#password').text('');
      $('#location').text('');
      $('#role').text('');
      $('#message').text('');
    });

  // Also try to load if password is filled by browser
  window.setTimeout(function() {
    loadFromMbuilder();
  }, 500);

});

// Submits form by sending message to mBuilder
function submitForm() {
  var password = $('#password').val();
  var data = {
    message: $('#message').val(),
    location: $('#location').val(),
    role: $('#role').val(),
    lang:$('#lang').val()
  };

  var url = MBUILDER_URL
    + 'external/application/' + MBUILDER_APP_ID
    + '/trigger/' + MBUILDER_TRIGGER
    + '?' + $.param(data);

  confirmSubmit(data, url, password);
};

// Loads contacts table in mbuilder
function loadFromMbuilder() {
  var password = $('#password').val();
  if (password == '') return;

  var url = MBUILDER_URL + 'api/applications/' + MBUILDER_APP_ID + '/tables/' + MBUILDER_CONTACTS_TABLE;
  $.ajax({
    url: url,
    type: "GET",
    dataType: 'json',
    headers: {
      "Authorization": "Basic " + btoa(USERNAME + ":" + password)
    },
    success: function(contacts) {
      extractAndLoad(contacts, 'Location', $('#location'));
      extractAndLoad(contacts, 'Role', $('#role'));
      extractAndLoad(contacts, 'Language', $('#lang'));
    }
  });
};

function extractAndLoad(contacts, field, dropdown) {
  var items = _.pluck(contacts, field).sort();
  items = _.uniq(items, true);
  dropdown.empty();
  _.each(items, function(item) {
    $('<option>' + item + '</option>').appendTo(dropdown);
  });
};

// Confirmation before submitting the message
function confirmSubmit(data,url,password){
  $("#response-message").text('Are you sure you want to send the message?');
  $("#dialog-confirm").dialog({
    resizable: false,
    height:180,
    modal: true,
    buttons: {
      "Ok": function() {
        ajaxSubmit(data,url,password);
      },
      "Cancel":function(){
        $(this).dialog("close");
      }
    }
  });
}

//Ajax submit
function ajaxSubmit(data,url,password) {
  $.ajax({
    url: url,
    type: "POST",
    dataType: 'json',
    contentType: 'text/plain',
    content: '',
    xhrFields: {
      withCredentials: false
    },
    headers: {
      "Authorization": "Basic " + btoa(USERNAME + ":" + password)
    },
    success: function(data) {
      //$('#message').val('');
      $('#response-message').text(data.length+" messages have been sent sucessfully!");
      $("#dialog-confirm").dialog({
        resizable: false,
        height:180,
        modal: true,
        buttons: {
          "Ok": function() {
            $(this).dialog("close");
          }
        }
      });
    },
    error: function(err) {
      console.log(err);
      $('#response-message').text('Submit failed. Your password/username is incorrect.');
      $("#dialog-confirm").dialog({
        resizable: false,
        height:180,
        modal: true,
        buttons: {
          "Ok": function() {
            $(this).dialog("close");
          }
        }
      });
    }
  });
};

<|endoftext|>


<commit_before>var SLIDING_DURATION = 100;

var tiles;
var tileHeight, tileWidth;

var generateGrid = function(width, height, columns, rows) {

    // Clear grid before generating new one
    $grid = $('#shufflegrid');
    $grid.empty();
    tiles = [];

    // Tile heights and widths include everything (border, padding, width)
    tileWidth = Math.floor(width/columns);
    tileHeight = Math.floor(height/rows);

    // The width and heigh parameters are the desired height and width only,
    // actual height and width may vary to eliminate gaps.
    var gridWidth = tileWidth*columns;
    var gridHeight = tileHeight*rows;

    console.log(gridWidth, gridHeight, tileWidth, tileHeight);

    // Set the new dimensions of the grid
    $grid.css("width", gridWidth);
    $grid.css("height", gridHeight);

    // Generate grid and tiles
    for (var y=0; y<rows; y++) {
        tiles[y] = [];
        for (var x=0; x<columns; x++) {
            if (x===columns-1 && y===rows-1) {  // if this is the final cell
                tiles[y][x] = null;  //TODO don't use null, use hidden tile instead
            } else {
                var $tile = $('

');

                // Set tile position
                $tile.css("top", y*tileHeight);
                $tile.css("left", x*tileWidth);

                // Set tile dimensions (the -2 is for the 1px border/margin)
                $tile.css("width", tileWidth-2);
                $tile.css("height", tileHeight-2);

                // Set the "correct position" of the tile when checking if solved
                $tile.data("x", x);
                $tile.data("y", y);

                // Set the background image (clipped)
                $tile.css("background-image", "url(images/Ammonite.gif)");
                $tile.css("background-size", gridWidth+"px "+gridHeight+"px");
                $tile.css("background-repeat", "no-repeat");  //TODO is this necessary?
                $tile.css("background-position", (-1*tileWidth*x-1)+"px "+(-1*tileHeight*y-1)+"px");

                $grid.append($tile);
                tiles[y][x] = $tile;
            }
        }
    }

    // Setup triggers for clicking on tiles
    $('.tile').click(function() {
        tryMoveTile($(this));
    });

};

var tryMoveTile = function($tile) {
    if ($tile === null) return;

    // Get x and y positions of this tile and the empty tile
    for (var y=0; y<tiles.length; y++) {
        for (var x=0; x<tiles[0].length; x++) {
            if (tiles[y][x]===null) {
                var emptyx = x, emptyy = y;
            } else if (tiles[y][x].data("x")===$tile.data("x") &&
                       tiles[y][x].data("y")===$tile.data("y")) {
                var thisx = x, thisy = y;
            }
        }
    }

    var animation = null;
    // Check if tile is in a movable position
    if (thisx===emptyx && thisy-emptyy===1) {  // Move this tile up
        animation = { top: "-="+tileHeight };
    } else if (thisx===emptyx && thisy-emptyy===-1) {  // Move this tile down
        animation = { top: "+="+tileHeight };
    } else if (thisx-emptyx===1 && thisy===emptyy) {  // Move this tile left
        animation = { left: "-="+tileWidth };
    } else if (thisx-emptyx===-1 && thisy===emptyy) {  // Move this tile right
        animation = { left: "+="+tileWidth };
    }

    // Move the tile
    // TODO: make animation synchronous using callbacks
    if (animation !== null) {
        $tile.animate(animation, SLIDING_DURATION);
        tiles[emptyy][emptyx] = tiles[thisy][thisx];
        tiles[thisy][thisx] = null;
    }

    console.log(isSolved());
    return animation !== null;
}

var randomShuffle = function(numMoves) {
    // Randomly select any tile from the grid and try to move it, only continue if a tile was actually moved
    for (var i=0; i<numMoves;) {
        var randomTile = tiles[Math.floor(Math.random()*tiles.length)][Math.floor(Math.random()*tiles[0].length)];
        if (tryMoveTile(randomTile)) i++;
    }
}

var isSolved = function() {
    // For all tiles in the tiles array, check that their actual position matches their creation position
    //TODO prevent moving a tile back to where it was immediately before
    for (var y=0; y<tiles.length; y++) {
        for (var x=0; x<tiles[0].length; x++) {
            if (tiles[y][x] !== null && (tiles[y][x].data("x") !== x || tiles[y][x].data("y") !== y))
                return false;
        }
    }
    return true;
}

$(document).ready(function() {

    // Setup initial grid
    generateGrid(300, 300, 3, 3);

    //TODO number of shuffles needs to be different depending on grid size
    randomShuffle(50);

});
<commit_msg>Empty tile can be placed anywhere<commit_after>var SLIDING_DURATION = 100;

var currentLevel;

var tiles;
var tileHeight, tileWidth;

var generateGrid = function(width, height, columns, rows, emptyx, emptyy) {

    // Clear grid before generating new one
    $grid = $('#shufflegrid');
    $grid.empty();
    tiles = [];

    // Tile heights and widths include everything (border, padding, width)
    tileWidth = Math.floor(width/columns);
    tileHeight = Math.floor(height/rows);

    // The width and heigh parameters are the desired height and width only,
    // actual height and width may vary to eliminate gaps.
    var gridWidth = tileWidth*columns;
    var gridHeight = tileHeight*rows;

    // Set the new dimensions of the grid
    $grid.css("width", gridWidth);
    $grid.css("height", gridHeight);

    // Check empty tile position is valid, if not use last tile
    if (emptyx<0 || emptyy<0 || emptyx>columns-1 || emptyy>rows-1) {
        emptyx = columns-1;
        emptyy = rows-1;
    }

    // Generate grid and tiles
    for (var y=0; y<rows; y++) {
        tiles[y] = [];
        for (var x=0; x<columns; x++) {
            if (x===emptyx && y===emptyy) {
                tiles[y][x] = null;  //TODO don't use null, use hidden tile instead
            } else {
                var $tile = $('

');

                // Set tile position
                $tile.css("top", y*tileHeight);
                $tile.css("left", x*tileWidth);

                // Set tile dimensions (the -2 is for the 1px border/margin)
                $tile.css("width", tileWidth-2);
                $tile.css("height", tileHeight-2);

                // Set the "correct position" of the tile when checking if solved
                $tile.data("x", x);
                $tile.data("y", y);

                // Set the background image (clipped)
                $tile.css("background-image", "url(images/Ammonite.gif)");
                $tile.css("background-size", gridWidth+"px "+gridHeight+"px");
                $tile.css("background-repeat", "no-repeat");  //TODO is this necessary?
                $tile.css("background-position", (-1*tileWidth*x-1)+"px "+(-1*tileHeight*y-1)+"px");

                $grid.append($tile);
                tiles[y][x] = $tile;
            }
        }
    }

    // Setup triggers for clicking on tiles
    $('.tile').click(function() {
        tryMoveTile($(this));
    });

};

var tryMoveTile = function($tile) {
    if ($tile === null) return;

    // Get x and y positions of this tile and the empty tile
    for (var y=0; y<tiles.length; y++) {
        for (var x=0; x<tiles[0].length; x++) {
            if (tiles[y][x]===null) {
                var emptyx = x, emptyy = y;
            } else if (tiles[y][x].data("x")===$tile.data("x") &&
                       tiles[y][x].data("y")===$tile.data("y")) {
                var thisx = x, thisy = y;
            }
        }
    }

    var animation = null;
    // Check if tile is in a movable position
    if (thisx===emptyx && thisy-emptyy===1) {  // Move this tile up
        animation = { top: "-="+tileHeight };
    } else if (thisx===emptyx && thisy-emptyy===-1) {  // Move this tile down
        animation = { top: "+="+tileHeight };
    } else if (thisx-emptyx===1 && thisy===emptyy) {  // Move this tile left
        animation = { left: "-="+tileWidth };
    } else if (thisx-emptyx===-1 && thisy===emptyy) {  // Move this tile right
        animation = { left: "+="+tileWidth };
    }

    // Move the tile
    // TODO: make animation synchronous using callbacks
    if (animation !== null) {
        $tile.animate(animation, SLIDING_DURATION);
        tiles[emptyy][emptyx] = tiles[thisy][thisx];
        tiles[thisy][thisx] = null;
    }

    console.log(isSolved());
    return animation !== null;
}

var randomShuffle = function(numMoves) {
    // Randomly select any tile from the grid and try to move it, only continue if a tile was actually moved
    for (var i=0; i<numMoves;) {
        var randomTile = tiles[Math.floor(Math.random()*tiles.length)][Math.floor(Math.random()*tiles[0].length)];
        if (tryMoveTile(randomTile)) i++;
    }
}

var isSolved = function() {
    // For all tiles in the tiles array, check that their actual position matches their creation position
    //TODO prevent moving a tile back to where it was immediately before?
    for (var y=0; y<tiles.length; y++) {
        for (var x=0; x<tiles[0].length; x++) {
            if (tiles[y][x] !== null && (tiles[y][x].data("x") !== x || tiles[y][x].data("y") !== y))
                return false;
        }
    }
    return true;
}

$(document).ready(function() {

    // Setup initial grid
    generateGrid(300, 300, 3, 3, 2, 2);

    //TODO number of shuffles needs to be different depending on grid size
    randomShuffle(3);

});
<|endoftext|>


<commit_before>$(document).ready(function() {
	$("button").click(function() {
		console.log("hi!");
	});
});
<commit_msg>use class name in script.js<commit_after>$(document).ready(function() {
	$(".submit-comment-button").click(function() {
		console.log("hi!");
	});
});
<|endoftext|>


<commit_before>var todos = {
  todos: [],
  add: function(text) {
    if (this.valid(text))
      this.todos.push({
        text: text,
        completed: false
      });
    this.persist();
  },
  edit: function(position, text) {
    if (this.valid(text))
      this.todos[position].text = text;
    this.persist();
  },
  destroy: function(position) {
    this.todos.splice(position, 1);
    this.persist();
  },
  toggle: function(position) {
    var todo = this.todos[position];
    todo.completed = !todo.completed;
    this.persist();
  },
  toggleAll: function() {
    var completed = this.completed().length;

    this.todos.forEach((t) => {
      t.completed = !(completed === this.count());
    }, this);
    this.persist();
  },
  left: function() {
    return this.count() - this.completed().length;
  },
  count: function() {
    return this.todos.length;
  },
  completed: function() {
    return this.todos.filter((t) => {
      return t.completed;
    });
  },
  valid: function(text) {
    return text.replace(/\s+/g, '');
  },
  persist: function() {
    localStorage.setItem('data', JSON.stringify(this.todos));
  }
};

var handlers = {
  add: function() {
    var input = document.getElementsByClassName('new-todo')[0];
    todos.add(input.value);
    input.value = '';
    view.update();
  },
  edit: function(position, text) {
    todos.edit(position, text);
    view.update();
  },
  destroy: function(position) {
    todos.destroy(position);
    view.update();
  },
  toggle: function(position) {
    todos.toggle(position);
    view.update();
  },
  toggleAll: function() {
    todos.toggleAll();
    view.update();
  },
};

var view = {
  update: function() {
    this.displayTodos();
    this.createFooter();
  },
  displayTodos: function() {
    var ul = document.querySelector('ul');
    ul.innerHTML = '';

    todos.todos.forEach(function(todo, i) {
      ul.appendChild(this.createListItem(todo, i));
    }, this);
  },
  createFooter: function() {
    var footer = document.querySelector('footer')
    footer.className = 'footer';
    footer.innerHTML = '' + this.countHTML() + '';

    footer.style.display = todos.count() ? 'block' : 'none';
  },
  countHTML: function() {
    var plural = todos.left() == 1 ? '' : 's';
    return '' + todos.left() + ' item' +
      plural + ' left';
  },
  createListItem: function(todo, i) {
    var li = document.createElement('li');
    li.id = i;
    li.className = todo.completed ? 'completed' : '';
    li.appendChild(this.createTodoItem(todo));
    return li;
  },
  createDeleteButton: function() {
    var deleteButton = document.createElement('button');
    deleteButton.className = 'destroy';
    return deleteButton;
  },
  createEditInput: function() {
    var edit = document.createElement('input');
    edit.className = 'edit';

    edit.addEventListener('keyup', (e) => {
      if (e.keyCode == 13) {
        handlers.edit(Number(e.target.parentElement.id), e.target.value);
        edit.parentNode.removeChild(edit);
      }
    });

    return edit;
  },
  createToggle: function() {
    var toggle = document.createElement('input');
    toggle.className = 'toggle';
    toggle.type = 'checkbox';

    toggle.addEventListener('click', function(e) {
      var parent = e.target.parentNode.parentNode;
      var id = parent.id;
      parent.className = parent.className === 'completed' ? '' : 'completed';
      handlers.toggle(Number(id));
    });

    return toggle;
  },
  createTodoItem: function(todo) {
    var div = document.createElement('div');
    div.className = 'view';

    var toggle = this.createToggle();
    toggle.checked = todo.completed;

    var label = document.createElement('label');
    label.textContent = todo.text;

    var edit = this.createEditInput();

    label.addEventListener('dblclick', (e) => {
      var val = e.target.textContent;
      e.target.parentNode.insertAdjacentElement('afterend', edit);
      e.target.parentNode.parentNode.className = 'editing';
      edit.value = val;
      edit.focus();
    });

    div.appendChild(toggle);
    div.appendChild(label);

    div.appendChild(this.createDeleteButton());

    return div;
  },
  setUpEventListeners: function() {
    var todosUl = document.querySelector('ul');
    todosUl.addEventListener('click', (e) => {
      var clickedElement = e.target;
      if (clickedElement.className === 'destroy') {
        handlers.destroy(parseInt(clickedElement.parentNode.id));
      }
    });

    var newTodo = document.getElementsByClassName('new-todo')[0];
    newTodo.addEventListener('keyup', (e) => {
      if (e.keyCode == 13) {
        handlers.add();
      }
    });

    document.addEventListener('click', function(e) {
      var edit = document.getElementsByClassName('edit')[0];
      if (edit && e.target.className !== 'edit') {
        handlers.edit(Number(edit.parentElement.id), edit.value);
        edit.parentNode.removeChild(edit);
      }
    });
  }
};

(function main() {
  view.setUpEventListeners();
  if (localStorage.length) {
    todos.todos = JSON.parse(localStorage.getItem('data'));
    view.update();
  }
})()
<commit_msg>Fix deleting correct item and footer<commit_after>var todos = {
  todos: [],
  add: function(text) {
    if (this.valid(text))
      this.todos.push({
        text: text,
        completed: false
      });
    this.persist();
  },
  edit: function(position, text) {
    if (this.valid(text))
      this.todos[position].text = text;
    this.persist();
  },
  delete: function(position) {
    this.todos.splice(position, 1);
    this.persist();
  },
  toggle: function(position) {
    var todo = this.todos[position];
    todo.completed = !todo.completed;
    this.persist();
  },
  toggleAll: function() {
    var completed = this.completed().length;

    this.todos.forEach((t) => {
      t.completed = !(completed === this.count());
    }, this);
    this.persist();
  },
  left: function() {
    return this.count() - this.completed().length;
  },
  count: function() {
    return this.todos.length;
  },
  completed: function() {
    return this.todos.filter((t) => {
      return t.completed;
    });
  },
  valid: function(text) {
    return text.replace(/\s+/g, '');
  },
  persist: function() {
    localStorage.setItem('data', JSON.stringify(this.todos));
  }
};

var handlers = {
  add: function() {
    var input = document.getElementsByClassName('new-todo')[0];
    todos.add(input.value);
    input.value = '';
    view.update();
  },
  edit: function(position, text) {
    todos.edit(position, text);
    view.update();
  },
  delete: function(position) {
    todos.delete(position);
    view.update();
  },
  toggle: function(position) {
    todos.toggle(position);
    view.update();
  },
  toggleAll: function() {
    todos.toggleAll();
    view.update();
  },
};

var view = {
  update: function() {
    this.displayTodos();
    this.createFooter();
  },
  displayTodos: function() {
    var ul = document.querySelector('ul');
    ul.innerHTML = '';

    todos.todos.forEach(function(todo, i) {
      ul.appendChild(this.createListItem(todo, i));
    }, this);
  },
  createFooter: function() {
    var footer = document.querySelector('footer')
    footer.className = 'footer';
    footer.innerHTML = '' + this.countHTML() + '';

    footer.style.display = todos.count() ? 'block' : 'none';
  },
  countHTML: function() {
    var plural = todos.left() == 1 ? '' : 's';
    return '' + todos.left() + ' item' +
      plural + ' left';
  },
  createListItem: function(todo, i) {
    var li = document.createElement('li');
    li.id = i;
    li.className = todo.completed ? 'completed' : '';
    li.appendChild(this.createTodoItem(todo));
    return li;
  },
  createDeleteButton: function() {
    var deleteButton = document.createElement('button');
    deleteButton.className = 'destroy';
    return deleteButton;
  },
  createEditInput: function() {
    var edit = document.createElement('input');
    edit.className = 'edit';

    edit.addEventListener('keyup', (e) => {
      if (e.keyCode == 13) {
        handlers.edit(Number(e.target.parentElement.id), e.target.value);
        edit.parentNode.removeChild(edit);
      }
    });

    return edit;
  },
  createToggle: function() {
    var toggle = document.createElement('input');
    toggle.className = 'toggle';
    toggle.type = 'checkbox';

    toggle.addEventListener('click', function(e) {
      var parent = e.target.parentNode.parentNode;
      var id = parent.id;
      parent.className = parent.className === 'completed' ? '' : 'completed';
      handlers.toggle(Number(id));
    });

    return toggle;
  },
  createTodoItem: function(todo) {
    var div = document.createElement('div');
    div.className = 'view';

    var toggle = this.createToggle();
    toggle.checked = todo.completed;

    var label = document.createElement('label');
    label.textContent = todo.text;

    var edit = this.createEditInput();

    label.addEventListener('dblclick', (e) => {
      var val = e.target.textContent;
      e.target.parentNode.insertAdjacentElement('afterend', edit);
      e.target.parentNode.parentNode.className = 'editing';
      edit.value = val;
      edit.focus();
    });

    div.appendChild(toggle);
    div.appendChild(label);

    div.appendChild(this.createDeleteButton());

    return div;
  },
  setUpEventListeners: function() {
    var todosUl = document.querySelector('ul');
    todosUl.addEventListener('click', (e) => {
      var clickedElement = e.target;
      if (clickedElement.className === 'destroy') {
        handlers.delete(parseInt(clickedElement.parentNode.parentNode.id));
      }
    });

    var newTodo = document.getElementsByClassName('new-todo')[0];
    newTodo.addEventListener('keyup', (e) => {
      if (e.keyCode == 13) {
        handlers.add();
      }
    });

    document.addEventListener('click', function(e) {
      var edit = document.getElementsByClassName('edit')[0];
      if (edit && e.target.className !== 'edit') {
        handlers.edit(Number(edit.parentElement.id), edit.value);
        edit.parentNode.removeChild(edit);
      }
    });
  }
};

(function main() {
  view.setUpEventListeners();
  if (localStorage.length) {
    todos.todos = JSON.parse(localStorage.getItem('data'));
  }
  view.update();
})();
<|endoftext|>


<commit_before>

var stage;

var renderer;

var Graphics;

requestAnimationFrame( animate );

var lowestUnfilledRow;

var currentplayer;

var messageBoard = "blah blah";

var board;
var tile;

function animate() {
	  requestAnimationFrame( animate );
	  // render the stage

	 renderer.render(stage);

	}

function init(){
    Graphics = PIXI.Graphics;
    // create an new instance of a pixi stage
    stage = new PIXI.Stage(0x66FF99);
    // create a renderer instance
    renderer = PIXI.autoDetectRenderer(640, 500);

    // add the renderer view element to the DOM
    document.getElementById("gameContainer").appendChild(renderer.view);

    lowestUnfilledRow = 5;
    currentplayer = "human";

    // keep another matrix internally to keep track of which cell is set,
    // and by whome and who is the winner etc,. we need a 2 dimention matrix to impliment the logic.
    board = [
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0]
    ];

    //#8, #9 -  create a board with tiles and set click event for each of them.
    for (var i = 6; i >= 0; i--) {
    for (var j = 5; j >= 0; j--) {
    tile = new Graphics();
    tile.beginFill(0xffffff);
    tile.drawRect(110 + 60 * i, 80 + 55 * j, 50, 50);
    tile.endFill();
    tile.buttonMode = true;
    tile.interactive = true;
    tile.val = j + "-" + i;
    tile.on('mousedown', onTilesClick);
    stage.addChild(tile);
    }
    }

}

//#15, #10, #9- finding the bottom most available row and fill a disc.
function onTilesClick(){
        // the val is saved as "rownum - colnum" so split on "-" and get the 1st element , that will be the column.
        var clickedColoumn = Number(this.val.split("-")[1]);
        var rowLength = board.length;
        var rowObj = findEmptyRow(clickedColoumn, rowLength - 1);
        //execute if empty slot present in that coloumn
        if (rowObj.available) {
            var insertionSlot = rowObj.slot + "-" + clickedColoumn;
            // colour the cell with above row and col value.
            for (var i = 0; i < stage.children.length; i++) {
                if (stage.children[i].val !== undefined && stage.children[i].val === insertionSlot) {
                    if(currentplayer == "human")
                    stage.children[i].tint = 0xfff000;
                    else stage.children[i].tint = 0x000fff;

                    // finally update the board matrix for our internal calculation
                    if (rowObj.slot < lowestUnfilledRow) {
                        lowestUnfilledRow = rowObj.slot;
                        }
                    // add some non 0 value to know it's filled
                    board[rowObj.slot][clickedColoumn] = currentplayer;
                    //change the player turn.
                    changePlayer();
                }
            }
        }
        renderer.render(stage);
    }

//#15, #10- finding the bottom most available row and fill a disc.
// search for a empty slot on the board by recurssion.
function findEmptyRow(a, index) {
    if (index === -1) {
        return {
            available: false,
            slot: -1
        }; // No empty slot in the col
    }
    if (board[index][a] === 0) {
        return {
            available: true,
            slot: index
        };
    }
    return findEmptyRow(a, index - 1);
}

// #11, #12 - alternate the player turns
function changePlayer(){
    checkHorizontalConnect();
    checkVerticalConnection();
    checkDiagnolConnection();
    if(currentplayer == "human"){
        currentplayer = "AI";
    }
    else{
        currentplayer = "human";
    }
}

//#17 - check for horizontal connection winner.
function checkHorizontalConnect(){
    for (var i = board.length - 1; i >= lowestUnfilledRow; i--) {
        for (var j = 0; j < board[i].length; j++) {
            //check if the middle col has opposite players number
            var midCol = board[0].length - 4;
            var middleElement = board[i][midCol];
            if (middleElement !== currentplayer || middleElement === 0) {
                //No chance of horizontal match with this condition
                break;
            }
            //Horizontal Checker
            if (currentplayer === board[i][j] &&
                board[i][j] === board[i][j + 1] &&
                board[i][j] === board[i][j + 2] &&
                board[i][j] === board[i][j + 3] &&
                board[i][j + 3] !== undefined) {
                console.log("horizontal connection winner " + currentplayer);
                displayMessage("horizontal connection winner " + currentplayer);
                return true;
            }
        }
    }
}
//#18 -  check for vertical connection winner.
function checkVerticalConnection(){
     for (var i = board.length - 1; i >= lowestUnfilledRow; i--) {
            for (var j = 0; j < board[i].length; j++) {
                if (i - 3 < 0) {
                    break;
                }
                if (currentplayer === board[i][j] &&
                    board[i][j] === board[i - 1][j] &&
                    board[i - 1][j] === board[i - 2][j] &&
                    board[i - 2][j] === board[i - 3][j] &&
                    board[i - 3] !== undefined) {
                    console.log("virtical connection winner "+currentplayer);
                    return true;

                }
            }
        }
}
//#19 - check for diagonal connection winner.
function checkDiagnolConnection(){
    //diagonally towards left
    for (var i = board.length - 1; i >= 3; i--) {
        for (var j = board[i].length - 1; j >= 0; j--) {
            if (board[i - 3] !== undefined &&
            currentplayer === board[i][j] &&
            board[i][j] === board[i - 1][j - 1] &&
            board[i - 1][j - 1] === board[i - 2][j - 2] &&
            board[i - 2][j - 2] === board[i - 3][j - 3]) {
                console.log("left diagnol connect winner "+currentplayer);
                return true;
            }
        }
    }

    //diagonally towards right
    for (var i = board.length - 1; i >= 3; i--) {
        for (var j = 0; j < board[i].length; j++) {
            if (board[i - 3] !== undefined &&
            currentplayer === board[i][j] &&
            board[i][j] === board[i - 1][j + 1] &&
            board[i - 1][j + 1] === board[i - 2][j + 2] &&
            board[i - 2][j + 2] === board[i - 3][j + 3]) {
                console.log("right diagnol connect winner "+currentplayer);
                return true;
            }
        }
    }
}

//#20 - message board to display messages on the game's message board.
function displayMessage(msg){
    document.getElementById("msgBoard").innerHTML = msg;
}

//#13 - reset button to reset the game.
function resetgame(){
    document.getElementById("gameContainer").removeChild(renderer.view);
    displayMessage("");
    init();
}

<commit_msg>intermediate saving changes b4 major restructuring and AI implimentation<commit_after>var stage;
var renderer;
var Graphics;
requestAnimationFrame( animate );
var lowestUnfilledRow;
var currentplayer;
var board;
var tile;
var isCurrentPlayerWon;
var isGameOver;

function animate() {
	  requestAnimationFrame( animate );
	  // render the stage

	 renderer.render(stage);

	}

function init(){
    Graphics = PIXI.Graphics;
    // create an new instance of a pixi stage
    stage = new PIXI.Stage(0x66FF99);
    // create a renderer instance
    renderer = PIXI.autoDetectRenderer(640, 500);

    // add the renderer view element to the DOM
    document.getElementById("gameContainer").appendChild(renderer.view);

    lowestUnfilledRow = 5;
    currentplayer = "human";

    displayMessage("");
    isCurrentPlayerWon = false;
    isGameOver = false;

    // keep another matrix internally to keep track of which cell is set,
    // and by whome and who is the winner etc,. we need a 2 dimention matrix to impliment the logic.
    board = [
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0]
    ];

    //#8, #9 -  create a board with tiles and set click event for each of them.
    for (var i = 6; i >= 0; i--) {
    for (var j = 5; j >= 0; j--) {
    tile = new Graphics();
    tile.beginFill(0xffffff);
    tile.drawRect(110 + 60 * i, 80 + 55 * j, 50, 50);
    tile.endFill();
    tile.buttonMode = true;
    tile.interactive = true;
    tile.val = j + "-" + i;
    tile.on('mousedown', onTilesClick);
    stage.addChild(tile);
    }
    }

}

//#15, #10, #9- finding the bottom most available row and fill a disc.
function onTilesClick(){
        // the val is saved as "rownum - colnum" so split on "-" and get the 1st element , that will be the column.
        var clickedColoumn = Number(this.val.split("-")[1]);
        var rowLength = board.length;
        var rowObj = findEmptyRow(clickedColoumn, rowLength - 1);
        //execute if empty slot present in that coloumn
        if (rowObj.available) {
            var insertionSlot = rowObj.slot + "-" + clickedColoumn;
            // colour the cell with above row and col value.
            for (var i = 0; i < stage.children.length; i++) {
                if (stage.children[i].val !== undefined && stage.children[i].val === insertionSlot) {
                    if(currentplayer == "human")
                    stage.children[i].tint = 0xfff000;
                    else stage.children[i].tint = 0x000fff;

                    // finally update the board matrix for our internal calculation
                    if (rowObj.slot < lowestUnfilledRow) {
                        lowestUnfilledRow = rowObj.slot;
                        }
                    // add some non 0 value to know it's filled
                    board[rowObj.slot][clickedColoumn] = currentplayer;
                    //change the player turn.
                    changePlayer();
                }
            }
        }
        renderer.render(stage);
    }

//#15, #10- finding the bottom most available row and fill a disc.
// search for a empty slot on the board by recurssion.
function findEmptyRow(a, index) {
    if (index === -1) {
        return {
            available: false,
            slot: -1
        }; // No empty slot in the col
    }
    if (board[index][a] === 0) {
        return {
            available: true,
            slot: index
        };
    }
    return findEmptyRow(a, index - 1);
}

// #11, #12 - alternate the player turns
function changePlayer(){
    if(currentplayer == "human"){
        currentplayer = "AI";
    }
    else{
        currentplayer = "human";
    }
}

//#17 - check for horizontal connection winner.
function checkHorizontalConnect(){
    for (var i = board.length - 1; i >= lowestUnfilledRow; i--) {
        for (var j = 0; j < board[i].length; j++) {
            //check if the middle col has opposite players number
            var midCol = board[0].length - 4;
            var middleElement = board[i][midCol];
            if (middleElement !== currentplayer || middleElement === 0) {
                //No chance of horizontal match with this condition
                break;
            }
            //Horizontal Checker
            if (currentplayer === board[i][j] &&
                board[i][j] === board[i][j + 1] &&
                board[i][j] === board[i][j + 2] &&
                board[i][j] === board[i][j + 3] &&
                board[i][j + 3] !== undefined) {
                console.log("horizontal connection winner " + currentplayer);
                //displayMessage("horizontal connection winner " + currentplayer);
                return true;
            }
            else return false;
        }
    }
}
//#18 -  check for vertical connection winner.
function checkVerticalConnection(){
     for (var i = board.length - 1; i >= lowestUnfilledRow; i--) {
            for (var j = 0; j < board[i].length; j++) {
                if (i - 3 < 0) {
                    break;
                }
                if (currentplayer === board[i][j] &&
                    board[i][j] === board[i - 1][j] &&
                    board[i - 1][j] === board[i - 2][j] &&
                    board[i - 2][j] === board[i - 3][j] &&
                    board[i - 3] !== undefined) {
                    console.log("virtical connection winner "+currentplayer);
                    return true;
                }
                else return false;
            }
        }
}
//#19 - check for diagonal connection winner.
function checkDiagnolConnection(){
    //diagonally towards left
    for (var i = board.length - 1; i >= 3; i--) {
        for (var j = board[i].length - 1; j >= 0; j--) {
            if (board[i - 3] !== undefined &&
            currentplayer === board[i][j] &&
            board[i][j] === board[i - 1][j - 1] &&
            board[i - 1][j - 1] === board[i - 2][j - 2] &&
            board[i - 2][j - 2] === board[i - 3][j - 3]) {
                console.log("left diagnol connect winner "+currentplayer);
                return true;
            }
            else return false;
        }
    }

    //diagonally towards right
    for (var i = board.length - 1; i >= 3; i--) {
        for (var j = 0; j < board[i].length; j++) {
            if (board[i - 3] !== undefined &&
            currentplayer === board[i][j] &&
            board[i][j] === board[i - 1][j + 1] &&
            board[i - 1][j + 1] === board[i - 2][j + 2] &&
            board[i - 2][j + 2] === board[i - 3][j + 3]) {
                console.log("right diagnol connect winner "+currentplayer);
                return true;
            }
            else return false;
        }
    }
}

//#20 - message board to display messages on the game's message board.
function displayMessage(msg){
    document.getElementById("msgBoard").innerHTML = msg;
}

//#13 - reset button to reset the game.
function resetgame(){
    document.getElementById("gameContainer").removeChild(renderer.view);
    init();
}

//#21 - check for the winner b4 changing the player
function checkCurrentGameStatus(){
    if( checkHorizontalConnect() ||
    checkVerticalConnection() ||
    checkDiagnolConnection()){
        isGameOver = true;
        displayMessage("Game Over , " + currentplayer+ " is the winner, click 'reset' to play again." );
    }
    else if (checkIfTie()){

    }
}

//#25 - check if game is draw.
function checkIfTie(){
    console.log();
    var rowObj = findEmptyRow(clickedColoumn, rowLength - 1);
 if (lowestUnfilledRow <= board.length - 4) {
}
}<|endoftext|>


<commit_before>/*jslint indent: 4, maxlen: 80 */
/*globals window, document */

(function (win, doc) {
    'use strict';

    var // Constants
        INTERVAL_BIG = 1000,
        INTERVAL_SMALL = INTERVAL_BIG / 3,

        // Variables
        c = win.Circles,
        allCircles,

        // Functions
        debounce,
        makeText,
        makeCircleOptions,
        updateTime,
        onResize;

    allCircles = {
        hours: {
            element: doc.getElementById('hours')
        },
        minutes: {
            element: doc.getElementById('minutes')
        },
        seconds: {
            element: doc.getElementById('seconds')
        }
    };

    // Source: http://goo.gl/c3mZHP
    debounce = function (func, wait) {
        var timeout,
            args,
            context,
            timestamp;

        return function () {
            context = this;
            args = [].slice.call(arguments, 0);
            timestamp = new Date();

            var later = function () {
                var last = (new Date()) - timestamp;

                if (last < wait) {
                    timeout = win.setTimeout(later, wait - last);
                } else {
                    timeout = null;
                    func.apply(context, args);
                }
            };

            if (!timeout) {
                timeout = win.setTimeout(later, wait);
            }
        };
    };

    makeText = function (val) {
        var output = parseInt(val, 10);

        if (output.toString().length === 1) {
            return '0' + output.toString();
        }

        return output;
    };

    makeCircleOptions = function (elementId, maxVal, color) {
        return {
            id: elementId,
            radius: 100,
            maxValue: maxVal,
            duration: null,
            width: 10,
            colors: ['#95a5a6', color],
            text: makeText
        };
    };

    updateTime = function () {
        var currentTime = new Date();

        allCircles.hours.circle.update(currentTime.getHours());
        allCircles.minutes.circle.update(currentTime.getMinutes());
        allCircles.seconds.circle.update(currentTime.getSeconds());
    };

    onResize = debounce(function () {
        Object.keys(allCircles).forEach(function (key) {
            var newWidth = allCircles[key].element.offsetWidth;

            allCircles[key].circle.updateRadius(newWidth / 2);
            allCircles[key].circle.updateWidth(newWidth / 2 * 0.25);
        });
    }, INTERVAL_SMALL);

    (function () {
        allCircles.hours.circle = c.create(
            makeCircleOptions('hours', 24, '#c0392b')
        );
        allCircles.minutes.circle =  c.create(
            makeCircleOptions('minutes', 60, '#d35400')
        );
        allCircles.seconds.circle = c.create(
            makeCircleOptions('seconds', 60, '#f39c12')
        );

        win.setInterval(updateTime, INTERVAL_BIG);
        win.addEventListener('resize', onResize);
        onResize();
    }());
}(window, document));
<commit_msg>Don't wait one second to set the time<commit_after>/*jslint indent: 4, maxlen: 80 */
/*globals window, document */

(function (win, doc) {
    'use strict';

    var // Constants
        INTERVAL_BIG = 1000,
        INTERVAL_SMALL = INTERVAL_BIG / 3,

        // Variables
        c = win.Circles,
        allCircles,

        // Functions
        debounce,
        makeText,
        makeCircleOptions,
        updateTime,
        onResize;

    allCircles = {
        hours: {
            element: doc.getElementById('hours')
        },
        minutes: {
            element: doc.getElementById('minutes')
        },
        seconds: {
            element: doc.getElementById('seconds')
        }
    };

    // Source: http://goo.gl/c3mZHP
    debounce = function (func, wait) {
        var timeout,
            args,
            context,
            timestamp;

        return function () {
            context = this;
            args = [].slice.call(arguments, 0);
            timestamp = new Date();

            var later = function () {
                var last = (new Date()) - timestamp;

                if (last < wait) {
                    timeout = win.setTimeout(later, wait - last);
                } else {
                    timeout = null;
                    func.apply(context, args);
                }
            };

            if (!timeout) {
                timeout = win.setTimeout(later, wait);
            }
        };
    };

    makeText = function (val) {
        var output = parseInt(val, 10);

        if (output.toString().length === 1) {
            return '0' + output.toString();
        }

        return output;
    };

    makeCircleOptions = function (elementId, maxVal, color) {
        return {
            id: elementId,
            radius: 100,
            maxValue: maxVal,
            duration: null,
            width: 10,
            colors: ['#95a5a6', color],
            text: makeText
        };
    };

    updateTime = function () {
        var currentTime = new Date();

        allCircles.hours.circle.update(currentTime.getHours());
        allCircles.minutes.circle.update(currentTime.getMinutes());
        allCircles.seconds.circle.update(currentTime.getSeconds());
    };

    onResize = debounce(function () {
        Object.keys(allCircles).forEach(function (key) {
            var newWidth = allCircles[key].element.offsetWidth;

            allCircles[key].circle.updateRadius(newWidth / 2);
            allCircles[key].circle.updateWidth(newWidth / 2 * 0.25);
        });
    }, INTERVAL_SMALL);

    (function () {
        allCircles.hours.circle = c.create(
            makeCircleOptions('hours', 24, '#c0392b')
        );
        allCircles.minutes.circle =  c.create(
            makeCircleOptions('minutes', 60, '#d35400')
        );
        allCircles.seconds.circle = c.create(
            makeCircleOptions('seconds', 60, '#f39c12')
        );

        onResize();
        updateTime();

        win.addEventListener('resize', onResize);
        win.setInterval(updateTime, INTERVAL_BIG);
    }());
}(window, document));
<|endoftext|>


<commit_before>var Planets = [];
var Particles = [];
var Enemies = [];

//The scrolling background...

var scrollSpeed = 20;
var step = 1;
var current = 0;
var imageWidth = 1000;
var restartWidth = 359;

var restartPosition = -(imageWidth - restartWidth);
function scrollBg(){
	current -= step;
	if (current == restartPosition) {current = 0;}
	$('#background').css("background-position",current+"px 0");
	};

setInterval("scrollBg()", scrollSpeed);

/***************************************************************************/
//Let's make the canvas ready...
$(document).ready(function() {

    var canvas = document.getElementById('background');
    var ctx = canvas.getContext("2d");
    window.addEventListener("keydown",doKeyDown, true);
    var playerX = 50;
    var playerY = 200;
    var playerWidth = 80;
    var playerHeight = 80;
    var playerDead = false;

    //For additional setIntervals...
    var tick1;
    var tick2;
    var tick3;

    //Let's import the sprites
    var cthulhu = new Image();
    cthulhu.src = 'http://i1287.photobucket.com/albums/a632/MrDeltoid/pruitpruit_zpsc847d437.png';
    var unicorn = new Image();
    unicorn.src = 'http://i1287.photobucket.com/albums/a632/MrDeltoid/unicorn1_zps9f61bb5b.png';

    function init() {
        clearBg();
        playerX = 50;
        playerY = 200;
        totalScore.reset();
        currentHealth.reset();
        playerDead = false;
        playerInvulnerable = false;
        setInterval(gameLoop,10);
        setInterval(generatePlanet, 6000);
        setInterval(generateEnemy, 3383);

    }

    function Enemy(posX, posY) {
        this.posX = posX;
        this.posY = posY;
        this.speed = 3;
        this.width = 100;
        this.height = 80;

        this.move = function() {
            this.posX -= this.speed;
            posX = this.posX;
        };

        this.draw = function() {
            ctx.drawImage(unicorn, posX, posY, this.width, this.height);
        };
    };

    function Planet(posX, posY, color1, color2) {
        this.posX = posX;
        this.posY = posY;
        this.radius = 100;
        this.height = 100;
        this.width = 100;
        this.color1 = color1;
        this.color2 = color2;

        this.move = function() {
            this.posX -= 1.5;
            posX = this.posX;
        };

        this.draw = function() {
        ctx.beginPath();
        ctx.arc(posX, posY, 50, 0, Math.PI*2);
        ctx.fillStyle = makeGradient(posX,posY,color1,color2);
        ctx.fill();
        ctx.closePath();
        ctx.stroke();

        };
    };

    //The explosion particles

    function Particle(x,y) {
        this.x = x;
        this.y = y;
        this.radius = 30;
        this.color;
        this.scale = 1.0;
        this.scaleSpd = 0.5;
        this.velocityX = 0;
        this.velocityY = 0;

        this.update = function(ms) {

            this.scale -= this.scaleSpd * ms / 1000.0;

            if (this.scale <= 0) {
                this.scale = 0;
                scale = 0;

            }
			this.x += this.velocityX * ms/1000.0;
			this.y += this.velocityY * ms/1000.0;
        };

        this.draw = function(ctx)
		{
			ctx.save();
			ctx.translate(this.x, this.y);
			ctx.scale(this.scale, this.scale);

			ctx.beginPath();
			ctx.arc(0, 0, this.radius, 0, Math.PI*2, true);
			ctx.closePath();

			ctx.fillStyle = this.color;
			ctx.fill();

			ctx.restore();
		};
    };

    function explosion(deadPlanet) {

        var posX = deadPlanet.posX;
        var posY = deadPlanet.posY;
        var color1 = deadPlanet.color1;
        var color2 = deadPlanet.color2;
        var count = 10;
        var minSpeed = 60.0;
	    var maxSpeed = 250.0;
	    var minScaleSpeed = 1.0;
	    var maxScaleSpeed = 3.0;
	    var minRadius = 15;
	    var maxRadius = 35;

	    for (var angle=0; angle < 360; angle += Math.round(360/count)) {
	        var colorRandomizer = Math.floor(Math.random()*2);
	        var particle = new Particle(posX,posY);
	        if (colorRandomizer === 1) {
	            particle.color = color1;
	        }
	        else {
	            particle.color = color2;
	        }
	        particle.scaleSpd = randomFloat(minScaleSpeed, maxScaleSpeed);
	        particle.radius = randomFloat(minRadius, maxRadius);

	        var speed = randomFloat(minSpeed, maxSpeed);

	        particle.velocityX = speed * Math.cos(angle * Math.PI / 180.0);
		    particle.velocityY = speed * Math.sin(angle * Math.PI / 180.0);

		    Particles.push(particle);

	    }

    };

    function randomFloat (min, max) {

	    return min + Math.random()*(max-min);
    };

    var playerInvulnerable = false;

    var foobar = function makeVulnerable() {
        playerInvulnerable = false;
    };

    function drawPlayer() {
        ctx.drawImage(cthulhu, playerX, playerY, playerWidth, playerHeight);
    };

    function makeGradient(posX, posY, color1, color2) {
        var grd = ctx.createLinearGradient(posX-50,posY-50,posX+50,posY+50);
        grd.addColorStop(0, color1);
        grd.addColorStop(1, color2);
        return grd;
    };

    function generateColor() {
        return '#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6);
    };

    function generatePlanet() {
        var x = 1050;
        var y = Math.floor(50 + Math.random()*500);
        var color1 = generateColor();
        var color2 = generateColor();
        var pla = new Planet(x,y,color1,color2);
        pla.draw();
        Planets.push(pla);

    };

    function generateEnemy() {
        var posX = 1050;
        var posY = Math.floor(80 + Math.random()*450);
        var nmy = new Enemy(posX,posY);
        nmy.draw();
        Enemies.push(nmy);

    };

    function isCollision(arrayP) {
        return playerX + playerWidth > arrayP.posX && arrayP.posX + arrayP.width > playerX &&
                   playerY + playerHeight > arrayP.posY && arrayP.posY + arrayP.height > playerY;
    };

    function Score() {
        var score = document.getElementById('score');
        this.points = 0;

        this.add = function(points) {
            this.points += points;
            this.update();
        };

        this.reset = function() {
            this.points = 0;
            this.update();
        };

        this.update = function() {
            score.textContent = "Score: " + this.points;
        };
    };

    var totalScore = new Score();

    function Health() {
        var playerHealth = document.getElementById('health');
        this.points = 100;

        this.add = function(points) {
            this.points += points;
            this.update();
        };

        this.substract = function(points) {
            this.points -= points;
            this.update();
        };

        this.reset = function() {
            this.points = 100;
            this.update();
        }

        this.update = function() {
            playerHealth.style.width = this.points + "%";
            if (this.points === 0) {
                gameOver();
            }
        };
    };

    var currentHealth = new Health();

    function clearBg() {
        canvas.width = canvas.width;
    };

    function gameOver() {
        playerDead = true;
        clearBg();
        clearInterval(theLoop);
        clearInterval(poop);
        clearInterval(enemySpawner);
        clearInterval(tick1);
        clearBg();
        ctx.fillStyle = "red";
        ctx.font = "bold 50px cursive";
        ctx.fillText("Game Over :P", 400, 300 );
        setTimeout(init, 3000);

    };

    function doKeyDown(e) {
        if (e.keyCode === 87 || e.keyCode === 38) {
            if (playerY < 0 ) {
                playerY = playerY;
            }
            else {
            playerY = playerY - 5;
            drawPlayer();
            }
        }
        if (e.keyCode === 83 || e.keyCode === 40) {
            if (playerY > 520) {
                playerY = playerY;
            }
            else {
            playerY = playerY + 5;
            drawPlayer();
            }
        }
        if (e.keyCode === 75) {
            alert("Particle 1 radius: " + Particles[0].radius);
        }
        if (e.keyCode === 76) {
            alert("Current particles: " + Particles.length);
        }
        if (e.keyCode === 73) {
            alert("Enemies: " + Enemies.length);
        }
    };

    //The main game loop,responsible for array iterations 'n stuff :)

    function gameLoop() {
            clearBg();
            if (!playerDead) {
                drawPlayer();
            }

        for (var i = 0; i < Enemies.length; i++) {
            if (Enemies[i].posX < -1000) {
                Enemies.splice(i,1);
            }
            else {
                Enemies[i].draw();
                Enemies[i].move();

            }
            if (isCollision(Enemies[i])) {
                if (!playerInvulnerable) {
                    currentHealth.substract(25);
                    playerInvulnerable = true;
                    setTimeout(foobar, 1500);

                }
            }
        }

        for (var i = 0; i < Planets.length; i++) {
            if (Planets[i].posX < -500) {
                Planets.splice(i,1);
            }
            else {
            Planets[i].draw();
            Planets[i].move();
            }
            if (isCollision(Planets[i])) {
                drawPlayer();
                explosion(Planets[i]);
                Planets.splice(i,1);
                totalScore.add(10);
                if (totalScore.points % 100 === 0) {
                    if (currentHealth.points < 100) {
                        currentHealth.add(10);
                    }
                }
                if (totalScore.points === 10) {
                    tick1 = setInterval(generateEnemy, 2363);
                }
            }

        }
        if (Particles.length === 50) {
            Particles.splice(0,40);
        }
        for (var i= 0; i < Particles.length; i++) {
            var currentParticle = Particles[i];
            currentParticle.update(10);
            currentParticle.draw(ctx);
        }

    };

    var theLoop = setInterval(gameLoop,10);
    var poop = setInterval(generatePlanet, 6000);
    var enemySpawner = setInterval(generateEnemy, 3383);

});

<commit_msg>Minor edits.<commit_after>var Planets = [];
var Particles = [];
var Enemies = [];

//The scrolling background...

var scrollSpeed = 20;
var step = 1;
var current = 0;
var imageWidth = 1000;
var restartWidth = 359;

var restartPosition = -(imageWidth - restartWidth);
function scrollBg(){
	current -= step;
	if (current == restartPosition) {current = 0;}
	$('#background').css("background-position",current+"px 0");
	};

setInterval("scrollBg()", scrollSpeed);

/***************************************************************************/
//Let's make the canvas ready...
$(document).ready(function() {

    var canvas = document.getElementById('background');
    var ctx = canvas.getContext("2d");
    window.addEventListener("keydown",doKeyDown, true);
    var playerX = 50;
    var playerY = 200;
    var playerWidth = 80;
    var playerHeight = 80;
    var playerDead = false;

    //For additional setIntervals...
    var tick1;
    var tick2;

    //Let's import the sprites
    var cthulhu = new Image();
    cthulhu.src = 'http://i1287.photobucket.com/albums/a632/MrDeltoid/pruitpruit_zpsc847d437.png';
    var unicorn = new Image();
    unicorn.src = 'http://i1287.photobucket.com/albums/a632/MrDeltoid/unicorn1_zps9f61bb5b.png';

    function init() {
        clearBg();
        playerX = 50;
        playerY = 200;
        totalScore.reset();
        currentHealth.reset();
        playerDead = false;
        playerInvulnerable = false;
        setInterval(gameLoop,10);
        setInterval(generatePlanet, 6000);
        setInterval(generateEnemy, 3383);

    }

    function Enemy(posX, posY) {
        this.posX = posX;
        this.posY = posY;
        this.speed = 3;
        this.width = 100;
        this.height = 80;

        this.move = function() {
            this.posX -= this.speed;
            posX = this.posX;
        };

        this.draw = function() {
            ctx.drawImage(unicorn, posX, posY, this.width, this.height);
        };
    };

    function Planet(posX, posY, color1, color2) {
        this.posX = posX;
        this.posY = posY;
        this.radius = 100;
        this.height = 100;
        this.width = 100;
        this.color1 = color1;
        this.color2 = color2;

        this.move = function() {
            this.posX -= 1.5;
            posX = this.posX;
        };

        this.draw = function() {
        ctx.beginPath();
        ctx.arc(posX, posY, 50, 0, Math.PI*2);
        ctx.fillStyle = makeGradient(posX,posY,color1,color2);
        ctx.fill();
        ctx.closePath();
        ctx.stroke();

        };
    };

    //The explosion particles

    function Particle(x,y) {
        this.x = x;
        this.y = y;
        this.radius = 30;
        this.color;
        this.scale = 1.0;
        this.scaleSpd = 0.5;
        this.velocityX = 0;
        this.velocityY = 0;

        this.update = function(ms) {

            this.scale -= this.scaleSpd * ms / 1000.0;

            if (this.scale <= 0) {
                this.scale = 0;
                scale = 0;

            }
			this.x += this.velocityX * ms/1000.0;
			this.y += this.velocityY * ms/1000.0;
        };

        this.draw = function(ctx)
		{
			ctx.save();
			ctx.translate(this.x, this.y);
			ctx.scale(this.scale, this.scale);

			ctx.beginPath();
			ctx.arc(0, 0, this.radius, 0, Math.PI*2, true);
			ctx.closePath();

			ctx.fillStyle = this.color;
			ctx.fill();

			ctx.restore();
		};
    };

    function explosion(deadPlanet) {

        var posX = deadPlanet.posX;
        var posY = deadPlanet.posY;
        var color1 = deadPlanet.color1;
        var color2 = deadPlanet.color2;
        var count = 10;
        var minSpeed = 60.0;
	    var maxSpeed = 250.0;
	    var minScaleSpeed = 1.0;
	    var maxScaleSpeed = 3.0;
	    var minRadius = 15;
	    var maxRadius = 35;

	    for (var angle=0; angle < 360; angle += Math.round(360/count)) {
	        var colorRandomizer = Math.floor(Math.random()*2);
	        var particle = new Particle(posX,posY);
	        if (colorRandomizer === 1) {
	            particle.color = color1;
	        }
	        else {
	            particle.color = color2;
	        }
	        particle.scaleSpd = randomFloat(minScaleSpeed, maxScaleSpeed);
	        particle.radius = randomFloat(minRadius, maxRadius);

	        var speed = randomFloat(minSpeed, maxSpeed);

	        particle.velocityX = speed * Math.cos(angle * Math.PI / 180.0);
		    particle.velocityY = speed * Math.sin(angle * Math.PI / 180.0);

		    Particles.push(particle);

	    }

    };

    function randomFloat (min, max) {

	    return min + Math.random()*(max-min);
    };

    var playerInvulnerable = false;

    var foobar = function makeVulnerable() {
        playerInvulnerable = false;
    };

    function drawPlayer() {
        ctx.drawImage(cthulhu, playerX, playerY, playerWidth, playerHeight);
    };

    function makeGradient(posX, posY, color1, color2) {
        var grd = ctx.createLinearGradient(posX-50,posY-50,posX+50,posY+50);
        grd.addColorStop(0, color1);
        grd.addColorStop(1, color2);
        return grd;
    };

    function generateColor() {
        return '#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6);
    };

    function generatePlanet() {
        var x = 1050;
        var y = Math.floor(50 + Math.random()*500);
        var color1 = generateColor();
        var color2 = generateColor();
        var pla = new Planet(x,y,color1,color2);
        pla.draw();
        Planets.push(pla);

    };

    function generateEnemy() {
        var posX = 1050;
        var posY = Math.floor(80 + Math.random()*450);
        var nmy = new Enemy(posX,posY);
        nmy.draw();
        Enemies.push(nmy);

    };

    function isCollision(arrayP) {
        return playerX + playerWidth > arrayP.posX && arrayP.posX + arrayP.width > playerX &&
                   playerY + playerHeight > arrayP.posY && arrayP.posY + arrayP.height > playerY;
    };

    function Score() {
        var score = document.getElementById('score');
        this.points = 0;

        this.add = function(points) {
            this.points += points;
            this.update();
        };

        this.reset = function() {
            this.points = 0;
            this.update();
        };

        this.update = function() {
            score.textContent = "Score: " + this.points;
        };
    };

    var totalScore = new Score();

    function Health() {
        var playerHealth = document.getElementById('health');
        this.points = 100;

        this.add = function(points) {
            this.points += points;
            this.update();
        };

        this.substract = function(points) {
            this.points -= points;
            this.update();
        };

        this.reset = function() {
            this.points = 100;
            this.update();
        }

        this.update = function() {
            playerHealth.style.width = this.points + "%";
            if (this.points === 0) {
                gameOver();
            }
        };
    };

    var currentHealth = new Health();

    function clearBg() {
        canvas.width = canvas.width;
    };

    function gameOver() {
        playerDead = true;
        clearBg();
        clearInterval(theLoop);
        clearInterval(poop);
        clearInterval(enemySpawner);
        clearInterval(tick1);
        clearBg();
        ctx.fillStyle = "red";
        ctx.font = "bold 50px cursive";
        ctx.fillText("Game Over :P", 400, 300 );
        setTimeout(init, 3000);

    };

    function doKeyDown(e) {
        if (e.keyCode === 87 || e.keyCode === 38) {
            if (playerY < 0 ) {
                playerY = playerY;
            }
            else {
            playerY = playerY - 5;
            drawPlayer();
            }
        }
        if (e.keyCode === 83 || e.keyCode === 40) {
            if (playerY > 520) {
                playerY = playerY;
            }
            else {
            playerY = playerY + 5;
            drawPlayer();
            }
        }
        if (e.keyCode === 75) {
            alert("Particle 1 radius: " + Particles[0].radius);
        }
        if (e.keyCode === 76) {
            alert("Current particles: " + Particles.length);
        }
        if (e.keyCode === 73) {
            alert("Enemies: " + Enemies.length);
        }
    };

    //The main game loop,responsible for array iterations 'n stuff :)

    function gameLoop() {
            clearBg();
            if (!playerDead) {
                drawPlayer();
            }

        for (var i = 0; i < Enemies.length; i++) {
            if (Enemies[i].posX < -1000) {
                Enemies.splice(i,1);
            }
            else {
                Enemies[i].draw();
                Enemies[i].move();

            }
            if (isCollision(Enemies[i])) {
                if (!playerInvulnerable) {
                    currentHealth.substract(25);
                    playerInvulnerable = true;
                    setTimeout(foobar, 1500);

                }
            }
        }

        for (var i = 0; i < Planets.length; i++) {
            if (Planets[i].posX < -500) {
                Planets.splice(i,1);
            }
            else {
            Planets[i].draw();
            Planets[i].move();
            }
            if (isCollision(Planets[i])) {
                drawPlayer();
                explosion(Planets[i]);
                Planets.splice(i,1);
                totalScore.add(10);
                if (totalScore.points % 100 === 0) {
                    if (currentHealth.points < 100) {
                        currentHealth.add(10);
                    }
                }
                if (totalScore.points === 200) {
                    tick1 = setInterval(generateEnemy, 2363);
                }
				if (totalScore.points === 400) {
					tick2 = setInterval(generateEnemy, 1975);
					}
            }

        }
        if (Particles.length === 50) {
            Particles.splice(0,40);
        }
        for (var i= 0; i < Particles.length; i++) {
            var currentParticle = Particles[i];
            currentParticle.update(10);
            currentParticle.draw(ctx);
        }

    };

    var theLoop = setInterval(gameLoop,10);
    var poop = setInterval(generatePlanet, 6000);
    var enemySpawner = setInterval(generateEnemy, 3383);

});

<|endoftext|>


<commit_before>'use strict';

const Script = require('smooch-bot').Script;

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say("Hello, je suis Harry ! Est ce que tu as un peu de temps de disponible ? =)")
            .then(() => 'askForTime');
        }
    },

    askForTime: {
        receive: (bot, message) => {
            return bot.say("Super, ça tombe bien, moi aussi ! Les forces du mal sont assez peu actives en ce moment...\n Est ce qu'on peut parler de ta présentation 'Evil Plan to Conquer the World' que tu as mis en ligne hier soir ?")
            .then(() => 'askForErrors');
        }
    },

    askForErrors: {
        receive: (bot, message) => {
            return bot.say("Alors, déjà, je n'ai trouvé que 8% de fautes, ce qui est vraiment pas mal !")
                .then(() => bot.say("Mais, slide 5, qu'est ce que tu entends par ?"))
                .then(() => 'finish');
        }
    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then((name) => bot.say(`Sorry ${name}, my creator didn't ` +
                        'teach me how to do anything else!'))
                .then(() => 'finish');
        }
    }
});
<commit_msg>'Test1'<commit_after>'use strict';

const Script = require('smooch-bot').Script;

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say("Hello, je suis Harry ! Est ce que tu as un peu de temps de disponible ? =)")
            .then(() => 'askForTime');
        }
    },

    askForTime: {
        receive: (bot, message) => {
            return bot.say("Super, ça tombe bien, moi aussi ! Les forces du mal sont assez peu actives en ce moment...")
            .then(() => bot.say("Est ce qu'on peut parler de ta présentation 'Evil Plan to Conquer the World' que tu as mis en ligne hier soir ?")
            .then(() => 'askForErrors');
        }
    },

    askForErrors: {
        receive: (bot, message) => {
            return bot.say("Alors, déjà, je n'ai trouvé que 8% de fautes, ce qui est vraiment pas mal !")
                .then(() => bot.say("Mais, slide 5, qu'est ce que tu entends par 'We have to '?"))
                .then(() => 'finish');
        }
    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then((name) => bot.say(`Sorry ${name}, my creator didn't ` +
                        'teach me how to do anything else!'))
                .then(() => 'finish');
        }
    }
});
<|endoftext|>


<commit_before>var MOV_SPEED = 200;
var ROT_SPEED = 40;
var TOUCHPAD_SIZE = 600;
var MAX_X = 300;
var MAX_Y = 300;

var hoverX, hoverY;
var moving = false;

$("#rot-cl-button").on("touchstart", function(e) {
  cl();
});
$("#rot-ccl-button").on("touchstart", function(e) {
  ccl();
});
$("#wiggle-button").on("touchstart", function(e) {
  wiggle();
});
$("#wiggle-button, #rot-cl-button, rot-ccl-button").on("touchend", function(e) {
  move(0, 0);
});
$(".sound button").on("touchstart", function(e) {
  $(this).children("audio").get(0).play();
  $(this).children("audio").attr("loop", "");
});
$(".sound button").on("touchend", function(e) {
  $(this).children("audio").removeAttr("loop");
});

$("#touchpad").on("move", function(e) {
  if (!moving) {
    hover(e.pageX, e.pageY);
    setTimeout(function() {
      moving = false;
    }, 250);
  }
});
$("#touchpad").on("moveend", function(e) {
  move(0, 0);
});

function hover(pX, pY) {
  console.log("everyday im hovering", pX, pY);
  var rect = $("#touchpad").get(0).getBoundingClientRect();
  hoverX = (pX - rect.left) - TOUCHPAD_SIZE/2;
  hoverY = -((pY - rect.top) - TOUCHPAD_SIZE/2);
  move(hoverX, hoverY);
}
function move(x, y) {
  $("#knob").css({"transform": "translate(" + x + "px, " + -y + "px)"});

  console.log("hoverXY",x,y);
  var vX = (x/MAX_X) * MOV_SPEED;
  var vY = (y/MAX_Y) * MOV_SPEED;
  console.log("vXY",vX,vY);
  robot(vX, vY, 0);
}

function wiggle() {
  robot(0, -200, 0);
  setTimeout(function() {
    robot(0, 200, 0);
    setTimeout(function() {
      robot(0, -200, 0);
      setTimeout(function() {
        robot(0, 200, 0);
      }, 320);
    }, 320);
  }, 320);
}

function robot(x, y, r) {
  $.post(
    "http://172.26.201.2:1337/x" + x + "y" + y + "r" + r
  );
}

function sign(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; }
<commit_msg>[fix] movement axes, [feat] improve sound button behavior<commit_after>var MOV_SPEED = 500;
var ROT_SPEED = 40;
var TOUCHPAD_SIZE = 600;
var MAX_X = 300;
var MAX_Y = 300;

var hoverX, hoverY;
var moving = false;

$("#rot-cl-button").on("touchstart", function(e) {
  cl();
});
$("#rot-ccl-button").on("touchstart", function(e) {
  ccl();
});
$("#wiggle-button").on("touchstart", function(e) {
  wiggle();
});
$("#wiggle-button, #rot-cl-button, #rot-ccl-button").on("touchend", function(e) {
  move(0, 0);
  setTimeout(function() {
    move(0, 0);
  }, 50);
});
$(".sound button").on("touchstart", function(e) {
  $(this).children("audio").get(0).play();
  $(this).children("audio").attr("loop", "");
});
$(".sound button").on("touchend", function(e) {
  $(this).children("audio").removeAttr("loop");
  $(this).children("audio").get(0).pause();
  $(this).children("audio").get(0).currentTime = 0;
});

$("#touchpad").on("move", function(e) {
  if (!moving) {
    hover(e.pageX, e.pageY);
    setTimeout(function() {
      moving = false;
    }, 250);
  }
});
$("#touchpad").on("moveend", function(e) {
  move(0, 0);
});

function hover(pX, pY) {
  console.log("everyday im hovering", pX, pY);
  var rect = $("#touchpad").get(0).getBoundingClientRect();
  hoverX = (pX - rect.left) - TOUCHPAD_SIZE/2;
  hoverY = -((pY - rect.top) - TOUCHPAD_SIZE/2);
  move(hoverX, hoverY);
}
function move(x, y) {
  $("#knob").css({"transform": "translate(" + x + "px, " + -y + "px)"});

  console.log("hoverXY",x,y);
  var vX = (Math.min(x, MAX_X)/MAX_X) * MOV_SPEED;
  var vY = (Math.min(y, MAX_Y)/MAX_Y) * MOV_SPEED;
  console.log("vXY",vX,vY);
  robot(Math.floor(vX), Math.floor(vY), 0);
}

function cl() {
  robot(0, 0, 60);
}
function ccl() {
  robot(0, 0, -60);
}
function wiggle() {
  robot(-MOV_SPEED*0.3, 0, 0);
  setTimeout(function() {
    robot(MOV_SPEED*0.3, 0, 0);
    setTimeout(function() {
      robot(-MOV_SPEED*0.3, 0, 0);
      setTimeout(function() {
        robot(MOV_SPEED*0.3, 0, 0);
        setTimeout(function() {
          robot(-MOV_SPEED*0.3, 0, 0);
          setTimeout(function() {
            robot(MOV_SPEED*0.3, 0, 0);
            setTimeout(function() {
              robot(0, 0, 0);
            }, 320);
          }, 320);
        }, 320);
      }, 320);
    }, 320);
  }, 320);
}

function robot(y, x, r) {
  $.post(
    "http://172.26.201.2:1337/x" + x + "y" + -y + "r" + r
  );
}
<|endoftext|>


<commit_before>var Input_Text = parseFloat(document.getElementById("input-text").value);
var Input_Units = "°F";
var Output_Units = "°C";

function round(float) {
    return Math.round(float * 1000)/1000;
}

function temperature_conversion() {
    Input_Text = parseFloat(document.getElementById("input-text").value);

    if (Input_Units === "°F") {
        if (Output_Units === "°F") {
            document.getElementById("output-text").value = round(Input_Text);
        }
        if (Output_Units === "°C") {
            document.getElementById("output-text").value = round((Input_Text - 32) * 5/9);
        }
        if (Output_Units === "K") {
            document.getElementById("output-text").value = round(((Input_Text - 32) * 5/9) + 273.15);
        }
    }
    if (Input_Units === "°C") {
        if (Output_Units === "°F") {
            document.getElementById("output-text").value = round((Input_Text * 9/5) + 32);
        }
        if (Output_Units === "°C") {
            document.getElementById("output-text").value = round(Input_Text);
        }
        if (Output_Units === "K") {
            document.getElementById("output-text").value = round(Input_Text + 273.15);
        }
    }
    if (Input_Units === "K") {
        if (Output_Units === "°F") {
            document.getElementById("output-text").value = round((Input_Text * 9/5) - 459.67);
        }
        if (Output_Units === "°C") {
            document.getElementById("output-text").value = round(Input_Text - 273.15);
        }
        if (Output_Units === "K") {
            document.getElementById("output-text").value = round(Input_Text);
        }
    }
}

function button_in_pressed(Pressed_Button) {
    Input_Units = Pressed_Button.value;
    if (Pressed_Button.hasAttribute("id") === false) {
        document.getElementById("active-in").removeAttribute("id");
        Pressed_Button.id = "active-in";
      }
    temperature_conversion();
}

function button_out_pressed(Pressed_Button) {
    Output_Units = Pressed_Button.value;
    if (Pressed_Button.hasAttribute("id") === false) {
        document.getElementById("active-out").removeAttribute("id");
        Pressed_Button.id = "active-out";
    }
    temperature_conversion();
}
<commit_msg>Update script.js<commit_after>var Input_Text = parseFloat(document.getElementById("input-text").value);
var Input_Units = "°F";
var Output_Units = "°C";

function round(float) {
	return Math.round(float * 1000) / 1000;
}

function temperature_conversion() {
	Input_Text = parseFloat(document.getElementById("input-text").value);
	var Temp_Temp = Input_Text;

	switch(Input_Units) { // Convert to degrees C
		/* Note Temp_Temp is already assigned */
		case "°F":
			Temp_Temp = (Input_Text - 32) / 1.8;
			break;
		case "K":
			Temp_Temp = Input_Text - 273.15;
			break;
		default:
			break;
	}

	switch(Output_Units) { // Convert from degrees C
			/* Note Temp_Temp is in degrees C */
		case "°F":
				Temp_Temp = Temp_Temp * 1.8 + 32;
				break;
		case "K":
			Temp_Temp = Temp_Temp + 273.15;
			break;
		/* No need for case C; Temp_Temp is already in C */
		default:
			break;
	}
	document.getElementById("output-text").value = round(Temp_Temp);
}

function button_in_pressed(Pressed_Button) {
	Input_Units = Pressed_Button.value;
	if (!Pressed_Button.hasAttribute("id")) {
		document.getElementById("active-in").removeAttribute("id");
		Pressed_Button.id = "active-in";
	}
	temperature_conversion();
}

function button_out_pressed(Pressed_Button) {
	Output_Units = Pressed_Button.value;
	if (!Pressed_Button.hasAttribute("id")) {
		document.getElementById("active-out").removeAttribute("id");
		Pressed_Button.id = "active-out";
	}
	temperature_conversion();
}
<|endoftext|>