<commit_before>'use strict';

function repo_init(){
    core_repo_init({
      'events': {
        'click-button': {
          'onclick': click_button,
        },
      },
      'globals': {
        'keyclick_ready': 1,
        'upgrades': {
          'manual': {
            'bonus': 1,
            'cost': 2,
            'multiplier': 2,
            'target': 'clicks-per-click',
          },
          'script': {
            'bonus': 1,
            'cost': 20,
            'multiplier': 4,
            'target': 'clicks-per-second',
          },
          'employee': {
            'bonus': 2,
            'cost': 50,
            'multiplier': 8,
            'target': 'clicks-per-second',
          },
          'server': {
            'bonus': 3,
            'cost': 100,
            'multiplier': 16,
            'target': 'clicks-per-second',
          },
          'cluster': {
            'bonus': 4,
            'cost': 200,
            'multiplier': 32,
            'target': 'clicks-per-second',
          },
          'coffeemaker': {
            'bonus': .1,
            'cost': 20,
            'multiplier': 64,
            'target': 'multiplier-per-click',
          },
          'investor': {
            'bonus': .01,
            'cost': 20,
            'multiplier': 64,
            'target': 'multiplier-per-second',
          },
        },
      },
      'storage': {
        'clicks': 0,
        'clicks-per-click': 1,
        'clicks-per-click-multiplied': 1,
        'clicks-per-second': 0,
        'clicks-per-second-multiplied': 0,
        'multiplier-per-click': 1,
        'multiplier-per-second': 1,
      },
      'title': 'Click.htm',
    });

    update_multiplied();

    for(let id in upgrades){
        let upgrade = id[0].toUpperCase() + id.substring(1);

        document.getElementById('upgrades').innerHTML +=
          '
0'
          + ' <input id=' + id + ' type=button value=' + upgrade + '>'
          + ' '
          + '<input class=hidden id=upgrade-' + id + '-cost>';
    }

    for(let id in upgrades){
        let storage = {};

        storage['upgrade-' + id] = 0;
        storage['upgrade-' + id + '-cost'] = upgrades[id]['cost'];

        core_storage_add({
          'storage': storage,
        });

        document.getElementById(id).onclick = function(){
            purchase(
              this.id,
              core_storage_data['upgrade-' + this.id + '-cost'],
              upgrades[this.id]['target']
            );
        };

        document.getElementById('ui-upgrade-' + id + '-cost').innerHTML = core_number_format({
          'decimals-min': 0,
          'number': upgrades[id]['cost'] + core_storage_data['upgrade-' + id + '-cost'],
        });
    }

    core_interval_modify({
      'id': 'second',
      'interval': 1000,
      'todo': second,
    });

    core_storage_update();
    core_ui_update({
      'ids': {
        'ui-clicks': core_number_format({
          'decimals-min': 2,
          'number': core_storage_data['clicks'],
        }),
      },
    });
}
<commit_msg>added supercomputer, fixed initial cost display<commit_after>'use strict';

function repo_init(){
    core_repo_init({
      'events': {
        'click-button': {
          'onclick': click_button,
        },
      },
      'globals': {
        'keyclick_ready': 1,
        'upgrades': {
          'manual': {
            'bonus': 1,
            'cost': 2,
            'multiplier': 2,
            'target': 'clicks-per-click',
          },
          'script': {
            'bonus': 1,
            'cost': 20,
            'multiplier': 4,
            'target': 'clicks-per-second',
          },
          'employee': {
            'bonus': 2,
            'cost': 50,
            'multiplier': 8,
            'target': 'clicks-per-second',
          },
          'server': {
            'bonus': 3,
            'cost': 100,
            'multiplier': 16,
            'target': 'clicks-per-second',
          },
          'cluster': {
            'bonus': 4,
            'cost': 200,
            'multiplier': 32,
            'target': 'clicks-per-second',
          },
          'supercomputer': {
            'bonus': 5,
            'cost': 500,
            'multiplier': 64,
            'target': 'clicks-per-second',
          },
          'coffeemaker': {
            'bonus': .1,
            'cost': 20,
            'multiplier': 64,
            'target': 'multiplier-per-click',
          },
          'investor': {
            'bonus': .01,
            'cost': 20,
            'multiplier': 64,
            'target': 'multiplier-per-second',
          },
        },
      },
      'storage': {
        'clicks': 0,
        'clicks-per-click': 1,
        'clicks-per-click-multiplied': 1,
        'clicks-per-second': 0,
        'clicks-per-second-multiplied': 0,
        'multiplier-per-click': 1,
        'multiplier-per-second': 1,
      },
      'title': 'Click.htm',
    });

    update_multiplied();

    for(let id in upgrades){
        let upgrade = id[0].toUpperCase() + id.substring(1);

        document.getElementById('upgrades').innerHTML +=
          '
0'
          + ' <input id=' + id + ' type=button value=' + upgrade + '>'
          + ' '
          + '<input class=hidden id=upgrade-' + id + '-cost>';
    }

    for(let id in upgrades){
        let storage = {};

        storage['upgrade-' + id] = 0;
        storage['upgrade-' + id + '-cost'] = upgrades[id]['cost'];

        core_storage_add({
          'storage': storage,
        });

        document.getElementById(id).onclick = function(){
            purchase(
              this.id,
              core_storage_data['upgrade-' + this.id + '-cost'],
              upgrades[this.id]['target']
            );
        };

        document.getElementById('ui-upgrade-' + id + '-cost').innerHTML = core_number_format({
          'decimals-min': 0,
          'number': core_storage_data['upgrade-' + id + '-cost'],
        });
    }

    core_interval_modify({
      'id': 'second',
      'interval': 1000,
      'todo': second,
    });

    core_storage_update();
    core_ui_update({
      'ids': {
        'ui-clicks': core_number_format({
          'decimals-min': 2,
          'number': core_storage_data['clicks'],
        }),
      },
    });
}
<|endoftext|>


<commit_before>/*----- DROP DOWN COUNTY SELECTION*/
var div_drop_down = "drop_down_counties";
var dispatch = d3.dispatch("load", "countychange");

//read county data
d3.csv("data/greenCars.csv", function(error, counties) {
	if (error) throw error;
	county_data = d3.map();
	counties.forEach(function(d) { county_data.set(d.Län, d); });
	dispatch.load(county_data);
	dispatch.countychange(county_data.get("Stockholms län")); //startvalue
});

// A drop-down menu for selecting a county; uses the "menu" namespace
dispatch.on("load.menu", function(green_cars_data) {
var select = d3.selectAll("."+div_drop_down)
  .append("div")
  .append("select")
  .on("change", function() { dispatch.countychange(county_data.get(this.value)); });

	select.selectAll("option")
	    .data(county_data.values())
	  	.enter().append("option")
	    .attr("value", function(d) { return d.Län; })
	    .text(function(d) { return d.Län; });

	dispatch.on("countychange.menu", function(county) {
	  select.property("value", county.Län);
	  updateTransportationSection(county.Län);
	});
});

/*----- TRANSPORTATION SECTION -------- */
//read data, green cars, number of cars etc
d3.csv("data/greenCars.csv", function(error, counties) {
	if (error) throw error;
	green_cars_data = d3.map();
	counties.forEach(function(d) { green_cars_data.set(d.Län, d); });
	dispatch.load(green_cars_data);
	//dispatch.countychange(green_cars_data.get("Stockholms län")); //startvalue
});

function updateTransportationSection(c){
	console.log(c);
	var data_test = green_cars_data.get(c);
	console.log(data_test.AntalMiljöbilar);
}

var sweden = new swedenMap("map", "white", "orange");
var donut = new donut("donut");
var venn = new vennDiagram("venn");

/* ------- LIQUID ------ */
var liquid1 = new liquidFillGauge();
var config1 = liquid1.liquidFillGaugeDefaultSettings();
    config1.circleColor = "#FF7777";
    config1.textColor = "#FF4444";
    config1.waveTextColor = "#FFAAAA";
    config1.waveColor = "#FFDDDD";
    config1.circleThickness = 0.2;
    config1.textVertPosition = 0.2;
    config1.waveAnimateTime = 1000;

liquid1.loadLiquidFillGauge("fillgauge1", 28, config1);

/* ------- COUNTER --------- */
countTo("test_text", 1082, 1200, false);

<commit_msg>added counters for transportation in main.js<commit_after>/*----- DROP DOWN COUNTY SELECTION*/
var div_drop_down = "drop_down_counties";
var dispatch = d3.dispatch("load", "countychange");

//read county data
d3.csv("data/greenCars.csv", function(error, counties) {
	if (error) throw error;
	county_data = d3.map();
	counties.forEach(function(d) { county_data.set(d.Län, d); });
	dispatch.load(county_data);
	dispatch.countychange(county_data.get("Stockholms län")); //startvalue
});

// A drop-down menu for selecting a county; uses the "menu" namespace
dispatch.on("load.menu", function(green_cars_data) {
var select = d3.selectAll("."+div_drop_down)
  .append("div")
  .append("select")
  .on("change", function() { dispatch.countychange(county_data.get(this.value)); });

	select.selectAll("option")
	    .data(county_data.values())
	  	.enter().append("option")
	    .attr("value", function(d) { return d.Län; })
	    .text(function(d) { return d.Län; });

	dispatch.on("countychange.menu", function(county) {
	  select.property("value", county.Län);
	  updateTransportationSection(county.Län);
	});
});

/*----- TRANSPORTATION SECTION -------- */
//read data, green cars, number of cars etc
d3.csv("data/greenCars.csv", function(error, counties) {
	if (error) throw error;
	green_cars_data = d3.map();
	counties.forEach(function(d) { green_cars_data.set(d.Län, d); });
});

function updateTransportationSection(c){
	var data_test = green_cars_data.get(c);
	countTo("nr_of_cars", data_test.AntalPersonbilarIlänet, 1200, false);
	countTo("green_cars", data_test.ProcentuellAndelMiljöbilar, 1200, true);
}

var sweden = new swedenMap("map", "white", "orange");
var donut = new donut("donut");
var venn = new vennDiagram("venn");

/* ------- LIQUID ------ */
var liquid1 = new liquidFillGauge();
var config1 = liquid1.liquidFillGaugeDefaultSettings();
    config1.circleColor = "#FF7777";
    config1.textColor = "#FF4444";
    config1.waveTextColor = "#FFAAAA";
    config1.waveColor = "#FFDDDD";
    config1.circleThickness = 0.2;
    config1.textVertPosition = 0.2;
    config1.waveAnimateTime = 1000;

liquid1.loadLiquidFillGauge("fillgauge1", 28, config1);

/* ------- COUNTER --------- */
countTo("test_text", 1082, 1200, false);

<|endoftext|>


<commit_before>$(document).ready(function () {

	$(".internalLink").click(function (e) {

		var pageToOpen = $(this).attr("name");
		$(".page.open").removeClass("open");
		$(".page[name=" + pageToOpen + "]").addClass("open");

		$("#contents").css({
			"top": "10%",
			"bottom": "10%"
		});

	});

	$(".title .fa").click(function() {
		$(".page.open").removeClass("open");
		$("#contents").removeAttr("style");
		$(".page[name=home]").addClass("open");

	});

});<commit_msg>just kidding, this is the last one...<commit_after>$(document).ready(function () {

	$(".internalLink").click(function (e) {

		var pageToOpen = $(this).attr("name");
		$(".page.open").removeClass("open");
		$(".page[name=" + pageToOpen + "]").addClass("open");

		$("#contents").css({
			"top": "5%",
			"bottom": "5%"
		});

	});

	$(".title .fa").click(function() {
		$(".page.open").removeClass("open");
		$("#contents").removeAttr("style");
		$(".page[name=home]").addClass("open");

	});

});<|endoftext|>


<commit_before>$(document).ready(function(event){
   $('#submit').click(function(event){
      getData();

   });
   $('#formThing').submit(function(event){
      event.preventDefault();
      getData();
   });
});
function getData(){
    $.get('https://beam.pro/api/v1/channels/' + $('#inputText').val(), "", function(data){
         var Avatar = "https://beam.pro/api/v1/users/" + data['user']['id'] + "/avatar";
         var Username = data['user']['username'];
         var Followers = data['numFollowers'];
         var Partnered = data['partnered'];
         var Tetris = data['interactive'];
         var Audience = data['audience'];
         var Experience = data['user']['experience'];
         var lvls = data['user']['level'];
         var Sparks = data['user']['sparks'];
         var ChannelID = data['user']['id'];
         var Tetrisid = data['tetrisGameId'];
         var Coverid = data['coverId'];
         var Thumbnail = data['thumbnailId'];
         var StreamMute = data['preferences']['channel:player:muteOwn'];
         var FollowNotify = data['preferences']['channel:notify:follow'];
         var TotalViews = data['viewersTotal'];
         var te = data['transcodingEnabled'];
         var Online = data['online'];
         if(data['type'] != null){
            var lastPlayed = data['type']['name'];
         }else{
            var lastPlayed = "None";
         }
         var joined = data['createdAt'];
         var html = '';
         html += '
' + Username + '
';
         html += '
Followers: ' + Followers+ '';
         html += '
Partnered: ' + Partnered +'';
         html += '
Total Views: ' + TotalViews +'';
         html += '
---Points---'
         html += '
Level: ' + lvls +'';
         html += '
Experience: ' + Experience +'';
         html += '
Sparks: ' + Sparks +'';
         html += '
---ID---'
         html += '
Tetris Game ID: ' + Tetrisid;
         html += '
Channel ID: ' + ChannelID;
         html += '
Cover ID: ' + Coverid;
         html += '
Thumbnail ID: ' + Thumbnail;
         html += '
---Preference---'
         html += '
interactive: ' + Tetris;
         html += '
Audience: ' + Audience;
         html += '
StreamMute: ' + StreamMute;
         html += '
transcoding: ' + te;
         html += '
------------'
         html += "
";
         if(Online){
             html += '
Online';
         }else{
             html += '
Offline';
         }
         html+= '
Last Played:'+lastPlayed+'';
         html += '
Joined on: '+joined+' '.replace('T', ' at ');
         $('.profile').html(html);
      }).fail(function(data){
            html = '
A Beam user with that name does not exist.';
             $('.profile').html(html);
            return;
      });;
}
<commit_msg>Update main.js<commit_after>$(document).ready(function(event){
   $('#submit').click(function(event){
      getData();

   });
   $('#formThing').submit(function(event){
      event.preventDefault();
      getData();
   });
});
function getData(){
    $.get('https://beam.pro/api/v1/channels/' + $('#inputText').val(), "", function(data){
         var Avatar = "https://beam.pro/api/v1/users/" + data['user']['id'] + "/avatar";
         var Username = data['user']['username'];
         var Followers = data['numFollowers'];
         var Partnered = data['partnered'];
         var Tetris = data['interactive'];
         var Audience = data['audience'];
         var Experience = data['user']['experience'];
         var lvls = data['user']['level'];
         var Sparks = data['user']['sparks'];
         var ChannelID = data['user']['id'];
         var Tetrisid = data['tetrisGameId'];
         var Coverid = data['coverId'];
         var Thumbnail = data['thumbnailId'];
         var StreamMute = data['preferences']['channel:player:muteOwn'];
         var FollowNotify = data['preferences']['channel:notify:follow'];
         var TotalViews = data['viewersTotal'];
         var te = data['transcodingEnabled'];
         var Online = data['online'];
         if(data['type'] != null){
            var lastPlayed = data['type']['name'];
         }else{
            var lastPlayed = "None";
         }
         var joined = data['createdAt'];
         var html = '';
         html += '
' + Username + '
';
         html += '
Followers: ' + Followers+ '';
         html += '
Partnered: ' + Partnered +'';
         html += '
Total Views: ' + TotalViews +'';
         html += '
---Points---'
         html += '
Level: ' + lvls +'';
         html += '
Experience: ' + Experience +'';
         html += '
Sparks: ' + Sparks +'';
         html += '
---ID---'
         html += '
Tetris Game ID: ' + Tetrisid;
         html += '
Channel ID: ' + ChannelID;
         html += '
Cover ID: ' + Coverid;
         html += '
Thumbnail ID: ' + Thumbnail;
         html += '
---Preference---'
         html += '
interactive: ' + Tetris;
         html += '
Audience: ' + Audience;
         html += '
SelfStreamMute: ' + StreamMute;
         html += '
BeamBot FollowNotify' + FollowNotify +'';
         html += '
transcoding: ' + te;
         html += '
------------'
         html += "
";
         if(Online){
             html += '
Online';
         }else{
             html += '
Offline';
         }
         html+= '
Last Played:'+lastPlayed+'';
         html += '
Joined on: '+joined+' '.replace('T', ' at ');
         $('.profile').html(html);
      }).fail(function(data){
            html = '
A Beam user with that name does not exist.';
             $('.profile').html(html);
            return;
      });;
}
<|endoftext|>


<commit_before>var currentBuilding = '113';
var historyTypes = { "electricity": "daily", "heating": "daily", "cooling": "daily" };
var buildingNameMap = {};
var jsonRequestQueue = [];
var liveTimeout = -1, historyTimeout = -1;
var historyGraphs = { 'electricity': null, 'heating': null, 'cooling': null };

new JSONHttpRequest('/buildingmap.json',
					function(result) {buildingNameMap = result;populateBuildings();},
					function() {showError("Unable to load building list. Please refresh.");}
					);

function JSONHttpRequest(URL, loadCallback, errorCallback)
{
	var _this = this;
	this.URL = URL;
	this.loadCallback = loadCallback;
	this.errorCallback = errorCallback;
	this.onRequestComplete = function () {
		try
		{
			var response = JSON.parse(_this.httpRequest.responseText);
		}
		catch(SyntaxError)
		{
			_this.errorCallback("Unable to parse server response.");
			return;
		}
		_this.loadCallback(response);
	};
	this.httpRequest = new XMLHttpRequest();
	this.httpRequest.addEventListener("load",
										function() {
											_this.onRequestComplete();
											delete jsonRequestQueue.shift();
										},
										false);
	this.httpRequest.addEventListener("error",
										function() {
											_this.errorCallback("Unable to access the server.");
											delete jsonRequestQueue.shift();
										},
										false);
	this.httpRequest.open('GET', URL);
	this.httpRequest.send();
	jsonRequestQueue.push(this);
}

// Everything has to load before we use polymer
document.addEventListener("DOMContentLoaded", init, false);

function  init() {
	// Start data load
	forceUpdate();
	// Setup dropdown callbacks
	var elecInter = document.querySelectorAll("history-card")[0].shadowRoot.querySelector('paper-dropdown-menu');
    elecInter.addEventListener('core-select', function() {
      historyTypes["electricity"] = historyString(this.selected);
      updateHistoricalData();
    });
	var elecInter = document.querySelectorAll("history-card")[1].shadowRoot.querySelector('paper-dropdown-menu');
    elecInter.addEventListener('core-select', function() {
      historyTypes["heating"] = historyString(this.selected);
      updateHistoricalData();
    });
	var elecInter = document.querySelectorAll("history-card")[2].shadowRoot.querySelector('paper-dropdown-menu');
    elecInter.addEventListener('core-select', function() {
      historyTypes["cooling"] = historyString(this.selected);
      updateHistoricalData();
    });
	// Warn about data accuracy
	setTimeout(showError("WARNING: UNC's servers are experiencing problems causing significant historical data innacuracies."), 1000);
}

function forceUpdate()
{
	updateLiveData();
	updateHistoricalData();
}
function updateLiveData()
{
	updateLiveChart(document.querySelectorAll("meter-card")[0].shadowRoot, currentBuilding, 'electricity');
	updateLiveChart(document.querySelectorAll("meter-card")[1].shadowRoot, currentBuilding, 'heating');
	updateLiveChart(document.querySelectorAll("meter-card")[2].shadowRoot, currentBuilding, 'cooling');
	if (liveTimeout != -1)
		clearTimeout(liveTimeout);
	// Continue to update the live data every 10s
	liveTimeout = setTimeout(updateLiveData, 10*1000);
}
function updateHistoricalData()
{
	updateHistoryGraph(document.querySelectorAll("history-card")[0].shadowRoot, currentBuilding, 'electricity');
	updateHistoryGraph(document.querySelectorAll("history-card")[1].shadowRoot, currentBuilding, 'heating');
	updateHistoryGraph(document.querySelectorAll("history-card")[2].shadowRoot, currentBuilding, 'cooling');
	if (historyTimeout != -1)
		clearTimeout(historyTimeout);
	// Continue to update the historical data every 15m
	historyTimeout = setTimeout(updateHistoricalData, 1000*60*15);
}

/*
 * Displays a small error popup
 */
function showError(message)
{
	try
	{
		var elem = document.querySelector('#ajaxError');
		elem.text = message;
		elem.show();
	}
	catch (error){;}
}
String.prototype.capitalize = function() {
	return this.charAt(0).toUpperCase() + this.slice(1);
}
function updateLiveChart(livecard, buildingID, energyType)
{
	var name = buildingNameMap[buildingID];
	// Request data
	var request = new JSONHttpRequest(
		'api.php?building=' + buildingID + '&live=true',
		function (result) {drawLiveChart(result, livecard, name, energyType);},
		showError
	);
}
function updateHistoryGraph(livecard, buildingID, energyType)
{
	// Request data
	var request = new JSONHttpRequest(
		'api.php?building=' + buildingID,
		function (result) {drawHistoryGraph(result, livecard, energyType);},
		showError
	);
}
function drawLiveChart(jsonResult, livecard, buildingName, energyType)
{
	if (!livecard)
		return;
	// Validate
	if (jsonResult == null)
	{
		showError("No data avalible.");
		livecard.host.style.display = "none";
		return;
	}
	if (jsonResult == {} || !jsonResult[energyType])
	{
		showError("Invalid live " + energyType + " data");
		livecard.host.style.display = "none";
		return;
	}
	else
	{
		livecard.host.style.display = "block";
	}

	var ctx = livecard.getElementById('livechart').getContext("2d");
	var graph = {};

    // User Specs
	graph.x = 200; // Center X
	graph.y = 200; // Center Y
	graph.d = 250; // Graph Diameter
	graph.val = jsonResult[energyType]['amount'] / jsonResult[energyType]['maxRange']; // Current decimal value (0.0 - 1.0)

    // Autogen
	graph.r = graph.d / 2.0;
	graph.start = 3 * Math.PI / 4.0;
	graph.end = 9 * Math.PI / 4.0;
	graph.valEnd = graph.start + graph.val * 3 * Math.PI / 2.0;

    // Gray
	ctx.beginPath();
	ctx.strokeStyle = "#FFFFFF";
	ctx.fillStyle = "#808080";
	ctx.arc(graph.x, graph.y, graph.r, graph.start, graph.end);
	ctx.arc(graph.x, graph.y, graph.r / 2.0, graph.end, graph.start, true);
	ctx.closePath();
	ctx.fill();
	ctx.stroke();
	var c = document.getElementById("myCanvas2");

    // Red
	ctx.beginPath();
	ctx.strokeStyle = "#FFFFFF";
	ctx.fillStyle = "#FF0000";
	ctx.arc(graph.x, graph.y, graph.r, graph.start, graph.valEnd);
	ctx.arc(graph.x, graph.y, graph.r / 2.0, graph.valEnd, graph.start, true);
	ctx.closePath();
	ctx.fill();
	ctx.stroke();

	// Fill
	livecard.getElementById("amount").innerHTML = jsonResult[energyType]['amount'];
	livecard.getElementById("units").innerHTML = jsonResult[energyType]['nativeUnit'];
	livecard.getElementById("building").innerHTML = buildingName;
	livecard.getElementById("title").innerHTML = "Current " + energyType.capitalize() + " Usage";
}
/**
 * WARNING: The history data is notoriously bad. This tries to show data from the previous year
 * and may have significant mislabeling.
 */
function drawHistoryGraph(jsonResult, historycard, energyType)
{
	if (!historycard)
		return;
	// Validate
	if (jsonResult == null)
	{
		showError("No data avalible.");
		historycard.host.style.display = "none";
		return;
	}
	try {
		var dataTable = generateHistory(jsonResult, energyType);
		historycard.host.style.display = "block";
	}
	catch (e) {
		showError("Invalid historical " + energyType + " data");
		historycard.host.style.display = "none";
		return;
	}
	var ctx = historycard.getElementById("historygraph").getContext("2d");
	var data = {
		labels: dataTable[1],
		datasets: [
			{
				label: energyType.capitalize(),
				fillColor: "rgba(220,220,220,0.2)",
				strokeColor: "rgba(220,220,220,1)",
				pointColor: "rgba(220,220,220,1)",
				pointStrokeColor: "#fff",
				pointHighlightFill: "#fff",
				pointHighlightStroke: "rgba(220,220,220,1)",
				data: dataTable[0]
			}
		]
	};
	var options = {
		scaleLabel: "<%= value + '" + dataTable[2] + "' %>",
		animationSteps: 20,
	};

	if (historyGraphs[energyType] == null)
		// Render initial chart
		historyGraphs[energyType] = new Chart(ctx).Line(data, options);
	else if (historyGraphs[energyType].datasets[0].points.length == data.datasets[0].data.length) {
		// Update existing chart
		for (var i = 0; i < data.datasets[0].data.length; i++) {
			historyGraphs[energyType].datasets[0].points[i].value = data.datasets[0].data[i];
			historyGraphs[energyType].update();
		}
	}
	else {
		// Reload existing chart with new data
		while (historyGraphs[energyType].datasets[0].points.length)
			historyGraphs[energyType].removeData();
		for (var i = 0; i < data.datasets[0].data.length; i++)
			historyGraphs[energyType].addData([data.datasets[0].data[i]], data.labels[i]);
	}
	historycard.getElementById("title").innerHTML = "Historical " + energyType.capitalize() + " Usage";
}
function historyString(input) {
	switch (input)
	{
	case 'Today':
		return 'daily';
	case 'This Month':
		return 'monthly';
	case 'This Week':
		return 'weekly';
	case 'This Year':
		return 'yearly';
	}
}
function generateHistory(jsonResult, energyType) {
	var history = [];
	var labels = [];
	var date = new Date();
	switch (historyTypes[energyType]) {
		case 'daily': {
			date.setHours(0);
			while (labels.length < 24) {
				if (jsonResult['data'][energyType][historyTypes[energyType]]['current'].length > labels.length)
					history.push(Math.round(Number(jsonResult['data'][energyType][historyTypes[energyType]]['current'][labels.length]['amount'])));
				else
					history.push(0);
				var hour;
				if (date.getHours() == 0 || date.getHours() == 12)
					hour = "12";
				else
					hour = String(date.getHours() % 12);
				if (date.getHours() < 12)
					hour += "am";
				else
					hour += "pm";
				labels.push(hour);
				date.setHours(date.getHours() + 1);
			}
			break;
		}
		case 'weekly': {
			var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
			date.setDate(1);
			while (labels.length < 7) {
				if (jsonResult['data'][energyType][historyTypes[energyType]]['current'].length > labels.length)
					history.push(Math.round(Number(jsonResult['data'][energyType][historyTypes[energyType]]['current'][labels.length]['amount'])));
				else
					history.push(0);
				labels.push(days[date.getDay()]);
				date.setDate(date.getDate() + 1);
			}
			break;
		}
		case 'monthly': {
			date.setDate(1);
			while (true) {
				if (jsonResult['data'][energyType][historyTypes[energyType]]['current'].length > labels.length)
					history.push(Math.round(Number(jsonResult['data'][energyType][historyTypes[energyType]]['current'][labels.length]['amount'])));
				else
					history.push(0);
				labels.push(date.getDate());
				date.setDate(date.getDate() + 1);
				if (date.getDate() == 1)
					break;
			}
			break;
		}
		case 'yearly': {
			var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
			date.setMonth(0);
			while (labels.length < 12) {
				if (jsonResult['data'][energyType][historyTypes[energyType]]['current'].length > labels.length)
					history.push(Math.round(Number(jsonResult['data'][energyType][historyTypes[energyType]]['current'][labels.length]['amount'])));
				else
					history.push(0);
				labels.push(months[date.getMonth()]);
				date.setMonth(date.getMonth() + 1);
			}
			break;
		}
		default: {
			showError("Invalid historyType.");
		}
	}
	var units = jsonResult['data'][energyType][historyTypes[energyType]]['previous'][0]['unit'];
	for (var i = 0; i < history.length; i++) {
		switch (energyType) {
			case 'electricity':
				// Default units for electricity are kWh, but there in the possiblity for larger units (eg. MWh, GWh...) So adjust back to Wh first.
				units = "Wh";
				history[i] *= 1000;
			case 'cooling':
				if (history[i] >= 1000) {
					history[i] *= 0.001;
					units = 'k' + units;
				}
				else if (history[i] >= 1000000) {
					history[i] *= 0.000001;
					units = 'M' + units;
				}
				else if (history[i] >= 1000000000) {
					history[i] *= 0.000000001;
					units = 'G' + units;
				}
				else if (history[i] >= 1000000000000) {
					history[i] *= 0.000000000001;
					units = 'T' + units;
				}
				break;
			case 'heating':
				// Not sure about these units
				break;
			default:
				showError("Unknown energy type");
		}
	}
	return [history, labels, units];
}

function changeBuilding(newID) {
	// Reset initial selection on new selection
	if (newID != "113")
		document.getElementById("113").className = "";
	while (jsonRequestQueue.length > 0)
		jsonRequestQueue.pop().httpRequest.abort();
	currentBuilding = newID;
	forceUpdate();
}

function populateBuildings() {
	var currName;
	var buildingList = document.querySelector('core-menu');
	for (var ID in buildingNameMap) {
		// We have a few hand-picked demo buildings at the top, don't include them twice.
		if (ID == "113" || ID == "104" || ID == "083" || ID == "086" || ID == "027")
			continue;
		currName = document.createElement("core-item");
		currName.label = buildingNameMap[ID];
		currName.id = ID;
		buildingList.appendChild(currName);
	}
}

<commit_msg>Fix load timing issues and cleanup<commit_after>var currentBuilding = '113';
var historyTypes = { "electricity": "daily", "heating": "daily", "cooling": "daily" };
var buildingNameMap = {};
var jsonRequestQueue = [];
var liveTimeout = -1, historyTimeout = -1;
var historyGraphs = { 'electricity': null, 'heating': null, 'cooling': null };

new JSONHttpRequest('/buildingmap.json',
					function(result) {buildingNameMap = result;populateBuildings();},
					function() {showError("Unable to load building list. Please refresh.");}
					);

function JSONHttpRequest(URL, loadCallback, errorCallback)
{
	var _this = this;
	this.URL = URL;
	this.loadCallback = loadCallback;
	this.errorCallback = errorCallback;
	this.onRequestComplete = function () {
		try
		{
			var response = JSON.parse(_this.httpRequest.responseText);
		}
		catch(SyntaxError)
		{
			_this.errorCallback("Unable to parse server response.");
			return;
		}
		_this.loadCallback(response);
	};
	this.httpRequest = new XMLHttpRequest();
	this.httpRequest.addEventListener("load",
										function() {
											_this.onRequestComplete();
											delete jsonRequestQueue.shift();
										},
										false);
	this.httpRequest.addEventListener("error",
										function() {
											_this.errorCallback("Unable to access the server.");
											delete jsonRequestQueue.shift();
										},
										false);
	this.httpRequest.open('GET', URL);
	this.httpRequest.send();
	jsonRequestQueue.push(this);
}

// Everything has to load before we use polymer
document.addEventListener("polymer-ready", init, false);

function  init() {
	// Start data load
	forceUpdate();
	// Setup dropdown callbacks
	var elecInter = document.querySelectorAll("history-card")[0].shadowRoot.querySelector('paper-dropdown-menu');
	elecInter.addEventListener('core-select', function() {
		historyTypes["electricity"] = historyString(this.selected);
		updateHistoricalData();
	});
	var elecInter = document.querySelectorAll("history-card")[1].shadowRoot.querySelector('paper-dropdown-menu');
	elecInter.addEventListener('core-select', function() {
		historyTypes["heating"] = historyString(this.selected);
		updateHistoricalData();
	});
	var elecInter = document.querySelectorAll("history-card")[2].shadowRoot.querySelector('paper-dropdown-menu');
	elecInter.addEventListener('core-select', function() {
		historyTypes["cooling"] = historyString(this.selected);
		updateHistoricalData();
	});
	// Warn about data accuracy
	setTimeout(showError("WARNING: UNC's servers are experiencing problems causing significant historical data innacuracies."), 1000);
}

function forceUpdate()
{
	updateLiveData();
	updateHistoricalData();
}
function updateLiveData()
{
	updateLiveChart(document.querySelectorAll("meter-card")[0].shadowRoot, currentBuilding, 'electricity');
	updateLiveChart(document.querySelectorAll("meter-card")[1].shadowRoot, currentBuilding, 'heating');
	updateLiveChart(document.querySelectorAll("meter-card")[2].shadowRoot, currentBuilding, 'cooling');
	if (liveTimeout != -1)
		clearTimeout(liveTimeout);
	// Continue to update the live data every 10s
	liveTimeout = setTimeout(updateLiveData, 10*1000);
}
function updateHistoricalData()
{
	updateHistoryGraph(document.querySelectorAll("history-card")[0].shadowRoot, currentBuilding, 'electricity');
	updateHistoryGraph(document.querySelectorAll("history-card")[1].shadowRoot, currentBuilding, 'heating');
	updateHistoryGraph(document.querySelectorAll("history-card")[2].shadowRoot, currentBuilding, 'cooling');
	if (historyTimeout != -1)
		clearTimeout(historyTimeout);
	// Continue to update the historical data every 15m
	historyTimeout = setTimeout(updateHistoricalData, 1000*60*15);
}

/*
 * Displays a small error popup
 */
function showError(message)
{
	try
	{
		var elem = document.querySelector('#ajaxError');
		elem.text = message;
		elem.show();
	}
	catch (error){;}
}
String.prototype.capitalize = function() {
	return this.charAt(0).toUpperCase() + this.slice(1);
}
function updateLiveChart(livecard, buildingID, energyType)
{
	var name = buildingNameMap[buildingID];
	// Request data
	var request = new JSONHttpRequest(
		'api.php?building=' + buildingID + '&live=true',
		function (result) {drawLiveChart(result, livecard, name, energyType);},
		showError
	);
}
function updateHistoryGraph(livecard, buildingID, energyType)
{
	// Request data
	var request = new JSONHttpRequest(
		'api.php?building=' + buildingID,
		function (result) {drawHistoryGraph(result, livecard, energyType);},
		showError
	);
}
function drawLiveChart(jsonResult, livecard, buildingName, energyType)
{
	if (!livecard)
		return;
	// Validate
	if (jsonResult == null)
	{
		showError("No data avalible.");
		livecard.host.style.display = "none";
		return;
	}
	if (jsonResult == {} || !jsonResult[energyType])
	{
		showError("Invalid live " + energyType + " data");
		livecard.host.style.display = "none";
		return;
	}
	else
	{
		livecard.host.style.display = "block";
	}

	var ctx = livecard.getElementById('livechart').getContext("2d");
	var graph = {};

    // User Specs
	graph.x = 200; // Center X
	graph.y = 200; // Center Y
	graph.d = 250; // Graph Diameter
	graph.val = jsonResult[energyType]['amount'] / jsonResult[energyType]['maxRange']; // Current decimal value (0.0 - 1.0)

    // Autogen
	graph.r = graph.d / 2.0;
	graph.start = 3 * Math.PI / 4.0;
	graph.end = 9 * Math.PI / 4.0;
	graph.valEnd = graph.start + graph.val * 3 * Math.PI / 2.0;

    // Gray
	ctx.beginPath();
	ctx.strokeStyle = "#FFFFFF";
	ctx.fillStyle = "#808080";
	ctx.arc(graph.x, graph.y, graph.r, graph.start, graph.end);
	ctx.arc(graph.x, graph.y, graph.r / 2.0, graph.end, graph.start, true);
	ctx.closePath();
	ctx.fill();
	ctx.stroke();
	var c = document.getElementById("myCanvas2");

    // Red
	ctx.beginPath();
	ctx.strokeStyle = "#FFFFFF";
	ctx.fillStyle = "#FF0000";
	ctx.arc(graph.x, graph.y, graph.r, graph.start, graph.valEnd);
	ctx.arc(graph.x, graph.y, graph.r / 2.0, graph.valEnd, graph.start, true);
	ctx.closePath();
	ctx.fill();
	ctx.stroke();

	// Fill
	livecard.getElementById("amount").innerHTML = jsonResult[energyType]['amount'];
	livecard.getElementById("units").innerHTML = jsonResult[energyType]['nativeUnit'];
	livecard.getElementById("building").innerHTML = buildingName;
	livecard.getElementById("title").innerHTML = "Current " + energyType.capitalize() + " Usage";
}
/**
 * WARNING: The histroy data labeling is broken
 */
function drawHistoryGraph(jsonResult, historycard, energyType)
{
	if (!historycard)
		return;
	// Validate
	if (jsonResult == null)
	{
		showError("No data avalible.");
		historycard.host.style.display = "none";
		return;
	}
	try {
		var dataTable = generateHistory(jsonResult, energyType);
		historycard.host.style.display = "block";
	}
	catch (e) {
		showError("Invalid historical " + energyType + " data");
		historycard.host.style.display = "none";
		return;
	}
	var ctx = historycard.getElementById("historygraph").getContext("2d");
	var data = {
		labels: dataTable[1],
		datasets: [
			{
				label: energyType.capitalize(),
				fillColor: "rgba(220,220,220,0.2)",
				strokeColor: "rgba(220,220,220,1)",
				pointColor: "rgba(220,220,220,1)",
				pointStrokeColor: "#fff",
				pointHighlightFill: "#fff",
				pointHighlightStroke: "rgba(220,220,220,1)",
				data: dataTable[0]
			}
		]
	};
	var options = {
		scaleLabel: "<%= value + '" + dataTable[2] + "' %>",
		animationSteps: 20,
	};

	if (historyGraphs[energyType] == null)
		// Render initial chart
		historyGraphs[energyType] = new Chart(ctx).Line(data, options);
	else if (historyGraphs[energyType].datasets[0].points.length == data.datasets[0].data.length) {
		// Update existing chart
		for (var i = 0; i < data.datasets[0].data.length; i++) {
			historyGraphs[energyType].datasets[0].points[i].value = data.datasets[0].data[i];
			historyGraphs[energyType].update();
		}
	}
	else {
		// Reload existing chart with new data
		while (historyGraphs[energyType].datasets[0].points.length)
			historyGraphs[energyType].removeData();
		for (var i = 0; i < data.datasets[0].data.length; i++)
			historyGraphs[energyType].addData([data.datasets[0].data[i]], data.labels[i]);
	}
	historycard.getElementById("title").innerHTML = "Historical " + energyType.capitalize() + " Usage";
}
function historyString(input) {
	switch (input)
	{
	case 'Today':
		return 'daily';
	case 'This Month':
		return 'monthly';
	case 'This Week':
		return 'weekly';
	case 'This Year':
		return 'yearly';
	}
}
function generateHistory(jsonResult, energyType) {
	var history = [];
	var labels = [];
	var date = new Date();
	switch (historyTypes[energyType]) {
		case 'daily': {
			date.setHours(0);
			while (labels.length < 24) {
				if (jsonResult['data'][energyType][historyTypes[energyType]]['current'].length > labels.length)
					history.push(Math.round(Number(jsonResult['data'][energyType][historyTypes[energyType]]['current'][labels.length]['amount'])));
				else
					history.push(0);
				var hour;
				if (date.getHours() == 0 || date.getHours() == 12)
					hour = "12";
				else
					hour = String(date.getHours() % 12);
				if (date.getHours() < 12)
					hour += "am";
				else
					hour += "pm";
				labels.push(hour);
				date.setHours(date.getHours() + 1);
			}
			break;
		}
		case 'weekly': {
			var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
			date.setDate(1);
			while (labels.length < 7) {
				if (jsonResult['data'][energyType][historyTypes[energyType]]['current'].length > labels.length)
					history.push(Math.round(Number(jsonResult['data'][energyType][historyTypes[energyType]]['current'][labels.length]['amount'])));
				else
					history.push(0);
				labels.push(days[date.getDay()]);
				date.setDate(date.getDate() + 1);
			}
			break;
		}
		case 'monthly': {
			date.setDate(1);
			while (true) {
				if (jsonResult['data'][energyType][historyTypes[energyType]]['current'].length > labels.length)
					history.push(Math.round(Number(jsonResult['data'][energyType][historyTypes[energyType]]['current'][labels.length]['amount'])));
				else
					history.push(0);
				labels.push(date.getDate());
				date.setDate(date.getDate() + 1);
				if (date.getDate() == 1)
					break;
			}
			break;
		}
		case 'yearly': {
			var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
			date.setMonth(0);
			while (labels.length < 12) {
				if (jsonResult['data'][energyType][historyTypes[energyType]]['current'].length > labels.length)
					history.push(Math.round(Number(jsonResult['data'][energyType][historyTypes[energyType]]['current'][labels.length]['amount'])));
				else
					history.push(0);
				labels.push(months[date.getMonth()]);
				date.setMonth(date.getMonth() + 1);
			}
			break;
		}
		default: {
			showError("Invalid historyType.");
		}
	}
	var units = jsonResult['data'][energyType][historyTypes[energyType]]['previous'][0]['unit'];
	for (var i = 0; i < history.length; i++) {
		switch (energyType) {
			case 'electricity':
				// Default units for electricity are kWh, but there in the possiblity for larger units (eg. MWh, GWh...) So adjust back to Wh first.
				units = "Wh";
				history[i] *= 1000;
			case 'cooling':
				if (history[i] >= 1000) {
					history[i] *= 0.001;
					units = 'k' + units;
				}
				else if (history[i] >= 1000000) {
					history[i] *= 0.000001;
					units = 'M' + units;
				}
				else if (history[i] >= 1000000000) {
					history[i] *= 0.000000001;
					units = 'G' + units;
				}
				else if (history[i] >= 1000000000000) {
					history[i] *= 0.000000000001;
					units = 'T' + units;
				}
				break;
			case 'heating':
				// Not sure about these units
				break;
			default:
				showError("Unknown energy type");
		}
	}
	return [history, labels, units];
}

function changeBuilding(newID) {
	// Reset initial selection on new selection
	if (newID != "113")
		document.getElementById("113").className = "";
	while (jsonRequestQueue.length > 0)
		jsonRequestQueue.pop().httpRequest.abort();
	currentBuilding = newID;
	forceUpdate();
}

function populateBuildings() {
	var currName;
	var buildingList = document.querySelector('core-menu');
	for (var ID in buildingNameMap) {
		// We have a few hand-picked demo buildings at the top, don't include them twice.
		if (ID == "113" || ID == "104" || ID == "083" || ID == "086" || ID == "027")
			continue;
		currName = document.createElement("core-item");
		currName.label = buildingNameMap[ID];
		currName.id = ID;
		buildingList.appendChild(currName);
	}
}

<|endoftext|>


<commit_before> if (localStorage.save) {
     var game = JSON.parse(atob(localStorage.save));
 } else {
     var game = {
         clicks: 0,
         upgrades: [0, 0, 0, 0, 0, 0, 0, 0],
         cps: 0,
         upgradePrice: [15, 100, 500, 2000, 7000, 50000, 1000000, 100000000],
         upgradeCps: [0.1, 0.5, 4, 10, 40, 100, 400, 7000]
     };
 }

 function saveGame() {
     localStorage.save = btoa(JSON.stringify(game));
 }

 function gameLoop() {
     game.clicks += game.cps;
     updateView();
     saveGame();
 }

 function buyUpgrade(x) {
     if (game.clicks >= game.upgradePrice[x]) {
         game.clicks -= game.upgradePrice[x];
         game.upgradePrice[x] = Math.ceil(game.upgradePrice[x] * 1.15);
         game.upgrades[x] += 1;
         game.cps += game.upgradeCps[x];
     }
 }
 var gameLoopInterval = setInterval(gameLoop, 1000);

 function updateView() {
     $("#count").html(Math.round(game.clicks).toLocaleString());
     $("#cps").html((Math.round(game.cps * 10) / 10).toFixed(1));
     $("#price0").html(game.upgradePrice[0]);
     $("#price1").html(game.upgradePrice[1]);
     $("#price2").html(game.upgradePrice[2]);
     $("#price3").html(game.upgradePrice[3]);
     $("#price4").html(game.upgradePrice[4]);
     $("#price5").html(game.upgradePrice[5]);
     $("#price6").html(game.upgradePrice[6]);
     $("#price7").html(game.upgradePrice[7]);
     $("#qty0").html(game.upgrades[0]);
     $("#qty1").html(game.upgrades[1]);
     $("#qty2").html(game.upgrades[2]);
     $("#qty3").html(game.upgrades[3]);
     $("#qty4").html(game.upgrades[4]);
     $("#qty5").html(game.upgrades[5]);
     $("#qty6").html(game.upgrades[6]);
     $("#qty7").html(game.upgrades[7]);
 }
 $(function() {
     $("#circle").click(function() {
      if(game.cps>4){
         game.clicks += game.cps / 4;
      }
      else{
         game.clicks += 1;
      }
         updateView();
     });
 });

 function exportSave() {
     prompt('This is your save. Keep it.', btoa(JSON.stringify(game)));
 }

 function importSave() {
     game = JSON.parse(atob(prompt('Enter your save here. Your previous save will not be saved.')));
     saveGame();
     location.reload();
 }

 function wipeSave() {
     if (confirm('Are you sure you would like to delete EVERYTHING?')) {
         clearInterval(gameLoopInterval);
         localStorage.save = "";
         alert('Deleted.');
         location.reload();
     } else {
         alert('Cancelled.');
     }
 }
<commit_msg>Update main.js<commit_after> if (localStorage.save) {
     var game = JSON.parse(atob(localStorage.save));
 } else {
     var game = {
         clicks: 0,
         upgrades: [0, 0, 0, 0, 0, 0, 0, 0],
         cps: 0,
         upgradePrice: [15, 100, 500, 2000, 7000, 50000, 1000000, 100000000],
         upgradeCps: [0.1, 0.5, 4, 10, 40, 100, 400, 7000]
     };
 }

 function saveGame() {
     localStorage.save = btoa(JSON.stringify(game));
 }

 function gameLoop() {
     game.clicks += game.cps;
     updateView();
     saveGame();
 }

 function buyUpgrade(x) {
     if (game.clicks >= game.upgradePrice[x]) {
         game.clicks -= game.upgradePrice[x];
         game.upgradePrice[x] = Math.ceil(game.upgradePrice[x] * 1.15);
         game.upgrades[x] += 1;
         game.cps += game.upgradeCps[x];
     }
 }
 var gameLoopInterval = setInterval(gameLoop, 1000);

 function updateView() {
     $("#count").html(Math.round(game.clicks).toLocaleString());
     $("#cps").html((Math.round(game.cps * 10) / 10).toFixed(1).toLocaleString());
     $("#price0").html(game.upgradePrice[0].toLocaleString());
     $("#price1").html(game.upgradePrice[1].toLocaleString());
     $("#price2").html(game.upgradePrice[2].toLocaleString());
     $("#price3").html(game.upgradePrice[3].toLocaleString());
     $("#price4").html(game.upgradePrice[4].toLocaleString());
     $("#price5").html(game.upgradePrice[5].toLocaleString());
     $("#price6").html(game.upgradePrice[6].toLocaleString());
     $("#price7").html(game.upgradePrice[7].toLocaleString());
     $("#qty0").html(game.upgrades[0].toLocaleString());
     $("#qty1").html(game.upgrades[1].toLocaleString());
     $("#qty2").html(game.upgrades[2].toLocaleString());
     $("#qty3").html(game.upgrades[3].toLocaleString());
     $("#qty4").html(game.upgrades[4].toLocaleString());
     $("#qty5").html(game.upgrades[5].toLocaleString());
     $("#qty6").html(game.upgrades[6].toLocaleString());
     $("#qty7").html(game.upgrades[7].toLocaleString());
 }
 $(function() {
     $("#circle").click(function() {
      if(game.cps>4){
         game.clicks += game.cps / 4;
      }
      else{
         game.clicks += 1;
      }
         updateView();
     });
 });

 function exportSave() {
     prompt('This is your save. Keep it.', btoa(JSON.stringify(game)));
 }

 function importSave() {
     game = JSON.parse(atob(prompt('Enter your save here. Your previous save will not be saved.')));
     saveGame();
     location.reload();
 }

 function wipeSave() {
     if (confirm('Are you sure you would like to delete EVERYTHING?')) {
         clearInterval(gameLoopInterval);
         localStorage.save = "";
         alert('Deleted.');
         location.reload();
     } else {
         alert('Cancelled.');
     }
 }
<|endoftext|>


<commit_before>// consts for color
const PLATFORMCOLOR = "#FFFFFF";

// consts for brick stuff
const widthDivisor = 10;
const heightDivisor = 20;
const numOfRows = 5;
const velocityDivisor = -250;

class Ball{
  constructor(locX, ctx){
    this.x = locX;
    //set initial y and size values
    this.y = ctx.canvas.height - (ctx.canvas.height / 5);
    this.rad = 25;
    this.velX = 0;
    this.velY = 0;
  }

  spawn(ctx){
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.rad, 0,2*Math.PI);
    ctx.fillStyle = "#cd2121";
    ctx.fill();
    ctx.stroke();

    //get a random number, negative one or positive one
    var randNum = Math.random();
    if (randNum <= .5){
      randNum = -1;
    }
    else{
      randNum = 1;
    }
    this.velX = ctx.canvas.width / velocityDivisor * randNum;
    this.velY = ctx.canvas.height / velocityDivisor;
  }

  update(ctx, bricks, platform){
    //check if the ball is at the upper or lower bounds
    if(this.y >= ctx.canvas.height - this.rad || this.y <= 0 + this.rad){
      this.velY = this.velY * -1;
    }
    else if(this.y >= (platform.y - platform.boxHeight) && this.x > (platform.x - this.rad) && this.x < (platform.x + platform.size + this.rad) && this.velY > 0){
      this.velY = this.velY * -1;
    }

    if(this.x >= ctx.canvas.width - this.rad || this.x <= 0 + this.rad){
      this.velX = this.velX * -1;
    }

    //update the location according to the velocity
    this.x += this.velX;
    this.y += this.velY;

    ctx.beginPath();
    ctx.arc(this.x, this.y, this.rad, 0,2*Math.PI);
    ctx.fillStyle = "#cd2121";
    ctx.fill();
    ctx.stroke();
  }
}

class Platform {
    constructor(locX, size, ctx) {
        this.x = locX;
        this.size = size;
        //set default variables
        this.y = ctx.canvas.height - (ctx.canvas.height / 10);
        this.boxHeight = window.innerHeight / 25;
    }

    draw(ctx) {
        ctx.fillStyle = PLATFORMCOLOR;
        ctx.fillRect(this.x, this.y, this.size, this.boxHeight);
    }

    update(ctx, mouseX) {
        this.x = mouseX;

        if (this.x > ctx.canvas.width - (this.size / 2)) {
            this.x = ctx.canvas.width - (this.size / 2);
        } else if (this.x < this.size / 2) {
            this.x = this.size / 2;
        }
      this.x = this.x - (ctx.canvas.width / 10) / 2;
      this.x = this.x - (ctx.canvas.width / 5) / 2;
      ctx.fillStyle = PLATFORMCOLOR;
      ctx.fillRect(this.x, this.y, this.size, this.boxHeight);
    }

}

function Brick(health, x, y, ctx) {
    this.health = health;
    this.xPosition = x;
    this.yPosition = y;
    this.color = 'hsl(' + 360 * Math.random() + ', 75%, 60%)'; // random color, same saturation and intensity

    // constant for all bricks
    this.width = ctx.canvas.width / widthDivisor;
    this.height = ctx.canvas.height / heightDivisor;

    //functions
    this.draw = function (ctx){
        // fill with color
        ctx.rect(this.xPosition, this.yPosition, this.width, this.height)
        ctx.fillStyle = this.color;
        ctx.fillRect(this.xPosition, this.yPosition, this.width, this.height);
        // add stroke
        ctx.lineWidth = 1;
        ctx.strokeStyle = "black";
        ctx.stroke();
    }

    this.update = function(ctx){
        ctx.beginPath();
        this.draw(ctx);
    }
}

function update(canvas, ctx, mouseX, platform, bricks, ball){
      //clear the canvas
      ctx.clearRect(0,0,canvas.width, canvas.height);

      //update the platform location
      platform.update(ctx, mouseX);

      ball.update(ctx, bricks, platform);

      // update bricks
      for (var b of bricks)
          b.update(ctx);
}

function init() {
    // class variables
    var bricks = [];

    var canvas = document.getElementById('game'),
        ctx = canvas.getContext('2d');

    //set default mouse position
    var mouseX = ctx.canvas.width / 2;

    // autosize canvas to window size
    ctx.canvas.width = window.innerWidth;
    ctx.canvas.height = window.innerHeight;

    // draw all the bricks
    for (y = 0; y < numOfRows; y++) {
        for (x = 0; x < widthDivisor; x++) {
            var b = new Brick(1, x * (ctx.canvas.width / widthDivisor), (ctx.canvas.height / widthDivisor) + (y * (ctx.canvas.height / heightDivisor)), ctx);
            b.draw(ctx);
            bricks.push(b);
        }
    }

    //create new platform and draw it
    var platform = new Platform(ctx.canvas.width / 2, ctx.canvas.width / 10, ctx);
    platform.draw(ctx);

    //spawn a ball
    var ball = new Ball(ctx.canvas.width / 2, ctx);
    ball.spawn(ctx);

    setInterval( function() {
      document.onmousemove = function(e){
        mouseX = e.clientX;
      }
      update(canvas, ctx, mouseX, platform, bricks, ball)
    }, 1);

    setInterval(function () {
        document.onmousemove = function (e) {
            mouseX = e.clientX;
        }
        update(canvas, ctx, mouseX, platform, bricks)
    }, 17);
}

document.addEventListener("DOMContentLoaded", init, false);
<commit_msg>fixed flashing<commit_after>// consts for color
const PLATFORMCOLOR = "#FFFFFF";

// consts for brick stuff
const widthDivisor = 10;
const heightDivisor = 20;
const numOfRows = 5;
const velocityDivisor = -250;

class Ball {
    constructor(locX, ctx) {
        this.x = locX;
        //set initial y and size values
        this.y = ctx.canvas.height - (ctx.canvas.height / 5);
        this.rad = 25;
        this.velX = 0;
        this.velY = 0;
    }

    spawn(ctx) {
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.rad, 0, 2 * Math.PI);
        ctx.fillStyle = "#cd2121";
        ctx.fill();
        ctx.stroke();

        //get a random number, negative one or positive one
        var randNum = Math.random();
        if (randNum <= .5) {
            randNum = -1;
        } else {
            randNum = 1;
        }
        this.velX = ctx.canvas.width / velocityDivisor * randNum;
        this.velY = ctx.canvas.height / velocityDivisor;
    }

    update(ctx, platform) {
        //check if the ball is at the upper or lower bounds
        if (this.y >= ctx.canvas.height - this.rad || this.y <= 0 + this.rad) {
            this.velY = this.velY * -1;
        } else if (this.y >= (platform.y - platform.boxHeight) && this.x > (platform.x - this.rad) && this.x < (platform.x + platform.size + this.rad) && this.velY > 0) {
            this.velY = this.velY * -1;
        }

        if (this.x >= ctx.canvas.width - this.rad || this.x <= 0 + this.rad) {
            this.velX = this.velX * -1;
        }

        //update the location according to the velocity
        this.x += this.velX;
        this.y += this.velY;

        ctx.beginPath();
        ctx.arc(this.x, this.y, this.rad, 0, 2 * Math.PI);
        ctx.fillStyle = "#cd2121";
        ctx.fill();
        ctx.stroke();
        ctx.closePath();
    }
}

class Platform {
    constructor(locX, size, ctx) {
        this.x = locX;
        this.size = size;
        //set default variables
        this.y = ctx.canvas.height - (ctx.canvas.height / 10);
        this.boxHeight = window.innerHeight / 25;
    }

    draw(ctx) {
        ctx.fillStyle = PLATFORMCOLOR;
        ctx.fillRect(this.x, this.y, this.size, this.boxHeight);
    }

    update(ctx, mouseX) {
        this.x = mouseX;

        if (this.x > ctx.canvas.width - (this.size / 2)) {
            this.x = ctx.canvas.width - (this.size / 2);
        } else if (this.x < this.size / 2) {
            this.x = this.size / 2;
        }
        this.x = this.x - (ctx.canvas.width / 10) / 2;
        this.x = this.x - (ctx.canvas.width / 5) / 2;
        ctx.fillStyle = PLATFORMCOLOR;
        ctx.fillRect(this.x, this.y, this.size, this.boxHeight);
    }

}

function Brick(health, x, y, ctx) {
    this.health = health;
    this.xPosition = x;
    this.yPosition = y;
    this.color = 'hsl(' + 360 * Math.random() + ', 75%, 60%)'; // random color, same saturation and intensity

    // constant for all bricks
    this.width = ctx.canvas.width / widthDivisor;
    this.height = ctx.canvas.height / heightDivisor;

    //functions
    this.draw = function (ctx) {
        // fill with color
        ctx.rect(this.xPosition, this.yPosition, this.width, this.height)
        ctx.fillStyle = this.color;
        ctx.fillRect(this.xPosition, this.yPosition, this.width, this.height);
        // add stroke
        ctx.lineWidth = 1;
        ctx.strokeStyle = "black";
        ctx.stroke();
    }

    this.update = function (ctx) {
        ctx.beginPath();
        this.draw(ctx);
    }
}

function update(canvas, ctx, mouseX, platform, bricks, ball) {
    //clear the canvas
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    //update the platform location
    platform.update(ctx, mouseX);

    ball.update(ctx, platform);

    // update bricks
    for (var b of bricks)
        b.update(ctx);
}

function init() {
    // class variables
    var bricks = [];

    var canvas = document.getElementById('game'),
        ctx = canvas.getContext('2d');

    //set default mouse position
    var mouseX = ctx.canvas.width / 2;

    // autosize canvas to window size
    ctx.canvas.width = window.innerWidth;
    ctx.canvas.height = window.innerHeight;

    // draw all the bricks
    for (y = 0; y < numOfRows; y++) {
        for (x = 0; x < widthDivisor; x++) {
            var b = new Brick(1, x * (ctx.canvas.width / widthDivisor), (ctx.canvas.height / widthDivisor) + (y * (ctx.canvas.height / heightDivisor)), ctx);
            b.draw(ctx);
            bricks.push(b);
        }
    }

    //create new platform and draw it
    var platform = new Platform(ctx.canvas.width / 2, ctx.canvas.width / 10, ctx);
    platform.draw(ctx);

    //spawn a ball
    var ball = new Ball(ctx.canvas.width / 2, ctx);
    ball.spawn(ctx);

    setInterval(function () {
        document.onmousemove = function (e) {
            mouseX = e.clientX;
        }
        update(canvas, ctx, mouseX, platform, bricks, ball)
    }, 17);
}

document.addEventListener("DOMContentLoaded", init, false);<|endoftext|>


<commit_before>var dtd = angular.module('d2d', ['ngAnimate', 'ui.bootstrap']);

dtd.controller("mainCtrl", ['$scope', '$location', '$http', function($scope, $location, $http){
  $scope.projects = [{
    'amountNeeded': 290,
    'amountSofar': 0,
    'location': 'Ashanti, Ghana',
    'money_description':'$280 to equip 1 Community Health Worker with essential medication and supplies. ',
    'treatment_description': 'Community Health Workers will be equipped with essential medication and supplies enabling them to treat women and children with critical illnesses including malaria, diarrhea, malnutrition, and pneumonia. These items make the difference between leading a productive life or being held back with increasingly serious medical conditions.',
    'focus': 'Health Kits Focus',
    'breakdown': [
      {'value': 71,
      'type': 'danger',
      'description': 'Essential medical and logistical supplies including e.g. soap, stationery (counseling cards and job aids), a thermometer, respiratory timer, water jugs and a backpack.'
    },{
        'value': 29,
        'type': 'success',
        'description':'Critical medication including medicines to treat diarrhea, malaria, pneumonia, malnutrition and care for pregnant mothers.'
      }
    ],
    'cashtag': 'fear',
    'type': 'success',
    'value': '40',
    'breakdown_txt': '71%: Essential medical and logistical supplies including e.g. soap, stationery (counseling cards and job aids), a thermometer, respiratory timer, water jugs and a backpack. 29%: Critical medication including medicines to treat diarrhea, malaria, pneumonia, malnutrition and care for pregnant mothers.'
  },{
    'amountNeeded': 425,
    'amountSofar': 313,
    'location': 'Hargeisa, Somaliland ',
    'description': 'My name is Dr. Shukri Mohamed Dahir and sitting next to me is Dr. Naima Ahmed Mohamed. We are both doctors: we went to Medical School together and are now working as a …',
    'focus': 'Birth Injuries Focus',
    'treatment_description': 'Our focus is on providing safe births and caesarean sections for mothers. In Somaliland most mothers do not receive prenatal care. As a result, they often have unknown problems such as anemia, diabetes or hypertension that go untreated. Sometimes more serious issues develop, such as obstructed labor; in these cases, we do a surgical procedure known as a caesarian section, which involves making an incision through the mother\'s abdomen to deliver the baby.',
    'cashtag': 'fear',
    'type': 'success',
    'value': '50',
    'breakdown_txt':'Operation. 19%: Medication & dressings. 19%: Hospital stay (8 days). 9%: Lab tests, screening, grouping & X-matching. 6%: Anesthesia.',
    'breakdown': [{
        'value': 47,
        'type': 'info'
      }, {
        'value': 19,
        'type': 'danger'
      }, {
        'value': 19,
        'type': 'warning'
      }, {
        'value': 9,
        'type': 'success'
      }, {
        'value': 6,
        'type': 'info'
      }
    ]
  }
  ];

  $scope.updateProgressBar = function() {
    var types = ['danger','warning','info','success'];
    for (project in $scope.projects) {
      project.value = Math.floor(project.amountSofar / project.amountNeeded * 100);
      project.type = types[Math.floor(project.value/25)];
    }
  };
  $scope.updateProgressBar();
}]);
<commit_msg>Added doctor name.<commit_after>var dtd = angular.module('d2d', ['ngAnimate', 'ui.bootstrap']);

dtd.controller("mainCtrl", ['$scope', '$location', '$http', function($scope, $location, $http){
  $scope.projects = [{
    'amountNeeded': 290,
    'amountSofar': 0,
    'doctorName': 'Padina Apam',
    'location': 'Ashanti, Ghana',
    'money_description':'$280 to equip 1 Community Health Worker with essential medication and supplies. ',
    'treatment_description': 'Community Health Workers will be equipped with essential medication and supplies enabling them to treat women and children with critical illnesses including malaria, diarrhea, malnutrition, and pneumonia. These items make the difference between leading a productive life or being held back with increasingly serious medical conditions.',
    'focus': 'Health Kits Focus',
    'breakdown': [
      {'value': 71,
      'type': 'danger',
      'description': 'Essential medical and logistical supplies including e.g. soap, stationery (counseling cards and job aids), a thermometer, respiratory timer, water jugs and a backpack.'
    },{
        'value': 29,
        'type': 'success',
        'description':'Critical medication including medicines to treat diarrhea, malaria, pneumonia, malnutrition and care for pregnant mothers.'
      }
    ],
    'cashtag': 'fear',
    'type': 'success',
    'value': '40',
    'breakdown_txt': '71%: Essential medical and logistical supplies including e.g. soap, stationery (counseling cards and job aids), a thermometer, respiratory timer, water jugs and a backpack. 29%: Critical medication including medicines to treat diarrhea, malaria, pneumonia, malnutrition and care for pregnant mothers.'
  },{
    'amountNeeded': 425,
    'amountSofar': 313,
    'doctorName': 'Dr. Shukri and Dr. Naima',
    'location': 'Hargeisa, Somaliland ',
    'description': 'My name is Dr. Shukri Mohamed Dahir and sitting next to me is Dr. Naima Ahmed Mohamed. We are both doctors: we went to Medical School together and are now working as a …',
    'focus': 'Birth Injuries Focus',
    'treatment_description': 'Our focus is on providing safe births and caesarean sections for mothers. In Somaliland most mothers do not receive prenatal care. As a result, they often have unknown problems such as anemia, diabetes or hypertension that go untreated. Sometimes more serious issues develop, such as obstructed labor; in these cases, we do a surgical procedure known as a caesarian section, which involves making an incision through the mother\'s abdomen to deliver the baby.',
    'cashtag': 'fear',
    'type': 'success',
    'value': '50',
    'breakdown_txt':'Operation. 19%: Medication & dressings. 19%: Hospital stay (8 days). 9%: Lab tests, screening, grouping & X-matching. 6%: Anesthesia.',
    'breakdown': [{
        'value': 47,
        'type': 'info'
      }, {
        'value': 19,
        'type': 'danger'
      }, {
        'value': 19,
        'type': 'warning'
      }, {
        'value': 9,
        'type': 'success'
      }, {
        'value': 6,
        'type': 'info'
      }
    ]
  }
  ];

  $scope.updateProgressBar = function() {
    var types = ['danger','warning','info','success'];
    for (project in $scope.projects) {
      project.value = Math.floor(project.amountSofar / project.amountNeeded * 100);
      project.type = types[Math.floor(project.value/25)];
    }
  };
  $scope.updateProgressBar();
}]);
<|endoftext|>


<commit_before>var map;
function initialize() {
  var mapOptions = {
    zoom: 9,
    enter: new google.maps.LatLng(34.708, -77.959),
    zoomControlOptions: {
        style: google.maps.ZoomControlStyle.SMALL
    }
  };

  google.maps.visualRefresh=true;
  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

  // Load a GeoJSON from the same server as our demo.
  var jsonData = "data/ncVacationData.json";
  map.data.loadGeoJson(jsonData);

  // Set mouseover event for each feature.
  map.data.addListener('mouseover', function(event) {
    content = event.feature.getProperty('Name');
  });

  var infoWindow = new google.maps.InfoWindow({
    content: content
  });

}

google.maps.event.addDomListener(window, 'load', initialize);
<commit_msg>Update main.js<commit_after>var map;
function initialize() {
  var mapOptions = {
    zoom: 9,
    enter: new google.maps.LatLng(34.708, -77.959),
    zoomControlOptions: {
        style: google.maps.ZoomControlStyle.SMALL
    }
  };

  google.maps.visualRefresh=true;
  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

  // Load a GeoJSON from the same server as our demo.
  var jsonData = "data/ncVacationData.json";
  map.data.loadGeoJson(jsonData);

  // Set mouseover event for each feature.
  map.data.addListener('mouseover', function(event) {
    content = event.feature.getProperty('Name');
  });

  var infoWindow = new google.maps.InfoWindow({
    // content: content
  });

}

google.maps.event.addDomListener(window, 'load', initialize);
<|endoftext|>


<commit_before>/*global $ */
'use strict';

//---Objects---//

//Player Class
function Player(name){
	this.name = name;
	this.stump = new TreeStump();
}

//ask for number of players and each players name
function startGame(){
		var numberOfPlayers = prompt('How many players do we have?'),playerName = '',player = {};
		//sanity check
		console.log('num of players is ' + numberOfPlayers);
		for (var i = 0; i < numberOfPlayers; i++) {
			playerName = prompt('What is this player '+ (i+1) +'\'s name?');
			player[i] = new Player(playerName);
			players.push(player[i]);
		}
		return players;
	}

//Makes a list of the players
function listPlayers(){
	var list = [],playerName,playerBox;
	for (var i = 0; i < players.length; i++) {
		playerName = players[i].name;
		playerBox = '
'+playerName+'
';
		list.push(playerBox);
	}
	return list;
}

//Spinner Class.
//Represents the spin wheel.
//Returns: id, name, instruction, and action of spin result
function Spinner() {
	//Array to represent the game spinner
	this.wheel = [
		{
			id: 0,
			name: 'Sneaky Squire',
			// verb: placeholderFunction(),
			instruction: 'You get to Steal an Acorn from another user!',
			action: 'steal'
		},
		{
			id: 1,
			name: 'Sleepy Squire',
			// verb: placeholderFunction(),
			instruction: 'Oh no! You lose your turn because you were sleeping. :(',
			action: 'skip'
		},
		{
			id: 2,
			name: 'Wind Storm',
			// verb: placeholderFunction(),
			instruction: 'A strong wind storm blew all your acorns away. Tough break.',
			action: 'clear'
		},
		{
			id: 3,
			name: 'Green',
            color:'green',
            //verb: addColorSquare(this.color),
			instruction: 'You get a Green Acorn'
		},
		{
			id: 4,
			name: 'Blue',
			color:'blue',
			// verb: placeholderFunction(),
			instruction: 'You get a Blue Acorn'
		},
		{
			id: 5,
			name: 'Red',
			color:'red',
			// verb: placeholderFunction(),
			instruction: 'You get a Red Acorn'
		},
		{
			id: 6,
			name: 'Purple',
			color:'purple',
			// verb: placeholderFunction(),
			instruction: 'You get a Purple Acorn'
		},
		{
			id: 7,
			name: 'Yellow',
			color:'yellow',
			// verb: placeholderFunction(),
			instruction: 'You get a Yellow Acorn'
		},
		{
			id: 8,
			name: 'Pick One',
			// verb: placeholderFunction(),
			instruction: 'You get to pick an Acorn',
			action: 'pick_one'
		},
		{
			id: 9,
			name: 'Pick Two',
			// verb: placeholderFunction(),
			instruction: 'You get to pick Two Acorns',
			action: 'pick_two'
		}
    ];

	//Spin the Wheel function. Returns a representation of landing on a color or event
	this.spin = function () {
		//get a random number
        var i = Math.floor((Math.random()*this.wheel.length));
        //feed that number to the wheel array to pull an individual item
        var result = this.wheel[i];
        return result;
    };
}

//function to check is player already has the acorn color in their stump
function acornCheck(player, result){
	for (var k = players[player].stump.space.length - 1; k >= 0; k--) {
		if(players[player].stump.space[k].color === result.color){
			if(players[player].stump.space[k].isEmpty === true){
				players[player].stump.space[k].isEmpty = false;
			}else{
				console.log('You already have this Acorn!');
			}
		}
	};
}

//Game Piece Class
function TreeStump() {
	var empty = Boolean(true);
	this.space = [
		{
			color: 'red',
			isEmpty: empty
		},
		{
			color: 'blue',
			isEmpty: empty
		},
		{
			color: 'yellow',
			isEmpty: empty
		},
		{
			color: 'green',
			isEmpty: empty
		},
		{
			color: 'purple',
			isEmpty: empty
		}
	];

	//display in html
	$('.playerBox').html('
playerCard
');
}

//manage who's turn it is
function playerTurn(){
	var numOfPlayers = players.length;
	var currentPlayer = players[0];
	return currentPlayer;

	// for (var i = 0; i <= numOfPlayers - 1; i++) {
	// 	players.player[i++];
	// };
}

//---Declare Variables---//

//holds the list of players
var players = []
	,spinner = new Spinner()
;

//Begin the game by asking the number of players and their name
startGame();

$(document).ready(function(){
	//make the players name visible
	$('.player_table').append(listPlayers());
	//who's turn is it?
	for(var j = 0; j < players.length;j++){
		//print who's turn it is
		$('.player_turn_information').html('It is player: '+ players[j].name +'\'s turn.');
		//1. when a user clicks Spin the Wheel, pick a random wheelElement
		$('#spin_button').click(function(){
			var result = spinner.spin();
			$('.spin_action_result').html(result.instruction);
			//2. check to see if the wheelElement is a Color or Event
			var colorOrAction = result.hasOwnProperty('color');
			if(colorOrAction){
				//sanity check
				console.log(result.color);
				console.log(players[j].name);
				//3. if it is a Color, check to see if the users treeStump already has the Color
				acornCheck(j,result);
			}
		});
		return;
	}
});

//3a. add color to treeStump if it doesn't exist, else skip turn
//3b. check to see if the active players treeStump is full.  if so, they win. else move to next player
//4. if it is an Event, check to see which Event it is
//4a. if event is Sneaky Squire - steal an Acorn from another player
//4a_A  bring up list of every player containing thier Acorns
//4a_B  When the active Player selects an Acorn from another list, add it to thier treeStump
//4a_C  check to see if treeStump is full. if so, they win End turn
//5. if event is Sleepy Squire - skip turn
//6. if event is Wind Storm - remove all Acorns from active Players list

<commit_msg>Got the player turn advancing working<commit_after>/*global $ */
'use strict';

//---Objects---//

//Player Class
function Player(name){
	this.name = name;
	this.stump = new TreeStump();
}

//ask for number of players and each players name
function startGame(){
		var numberOfPlayers = prompt('How many players do we have?'),playerName = '',player = {};
		//sanity check
		console.log('num of players is ' + numberOfPlayers);
		for (var i = 0; i < numberOfPlayers; i++) {
			playerName = prompt('What is this player '+ (i+1) +'\'s name?');
			player[i] = new Player(playerName);
			players.push(player[i]);
		}
		return players;
	}

//Makes a list of the players
function listPlayers(){
	var list = [],playerName,playerBox;
	for (var i = 0; i < players.length; i++) {
		playerName = players[i].name;
		playerBox = '
'+playerName+'
';
		list.push(playerBox);
	}
	return list;
}

//Spinner Class.
//Represents the spin wheel.
//Returns: id, name, instruction, and action of spin result
function Spinner() {
	//Array to represent the game spinner
	this.wheel = [
		{
			id: 0,
			name: 'Sneaky Squire',
			// verb: placeholderFunction(),
			instruction: 'You get to Steal an Acorn from another user!',
			action: 'steal'
		},
		{
			id: 1,
			name: 'Sleepy Squire',
			// verb: placeholderFunction(),
			instruction: 'Oh no! You lose your turn because you were sleeping. :(',
			action: 'skip'
		},
		{
			id: 2,
			name: 'Wind Storm',
			// verb: placeholderFunction(),
			instruction: 'A strong wind storm blew all your acorns away. Tough break.',
			action: 'clear'
		},
		{
			id: 3,
			name: 'Green',
            color:'green',
            //verb: addColorSquare(this.color),
			instruction: 'You get a Green Acorn'
		},
		{
			id: 4,
			name: 'Blue',
			color:'blue',
			// verb: placeholderFunction(),
			instruction: 'You get a Blue Acorn'
		},
		{
			id: 5,
			name: 'Red',
			color:'red',
			// verb: placeholderFunction(),
			instruction: 'You get a Red Acorn'
		},
		{
			id: 6,
			name: 'Purple',
			color:'purple',
			// verb: placeholderFunction(),
			instruction: 'You get a Purple Acorn'
		},
		{
			id: 7,
			name: 'Yellow',
			color:'yellow',
			// verb: placeholderFunction(),
			instruction: 'You get a Yellow Acorn'
		},
		{
			id: 8,
			name: 'Pick One',
			// verb: placeholderFunction(),
			instruction: 'You get to pick an Acorn',
			action: 'pick_one'
		},
		{
			id: 9,
			name: 'Pick Two',
			// verb: placeholderFunction(),
			instruction: 'You get to pick Two Acorns',
			action: 'pick_two'
		}
    ];

	//Spin the Wheel function. Returns a representation of landing on a color or event
	this.spin = function () {
		//get a random number
        var i = Math.floor((Math.random()*this.wheel.length));
        //feed that number to the wheel array to pull an individual item
        var result = this.wheel[i];
        return result;
    };
}

//function to check is player already has the acorn color in their stump
function acornCheck(player, result){
	var message;
	for (var k = currentPlayer.stump.space.length - 1; k >= 0; k--) {
		if(currentPlayer.stump.space[k].color === result.color){
			if(currentPlayer.stump.space[k].isEmpty === true){
				currentPlayer.stump.space[k].isEmpty = false;
			}else{
				console.log('You already have this Acorn!');
				message = ' ,but you already have this Acorn!';
				$('.spin_action_result').append(message);
			}
		}
	}
	return;
}

//Game Piece Class
function TreeStump() {
	var empty = Boolean(true);
	this.space = [
		{
			color: 'red',
			isEmpty: empty
		},
		{
			color: 'blue',
			isEmpty: empty
		},
		{
			color: 'yellow',
			isEmpty: empty
		},
		{
			color: 'green',
			isEmpty: empty
		},
		{
			color: 'purple',
			isEmpty: empty
		}
	];

	//display in html
	$('.playerBox').html('
playerCard
');
}

//Counter
function countByOne(){
	if(counter >= players.length -1){
		counter = 0;
	}else{
		counter = counter + 1;
	}
	return counter;
}

//manage who's turn it is
function playerTurn(){
	countByOne();
	currentPlayer = players[counter];
	return currentPlayer;
}

function playerTurnActions(){
	$('#spin_button').click(function(){
		//1. when a user clicks Spin the Wheel, pick a random wheelElement
		var result = spinner.spin();
		//print who's turn it is
		$('.player_turn_information').html('It is player: '+ currentPlayer.name +'\'s turn.');
		$('.spin_action_result').html(result.instruction);
		//2. check to see if the wheelElement is a Color or Event
		var colorOrAction = result.hasOwnProperty('color');
		if(colorOrAction){
			//sanity check
			console.log(result.color);
			console.log(currentPlayer.name);
			//3. if it is a Color, check to see if the users treeStump already has the Color
			//3a. add color to treeStump if it doesn't exist, else skip turn
			acornCheck(currentPlayer,result);
		}
		playerTurn();
	});
}

//---Declare Variables---//

//holds the list of players, creates a spinner, sets current player, and sets initial counter
var players = [],spinner = new Spinner(),currentPlayer,counter;

//Begin the game by asking the number of players and their name
startGame();
//initialize the first player
counter = 0;
currentPlayer = players[0];

$(document).ready(function(){
	//make the players name visible
	$('.player_table').append(listPlayers());
	$('.player_turn_information').html('It is player: '+ currentPlayer.name +'\'s turn.');
});

playerTurnActions(currentPlayer);

//3b. check to see if the active players treeStump is full.  if so, they win. else move to next player
//4. if it is an Event, check to see which Event it is
//4a. if event is Sneaky Squire - steal an Acorn from another player
//4a_A  bring up list of every player containing thier Acorns
//4a_B  When the active Player selects an Acorn from another list, add it to thier treeStump
//4a_C  check to see if treeStump is full. if so, they win End turn
//5. if event is Sleepy Squire - skip turn
//6. if event is Wind Storm - remove all Acorns from active Players list

<|endoftext|>


<commit_before>"use strict";
// Init function:

$(document).ready(function() {
  sf.setup.context = $('#screen')[0].getContext('2d');
  sf.debug('Starting game....');
  $(document).keydown(function(event) {
    sf.controls.handlers.keydown(event);
  });
  $(document).keyup(function(eventInformation) {
    sf.controls.handlers.keyup(event);
  });
  $('#screen').mouseup(function(event) {
    sf.controls.handlers.mouseclick(event);
    //console.log(event.offsetX, event.offsetY);
  });
  $('#screen').mousemove(function(event) {
    sf.controls.handlers.mousemove(event);
  });
  $('#screen').mouseout(function(event) {
    sf.controls.handlers.mouseout();
  });
  sf.levels.initWorld(sf.setup.levelsFile);
  sf.engine.main.state('START_SCREEN');
  sf.engine.main.tick();
});

<commit_msg>shoots on mousedown now<commit_after>"use strict";
// Init function:

$(document).ready(function() {
  sf.setup.context = $('#screen')[0].getContext('2d');
  sf.debug('Starting game....');
  $(document).keydown(function(event) {
    sf.controls.handlers.keydown(event);
  });
  $(document).keyup(function(eventInformation) {
    sf.controls.handlers.keyup(event);
  });
  $('#screen').mousedown(function(event) {
    sf.controls.handlers.mouseclick(event);
  });
  $('#screen').mousemove(function(event) {
    sf.controls.handlers.mousemove(event);
  });
  $('#screen').mouseout(function(event) {
    sf.controls.handlers.mouseout();
  });
  sf.levels.initWorld(sf.setup.levelsFile);
  sf.engine.main.state('START_SCREEN');
  sf.engine.main.tick();
});

<|endoftext|>


<commit_before>var canvas;
var ctx;
var gameLoop;

var alpha = 1.0 / 3.0;

var colors = [
	new Color(255, 0, 0, alpha),
	new Color(0, 255, 0, alpha),
	new Color(0, 0, 255, alpha),
];

var keys = {
	'a': 65,
	'd': 68,
	's': 83,

	'up': 38,
	'down': 40,
}

var player = {x: 50, y: 50, width: 30, height: 30, color: 0};
player.draw = function() {
	ctx.beginPath();
	ctx.fillStyle = colors[this.color % colors.length].toString();
	ctx.rect(this.x, this.y, this.width, this.height);
	ctx.fill();
}

function init() {
	canvas = document.getElementById("game");
	ctx = canvas.getContext("2d");

	registerListeners();

	gameLoop = setInterval(runGame, 25);
}

function runGame() {
	clearCtx();
	player.draw();
}

function clearCtx() {
	ctx.clearRect(0, 0, canvas.width, canvas.height);
}

function registerListeners() {
	document.addEventListener('keydown', handleKeyDown);
}

function handleKeyDown(e) {
	console.log(e);
	document.getElementById("keycode").innerHTML = e.keyCode;

	switch (e.keyCode) {
		case keys.up:
			player.color++;
			e.preventDefault();
			break;
		case keys.down:
			player.color--;
			e.preventDefault();
			break;
	}
}

function drawTestShapes() {
	// draw some test shapes
	ctx.fillStyle = "rgba(255, 0, 0, " + alpha + ")";
	ctx.beginPath()
	ctx.rect(40, 40, 60, 30);
	ctx.fill();

	ctx.fillStyle = "rgba(0, 255, 0, " + alpha + ")";
	ctx.beginPath()
	ctx.rect(60, 40, 60, 30);
	ctx.fill();

	ctx.fillStyle = "rgba(0, 0, 255, " + alpha + ")";
	ctx.beginPath()
	ctx.rect(50, 50, 60, 30);
	ctx.fill();
}

function Color(r, g, b, a) {
	this.r = r;
	this.g = g;
	this.b = b;
	this.a = a;
}

Color.prototype.toString = function() {
	return 'rgba(' + this.r + ',' + this.g + ',' + this.b + ',' + this.a + ')';
}
<commit_msg>Fix player.color negative-index bug<commit_after>var canvas;
var ctx;
var gameLoop;

var alpha = 1.0 / 3.0;

var colors = [
	new Color(255, 0, 0, alpha),
	new Color(0, 255, 0, alpha),
	new Color(0, 0, 255, alpha),
];

var keys = {
	'a': 65,
	'd': 68,
	's': 83,

	'up': 38,
	'down': 40,
}

var player = {x: 50, y: 50, width: 30, height: 30, color: 0};
player.draw = function() {
	ctx.beginPath();
	ctx.fillStyle = colors[this.color % colors.length].toString();
	ctx.rect(this.x, this.y, this.width, this.height);
	ctx.fill();
}

// negative numbers don't work with % in JS, it seems
// so, MUST use a check for < 0
player.colorDown = function() {
	player.color--;
	while (player.color < 0) {
		player.color = colors.length - player.color;
	}
}

function init() {
	canvas = document.getElementById("game");
	ctx = canvas.getContext("2d");

	registerListeners();

	gameLoop = setInterval(runGame, 25);
}

function runGame() {
	clearCtx();
	player.draw();
}

function clearCtx() {
	ctx.clearRect(0, 0, canvas.width, canvas.height);
}

function registerListeners() {
	document.addEventListener('keydown', handleKeyDown);
}

function handleKeyDown(e) {
	console.log(e);
	document.getElementById("keycode").innerHTML = e.keyCode;

	switch (e.keyCode) {
		case keys.up:
			player.color++;
			e.preventDefault();
			break;
		case keys.down:
			player.colorDown();
			e.preventDefault();
			break;
	}
}

function drawTestShapes() {
	// draw some test shapes
	ctx.fillStyle = "rgba(255, 0, 0, " + alpha + ")";
	ctx.beginPath()
	ctx.rect(40, 40, 60, 30);
	ctx.fill();

	ctx.fillStyle = "rgba(0, 255, 0, " + alpha + ")";
	ctx.beginPath()
	ctx.rect(60, 40, 60, 30);
	ctx.fill();

	ctx.fillStyle = "rgba(0, 0, 255, " + alpha + ")";
	ctx.beginPath()
	ctx.rect(50, 50, 60, 30);
	ctx.fill();
}

function Color(r, g, b, a) {
	this.r = r;
	this.g = g;
	this.b = b;
	this.a = a;
}

Color.prototype.toString = function() {
	return 'rgba(' + this.r + ',' + this.g + ',' + this.b + ',' + this.a + ')';
}
<|endoftext|>


<commit_before>var list_container = document.getElementById('article_list');
var frame = document.getElementById('article_frame');

function main() {
    if(articleDatas){
        if(articleDatas.error_code!=null && articleDatas.error_code === 0 && articleDatas.data && articleDatas.data.length > 0){
            var length = articleDatas.data.length;
            for(var i=0; i<length; i++){
                var articleData = articleDatas.data[i];
                if(articleData){
                    //是否已经建立此分类
                    var container = getCategoryContainer(articleData.category_id);
                    if(container == null){
                        container = createCategory(articleData.category_id,articleData.category_name);
                    }
                    addNewArticle(container,articleData.category_id,articleData.article_title,
                        articleData.src_url,articleData.publish_date);
                }
            }
        }
        else{
            if(articleDatas.error_msg){
                alert(articleDatas.error_msg);
            }
            else{
                alert('缺少错误信息!');
            }
        }
    }
    else {
        alert('没有找到数据或数据不合法!');
    }

}

/**
 * 增加一篇文章
 * @param container 分类的div元素
 * @param id
 * @param title
 * @param src
 * @param date
 */
function addNewArticle(container, id, title, src, date) {
    var list_id = 'cate_list_'+container.getAttribute('id');
    var list = document.getElementById(list_id);
    // console.log(list.nodeName);
    if(list!=null && list.nodeName.toLowerCase() === 'ul'){
        var article = document.createElement('li');
        article.setAttribute('id',id);
        article.innerHTML = title;
        article.onclick = function () {
            if(frame){
                frame.src = src;
            }
        };
        var txtdate = document.createElement('span');
        txtdate.innerHTML = date;
        article.appendChild(txtdate);
        list.appendChild(article);
    }
}

/**
 * 创建一个分类
 * 结构为

*n

 * @param id
 * @param name
 * @returns {Element}
 */
function createCategory(id,name) {
    var container = document.createElement('div');
    container.setAttribute('id',id);
    var category_bar = document.createElement('p');
    category_bar.innerHTML = name;
    category_bar.setAttribute('id','cate_bar_'+id);
    container.appendChild(category_bar);
    var article_list = document.createElement('ul');
    article_list.setAttribute('id','cate_list_'+id);
    container.appendChild(article_list);
    list_container.appendChild(container);
    return container;
}

/**
 * 找到Category的Container
 * @param id
 * @returns {Element}
 */
function getCategoryContainer(id) {
    return document.getElementById(id);
}

/**
 * 移除网页版的文章二维码
 */
function removeQRcode(){
    var elements = document.getElementsByClassName('qr_code_pc');
    if(elements!=null && elements.length === 1){
        var qr_code = elements[0];
        qr_code.style.display = 'none';
    }
}
<commit_msg>文章列表中的文字改用a标签<commit_after>var list_container = document.getElementById('article_list');
var frame = document.getElementById('article_frame');

function main() {
    if(articleDatas){
        if(articleDatas.error_code!=null && articleDatas.error_code === 0 && articleDatas.data && articleDatas.data.length > 0){
            var length = articleDatas.data.length;
            for(var i=0; i<length; i++){
                var articleData = articleDatas.data[i];
                if(articleData){
                    //是否已经建立此分类
                    var container = getCategoryContainer(articleData.category_id);
                    if(container == null){
                        container = createCategory(articleData.category_id,articleData.category_name);
                    }
                    addNewArticle(container,articleData.category_id,articleData.article_title,
                        articleData.src_url,articleData.publish_date);
                }
            }
        }
        else{
            if(articleDatas.error_msg){
                alert(articleDatas.error_msg);
            }
            else{
                alert('缺少错误信息!');
            }
        }
    }
    else {
        alert('没有找到数据或数据不合法!');
    }

}

/**
 * 增加一篇文章
 * @param container 分类的div元素
 * @param id
 * @param title
 * @param src
 * @param date
 */
function addNewArticle(container, id, title, src, date) {
    var list_id = 'cate_list_'+container.getAttribute('id');
    var list = document.getElementById(list_id);
    // console.log(list.nodeName);
    if(list!=null && list.nodeName.toLowerCase() === 'ul'){
        var article = document.createElement('li');
        article.setAttribute('id',id);
        var link = document.createElement('a');
        link.innerHTML = title;
        link.setAttribute('href','javascript:setUrl("'+src+'")');
        article.appendChild(link);
        var txtdate = document.createElement('span');
        txtdate.innerHTML = date;
        article.appendChild(txtdate);
        list.appendChild(article);
    }
}

/**
 * 给iframe设置src_url
 */
function setUrl(src) {
    if(frame){
        frame.src = src;
    }
}

/**
 * 创建一个分类
 * 结构为

*n

 * @param id
 * @param name
 * @returns {Element}
 */
function createCategory(id,name) {
    var container = document.createElement('div');
    container.setAttribute('id',id);
    var category_bar = document.createElement('p');
    category_bar.innerHTML = name;
    category_bar.setAttribute('id','cate_bar_'+id);
    container.appendChild(category_bar);
    var article_list = document.createElement('ul');
    article_list.setAttribute('id','cate_list_'+id);
    container.appendChild(article_list);
    list_container.appendChild(container);
    return container;
}

/**
 * 找到Category的Container
 * @param id
 * @returns {Element}
 */
function getCategoryContainer(id) {
    return document.getElementById(id);
}

/**
 * 移除网页版的文章二维码
 */
function removeQRcode(){
    var elements = document.getElementsByClassName('qr_code_pc');
    if(elements!=null && elements.length === 1){
        var qr_code = elements[0];
        qr_code.style.display = 'none';
    }
}
<|endoftext|>


<commit_before>function LWConsole() {
    var consoleDiv = document.getElementById("lwConsole");
    var consoleOutDOM = document.getElementById("consoleOut");
    var consoleInDOM = document.getElementById("consoleIn");
    var consoleOut = "";
    var motd = "Welcome to paul.zuehlcke.de!\nType 'help' for help.\n";
    var commands = [
        {
            name: "help",
            description: "Shows a list of commands",
            visible: true,
            handler: helpCMD
        },
        {
            name: "motd",
            description: "Shows the message of the day",
            visible: true,
            handler: function () {
                return motd;
            }
        },
        {
            name: "echo",
            description: "Displays message on console - no pipes yet :-(",
            visible: true,
            handler: echoCMD
        },
        {
            name: "invert",
            description: "Invert website colors",
            visible: true,
            handler: function () {
                util.toggleInvert();
                return "Page inverted!";
            }
        },
        {
            name: "clear",
            description: "Clears the console",
            visible: true, //Visible in help page?
            handler: function () {
                consoleOut = "";
                consoleOutDOM.value = consoleOut;
            }
        },
        {
            name: "exit",
            description: "Exit console",
            visible: true,
            handler: function () {
                util.toggleConsole();
            }
        },
        {
            name: "kleinhase",
            description: "Secret message",
            visible: false,
            handler: function () {
                return "<3";
            }
        }
    ];

    //Get initial state depending on dom
    this.visible = window.getComputedStyle(consoleDiv).getPropertyValue("visibility") === "visible";

    //Attach key handler to enter key
    document.addEventListener("keydown", function (e) {
        if (consoleInDOM === document.activeElement && e.keyCode == 13) {
            var value = consoleInDOM.value;
            if (value === "") { //Do not trigger cmd when input is empty
                return;
            }
            sendCMD(value);
            consoleInDOM.value = ""; //Empty after cmd sent
        }
    });

    //Set initial content of textarea
    print(motd);

    //Methods ======================================

    this.show = function (state) {
        if (state) {
            consoleDiv.style.visibility = "visible";
            this.visible = true;
            //Set focus to console
            consoleInDOM.focus();
        }
        else {
            consoleDiv.style.visibility = "hidden";
            this.visible = false;
        }
    };

    this.isVisible = function () {
        return this.visible;
    };

    /**
     * Prints message to console and updates cursor position (scroll)
     * @param str message to print
     */
    function print(str) {
        if (str) {
            consoleOut += str + "\n"; //Append string to print and newline
            consoleOutDOM.value = consoleOut; //update textarea text
            consoleOutDOM.scrollTop = consoleOutDOM.scrollHeight; //scroll down in textarea for console-like behavior
        }
    }

    /**
     * Executes user cmd and updates output accordingly
     * @param cmd raw cmd by user
     */
    function sendCMD(cmd) {
        var splitCMD = cmd.split(" "); //split cmd by space (cmd name, args)
        print("> " + cmd); //Print cmd from user
        print(executeCMD(splitCMD)); //Print result of cmd-execution
    }

    function executeCMD(cmd) {
        for (var c in commands) {
            if (commands[c].name === cmd[0]) {
                cmd.shift(); //remove cmd name from array, only leaving args
                return commands[c].handler(cmd); //Execute handler with array of args
            }
        }
        return "Unknown command.";
    }

    // Command handlers

    function helpCMD() {
        var msg = "Available commands:";
        for (var c in commands) {
            if (commands[c].visible) {
                msg += "\n" + commands[c].name + ": " + commands[c].description;
            }
        }
        return msg;
    }

    function echoCMD(args) {
        var init = true;
        var str = "";

        for (var arg in args) {
            if (!init) {
                str += " ";
            }
            init = false;
            str += args[arg];
        }
        return str;
    }
}

function JSUtil() {
    var isInverted = false;
    var lwConsole = new LWConsole();

    function invert(state) {
        var invertStr;
        if (state) {
            invertStr = "100%";
        }
        else {
            invertStr = "0%";
        }
        document.getElementById("monitor").style.filter = "invert(" + invertStr + ")";
    }

    this.toggleInvert = function () {
        isInverted = !isInverted;
        invert(isInverted);
    };

    this.toggleConsole = function () {
        lwConsole.show(!lwConsole.isVisible());
    }
}
var util = new JSUtil();<commit_msg>dynamic host name in motd<commit_after>function LWConsole() {
    var consoleDiv = document.getElementById("lwConsole");
    var consoleOutDOM = document.getElementById("consoleOut");
    var consoleInDOM = document.getElementById("consoleIn");
    var consoleOut = "";
    var motd = "Welcome to " + window.location.hostname + "\nType 'help' for help.\n";
    var commands = [
        {
            name: "help",
            description: "Shows a list of commands",
            visible: true,
            handler: helpCMD
        },
        {
            name: "motd",
            description: "Shows the message of the day",
            visible: true,
            handler: function () {
                return motd;
            }
        },
        {
            name: "echo",
            description: "Displays message on console - no pipes yet :-(",
            visible: true,
            handler: echoCMD
        },
        {
            name: "invert",
            description: "Invert website colors",
            visible: true,
            handler: function () {
                util.toggleInvert();
                return "Page inverted!";
            }
        },
        {
            name: "clear",
            description: "Clears the console",
            visible: true, //Visible in help page?
            handler: function () {
                consoleOut = "";
                consoleOutDOM.value = consoleOut;
            }
        },
        {
            name: "exit",
            description: "Exit console",
            visible: true,
            handler: function () {
                util.toggleConsole();
            }
        },
        {
            name: "kleinhase",
            description: "Secret message",
            visible: false,
            handler: function () {
                return "<3";
            }
        }
    ];

    //Get initial state depending on dom
    this.visible = window.getComputedStyle(consoleDiv).getPropertyValue("visibility") === "visible";

    //Attach key handler to enter key
    document.addEventListener("keydown", function (e) {
        if (consoleInDOM === document.activeElement && e.keyCode == 13) {
            var value = consoleInDOM.value;
            if (value === "") { //Do not trigger cmd when input is empty
                return;
            }
            sendCMD(value);
            consoleInDOM.value = ""; //Empty after cmd sent
        }
    });

    //Set initial content of textarea
    print(motd);

    //Methods ======================================

    this.show = function (state) {
        if (state) {
            consoleDiv.style.visibility = "visible";
            this.visible = true;
            //Set focus to console
            consoleInDOM.focus();
        }
        else {
            consoleDiv.style.visibility = "hidden";
            this.visible = false;
        }
    };

    this.isVisible = function () {
        return this.visible;
    };

    /**
     * Prints message to console and updates cursor position (scroll)
     * @param str message to print
     */
    function print(str) {
        if (str) {
            consoleOut += str + "\n"; //Append string to print and newline
            consoleOutDOM.value = consoleOut; //update textarea text
            consoleOutDOM.scrollTop = consoleOutDOM.scrollHeight; //scroll down in textarea for console-like behavior
        }
    }

    /**
     * Executes user cmd and updates output accordingly
     * @param cmd raw cmd by user
     */
    function sendCMD(cmd) {
        var splitCMD = cmd.split(" "); //split cmd by space (cmd name, args)
        print("> " + cmd); //Print cmd from user
        print(executeCMD(splitCMD)); //Print result of cmd-execution
    }

    function executeCMD(cmd) {
        for (var c in commands) {
            if (commands[c].name === cmd[0]) {
                cmd.shift(); //remove cmd name from array, only leaving args
                return commands[c].handler(cmd); //Execute handler with array of args
            }
        }
        return "Unknown command.";
    }

    // Command handlers

    function helpCMD() {
        var msg = "Available commands:";
        for (var c in commands) {
            if (commands[c].visible) {
                msg += "\n" + commands[c].name + ": " + commands[c].description;
            }
        }
        return msg;
    }

    function echoCMD(args) {
        var init = true;
        var str = "";

        for (var arg in args) {
            if (!init) {
                str += " ";
            }
            init = false;
            str += args[arg];
        }
        return str;
    }
}

function JSUtil() {
    var isInverted = false;
    var lwConsole = new LWConsole();

    function invert(state) {
        var invertStr;
        if (state) {
            invertStr = "100%";
        }
        else {
            invertStr = "0%";
        }
        document.getElementById("monitor").style.filter = "invert(" + invertStr + ")";
    }

    this.toggleInvert = function () {
        isInverted = !isInverted;
        invert(isInverted);
    };

    this.toggleConsole = function () {
        lwConsole.show(!lwConsole.isVisible());
    }
}
var util = new JSUtil();<|endoftext|>