<commit_before>/* Main code */

/* RequireJS configurations */
requirejs.config({
	shim: {
		'bootstrap':{
			deps: ['jquery']
		},
		'showdown':{
			deps: [],
			exports: 'Showdown'
		}
	}
});

var INFODESK_GLOBAL = {};

/* Pop error message */
function add_error(args) {
	//alert('error: '+ JSON.stringify(args));
	var data, dialog;
	if(args && (typeof args === 'object')) {
		if(args.title || args.desc) {
			data = args;
		} else {
			data = {'desc': JSON.stringify(args)};
		}
	} else {
		data = {'title':''+args};
	}
	if(!data.date) data.date = new Date();
	require(["jquery"], function(jquery) {
		dialog = jquery('#elements .error_dialog').clone();
		dialog.find('.date').text(data.date);
		dialog.find('.title').text(data.title);
		if(data.desc && ((data.desc+'').length > 0) ) {
			dialog.find('.desc').text(data.desc);
		} else {
			dialog.find('.desc_container').hide();
		}
		dialog.prependTo('#notifications');
		dialog.alert();
	}, function(err) {
		alert('Error: ' . err);
	});
};

/* Post message to server */
function post_msg(args) {
		//alert('In post_msg() with args=' + JSON.stringify(args) );
		var args = args || {};
		var msg = (args && (typeof args === 'object') && args.msg) ? ''+args.msg : '';
		if(msg.length === 0) {
			return;
		}
		var jqxhr;
		require(["jquery"], function(jquery) {
			jqxhr = jquery.post('backend.php', {'send_msg':'1', 'msg':''+msg});
		}, function(err) { add_error(JSON.stringify(err)); });
		jqxhr.complete(function(response) {
			try {
				if(response && response.status && (200 === response.status) && (response.responseText.substr(0, 2) === 'OK') ) {
					require(["jquery"], function(jquery) {
						jquery("#control_form .msg_field").val('');
					}, function(err) { add_error(JSON.stringify(err)); });
					update_events();
				} else if(response && (response.status !== undefined)) {
					add_error({'title':'Connection failed with #' + response.status, 'desc':response.responseText});
				} else {
					add_error('Connection failed');
				}
			} catch(e) {
				add_error('Connection failed');
			}
		});
	/*
	require(["jquery"], function(jquery) {
	}, function(err) {
		add_error({'title':'Connection failed', 'desc':JSON.stringify(err)});
	});
	*/
}

/* Post message to server */
function post_msg_form() {
	var msg;
	require(["jquery"], function(jquery) {
		msg = jquery('#control_form').find('.msg_field').val();
	}, function(err) {
		add_error({'title':'Clearing form failed', 'desc':JSON.stringify(err)});
	});
	//alert('Calling post_msg() with msg=' + msg);
	post_msg({'msg':msg});
	return false;
}

/* */
function change_search_string(q) {

	if(INFODESK_GLOBAL.updating === true) { return; }

	//alert(hashtag);
	INFODESK_GLOBAL.search_string = ''+q;
	require(["jquery"], function(jquery) {
		jquery('#events .events-header').html( jquery('
').text('Results for ' + q) );
		jquery('#events .events-body').empty();
		jquery('#search_field').val(INFODESK_GLOBAL.search_string);
	}, function(err) { add_error(JSON.stringify(err)); });
	INFODESK_GLOBAL.last_id = 0;
	update_events();
}

/* */
function update_events() {
	var next_id, hashtag;
	if(INFODESK_GLOBAL.updating === true) { return; }
	INFODESK_GLOBAL.updating = true;
	next_id = INFODESK_GLOBAL.last_id+1;
	require(["jquery"], function(jquery) {
		var options = {'msgs':'1', 'start':''+next_id};
		if(INFODESK_GLOBAL.search_string && (INFODESK_GLOBAL.search_string !== '')) {
			options.q = INFODESK_GLOBAL.search_string;
		}
		jquery.get('backend.php', options, function(data) {
			var events = JSON.parse(data), event, div, id, msg;
			//alert('got events: ' + events.length);
			for(i in events) if(events.hasOwnProperty(i)) {
				event = events[i];
				id = parseInt(event.log_id, 10);
				if(id > INFODESK_GLOBAL.last_id) {
					INFODESK_GLOBAL.last_id = id;
				}
				div = jquery('#elements .event_container').clone();
				div.find('.log_id').text(''+event.log_id);
				div.find('.date').text(''+event.updated);
				msg = jquery('
').text(event.msg).html();
				msg = msg.replace(/#([a-zA-Z0-9\.]+)/g, function($0, $1) {
					var h = (''+$1).toLowerCase();
					var div = jquery('
');
					var a = jquery('').text('#'+$1);
					a.appendTo(div);
					return div.html();
				});
				div.find('.msg').html(msg);
				div.prependTo('#events .events-body');
			}
			INFODESK_GLOBAL.updating = false;
		});
	}, function(err) { add_error(JSON.stringify(err)); });
}

/* */
function update_clock() {
	function f(d) { return ((''+d).length===1) ? '0'+d : ''+d; }
	require(["jquery"], function(jquery) {
		var now = new Date();
		jquery('#clock').val( f(now.getHours()) + ':' + f(now.getMinutes()) + ':' + f(now.getSeconds()) );
	});
}

/* */
INFODESK_GLOBAL.timer = undefined;
INFODESK_GLOBAL.updating = false;
INFODESK_GLOBAL.last_id = 0;
function update_events_timer() {
	update_events();
	update_clock();
	setTimeout('update_events_timer()', 1000);
}

/* Init everything at onLoad event */
window.onload = function() {
	require(["bootstrap"], function(b) {});

	// TODO: Setup simple clock on control form

	// TODO: Setup previous event history
	// TODO: Start fetching new events
	//update_events();
	update_events_timer();

	//
	require(['jquery'], function(jquery) {

		// Setup search form
		jquery('.form-search').submit(function() {
			var q = jquery('#search_field').val();
			change_search_string(q);
			return false;
		});

		// Setup about modal's body
		require(['showdown'], function(Showdown) {
			jquery.get('README.md', function(data) {
				var converter = new Showdown.converter();
				jquery('#about .modal-body').html(converter.makeHtml(data));
			});
		});
	});
};

/* EOF */
<commit_msg>Updated<commit_after>/* Main code */

/* RequireJS configurations */
requirejs.config({
	shim: {
		'bootstrap':{
			deps: ['jquery']
		},
		'showdown':{
			deps: [],
			exports: 'Showdown'
		}
	}
});

var INFODESK_GLOBAL = {};

/* Pop error message */
function add_error(args) {
	//alert('error: '+ JSON.stringify(args));
	var data, dialog;
	if(args && (typeof args === 'object')) {
		if(args.title || args.desc) {
			data = args;
		} else {
			data = {'desc': JSON.stringify(args)};
		}
	} else {
		data = {'title':''+args};
	}
	if(!data.date) data.date = new Date();
	require(["jquery"], function(jquery) {
		dialog = jquery('#elements .error_dialog').clone();
		dialog.find('.date').text(data.date);
		dialog.find('.title').text(data.title);
		if(data.desc && ((data.desc+'').length > 0) ) {
			dialog.find('.desc').text(data.desc);
		} else {
			dialog.find('.desc_container').hide();
		}
		dialog.prependTo('#notifications');
		dialog.alert();
	}, function(err) {
		alert('Error: ' . err);
	});
};

/* Post message to server */
function post_msg(args) {
		//alert('In post_msg() with args=' + JSON.stringify(args) );
		var args = args || {};
		var msg = (args && (typeof args === 'object') && args.msg) ? ''+args.msg : '';
		if(msg.length === 0) {
			return;
		}
		var jqxhr;
		require(["jquery"], function(jquery) {
			jqxhr = jquery.post('backend.php', {'send_msg':'1', 'msg':''+msg});
		}, function(err) { add_error(JSON.stringify(err)); });
		jqxhr.complete(function(response) {
			try {
				if(response && response.status && (200 === response.status) && (response.responseText.substr(0, 2) === 'OK') ) {
					require(["jquery"], function(jquery) {
						jquery("#control_form .msg_field").val('');
					}, function(err) { add_error(JSON.stringify(err)); });
					update_events();
				} else if(response && (response.status !== undefined)) {
					add_error({'title':'Connection failed with #' + response.status, 'desc':response.responseText});
				} else {
					add_error('Connection failed');
				}
			} catch(e) {
				add_error('Connection failed');
			}
		});
	/*
	require(["jquery"], function(jquery) {
	}, function(err) {
		add_error({'title':'Connection failed', 'desc':JSON.stringify(err)});
	});
	*/
}

/* Post message to server */
function post_msg_form() {
	var msg;
	require(["jquery"], function(jquery) {
		msg = jquery('#control_form').find('.msg_field').val();
	}, function(err) {
		add_error({'title':'Clearing form failed', 'desc':JSON.stringify(err)});
	});
	//alert('Calling post_msg() with msg=' + msg);
	post_msg({'msg':msg});
	return false;
}

/* */
function change_search_string(q) {

	if(INFODESK_GLOBAL.updating === true) { return; }

	//alert(hashtag);
	INFODESK_GLOBAL.search_string = ''+q;
	require(["jquery"], function(jquery) {
		jquery('#events .events-header').html( jquery('
').text('Results for '+format_msg(jquery, ''+q)) );
		jquery('#events .events-body').empty();
		jquery('#search_field').val(INFODESK_GLOBAL.search_string);
	}, function(err) { add_error(JSON.stringify(err)); });
	INFODESK_GLOBAL.last_id = 0;
	update_events();
}

/* */
function format_msg(jquery, msg) {
	msg = jquery('
').text(msg).html();

	// Format hashtags
	msg = msg.replace(/#([a-zA-Z0-9\.]+)/g, function($0, $1) {
		var h = (''+$1).toLowerCase();
		var div = jquery('
');
		var a = jquery('').text('#'+$1);
		a.appendTo(div);
		return div.html();
	});

	return msg;
}

/* */
function update_events() {
	var next_id, hashtag;
	if(INFODESK_GLOBAL.updating === true) { return; }
	INFODESK_GLOBAL.updating = true;
	next_id = INFODESK_GLOBAL.last_id+1;
	require(["jquery"], function(jquery) {
		var options = {'msgs':'1', 'start':''+next_id};
		if(INFODESK_GLOBAL.search_string && (INFODESK_GLOBAL.search_string !== '')) {
			options.q = INFODESK_GLOBAL.search_string;
		}
		jquery.get('backend.php', options, function(data) {
			var events = JSON.parse(data), event, div, id, msg;
			//alert('got events: ' + events.length);
			for(i in events) if(events.hasOwnProperty(i)) {
				event = events[i];
				id = parseInt(event.log_id, 10);
				if(id > INFODESK_GLOBAL.last_id) {
					INFODESK_GLOBAL.last_id = id;
				}
				div = jquery('#elements .event_container').clone();
				div.find('.log_id').text(''+event.log_id);
				div.find('.date').text(''+event.updated);
				div.find('.msg').html( format_msg(jquery, event.msg) );
				div.prependTo('#events .events-body');
			}
			INFODESK_GLOBAL.updating = false;
		});
	}, function(err) { add_error(JSON.stringify(err)); });
}

/* */
function update_clock() {
	function f(d) { return ((''+d).length===1) ? '0'+d : ''+d; }
	require(["jquery"], function(jquery) {
		var now = new Date();
		jquery('#clock').val( f(now.getHours()) + ':' + f(now.getMinutes()) + ':' + f(now.getSeconds()) );
	});
}

/* */
INFODESK_GLOBAL.timer = undefined;
INFODESK_GLOBAL.updating = false;
INFODESK_GLOBAL.last_id = 0;
function update_events_timer() {
	update_events();
	update_clock();
	setTimeout('update_events_timer()', 1000);
}

/* Init everything at onLoad event */
window.onload = function() {
	require(["bootstrap"], function(b) {});

	// TODO: Setup simple clock on control form

	// TODO: Setup previous event history
	// TODO: Start fetching new events
	//update_events();
	update_events_timer();

	//
	require(['jquery'], function(jquery) {

		// Setup search form
		jquery('.form-search').submit(function() {
			var q = jquery('#search_field').val();
			change_search_string(q);
			return false;
		});

		// Setup about modal's body
		require(['showdown'], function(Showdown) {
			jquery.get('README.md', function(data) {
				var converter = new Showdown.converter();
				jquery('#about .modal-body').html(converter.makeHtml(data));
			});
		});
	});
};

/* EOF */
<|endoftext|>


<commit_before>var skills = {};
var character = {"level":0, "engrams": 0, "spent":0};

$(document).ready(function() {
	fillLevels();
	totalEngrams();

	$.getJSON('json/skills.json', function(data) { //Http://www.enjoythegame.net/arkplanner/json/skills.json for ETG site
		skills = data;
		buildSkillsTable();
		updateEngramDisplay();
	});

	$('#levelSelect').on('change', function() {
		totalEngrams();

		updateAllSkillViews();

		updateEngramDisplay();
	});

	$('#viewSelect').on('change', function() {
		updateAllSkillViews();
	});

	var charstring = getParameterByName("char");

	if (charstring != "") {
		loadSavedCharacter(charstring);
	}
});

function buildSkillsTable() {  //builds main table of skill divs
	$.each(skills.skills, function(key, val) {
		var skillItem = document.createElement("div");
		$(skillItem).data(val);
		$(skillItem).attr("id", $(skillItem).data("skillName").split(" ").join(""));
		$(skillItem).addClass("skillitem");
		$(skillItem).css("background","url(img/engram/Spear_Icon.png)");
		$(skillItem).css("background","url(" + $(skillItem).data("image") + ")");
		$(skillItem).css("background-size", "contain");
		$('#body').append(skillItem);
		var skillItemText = document.createElement("span");
		skillItemText.innerHTML = $(skillItem).data("skillName");
		$(skillItem).append(skillItemText);

		updateAllSkillViews(); // this causes an ugly effect.  After drawing everything to screen it goes back and hides things.
	});

	$(".skillitem").hover(function() {
		if (!($(this).data("selected"))) {
			$(this).animate({opacity: '1'}, 300);
		}
	}, function() {
		if (!($(this).data("selected"))) {
			$(this).animate({opacity: '0.5'}, 300);
		}
	});

	$(".skillitem").click(function() {
		if (($(this).data("selected"))) {
			deselectSkill($(this));
		}
		else {
			selectSkill($(this));
		}

		checkSkillDependencies($.data(this, "requiredBy"));
	})

	$(window).resize(function() {
		resizeSkillWidth();
	});

	resizeSkillWidth();
}

function resizeSkillWidth() {
	$(".skillitem").css({'height':$('.skillitem').width() + 'px'});
}

function fillLevels() {
	for (var i = 1; i <= 65; i++) {
		$('#levelSelect')
			.append($('<option>', { i : i })
			.text(i));
	}

	$('#levelSelect option:last-child').attr('selected', 'selected');

	return true;
}

function totalEngrams() {
	var oldValue = character.engrams;

	var x = parseInt($("#levelSelect option:selected").val());
	character.level = x;
	switch(true) {
		case (x === 1):
			character.engrams = 0;
			break;
		case (x >= 2 && x < 10):
			character.engrams = ((x-1) * 8);
			break;
		case (x >= 10 && x < 20):
			character.engrams = (64 + ((x - 9) * 12));
			break;
		case (x >= 20 && x < 30):
			character.engrams = (184 + ((x - 19) * 16));
			break;
		case (x >= 30 && x < 40):
			character.engrams = (344 + ((x - 29) * 20));
			break;
		case (x >= 40 && x < 50):
			character.engrams = (544 + ((x - 39) * 24));
			break;
		case (x >= 50 && x < 60):
			character.engrams = (784 + ((x - 49) * 28));
			break;
		case (x >= 60 && x < 65):
			character.engrams = (1064 + ((x - 59) * 40));
			break;
		case (x === 65):
			character.engrams = (1265);
		default:
			$("#totalEngrams").text("you a haxor");
			break;
	}

	$('#totalEngrams').prop('number', oldValue).animateNumber({number: character.engrams},200);

	return true;
}

function checkSkillDependencies(skills) {  // Takes in an array of hidden skills.  checks each skill to see if they should be unhidden.
	for (var i =0; i < skills.length; i++) {
		var itemToBeChecked = $("#" + skills[i]);
		updateSkillView(itemToBeChecked);
	}
}

function checkRequirements(skill) {  //takes in a skill jquery object.  returns "", else returns requirement not met.
	var requirmentsMet = "";

	if (skill.data("engrams") > (character.engrams - character.spent)) {
		requirmentsMet = "engrams";
	}

	if (hasOwnProperty.call(skill.data(), "requires")) {
		for (var i = 0; i < skill.data("requires").length; i++) {
			if ( !($("#" + skill.data("requires")[i]).data( "selected" )))  {
				requirmentsMet = "requires";
			}
		}
	}

	if (skill.data("level") > character.level) {
		requirmentsMet = "level";
	}

	return requirmentsMet;
}

function selectSkill(skill) {  //takes in a jquery object skill div. checks requirements to select. then runs select logic
	var requirementsMissing = checkRequirements(skill);

	if (requirementsMissing === "") {
		character.spent += skill.data("engrams");
		updateEngramDisplay();
		skill.data("selected", true);
		skill.addClass("selected");
		skill.animate({opacity: '1'}, 300);
		return true;
	}
	else{
		switch (requirementsMissing) {
			case "level":
				showError(skill);
				showError($("#currentLevelDiv"));
				break;
			case "requires":
				showError(skill);

				/////////////////////add code here for showing unmet required skills
				break;
			case "engrams":
				showError(skill);
				showError($("#remainingEngramsDiv"));
				break;
			default:
				showError(skill);
		}
		return false;
	}
}

function deselectSkill(skill) { //takes in a jquery object skill div. runs de-select logic
	if (skill.data("selected") == true) {
		character.spent -= skill.data("engrams");
		updateEngramDisplay();
	}
	skill.data("selected", false);
	skill.removeClass( "selected" );
	skill.animate({opacity: '0.5'}, 300);
	return true;
}

function updateEngramDisplay() {
	var oldSpentValue = parseInt($("#spentEngrams").text());
	var oldRemainingValue = parseInt($("#remainingEngrams").text());
	var newRemainingValue = (character.engrams - character.spent);

	$('#spentEngrams').prop('number', oldSpentValue).animateNumber({number: character.spent},200);
	$('#remainingEngrams').prop('number', oldRemainingValue).animateNumber({number: newRemainingValue},200);

}

function loadSavedCharacter(characterString) { ////eventually will select skills, level, etc based on GET parameter base64 string.
	var decodedCharacter = atob(characterString);
	alert(decodedCharacter);
}

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

function updateAllSkillViews() { //// updates view for all skills
	$("#body>div").each(function() {
		updateSkillView($(this));
	});
}

function updateSkillView(skill) { ///updates view for one skill
	var missingRequirements = checkRequirements(skill);
	if (missingRequirements == "") {
		skill.show(200);
		return true;
	}
	switch (missingRequirements) {
		case "level":
			deselectSkill(skill);
			if ($("#viewSelect option:selected").val() == "0") {
				skill.hide(200);
			}
			else {
				skill.show(200);
			}
			break;
		case "requires":
			deselectSkill(skill);
			if ($("#viewSelect option:selected").val() == "0") {
				skill.hide(200);
			}
			else {
				skill.show(200);
			}
			break;
		default:
			skill.show(200);
	}
	return false;
}

function showError(errorDiv) { ///takes in a jquery object.  animates that object with the 'error' animation.  currently flash some red
	errorDiv.toggleClass("transition");
	errorDiv.toggleClass("error");

	setTimeout(function (){
		errorDiv.toggleClass("error");
		errorDiv.toggleClass("transition");
	}, 750);
}

<commit_msg>changed loading animation for skills that dont meet initial requirments<commit_after>var skills = {};
var character = {"level":0, "engrams": 0, "spent":0};

$(document).ready(function() {
	fillLevels();
	totalEngrams();

	$.getJSON('json/skills.json', function(data) { //Http://www.enjoythegame.net/arkplanner/json/skills.json for ETG site
		skills = data;
		buildSkillsTable();
		updateEngramDisplay();
	});

	$('#levelSelect').on('change', function() {
		totalEngrams();

		updateAllSkillViews();

		updateEngramDisplay();
	});

	$('#viewSelect').on('change', function() {
		updateAllSkillViews();
	});

	var charstring = getParameterByName("char");

	if (charstring != "") {
		loadSavedCharacter(charstring);
	}
});

function buildSkillsTable() {  //builds main table of skill divs
	$.each(skills.skills, function(key, val) {
		var skillItem = document.createElement("div");
		$(skillItem).data(val);
		$(skillItem).attr("id", $(skillItem).data("skillName").split(" ").join(""));
		$(skillItem).addClass("skillitem");
		$(skillItem).css("background","url(img/engram/Spear_Icon.png)");
		$(skillItem).css("background","url(" + $(skillItem).data("image") + ")");
		$(skillItem).css("background-size", "contain");
		$('#body').append(skillItem);
		var skillItemText = document.createElement("span");
		skillItemText.innerHTML = $(skillItem).data("skillName");
		$(skillItem).append(skillItemText);

		if (hasOwnProperty.call(this, "requires")) { //better effect. may not work good with saved characters
			$(skillItem).hide();
		}

		if (val.level > character.level) { //better effect. may not work good with saved characters
			$(skillItem).hide();
		}
		//updateSkillView($(skillItem)); // this causes an ugly effect.  After drawing everything to screen it goes back and hides things.
		//updateAllSkillViews(); // this causes an ugly effect.  After drawing everything to screen it goes back and hides things.
	});

	$(".skillitem").hover(function() {
		if (!($(this).data("selected"))) {
			$(this).animate({opacity: '1'}, 300);
		}
	}, function() {
		if (!($(this).data("selected"))) {
			$(this).animate({opacity: '0.5'}, 300);
		}
	});

	$(".skillitem").click(function() {
		if (($(this).data("selected"))) {
			deselectSkill($(this));
		}
		else {
			selectSkill($(this));
		}

		checkSkillDependencies($.data(this, "requiredBy"));
	})

	$(window).resize(function() {
		resizeSkillWidth();
	});

	resizeSkillWidth();
}

function resizeSkillWidth() {
	$(".skillitem").css({'height':$('.skillitem').width() + 'px'});
}

function fillLevels() {
	for (var i = 1; i <= 65; i++) {
		$('#levelSelect')
			.append($('<option>', { i : i })
			.text(i));
	}

	$('#levelSelect option:last-child').attr('selected', 'selected');

	return true;
}

function totalEngrams() {
	var oldValue = character.engrams;

	var x = parseInt($("#levelSelect option:selected").val());
	character.level = x;
	switch(true) {
		case (x === 1):
			character.engrams = 0;
			break;
		case (x >= 2 && x < 10):
			character.engrams = ((x-1) * 8);
			break;
		case (x >= 10 && x < 20):
			character.engrams = (64 + ((x - 9) * 12));
			break;
		case (x >= 20 && x < 30):
			character.engrams = (184 + ((x - 19) * 16));
			break;
		case (x >= 30 && x < 40):
			character.engrams = (344 + ((x - 29) * 20));
			break;
		case (x >= 40 && x < 50):
			character.engrams = (544 + ((x - 39) * 24));
			break;
		case (x >= 50 && x < 60):
			character.engrams = (784 + ((x - 49) * 28));
			break;
		case (x >= 60 && x < 65):
			character.engrams = (1064 + ((x - 59) * 40));
			break;
		case (x === 65):
			character.engrams = (1265);
		default:
			$("#totalEngrams").text("you a haxor");
			break;
	}

	$('#totalEngrams').prop('number', oldValue).animateNumber({number: character.engrams},200);

	return true;
}

function checkSkillDependencies(skills) {  // Takes in an array of hidden skills.  checks each skill to see if they should be unhidden.
	for (var i =0; i < skills.length; i++) {
		var itemToBeChecked = $("#" + skills[i]);
		updateSkillView(itemToBeChecked);
	}
}

function checkRequirements(skill) {  //takes in a skill jquery object.  returns "", else returns requirement not met.
	var requirmentsMet = "";

	if (skill.data("engrams") > (character.engrams - character.spent)) {
		requirmentsMet = "engrams";
	}

	if (hasOwnProperty.call(skill.data(), "requires")) {
		for (var i = 0; i < skill.data("requires").length; i++) {
			if ( !($("#" + skill.data("requires")[i]).data( "selected" )))  {
				requirmentsMet = "requires";
			}
		}
	}

	if (skill.data("level") > character.level) {
		requirmentsMet = "level";
	}

	return requirmentsMet;
}

function selectSkill(skill) {  //takes in a jquery object skill div. checks requirements to select. then runs select logic
	var requirementsMissing = checkRequirements(skill);

	if (requirementsMissing === "") {
		character.spent += skill.data("engrams");
		updateEngramDisplay();
		skill.data("selected", true);
		skill.addClass("selected");
		skill.animate({opacity: '1'}, 300);
		return true;
	}
	else{
		switch (requirementsMissing) {
			case "level":
				showError(skill);
				showError($("#currentLevelDiv"));
				break;
			case "requires":
				showError(skill);

				/////////////////////add code here for showing unmet required skills
				break;
			case "engrams":
				showError(skill);
				showError($("#remainingEngramsDiv"));
				break;
			default:
				showError(skill);
		}
		return false;
	}
}

function deselectSkill(skill) { //takes in a jquery object skill div. runs de-select logic
	if (skill.data("selected") == true) {
		character.spent -= skill.data("engrams");
		updateEngramDisplay();
	}
	skill.data("selected", false);
	skill.removeClass( "selected" );
	skill.animate({opacity: '0.5'}, 300);
	return true;
}

function updateEngramDisplay() {
	var oldSpentValue = parseInt($("#spentEngrams").text());
	var oldRemainingValue = parseInt($("#remainingEngrams").text());
	var newRemainingValue = (character.engrams - character.spent);

	$('#spentEngrams').prop('number', oldSpentValue).animateNumber({number: character.spent},200);
	$('#remainingEngrams').prop('number', oldRemainingValue).animateNumber({number: newRemainingValue},200);

}

function loadSavedCharacter(characterString) { ////eventually will select skills, level, etc based on GET parameter base64 string.
	var decodedCharacter = atob(characterString);
	alert(decodedCharacter);
}

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

function updateAllSkillViews() { //// updates view for all skills
	$("#body>div").each(function() {
		updateSkillView($(this));
	});
}

function updateSkillView(skill) { ///updates view for one skill
	var missingRequirements = checkRequirements(skill);
	if (missingRequirements == "") {
		skill.show(200);
		return true;
	}
	switch (missingRequirements) {
		case "level":
			deselectSkill(skill);
			if ($("#viewSelect option:selected").val() == "0") {
				skill.hide(200);
			}
			else {
				skill.show(200);
			}
			break;
		case "requires":
			deselectSkill(skill);
			if ($("#viewSelect option:selected").val() == "0") {
				skill.hide(200);
			}
			else {
				skill.show(200);
			}
			break;
		default:
			skill.show(200);
	}
	return false;
}

function showError(errorDiv) { ///takes in a jquery object.  animates that object with the 'error' animation.  currently flash some red
	errorDiv.toggleClass("transition");
	errorDiv.toggleClass("error");

	setTimeout(function (){
		errorDiv.toggleClass("error");
		errorDiv.toggleClass("transition");
	}, 750);
}

<|endoftext|>


<commit_before>var seaworthy = (function (gameloop) {
  // defaults, will get overwritten by storage value if it exists
  // FIXME extract constants to configuration
  var state = {
    distance: 0,
    seaworth: 0,
    accSeaworth: 0,
    nextSeaworth: 3
  };

  function row() {
    state.accSeaworth++;
    $('#distance').text(++state.distance);
  }

  function seaworth() {
    if (state.accSeaworth >= state.nextSeaworth) {
      state.accSeaworth = 0;
      // FIXME extract constants to configuration
      // TODO extract pricing function
      state.nextSeaworth = 2 + Math.floor(Math.pow(1.05, ++state.seaworth));
      $('#seaworth').text(state.seaworth);
    }
  }

  function autosave() {
    // FIXME extract constants to configuration
    localStorage.setItem('seaworthy-data', JSON.stringify(state));
  }

  function load() {
    // FIXME extract constants to configuration
    state = JSON.parse(localStorage.getItem('seaworthy-data')) || state;
    $('#distance').text(state.distance);
    $('#seaworth').text(state.seaworth);
  }

  $('#row').click(function () {
    row();
    seaworth();
  });

  (function () {
    load();

    // FIXME extract constants to configuration
    gameloop.add(autosave, 60);

    gameloop.start();
  }());
}(gameloop));
<commit_msg>alphabetizing function order ftw<commit_after>var seaworthy = (function (gameloop) {
  // defaults, will get overwritten by storage value if it exists
  // FIXME extract constants to configuration
  var state = {
    distance: 0,
    seaworth: 0,
    accSeaworth: 0,
    nextSeaworth: 3
  };

  function autosave() {
    // FIXME extract constants to configuration
    localStorage.setItem('seaworthy-data', JSON.stringify(state));
  }

  function load() {
    // FIXME extract constants to configuration
    state = JSON.parse(localStorage.getItem('seaworthy-data')) || state;
    $('#distance').text(state.distance);
    $('#seaworth').text(state.seaworth);
  }

  function row() {
    state.accSeaworth++;
    $('#distance').text(++state.distance);
  }

  function seaworth() {
    if (state.accSeaworth >= state.nextSeaworth) {
      state.accSeaworth = 0;
      // FIXME extract constants to configuration
      // TODO extract pricing function
      state.nextSeaworth = 2 + Math.floor(Math.pow(1.05, ++state.seaworth));
      $('#seaworth').text(state.seaworth);
    }
  }

  $('#row').click(function () {
    row();
    seaworth();
  });

  (function () {
    load();

    // FIXME extract constants to configuration
    gameloop.add(autosave, 60);

    gameloop.start();
  }());
}(gameloop));
<|endoftext|>


<commit_before>// Create an image element
var FPS = 30;
var canvas    = document.getElementById('c');
canvas.width  = window.innerWidth;
canvas.height = window.innerHeight;

var ctx    = canvas.getContext('2d');
var img    = document.createElement('IMG');
var width  = canvas.width;
var height = canvas.height;
var radius = 10;

var player = {
  x:width/2-radius,
  y:height/2-radius,
  direction:90*Math.PI/180,
  visionRadius: canvas.width*2,
  radius:radius,
  velocity:5,
  turningLeft:false,
  turningRight:false,
  movingForward:false,
  movingBack:false
};

function drawPlayer(ctx,player){
  var x = player.x;
  var y = player.y;
  var direction = player.direction;

  ctx.beginPath();
  ctx.fillStyle = "#ffffff";
  ctx.arc(x,y, radius+2, 0, Math.PI*2, false);
  ctx.fill();
  ctx.closePath();

  ctx.beginPath();
  ctx.fillStyle = "#5e9fd2";
  ctx.arc(x,y, radius, 0, Math.PI*2, false);
  ctx.fill();
  ctx.closePath();

  drawPeripheryVision(ctx,player);
  drawCentralVision(ctx,player);
}

function solveASA(angle1,side,angle2){
  // Solve the triangle to get S
  var a,b,c; // sides
  var A,B,C; // angles
  c = side;
  A = angle1 * Math.PI / 180;// half of the visual field
  B = angle2 * Math.PI / 180;
  C = (180-(angle1+angle2)) * Math.PI / 180;

  // law of sines => a/sin(A) = b/sin(B) = c/sin(C)
  // c/sin(C) = y/sin(60) = 300/sin(60) = 150*sqrt(3)
  // 150*sqrt(3) = a/sin(A)
  // 150*sqrt(3) = a/sin(30)
  // 150*sqrt(3) * sin(30) = a
  // 150*sqrt(3) * sin(30) = 129.904
  a = (c/Math.sin(C)) * Math.sin(A);
  b = Math.sin(B) * (a/Math.sin(A));
  return {
    A:A,
    B:B,
    C:C,
    a:a,
    b:b,
    c:c
  };
}

function drawPeripheryVision(ctx,player){
  ctx.beginPath();

  ctx.strokeStyle = "#dddddd";
  ctx.fillStyle = "#dddddd";

  ctx.moveTo(player.x,player.y);

  var trianglePointX = player.x + player.visionRadius*Math.cos(player.direction - (50*Math.PI/180));
  var trianglePointY = player.y + player.visionRadius*Math.sin(player.direction - (50*Math.PI/180));

  ctx.lineTo(trianglePointX,trianglePointY);

  trianglePointX = player.x + player.visionRadius*Math.cos(player.direction + (50*Math.PI/180));
  trianglePointY = player.y + player.visionRadius*Math.sin(player.direction + (50*Math.PI/180));

  ctx.lineTo(trianglePointX,trianglePointY);
  ctx.lineTo(player.x,player.y);

  ctx.closePath();
  ctx.fill();
}

function drawCentralVision(ctx,player) {
  var x = player.x;
  var y = player.y;
  var direction = player.direction;

  ctx.beginPath();

  ctx.strokeStyle = "#ffffff";
  ctx.fillStyle = "#ffffff";
  ctx.moveTo(x,y);

  var trianglePointX = player.x + player.visionRadius*Math.cos(player.direction - (15*Math.PI/180));
  var trianglePointY = player.y + player.visionRadius*Math.sin(player.direction - (15*Math.PI/180));

  ctx.lineTo(trianglePointX,trianglePointY);

  trianglePointX = player.x + player.visionRadius*Math.cos(player.direction + (15*Math.PI/180));
  trianglePointY = player.y + player.visionRadius*Math.sin(player.direction + (15*Math.PI/180));
  ctx.lineTo(trianglePointX,trianglePointY);
  ctx.lineTo(x,y);

  ctx.closePath();
  ctx.fill();
}

document.onkeydown = function(e){
  var movement=false;
  if(e.which == 38){
    player.movingForward=true;
    movement=true;
  }
  if(e.which == 40){
    player.movingBack=true;
    movement=true;
  }
  if(e.which == 37 ){
    player.turningLeft=true;
    movement=true;
  }
  if(e.which == 39 ){
    player.turningRight=true;
    movement=true;
  }
  return !movement; // don't bubble event
}
document.onkeyup = function(e){
  if(e.which == 38){
    player.movingForward=false;
  }
  if(e.which==40){
    player.movingBack=false;
  }
  if(e.which==37){
    player.turningLeft=false;
  }
  if(e.which==39){
    player.turningRight=false;
  }
  return false; // don't bubble event
}
window.onresize = function(){
  canvas.height = window.innerHeight;
  canvas.width  = window.innerWidth;
  width  = canvas.width;
  height = canvas.height;
  player.visionRadius = canvas.width*2;
}

var requestAnimationFrame = window.requestAnimationFrame ||
                            window.webkitRequestAnimationFrame ||
                            window.mozRequestAnimationFrame ||
                            function(func) { setTimeout(func, 1000 / FPS); }
function handleMovement(player) {
  if(player.movingForward){
    player.y += player.velocity * Math.sin(player.direction);
    player.x += player.velocity * Math.cos(player.direction);
  }
  if(player.movingBack){
    player.y -= player.velocity * Math.sin(player.direction);
    player.x -= player.velocity * Math.cos(player.direction);
  }
  if(player.turningRight){
    player.direction += (5*Math.PI/180);
  }
  if(player.turningLeft){
    player.direction -= (5*Math.PI/180);
  }
  player.x = (player.x-player.radius) < 0 ? player.radius : player.x;
  player.x = (player.x+player.radius) > ctx.canvas.width ? ctx.canvas.width-player.radius : player.x;
  player.y = (player.y-player.radius) < 0 ? player.radius : player.y;
  player.y = (player.y+player.radius) > ctx.canvas.height ? ctx.canvas.height-player.radius : player.y;
}
function frame(){
  ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
  handleMovement(player);
  drawPlayer(ctx,player);
  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);

<commit_msg>Clipping objects in scene based on view field.<commit_after>// Create an image element
var canvas = document.getElementById('c');
var ctx    = canvas.getContext('2d');
var img    = document.createElement('IMG');
var radius = 10;
var FPS    = 60;
var width  = 0;
var height = 0;
var scene  = []

canvas.width  = window.innerWidth;
canvas.height = window.innerHeight;
width         = canvas.width;
height        = canvas.height;

var player = {
  x:width/2-radius,
  y:height/2-radius,
  direction:deg2rad(191),
  visionRadius: canvas.width*2,
  radius:radius,
  velocity:3,
  turningLeft:false,
  turningRight:false,
  movingForward:false,
  movingBack:false,
  periphery:[[0,0],[0,0],[0,0]],
  central:  [[0,0],[0,0],[0,0]]
};

scene.push({
  x: 10,
  y: 10,
  width: 50,
  height: 50,
  fillStyle: 'rgb(255,0,0)',
  draw:function(){
    ctx.fillStyle = this.fillStyle;
    ctx.fillRect(this.x,this.y,this.width,this.height);
  }
});
scene.push({
  x: 400,
  y: 400,
  width: 30,
  height: 30,
  fillStyle: 'rgb(0,255,0)',
  draw:function(){
    ctx.fillStyle = this.fillStyle;
    ctx.fillRect(this.x,this.y,this.width,this.height);
  }
});

function deg2rad(degree) {
  return degree * Math.PI / 180;
}
function rad2deg(radian){
  return radian * (180/Math.PI);
}

function drawPlayer(ctx,player){
  var x = player.x;
  var y = player.y;
  var direction = player.direction;

  ctx.beginPath();
  ctx.fillStyle = "#ffffff";
  ctx.arc(x,y, radius+2, 0, Math.PI*2, false);
  ctx.fill();
  ctx.closePath();

  ctx.beginPath();
  ctx.fillStyle = "#5e9fd2";
  ctx.arc(x,y, radius, 0, Math.PI*2, false);
  ctx.fill();
  ctx.closePath();

  //drawPeripheryVision(ctx,player);
  drawCentralVision(ctx,player);
}

function drawPeripheryVision(ctx,player){
  ctx.save();
  ctx.beginPath();

  ctx.fillStyle = "rgba(240,240,240,0.1)";
  player.periphery = [];

  ctx.moveTo(player.x,player.y);
  player.periphery.push(player.x,player.y);

  var trianglePointX = player.x + player.visionRadius*Math.cos(player.direction - deg2rad(50));
  var trianglePointY = player.y + player.visionRadius*Math.sin(player.direction - deg2rad(50));

  ctx.lineTo(trianglePointX,trianglePointY);
  player.periphery.push([trianglePointX,trianglePointY]);

  trianglePointX = player.x + player.visionRadius*Math.cos(player.direction + deg2rad(50));
  trianglePointY = player.y + player.visionRadius*Math.sin(player.direction + deg2rad(50));

  ctx.lineTo(trianglePointX,trianglePointY);
  player.periphery.push([trianglePointX,trianglePointY]);

  ctx.lineTo(player.x,player.y);
  ctx.closePath();
  ctx.fill();
  ctx.restore();
}

function drawCentralVision(ctx,player) {
  ctx.beginPath();

  ctx.fillStyle = "rgba(200,200,200,0.1)";
  ctx.moveTo(player.x,player.y);

  player.central = [];
  player.central.push([player.x,player.y]);

  var trianglePointX = player.x + player.visionRadius * Math.cos(player.direction - deg2rad(15));
  var trianglePointY = player.y + player.visionRadius * Math.sin(player.direction - deg2rad(15));

  ctx.lineTo(trianglePointX,trianglePointY);
  player.central.push([trianglePointX,trianglePointY]);

  trianglePointX = player.x + player.visionRadius * Math.cos(player.direction + deg2rad(15));
  trianglePointY = player.y + player.visionRadius * Math.sin(player.direction + deg2rad(15));
  ctx.lineTo(trianglePointX,trianglePointY);
  player.central.push([trianglePointX,trianglePointY]);

  ctx.lineTo(player.x,player.y);

  ctx.closePath();
  ctx.fill();
  ctx.clip();
}

function drawScene(player){
  var i = 0;
  var len = scene.length;
  for(;i<len;i++){
    if(playerCanSee(player,scene[i])){
      scene[i].draw();
    }
  }
}

document.onkeydown = function(e){
  var movement=false;
  if(e.which == 38){
    player.movingForward = true;
    player.movingBack    = false;
    movement=true;
  }
  if(e.which == 40){
    player.movingBack    = true;
    player.movingForward = false;
    movement=true;
  }
  if(e.which == 37 ){
    player.turningLeft   = true;
    player.turningRight  = false;
    movement=true;
  }
  if(e.which == 39 ){
    player.turningRight  = true;
    player.turningLeft   = false;
    movement=true;
  }
  return !movement; // don't bubble event
}

document.onkeyup = function(e){
  if(e.which == 38){
    player.movingForward=false;
  }
  if(e.which==40){
    player.movingBack=false;
  }
  if(e.which==37){
    player.turningLeft  = false;
  }
  if(e.which==39){
    player.turningRight = false;
  }
  return false; // don't bubble event
}

window.onresize = function(){
  canvas.height = window.innerHeight;
  canvas.width  = window.innerWidth;
  width  = canvas.width;
  height = canvas.height;
  player.visionRadius = canvas.width*2;
}

var requestAnimationFrame = window.requestAnimationFrame ||
                            window.webkitRequestAnimationFrame ||
                            window.mozRequestAnimationFrame ||
                            function(func) { setTimeout(func, 1000 / FPS); }

function handleMovement(player) {
  if(player.movingForward){
    player.y += player.velocity * 2.5 * Math.sin(player.direction);
    player.x += player.velocity * 2.5 * Math.cos(player.direction);
  }
  if(player.movingBack){
    player.y -= player.velocity * 2.5 * Math.sin(player.direction);
    player.x -= player.velocity * 2.5 * Math.cos(player.direction);
  }
  if(player.turningRight){
    player.direction += deg2rad(player.velocity);
  }
  if(player.turningLeft){
    player.direction -= deg2rad(player.velocity);
  }
  player.x = (player.x-player.radius) < 0 ? player.radius : player.x;
  player.x = (player.x+player.radius) > ctx.canvas.width ? ctx.canvas.width-player.radius : player.x;
  player.y = (player.y-player.radius) < 0 ? player.radius : player.y;
  player.y = (player.y+player.radius) > ctx.canvas.height ? ctx.canvas.height-player.radius : player.y;
}

function playerCanSee(player,obj){
  // determine if the object is within the player.central or player.periphery triangles
  return true;
}

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

  handleMovement(player);

  ctx.save();
  drawPlayer(ctx,player);
  drawScene(player);
  ctx.restore();

  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);

<|endoftext|>


<commit_before>/**
 * Created by Owner on 8/25/2015.
 */

var map = null;
var visible = null;
var groundObjects;
var itemObjects;
var monsterObjects;
var structureObjects;
var player = {xPos:0, yPos: 0, symbol: "@"};
var menuState = false;
const viewWidth = 51;
const viewHeight = 31;
const mapWidth = 250;
const mapHeight = 250;
const entityViewerName = "entities";

Array.prototype.peek = function() {
    return this[this.length-1];
};

document.addEventListener("keydown", function(e) {
    if (menuState == false)
        move(e);
});

function move(e){
    var keyValue = e.keyCode - 96;
    var xChange = 0;
    var yChange = 0;
    switch (keyValue) {
        case 1:

            xChange -= 1;
            yChange -= 1;
            break;
        case 2:
            yChange -= 1;
            break;
        case 3:
            xChange += 1;
            yChange -= 1;
            break;
        case 4:
            xChange -= 1;
            break;
        case 5:
            break;
        case 6:
            xChange += 1;
            break;
        case 7:
            xChange -= 1;
            yChange += 1;
            break;
        case 8:
            yChange += 1;
            break;
        case 9:
            xChange += 1;
            yChange += 1;
            break;
        default:
            break;
    }

if(map[player.xPos+xChange][player.yPos+yChange].peek().unpathable)
    {
        vision();
        console.log("well fuck");
        return 0;
    }
        map[player.xPos][player.yPos].pop();
        player.xPos += xChange;
        player.yPos += yChange;
        map[player.xPos][player.yPos].push(player);
        vision();

}

function init() {

    $.ajaxSetup({
        async: false
    });

    $.getJSON("json/ground.json", function (json) {
        groundObjects = json;
    });

    $.getJSON("json/items.json", function (json) {
        itemObjects = json;
    });
    $.getJSON("json/monsters.json", function (json) {
        monsterObjects = json;
    });
    $.getJSON("json/structures.json", function (json) {
        structureObjects = json;
    });

    map = [];
    visible = [viewWidth][viewHeight];
    player.xPos = mapWidth/2;
    player.yPos = mapHeight/2;

    for (var i = 0; i < 250; i++) {
        map[i]= new Array();
        for (var j = 0; j < 250; j++) {
            map[i][j] = new Array();
            map[i][j].push(groundObjects[1]);
        }
    }
    map[player.xPos][player.yPos].push(player);
    map[0][0].push(structureObjects[1]);
    map[0][249].push(structureObjects[1]);
    map[249][0].push(structureObjects[1]);
    map[249][249].push(structureObjects[1]);
    map[130][130].push(structureObjects[1]);
    for(i = 1; i < 250; i++){
        map[i][1].push(structureObjects[1]);
        map[i][248].push(structureObjects[1]);
        map[1][i].push(structureObjects[1]);
        map[248][i].push(structureObjects[1]);
    }

vision();
}

function vision(){
    var leftX, topY;

    if(player.xPos - Math.floor(viewWidth/2) > 0)
    leftX = player.xPos - Math.floor(viewWidth/2);
    else
    leftX = 0
    if(player.xPos - Math.floor(viewWidth/2) > 0)
    topY =  player.yPos - Math.floor(viewHeight/2);
    var buffer = "";
    for(var y=topY+viewHeight; y>topY;y--){
        for(var x=leftX; x<leftX+viewWidth; x++){
            buffer += map[x][y].peek().symbol;
            }
        buffer += "
";
    }
    document.getElementById(entityViewerName).innerHTML = buffer;
}<commit_msg>vision now working<commit_after>/**
 * Created by Owner on 8/25/2015.
 */

var map = null;
var visible = null;
var groundObjects;
var itemObjects;
var monsterObjects;
var structureObjects;
var player = {xPos:0, yPos: 0, symbol: "@"};
var menuState = false;
const viewWidth = 51;
const viewHeight = 31;
const mapWidth = 250;
const mapHeight = 250;
const entityViewerName = "entities";

Array.prototype.peek = function() {
    return this[this.length-1];
};

document.addEventListener("keydown", function(e) {
    if (menuState == false)
        move(e);
});

function move(e){
    var keyValue = e.keyCode - 96;
    var xChange = 0;
    var yChange = 0;
    switch (keyValue) {
        case 1:

            xChange -= 1;
            yChange -= 1;
            break;
        case 2:
            yChange -= 1;
            break;
        case 3:
            xChange += 1;
            yChange -= 1;
            break;
        case 4:
            xChange -= 1;
            break;
        case 5:
            break;
        case 6:
            xChange += 1;
            break;
        case 7:
            xChange -= 1;
            yChange += 1;
            break;
        case 8:
            yChange += 1;
            break;
        case 9:
            xChange += 1;
            yChange += 1;
            break;
        default:
            break;
    }

if(map[player.xPos+xChange][player.yPos+yChange].peek().unpathable)
    {
        vision();
        console.log("well fuck");
        return 0;
    }
        map[player.xPos][player.yPos].pop();
        player.xPos += xChange;
        player.yPos += yChange;
        map[player.xPos][player.yPos].push(player);
        vision();

}

function init() {

    $.ajaxSetup({
        async: false
    });

    $.getJSON("json/ground.json", function (json) {
        groundObjects = json;
    });

    $.getJSON("json/items.json", function (json) {
        itemObjects = json;
    });
    $.getJSON("json/monsters.json", function (json) {
        monsterObjects = json;
    });
    $.getJSON("json/structures.json", function (json) {
        structureObjects = json;
    });

    map = [];
    visible = [viewWidth][viewHeight];
    player.xPos = mapWidth/2;
    player.yPos = mapHeight/2;

    for (var i = 0; i < 250; i++) {
        map[i]= new Array();
        for (var j = 0; j < 250; j++) {
            map[i][j] = new Array();
            map[i][j].push(groundObjects[1]);
        }
    }
    map[player.xPos][player.yPos].push(player);
    map[0][0].push(structureObjects[1]);
    map[0][249].push(structureObjects[1]);
    map[249][0].push(structureObjects[1]);
    map[249][249].push(structureObjects[1]);
    map[130][130].push(structureObjects[1]);
    for(i = 1; i < 249; i++){
        map[i][0].push(structureObjects[1]);
        map[i][249].push(structureObjects[1]);
        map[0][i].push(structureObjects[1]);
        map[249][i].push(structureObjects[1]);
    }

vision();
}

function vision(){
    var leftX, topY;

    if(player.xPos - Math.floor(viewWidth/2) < 0)
    leftX = 0;
    else if(player.xPos + Math.floor(viewWidth/2) > mapWidth)
    leftX = mapWidth - viewWidth;
    else
    leftX = player.xPos - Math.floor(viewWidth/2);

    if(player.yPos - Math.floor(viewHeight/2) < 0)
        topY = 0;
    else if(player.yPos + Math.floor(viewHeight/2) > mapHeight)
        topY = mapHeight - viewHeight -1 ;
    else
        topY = player.yPos - Math.floor(viewHeight/2);
    //if(player.xPos - Math.floor(viewWidth/2) < 0)
    //leftX = player.xPos - Math.floor(viewWidth/2);
    //else
    //leftX = 0;
    //if(player.yPos - Math.floor(viewHeight/2) > 0)
    //topY =  player.yPos - Math.floor(viewHeight/2);
    //else
    //topY = 0;
    var buffer = "";
    for(var y=topY+viewHeight; y>=topY;y--){
        for(var x=leftX; x<leftX+viewWidth; x++){
            buffer += map[x][y].peek().symbol;
            }
        buffer += "
";
    }
    document.getElementById(entityViewerName).innerHTML = buffer;
}<|endoftext|>


<commit_before>/* Main code */

/* RequireJS configurations */
requirejs.config({
	shim: {
		'bootstrap':{
			deps: ['jquery']
		},
		'showdown':{
			deps: [],
			exports: 'Showdown'
		}
	}
});

require(["jquery", "moment", "bootstrap"], function(jquery, moment, bootstrap) {

	var INFODESK_GLOBAL = {};

	/* Pop error message */
	function add_error(args) {
		//alert('error: '+ JSON.stringify(args));
		var data, dialog;
		if(args && (typeof args === 'object')) {
			if(args.error) {
				args.title = args.error;
				delete args.error;
			}
			if(args.title || args.desc) {
				data = args;
			} else {
				data = {'desc': JSON.stringify(args)};
			}
		} else {
			data = {'title':''+args};
		}
		if(!data.date) data.date = new Date();
		dialog = jquery('#elements .error_dialog').clone();
		dialog.find('.date').text(data.date);
		dialog.find('.title').text(data.title);
		if(data.desc && ((data.desc+'').length > 0) ) {
			dialog.find('.desc').text(data.desc);
		} else {
			dialog.find('.desc_container').hide();
		}
		dialog.prependTo('#notifications');
		dialog.alert();
	};

	/* Post message to server */
	function remove_msg(log_id, success_fn) {
		var jqxhr = jquery.post('backend.php', {'remove_msg':log_id});
		jqxhr.complete(function(response) {
			try {
				if(response && response.status && (200 === response.status) && (response.responseText.substr(0, 2) === 'OK') ) {
					success_fn();
				} else if(response && (response.status !== undefined)) {
					add_error({'title':'Connection failed with #' + response.status, 'desc':response.responseText});
				} else {
					add_error('Connection failed');
				}
			} catch(e) {
				add_error('Connection failed');
			}
		});
	}

	/* Post message to server */
	function post_msg(args) {
		//alert('In post_msg() with args=' + JSON.stringify(args) );
		var args = args || {};
		var msg = (args && (typeof args === 'object') && args.msg) ? ''+args.msg : '';
		if( (msg.length === 0) || (msg.length >= 1024) ) {
			return;
		}
		var jqxhr = jquery.post('backend.php', {'send_msg':'1', 'msg':''+msg});
		jqxhr.complete(function(response) {
			try {
				if(response && response.status && (200 === response.status) && (response.responseText.substr(0, 2) === 'OK') ) {
					jquery("#control_form .msg_field").val('');
					update_events();
				} else if(response && (response.status !== undefined)) {
					add_error({'title':'Connection failed with #' + response.status, 'desc':response.responseText});
				} else {
					add_error('Connection failed');
				}
			} catch(e) {
				add_error('Connection failed');
			}
		});
	}

	/* Post message to server */
	function post_msg_form() {
		var msg = jquery('#control_form').find('.msg_field').val();
		//alert('Calling post_msg() with msg=' + msg);
		post_msg({'msg':msg});
		return false;
	}

	/* */
	function change_search_string(q) {

		if(INFODESK_GLOBAL.updating === true) { return; }

		//alert(hashtag);
		INFODESK_GLOBAL.search_string = ''+q;
		jquery('#events .events-header').empty();
		jquery('#events .events-body').empty();
		if(q !== '') {
			var header = jquery('
').append('Results for ').append(format_msg(''+q)).append(' ');
			var link = jquery('').html("Close ×").click(function(event){
				event.preventDefault();
				change_search_string('');
				return false;
			});
			link.appendTo(header);
			header.appendTo('#events .events-header');
		}
		jquery('#search_field').val('');
		INFODESK_GLOBAL.last_id = 0;
		update_events();
	}

	/* */
	function format_msg(msg) {
		msg = jquery('
').text(msg).html();

		// Format hashtags
		msg = msg.replace(/#([a-zA-Z0-9\.]+)/g, function($0, $1) {
			var h = (''+$1).toLowerCase();
			var div = jquery('
');
			var a = jquery('').text('#'+$1);
			a.appendTo(div);
			return div.html();
		});

		var elem = jquery('').html(msg);
		elem.find('.hashtag_link').click(function(e) {
			e.preventDefault();
			change_search_string( jquery(this).text() );
			return false;
		});
		return elem.contents();
	}

	/* */
	function update_events() {
		var next_id, hashtag;
		if(INFODESK_GLOBAL.updating === true) { return; }
		INFODESK_GLOBAL.updating = true;
		next_id = INFODESK_GLOBAL.last_id+1;
		var options = {'msgs':'1', 'start':''+next_id};
		if(INFODESK_GLOBAL.search_string && (INFODESK_GLOBAL.search_string !== '')) {
			options.q = INFODESK_GLOBAL.search_string;
		}
		var jqxhr = jquery.get('backend.php', options, function(data) {
			var response = JSON.parse(data),
			    events = response.events,
			    server_time = response.time,
			    our_user_id = response.user_id;

			//alert('got events: ' + events.length);
			for(i in events) if(events.hasOwnProperty(i)) {
				(function() {
					var event = events[i],
					    id = parseInt(event.log_id, 10),
					    seconds_since = server_time - event.updated,
					    updated = new Date();

						updated.setTime( event.updated*1000 );

					if(id > INFODESK_GLOBAL.last_id) {
						INFODESK_GLOBAL.last_id = id;
					}

					var div = jquery('#elements .event_container').clone();
					div.find('.log_id').text(''+event.log_id);
					div.find('.date').text( moment(updated).format("HH:mm:ss") );
					div.find('.msg').append( format_msg(event.msg) );

					var close = div.find('.close');
					if ( (our_user_id === event.user_id) && (seconds_since < 5*60) ) {
						//alert("seconds_since = " + seconds_since);
						close.show();
						setTimeout(function() {
							close.hide();
						}, (5*60 - seconds_since)*1000);
					} else {
						close.hide();
					}

					close.click(function(e) {
						e.preventDefault();
						remove_msg(event.log_id, function() {
							div.remove();
						});
						return false;
					});

					div.prependTo('#events .events-body');
				}());
			}
			INFODESK_GLOBAL.updating = false;
		});

		jqxhr.complete(function(data, status) {
			if(status === "success") return;
			if(data && data.responseText) {
				try {
					var obj = JSON.parse(data.responseText);
					if(obj && obj.error) {
						add_error(obj.error, jquery);
						return;
					}
					add_error(obj);
				} catch(e) {
					add_error(data);
				}
			} else {
				add_error(status + ' with ' + data);
			}
		});
	}

	/* */
	function update_clock() {
		function f(d) { return ((''+d).length===1) ? '0'+d : ''+d; }
		var now = new Date();
		jquery('#clock').val( f(now.getHours()) + ':' + f(now.getMinutes()) );
	}

	/* */
	INFODESK_GLOBAL.timer = undefined;
	INFODESK_GLOBAL.updating = false;
	INFODESK_GLOBAL.last_id = 0;
	function update_events_timer() {
		update_events();
		//update_clock();
		setTimeout(update_events_timer, 1000);
	}

	/* Init everything at onLoad event */
	window.onload = function() {

		// TODO: Setup simple clock on control form

		// TODO: Setup previous event history
		// TODO: Start fetching new events
		//update_events();
		update_events_timer();

		// Setup ajax calls
		jquery.ajaxSetup({cache:false});

		// Setup search form
		jquery('.form-search').submit(function() {
			var q = jquery('#search_field').val();
			change_search_string(q);
			return false;
		});

		// Setup about modal's body
		require(['showdown'], function(Showdown) {
			jquery.get('README.md', function(data) {
				var converter = new Showdown.converter();
				jquery('#about .modal-body').html(converter.makeHtml(data));
			});
		});

		// Focus on message field
		jquery('#control_form .msg_field').focus();

		// Update form message size
		var form = jquery('#control_form');
		var field = form.find('.msg_field');
		var field_help = form.find('.msg_field_help');
		var field_max = parseInt(field.attr("maxlength"), 10);
		field.removeAttr("maxlength");
		function field_update() {
			var len = field.val().length;
			if(len < field_max) {
				// Success
				field_help.show();
				if(!form.hasClass('success')) form.toggleClass('success');
				if(form.hasClass('error')) form.toggleClass('error');
				field_help.text('' + (field_max-len));
			} else {
				// Error
				field_help.show();
				if(form.hasClass('success')) form.toggleClass('success');
				if(!form.hasClass('error')) form.toggleClass('error');
				field_help.text('' + (field_max-len));
			}
		}
		field.keydown(field_update);
		field.keyup(field_update);
		field.change(field_update);

		// Setup send message button
		jquery("#controls .submit-btn").removeAttr('disabled').click(function(event){
			event.preventDefault();
			post_msg_form();
			return false;
		});
	};

// End of require
}, function(err) {
	alert('Error: ' . err);
});
/* EOF */
<commit_msg>Updated<commit_after>/* Main code */

/* RequireJS configurations */
requirejs.config({
	shim: {
		'bootstrap':{
			deps: ['jquery']
		},
		'showdown':{
			deps: [],
			exports: 'Showdown'
		}
	}
});

require(["jquery", "moment", "bootstrap"], function(jquery, moment, bootstrap) {

	var INFODESK_GLOBAL = {};

	/* Pop error message */
	function add_error(args) {
		//alert('error: '+ JSON.stringify(args));
		var data, dialog;
		if(args && (typeof args === 'object')) {
			if(args.error) {
				args.title = args.error;
				delete args.error;
			}
			if(args.title || args.desc) {
				data = args;
			} else {
				data = {'desc': JSON.stringify(args)};
			}
		} else {
			data = {'title':''+args};
		}
		if(!data.date) data.date = new Date();
		dialog = jquery('#elements .error_dialog').clone();
		dialog.find('.date').text(data.date);
		dialog.find('.title').text(data.title);
		if(data.desc && ((data.desc+'').length > 0) ) {
			dialog.find('.desc').text(data.desc);
		} else {
			dialog.find('.desc_container').hide();
		}
		dialog.prependTo('#notifications');
		dialog.alert();
	};

	/* Post message to server */
	function remove_msg(log_id, success_fn) {
		var jqxhr = jquery.post('backend.php', {'remove_msg':log_id});
		jqxhr.complete(function(response) {
			try {
				if(response && response.status && (200 === response.status) && (response.responseText.substr(0, 2) === 'OK') ) {
					success_fn();
				} else if(response && (response.status !== undefined)) {
					add_error({'title':'Connection failed with #' + response.status, 'desc':response.responseText});
				} else {
					add_error('Connection failed');
				}
			} catch(e) {
				add_error('Connection failed');
			}
		});
	}

	/* Post message to server */
	function post_msg(args) {
		//alert('In post_msg() with args=' + JSON.stringify(args) );
		var args = args || {};
		var msg = (args && (typeof args === 'object') && args.msg) ? ''+args.msg : '';
		if( (msg.length === 0) || (msg.length >= 1024) ) {
			return;
		}
		var jqxhr = jquery.post('backend.php', {'send_msg':'1', 'msg':''+msg});
		jqxhr.complete(function(response) {
			try {
				if(response && response.status && (200 === response.status) && (response.responseText.substr(0, 2) === 'OK') ) {
					jquery("#control_form .msg_field").val('');
					update_events();
				} else if(response && (response.status !== undefined)) {
					add_error({'title':'Connection failed with #' + response.status, 'desc':response.responseText});
				} else {
					add_error('Connection failed');
				}
			} catch(e) {
				add_error('Connection failed');
			}
		});
	}

	/* Post message to server */
	function post_msg_form() {
		var msg = jquery('#control_form').find('.msg_field').val();
		//alert('Calling post_msg() with msg=' + msg);
		post_msg({'msg':msg});
		return false;
	}

	/* */
	function change_search_string(q) {

		if(INFODESK_GLOBAL.updating === true) { return; }

		//alert(hashtag);
		INFODESK_GLOBAL.search_string = ''+q;
		jquery('#events .events-header').empty();
		jquery('#events .events-body').empty();
		if(q !== '') {
			var header = jquery('
').append('Results for ').append(format_msg(''+q)).append(' ');
			var link = jquery('').html("Close ×").click(function(event){
				event.preventDefault();
				change_search_string('');
				return false;
			});
			link.appendTo(header);
			header.appendTo('#events .events-header');
		}
		jquery('#search_field').val('');
		INFODESK_GLOBAL.last_id = 0;
		update_events();
	}

	/* */
	function format_msg(msg) {
		msg = jquery('
').text(msg).html();

		// Format hashtags
		msg = msg.replace(/#([a-zA-Z0-9\._]+)/g, function($0, $1) {
			var h = (''+$1).toLowerCase();
			var div = jquery('
');
			var a = jquery('').text('#'+$1);
			a.appendTo(div);
			return div.html();
		});

		var elem = jquery('').html(msg);
		elem.find('.hashtag_link').click(function(e) {
			e.preventDefault();
			change_search_string( jquery(this).text() );
			return false;
		});
		return elem.contents();
	}

	/* */
	function update_events() {
		var next_id, hashtag;
		if(INFODESK_GLOBAL.updating === true) { return; }
		INFODESK_GLOBAL.updating = true;
		next_id = INFODESK_GLOBAL.last_id+1;
		var options = {'msgs':'1', 'start':''+next_id};
		if(INFODESK_GLOBAL.search_string && (INFODESK_GLOBAL.search_string !== '')) {
			options.q = INFODESK_GLOBAL.search_string;
		}
		var jqxhr = jquery.get('backend.php', options, function(data) {
			var response = JSON.parse(data),
			    events = response.events,
			    server_time = response.time,
			    our_user_id = response.user_id;

			//alert('got events: ' + events.length);
			for(i in events) if(events.hasOwnProperty(i)) {
				(function() {
					var event = events[i],
					    id = parseInt(event.log_id, 10),
					    seconds_since = server_time - event.updated,
					    updated = new Date();

						updated.setTime( event.updated*1000 );

					if(id > INFODESK_GLOBAL.last_id) {
						INFODESK_GLOBAL.last_id = id;
					}

					var div = jquery('#elements .event_container').clone();
					div.find('.log_id').text(''+event.log_id);
					div.find('.date').text( moment(updated).format("HH:mm:ss") );
					div.find('.msg').append( format_msg(event.msg) );

					var close = div.find('.close');
					if ( (our_user_id === event.user_id) && (seconds_since < 5*60) ) {
						//alert("seconds_since = " + seconds_since);
						close.show();
						setTimeout(function() {
							close.hide();
						}, (5*60 - seconds_since)*1000);
					} else {
						close.hide();
					}

					close.click(function(e) {
						e.preventDefault();
						remove_msg(event.log_id, function() {
							div.remove();
						});
						return false;
					});

					div.prependTo('#events .events-body');
				}());
			}
			INFODESK_GLOBAL.updating = false;
		});

		jqxhr.complete(function(data, status) {
			if(status === "success") return;
			if(data && data.responseText) {
				try {
					var obj = JSON.parse(data.responseText);
					if(obj && obj.error) {
						add_error(obj.error, jquery);
						return;
					}
					add_error(obj);
				} catch(e) {
					add_error(data);
				}
			} else {
				add_error(status + ' with ' + data);
			}
		});
	}

	/* */
	function update_clock() {
		function f(d) { return ((''+d).length===1) ? '0'+d : ''+d; }
		var now = new Date();
		jquery('#clock').val( f(now.getHours()) + ':' + f(now.getMinutes()) );
	}

	/* */
	INFODESK_GLOBAL.timer = undefined;
	INFODESK_GLOBAL.updating = false;
	INFODESK_GLOBAL.last_id = 0;
	function update_events_timer() {
		update_events();
		//update_clock();
		setTimeout(update_events_timer, 1000);
	}

	/* Init everything at onLoad event */
	window.onload = function() {

		// TODO: Setup simple clock on control form

		// TODO: Setup previous event history
		// TODO: Start fetching new events
		//update_events();
		update_events_timer();

		// Setup ajax calls
		jquery.ajaxSetup({cache:false});

		// Setup search form
		jquery('.form-search').submit(function() {
			var q = jquery('#search_field').val();
			change_search_string(q);
			return false;
		});

		// Setup about modal's body
		require(['showdown'], function(Showdown) {
			jquery.get('README.md', function(data) {
				var converter = new Showdown.converter();
				jquery('#about .modal-body').html(converter.makeHtml(data));
			});
		});

		// Focus on message field
		jquery('#control_form .msg_field').focus();

		// Update form message size
		var form = jquery('#control_form');
		var field = form.find('.msg_field');
		var field_help = form.find('.msg_field_help');
		var field_max = parseInt(field.attr("maxlength"), 10);
		field.removeAttr("maxlength");
		function field_update() {
			var len = field.val().length;
			if(len < field_max) {
				// Success
				field_help.show();
				if(!form.hasClass('success')) form.toggleClass('success');
				if(form.hasClass('error')) form.toggleClass('error');
				field_help.text('' + (field_max-len));
			} else {
				// Error
				field_help.show();
				if(form.hasClass('success')) form.toggleClass('success');
				if(!form.hasClass('error')) form.toggleClass('error');
				field_help.text('' + (field_max-len));
			}
		}
		field.keydown(field_update);
		field.keyup(field_update);
		field.change(field_update);

		// Setup send message button
		jquery("#controls .submit-btn").removeAttr('disabled').click(function(event){
			event.preventDefault();
			post_msg_form();
			return false;
		});
	};

// End of require
}, function(err) {
	alert('Error: ' . err);
});
/* EOF */
<|endoftext|>


<commit_before>angular
    .module('Portfolio', ['ngMaterial'])
    .config(function($mdThemingProvider, palettes){
      var customPrimary = {
        '50': '#ff7b82',
        '100': '#ff626a',
        '200': '#ff4852',
        '300': '#ff2f3a',
        '400': '#ff1522',
        '500': '#fb000d',
        '600': '#e1000c',
        '700': '#c8000a',
        '800': '#ae0009',
        '900': '#950008',
        'A100': '#ff959a',
        'A200': '#ffaeb3',
        'A400': '#ffc8cb',
        'A700': '#7b0006'
      };
      var customAccent = {
        '50': '#000a08',
        '100': '#00231d',
        '200': '#003d31',
        '300': '#005646',
        '400': '#00705a',
        '500': '#00896f',
        '600': '#00bc97',
        '700': '#00d6ac',
        '800': '#00efc0',
        '900': '#0affcf',
        'A100': '#00bc97',
        'A200': '#00a383',
        'A400': '#00896f',
        'A700': '#23ffd4'
      };
      var customWarn = {
        '50': '#ffb280',
        '100': '#ffa266',
        '200': '#ff934d',
        '300': '#ff8333',
        '400': '#ff741a',
        '500': '#ff6400',
        '600': '#e65a00',
        '700': '#cc5000',
        '800': '#b34600',
        '900': '#993c00',
        'A100': '#ffc199',
        'A200': '#ffd1b3',
        'A400': '#ffe0cc',
        'A700': '#803200'
      };
      var customBackground = {
        '50': '#737373',
        '100': '#666666',
        '200': '#595959',
        '300': '#4d4d4d',
        '400': '#404040',
        '500': '#333',
        '600': '#262626',
        '700': '#1a1a1a',
        '800': '#0d0d0d',
        '900': '#000000',
        'A100': '#808080',
        'A200': '#8c8c8c',
        'A400': '#999999',
        'A700': '#000000'
      };
      $mdThemingProvider.definePalette('customPrimary', customPrimary);
      $mdThemingProvider.definePalette('customAccent', customAccent);
      $mdThemingProvider.definePalette('customWarn', customWarn);
      $mdThemingProvider.definePalette('customBackground', customBackground);

      $mdThemingProvider.theme('default')
       .primaryPalette('customPrimary')
       .accentPalette('customAccent')
       .warnPalette('customWarn')
       .backgroundPalette('customBackground')
    })
    .config(function($mdIconProvider) {
      $mdIconProvider.defaultIconSet('/images/mdi.svg')
    });
<commit_msg>work damn you<commit_after>angular.module('Portfolio', ['ngMaterial'])
    .config(function($mdThemingProvider, palettes){
      var customPrimary = {
        '50': '#ff7b82',
        '100': '#ff626a',
        '200': '#ff4852',
        '300': '#ff2f3a',
        '400': '#ff1522',
        '500': '#fb000d',
        '600': '#e1000c',
        '700': '#c8000a',
        '800': '#ae0009',
        '900': '#950008',
        'A100': '#ff959a',
        'A200': '#ffaeb3',
        'A400': '#ffc8cb',
        'A700': '#7b0006'
      };
      var customAccent = {
        '50': '#000a08',
        '100': '#00231d',
        '200': '#003d31',
        '300': '#005646',
        '400': '#00705a',
        '500': '#00896f',
        '600': '#00bc97',
        '700': '#00d6ac',
        '800': '#00efc0',
        '900': '#0affcf',
        'A100': '#00bc97',
        'A200': '#00a383',
        'A400': '#00896f',
        'A700': '#23ffd4'
      };
      var customWarn = {
        '50': '#ffb280',
        '100': '#ffa266',
        '200': '#ff934d',
        '300': '#ff8333',
        '400': '#ff741a',
        '500': '#ff6400',
        '600': '#e65a00',
        '700': '#cc5000',
        '800': '#b34600',
        '900': '#993c00',
        'A100': '#ffc199',
        'A200': '#ffd1b3',
        'A400': '#ffe0cc',
        'A700': '#803200'
      };
      var customBackground = {
        '50': '#737373',
        '100': '#666666',
        '200': '#595959',
        '300': '#4d4d4d',
        '400': '#404040',
        '500': '#333',
        '600': '#262626',
        '700': '#1a1a1a',
        '800': '#0d0d0d',
        '900': '#000000',
        'A100': '#808080',
        'A200': '#8c8c8c',
        'A400': '#999999',
        'A700': '#000000'
      };
      $mdThemingProvider.definePalette('customPrimary', customPrimary);
      $mdThemingProvider.definePalette('customAccent', customAccent);
      $mdThemingProvider.definePalette('customWarn', customWarn);
      $mdThemingProvider.definePalette('customBackground', customBackground);

      $mdThemingProvider.theme('default')
       .primaryPalette('customPrimary')
       .accentPalette('customAccent')
       .warnPalette('customWarn')
       .backgroundPalette('customBackground')
    })
    .config(function($mdIconProvider) {
      $mdIconProvider.defaultIconSet('/images/mdi.svg')
    });
<|endoftext|>


<commit_before>$(function() {
	// fire AccessifyHTML5 – use actual container ids!
	AccessifyHTML5({
		header: '#header',
		main:   '#content',
		footer: '#footer'
	});
});
// Won't work locally without a webserver
$.getScript = function(url, callback){
	$.ajax({
		type: "GET",
		url: url,
		success: callback,
		dataType: "script",
		cache: true
	});
};
// Usage example
// $(window).load(function(){
	// Lazyload condition
	// var $hasTooltips = $('#main').has('.tooltips');
	// if($hasTooltips.size() > 0) {
	// Relative to page, not script; can be used without function to just load
		// $.getScript('scripts/plugins/jquery.tipsy.js', function() {
	// Fire plugin code here
			// $('.tooltips a[title]').tipsy({ gravity: 's' });
		// });
	// }
// });
<commit_msg>Some cleanup.<commit_after>$(function() {
	// fire AccessifyHTML5 – use actual container selectors!
	AccessifyHTML5({
		header: 'body>header',
		footer: 'body>footer'
	});
});

// Won't work locally without a webserver
$.getScript = function(url, callback){
	$.ajax({
		type: "GET",
		url: url,
		success: callback,
		dataType: "script",
		cache: true
	});
};

// Usage example
// $(window).load(function(){
// 	// Lazyload condition
// 	var $hasTooltips = $('main').has('.tooltips');

// 	if($hasTooltips.size() > 0) {
//         // Relative to page, not script; can be used without function to just load
// 		$.getScript('scripts/plugins/jquery.tipsy.js', function() {
//             // Fire plugin code here
// 			$('.tooltips a[title]').tipsy({ gravity: 's' });
// 		});
// 	}
// });
<|endoftext|>


<commit_before>var $ = require('jquery');
var records = require('./data').records;

// 各テキストボックスのEnter押下で検索押下のイベント登録
$('input[type="text"]').keypress(function(e) {
  if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
    $('#search-btn').click();
  }
});

$('#total-count').text('登録件数：' + records.length + '件');

// 検索ボタン押下処理
$('#search-btn').click(function() {
  var $searchResult = $('#search-result').empty();
  var searchResult = search();

  $.each(searchResult, function(i, record) {
    var recordId = ('000000000000' + record.id).slice(-10);
    var tags = "";
    $.each(record.tags, function(i, tag) {
      tags += ('
' + tag + '
');
    });
    $searchResult.append('

' + recordId + '
' + tags + '
');
  });
  $('#count').text('マッチ件数：' + searchResult.length + '件');
});

var search = function() {
  var escapeRegExpExceptForAstarisk = function(str) {
    return str.replace(/([.+?^=!:${}()|[\]\/\\])/g, "\\$1");
  };

  var isTagMatch = function(searchTag, tags) {
    for(var i = 0, len = tags.length; i < len; i++) {
      if(tags[i].match(searchTag)) {
        return true;
      }
    };

    return false;
  };

  var word = $('#word').val();
  word = word.replace(new RegExp("　", "g"), ' ');
  tags = word.split(' ');

  // 条件に含めるタグ配列生成
  var plusTags = tags.filter(function(tag) {
    if (!tag) {
      return false;
    }
    return tag.charAt(0) !== '-';
  });
  plusTags = plusTags.map(function(tag) {
    var pattern = escapeRegExpExceptForAstarisk(tag).replace(/\*/g, '.*');
    return new RegExp('^' + pattern + '$', 'i');
  });

  // 条件から除外するタグ配列作成
  var minusTags = tags.filter(function(tag) {
    if (!tag) {
      return false;
    }
    return tag.charAt(0) === '-';
  });
  minusTags = minusTags.map(function(tag) {
    tag = tag.substring(1);
    var pattern = escapeRegExpExceptForAstarisk(tag).replace(/\*/g, '.*');
    return new RegExp('^' + pattern + '$', 'i');
  });

  return records.filter(function(record) {
    var tags = record.tags;

    // タグの判定
    var i;
    var len;
    for(i = 0, len = plusTags.length; i < len; i++) {
      if (!isTagMatch(plusTags[i], tags)) {
        return false;
      }
    }

    for(i = 0, len = minusTags.length; i < len; i++) {
      if (isTagMatch(minusTags[i], tags)) {
        return false;
      }
    }

    return true;
  });
};
<commit_msg>インデントを修正する<commit_after>(function() {
  var $ = require('jquery');
  var records = require('./data').records;

  // 各テキストボックスのEnter押下で検索押下のイベント登録
  $('input[type="text"]').keypress(function(e) {
    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
      $('#search-btn').click();
    }
  });

  $('#total-count').text('登録件数：' + records.length + '件');

  // 検索ボタン押下処理
  $('#search-btn').click(function() {
    var $searchResult = $('#search-result').empty();
    var searchResult = search();

    $.each(searchResult, function(i, record) {
      var recordId = ('000000000000' + record.id).slice(-10);
      var tags = "";
      $.each(record.tags, function(i, tag) {
        tags += ('
' + tag + '
');
      });
      $searchResult.append('

' + recordId + '
' + tags + '
');
    });
    $('#count').text('マッチ件数：' + searchResult.length + '件');
  });

  var search = function() {
    var escapeRegExpExceptForAstarisk = function(str) {
      return str.replace(/([.+?^=!:${}()|[\]\/\\])/g, "\\$1");
    };

    var isTagMatch = function(searchTag, tags) {
      for(var i = 0, len = tags.length; i < len; i++) {
        if(tags[i].match(searchTag)) {
          return true;
        }
      };

      return false;
    };

    var word = $('#word').val();
    word = word.replace(new RegExp("　", "g"), ' ');
    tags = word.split(' ');

    // 条件に含めるタグ配列生成
    var plusTags = tags.filter(function(tag) {
      if (!tag) {
        return false;
      }
      return tag.charAt(0) !== '-';
    });
    plusTags = plusTags.map(function(tag) {
      var pattern = escapeRegExpExceptForAstarisk(tag).replace(/\*/g, '.*');
      return new RegExp('^' + pattern + '$', 'i');
    });

    // 条件から除外するタグ配列作成
    var minusTags = tags.filter(function(tag) {
      if (!tag) {
        return false;
      }
      return tag.charAt(0) === '-';
    });
    minusTags = minusTags.map(function(tag) {
      tag = tag.substring(1);
      var pattern = escapeRegExpExceptForAstarisk(tag).replace(/\*/g, '.*');
      return new RegExp('^' + pattern + '$', 'i');
    });

    return records.filter(function(record) {
      var tags = record.tags;

      // タグの判定
      var i;
      var len;
      for(i = 0, len = plusTags.length; i < len; i++) {
        if (!isTagMatch(plusTags[i], tags)) {
          return false;
        }
      }

      for(i = 0, len = minusTags.length; i < len; i++) {
        if (isTagMatch(minusTags[i], tags)) {
          return false;
        }
      }

      return true;
    });
  };
})();
<|endoftext|>


<commit_before>var globalColorWheel;
var timersList = [];
var outerWheel, innerWheel;

var count = 0;
function callTimerCallbacks() {
  count = (count + 1) % 60;
  for(var i = 0; i < timersList.length; i++) {
    timersList[i](count);
  }
}

//---------------------------------------------------------------------------------
var Led = React.createClass({
  getInitialState:function() {
    return {rgb:{r:255, g:0, b:0}}; // Set it to red
  },

  setLed: function() {
    this.setState({rgb:globalColorWheel.state.rgb});
  },

  render: function(){
    var x = this.props.x;
    var y = this.props.y;
    var a = this.props.angle;
    var thickness = this.props.thickness;
    var dx = Math.round(Math.cos(a) * (thickness-2));
    var dy = Math.round(Math.sin(a) * (thickness-2));
    var rgb = this.state.rgb;

    return(
    <path
      d={
        "M" + x + "," + y + " " +
        "l" + (+dy/2) + "," + (dx/2) + " " +
        "l" + (+dx) + "," + (-dy) + " " +
        "l" + (-dy) + "," + (-dx) + " " +
        "l" + (-dx) + "," + (+dy) + " " +
        "z"
      }
      fill={"rgb(" + rgb.r + "," + rgb.g + "," +  rgb.b + ")"}
      stroke = "black"
      onClick = {this.setLed}
    />);
  }
})

//---------------------------------------------------------------------------------
var LedOneWheel = React.createClass({
  getInitialState:function() {
    return {speed:0, angle:0, counter:60};
  },

  changeSpeed:function(speedInc) {
    if ((speedInc == 1 && this.state.speed < 1)
      || (speedInc == -1 && this.state.speed > -1)) {
      console.log("LedOneWheel n=", this.props.n, " speedInc=", speedInc);
      this.setState({speed:this.state.speed + speedInc})
    }
  },

  tick:function(count) {
    if (this.state.speed == 0)
      return;
    if (count==0 || count % this.state.counter == 0) {
      var a = this.state.angle;
      a = (a + this.state.speed) % this.props.n;
      this.setState({angle:a});
    }
  },

  componentDidMount: function() {
    timersList.push(this.tick);
    console.log("Adding timer for LedOneWheel");
  },

  componentWillUnmount: function() {
    var index = timersList.indexof(this.tick);
    if (index > -1) timersList.splice( index, 1 );
    console.log("Removing timer for LedOneWheel");
  },

  render:function() {
    var n = this.props.n;
    var radius = this.props.radius;
    var r = this.props.r;
    var thickness = this.props.thickness;
    var r2 = r - thickness;
    var leds = [];
    for(var i = 0; i < n; i++) {
      var a1 = Math.PI * 2 * i / n;
      var x = radius + Math.round(Math.cos(a1)*r);
      var y = radius - Math.round(Math.sin(a1)*r);

      leds.push(<Led key={i} angle={a1} thickness={thickness-2} x={x} y={y}/>);
    }
    return (<g transform={"rotate(" + (360* this.state.angle/n) + " " + radius + " " + radius + ")"}>{leds}</g>);
  }
})

//---------------------------------------------------------------------------------
var LedWheel = React.createClass({
  // The state is minumum of the radius sepcified in the props, and the available radius
  getInitialState:function() {
    console.log("LedWheel.getInitialState", this.props.radius);
    return {radius:this.props.radius};
  },

  computeAvailableRadius:function() {
    console.log("LedWheel.computeAvailableRadius", this.props.radius);
    if (this.elem) {
      // calculate parent's width - padding
      var p = this.elem.parentNode;
      var s= window.getComputedStyle(p);
      var w = p.clientWidth - parseFloat(s.paddingLeft) - parseFloat(s.paddingLeft); // Need parseFloat to get rid of px in 14px
      // Divide width by 2, and leave off an extra pixel
      var r = Math.min(this.props.radius, Math.round(w/2));
      console.log("Computed Radius", r);
      this.setState({radius:r})
    }
  },

  handleResize: function(e) {
    this.computeAvailableRadius();
  },

  componentDidMount: function() {
    this.computeAvailableRadius();
    window.addEventListener('resize', 100, this.handleResize);
  },

  componentWillUnmount: function() {
    window.removeEventListener('resize', this.handleResize);
  },

  getDefaultProps: function() {
    return { radius:200 };
  },

  // thickeness is calculated from radius as follows
  //    radius^2 = thickness/2 ^2  + (r1 + thickness)^2
  //    thickness/2  / r1  = tan(PI/24)
  // Solving
  //   r1 = thickness / (2*tan(PI/24))
  //   radius^2 = thickness^2 * (  (1/2)^2 + (1/(2*tan(PI/24) + 1)^2 )

  render: function() {
    var radius = this.state.radius-1;
    var thickness = radius / Math.sqrt(0.25 + Math.pow(1 + (1/(2*Math.tan(Math.PI/24))), 2) );
    var r1 = thickness / (2 * Math.tan(Math.PI/24));
    var r2 = thickness / (2 * Math.tan(Math.PI/12));

    var self = this;
    return (<svg
      ref={function(input) { self.elem = input; }}
      height={radius*2} width={radius*2}>
        <LedOneWheel
          ref={function(input) { outerWheel = input; }}
          key="g0" n={24} radius={radius} thickness={thickness} circleIndex={0} r={r1}/>
        <LedOneWheel
          ref={function(input) { innerWheel = input; }}
          key="g1" n={12} radius={radius} thickness={thickness} circleIndex={1} r={r2}/>
      </svg>);
  }
})

//---------------------------------------------------------------------------------
var HueSquare = React.createClass({
  getInitialState: function() {
    return {hue:0}; // initial hue is 0, inicial color is red
  },

  getDefaultProps: function() {
    return { n: 8, radius:100, thickness:30 };
  },

  render: function() {
    var n = this.props.n;
    var radius = this.props.radius;
    var thickness = this.props.thickness;

    var radius2 = radius - thickness - thickness/2;
    var squareSize = 2 * radius2/Math.sqrt(2) - 2; // side of square that fits in inner circle
    var smallSquareSize = squareSize/n;

    var colorSquares = [];
    var sat = 255;
    for(var j = 0; j < n; j++) {
      var val = 255;
      for(var i = 0; i < n; i++) {
        var hsv = {hue:this.state.hue, sat:sat, val:val};
        var rgb = hsv2rgb(hsv);

        //console.log(hsv, rgb);
        colorSquares.push(<path
          key={"path" + j + "_" + i}
          d={
            "M" + (radius -squareSize/2 + squareSize*j/n) + "," + (radius - squareSize/2 + squareSize*i/n) + " " +
            "l" + (+smallSquareSize) + "," + 0 + " " +
            "l" + 0 + "," + (+smallSquareSize) + " " +
            "l" + (-smallSquareSize) + "," + 0 + " " +
            "z"
          }
          fill={"rgb(" + rgb.r + "," + rgb.g + "," +  rgb.b + ")"}
          stroke = "none"
        />);
        val = val -256/n;
      }
      sat = sat -256/n;
    }
    return (<g>{colorSquares}</g>);
  }
})

//---------------------------------------------------------------------------------
var ColorWheel = React.createClass({
  // The state is minumum of the radius sepcified in the props, and the available radius
  getInitialState:function() {
    console.log("ColorWheel.getInitialState", this.props.radius);
    return {radius:this.props.radius, hueIndex:0, hue:0, rgb:{r:255,g:0,b:0}}; // initial hue is 0, inicial color is red
  },

  computeAvailableRadius:function() {
    if (this.elem) {
      // calculate parent's width - padding
      var p = this.elem.parentNode;
      var s= window.getComputedStyle(p);
      var w = p.clientWidth - parseFloat(s.paddingLeft) - parseFloat(s.paddingLeft); // Need parseFloat to get rid of px in 14px
      // Divide width by 2, and leave off an extra pixel
      var r = Math.min(this.props.radius, Math.round(w/2));
      console.log("Computed Radius", r);
      this.setState({radius:r})
    }
  },

  handleResize: function(e) {
    this.computeAvailableRadius();
  },

  componentDidMount: function() {
    this.computeAvailableRadius();
    window.addEventListener('resize', this.handleResize);
    globalColorWheel = this;
  },

  componentWillUnmount: function() {
    window.removeEventListener('resize', this.handleResize);
  },

  selectHue: function(i, hue, rgb) {
    this.setState({hueIndex:i, hue:hue, rgb:rgb});
    this.hueSquare.setState({hue:hue});
  },

  getDefaultProps: function() {
    return { n: 24, radius:100};
  },

  render: function() {
    var n = this.props.n;
    var radius = this.state.radius -1;
    var thickness = Math.round(radius/3);
    // radus is the outer radius

    var radius2 = radius - thickness - thickness/2;
    var radius3 = radius - thickness/2;

    var colorSegments = [];
    for(var i = 0; i < n; i++) {
      var a1 = Math.PI * 2 * i / n;
      var a2 = Math.PI * 2 * (i+1)/n;
      var hue = Math.round(256 * i/n);
      var hsv = {hue:hue, sat:255, val:255};
      var rgb = hsv2rgb(hsv);
      var r = this.state.hueIndex == i ? radius : radius3;

      //console.log(hsv, rgb);
      colorSegments.push(<path
        key={"path" + i}
        id={"path" + i}
        d={
          "M" + (radius + Math.round(Math.cos(a1) * r)) + "," + (radius - Math.round(Math.sin(a1) * r)) + " " +
          "A" + r + "," + r + " 0 0,0 " + (radius + Math.round(Math.cos(a2) * r)) + "," + (radius - Math.round(Math.sin(a2) * r)) + " " +
          "L" + (radius + Math.round(Math.cos(a2) * radius2)) + "," + (radius - Math.round(Math.sin(a2) * radius2)) + " " +
          "A" + radius2 + "," + radius2 + " 0 0,1 " + (radius + Math.round(Math.cos(a1) * radius2)) + "," + (radius - Math.round(Math.sin(a1) * radius2)) + " " +
          "Z"
        }
        fill={"rgb(" + rgb.r + "," + rgb.g + "," +  rgb.b + ")"}
        stroke = "black"
        strokeWidth = {this.state.hueIndex == i ? "1.5" : "1"}
        onClick = {this.selectHue.bind(this, i, hue, rgb)}
      />);
    }
    console.log("ColorWheel", radius);
    var self = this;
    return (<svg height={radius*2} width={radius*2}
      ref={function(input) { self.elem = input; }}
      >
      <g>{colorSegments}</g>
      <HueSquare
        ref={function(input) {self.hueSquare = input }}
        radius={this.state.radius} n={8} thickness={thickness} />
    </svg>);
  }
})

//---------------------------------------------------------------------------------
var LeftRightArrow = React.createClass({
  changeSpeed:function(speedInc) {
    this.setState({speed:(this.state.speed + speedInc)});
  },

  getInitialState: function() {
    return {speed:0};
  },

  render: function() {
    return(

              {this.props.label}
              <button type="button" className="ui compact icon button" onClick={this.changeSpeed.bind(this, -1)}></button>
              {this.state.speed}
              <button type="button" className="ui compact icon button" onClick={this.changeSpeed.bind(this, +1)}></button>

);
  }
})

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

ReactDOM.render(
      <LedWheel radius={200}/>,
      document.getElementById('main')
)

ReactDOM.render(
      <ColorWheel radius={100} n={24}/>,
      document.getElementById('right')
)

ReactDOM.render(
      <form className="ui form">
      <LeftRightArrow label="Outer Circle" wheelObj={outerWheel}/>
      <LeftRightArrow label="Inner Circle" wheelObj={innerWheel}/>
      </form>,
      document.getElementById('left')
)

window.setInterval(callTimerCallbacks, 20);
<commit_msg>Update main.js<commit_after>var globalColorWheel;
var timersList = [];
var outerWheel, innerWheel;

var count = 0;
function callTimerCallbacks() {
  count = (count + 1) % 60;
  for(var i = 0; i < timersList.length; i++) {
    timersList[i](count);
  }
}

//---------------------------------------------------------------------------------
var Led = React.createClass({
  getInitialState:function() {
    return {rgb:{r:255, g:0, b:0}}; // Set it to red
  },

  setLed: function() {
    this.setState({rgb:globalColorWheel.state.rgb});
  },

  render: function(){
    var x = this.props.x;
    var y = this.props.y;
    var a = this.props.angle;
    var thickness = this.props.thickness;
    var dx = Math.round(Math.cos(a) * (thickness-2));
    var dy = Math.round(Math.sin(a) * (thickness-2));
    var rgb = this.state.rgb;

    return(
    <path
      d={
        "M" + x + "," + y + " " +
        "l" + (+dy/2) + "," + (dx/2) + " " +
        "l" + (+dx) + "," + (-dy) + " " +
        "l" + (-dy) + "," + (-dx) + " " +
        "l" + (-dx) + "," + (+dy) + " " +
        "z"
      }
      fill={"rgb(" + rgb.r + "," + rgb.g + "," +  rgb.b + ")"}
      stroke = "black"
      onClick = {this.setLed}
    />);
  }
})

//---------------------------------------------------------------------------------
var LedOneWheel = React.createClass({
  getInitialState:function() {
    return {speed:0, angle:0, counter:60};
  },

  changeSpeed:function(speedInc) {
    if ((speedInc == 1 && this.state.speed < 1)
      || (speedInc == -1 && this.state.speed > -1)) {
      console.log("LedOneWheel n=", this.props.n, " speedInc=", speedInc);
      this.setState({speed:this.state.speed + speedInc})
    }
  },

  tick:function(count) {
    if (this.state.speed == 0)
      return;
    if (count==0 || count % this.state.counter == 0) {
      var a = this.state.angle;
      a = (a + this.state.speed) % this.props.n;
      this.setState({angle:a});
    }
  },

  componentDidMount: function() {
    timersList.push(this.tick);
    console.log("Adding timer for LedOneWheel");
  },

  componentWillUnmount: function() {
    var index = timersList.indexof(this.tick);
    if (index > -1) timersList.splice( index, 1 );
    console.log("Removing timer for LedOneWheel");
  },

  render:function() {
    var n = this.props.n;
    var radius = this.props.radius;
    var r = this.props.r;
    var thickness = this.props.thickness;
    var r2 = r - thickness;
    var leds = [];
    for(var i = 0; i < n; i++) {
      var a1 = Math.PI * 2 * i / n;
      var x = radius + Math.round(Math.cos(a1)*r);
      var y = radius - Math.round(Math.sin(a1)*r);

      leds.push(<Led key={i} angle={a1} thickness={thickness-2} x={x} y={y}/>);
    }
    return (<g transform={"rotate(" + (360* this.state.angle/n) + " " + radius + " " + radius + ")"}>{leds}</g>);
  }
})

//---------------------------------------------------------------------------------
var LedWheel = React.createClass({
  // The state is minumum of the radius sepcified in the props, and the available radius
  getInitialState:function() {
    console.log("LedWheel.getInitialState", this.props.radius);
    return {radius:this.props.radius};
  },

  computeAvailableRadius:function() {
    console.log("LedWheel.computeAvailableRadius", this.props.radius);
    if (this.elem) {
      // calculate parent's width - padding
      var p = this.elem.parentNode;
      var s= window.getComputedStyle(p);
      var w = p.clientWidth - parseFloat(s.paddingLeft) - parseFloat(s.paddingLeft); // Need parseFloat to get rid of px in 14px
      // Divide width by 2, and leave off an extra pixel
      var r = Math.min(this.props.radius, Math.round(w/2));
      console.log("Computed Radius", r);
      this.setState({radius:r})
    }
  },

  handleResize: function(e) {
    this.computeAvailableRadius();
  },

  componentDidMount: function() {
    this.computeAvailableRadius();
    window.addEventListener('resize', 100, this.handleResize);
  },

  componentWillUnmount: function() {
    window.removeEventListener('resize', this.handleResize);
  },

  getDefaultProps: function() {
    return { radius:200 };
  },

  // thickeness is calculated from radius as follows
  //    radius^2 = thickness/2 ^2  + (r1 + thickness)^2
  //    thickness/2  / r1  = tan(PI/24)
  // Solving
  //   r1 = thickness / (2*tan(PI/24))
  //   radius^2 = thickness^2 * (  (1/2)^2 + (1/(2*tan(PI/24) + 1)^2 )

  render: function() {
    var radius = this.state.radius-1;
    var thickness = radius / Math.sqrt(0.25 + Math.pow(1 + (1/(2*Math.tan(Math.PI/24))), 2) );
    var r1 = thickness / (2 * Math.tan(Math.PI/24));
    var r2 = thickness / (2 * Math.tan(Math.PI/12));

    var self = this;
    return (<svg
      ref={function(input) { self.elem = input; }}
      height={radius*2} width={radius*2}>
        <LedOneWheel
          ref={function(input) { outerWheel = input; }}
          key="g0" n={24} radius={radius} thickness={thickness} circleIndex={0} r={r1}/>
        <LedOneWheel
          ref={function(input) { innerWheel = input; }}
          key="g1" n={12} radius={radius} thickness={thickness} circleIndex={1} r={r2}/>
      </svg>);
  }
})

//---------------------------------------------------------------------------------
var HueSquare = React.createClass({
  getInitialState: function() {
    return {hue:0}; // initial hue is 0, inicial color is red
  },

  getDefaultProps: function() {
    return { n: 8, radius:100, thickness:30 };
  },

  render: function() {
    var n = this.props.n;
    var radius = this.props.radius;
    var thickness = this.props.thickness;

    var radius2 = radius - thickness - thickness/2;
    var squareSize = 2 * radius2/Math.sqrt(2) - 2; // side of square that fits in inner circle
    var smallSquareSize = squareSize/n;

    var colorSquares = [];
    var sat = 255;
    for(var j = 0; j < n; j++) {
      var val = 255;
      for(var i = 0; i < n; i++) {
        var hsv = {hue:this.state.hue, sat:sat, val:val};
        var rgb = hsv2rgb(hsv);

        //console.log(hsv, rgb);
        colorSquares.push(<path
          key={"path" + j + "_" + i}
          d={
            "M" + (radius -squareSize/2 + squareSize*j/n) + "," + (radius - squareSize/2 + squareSize*i/n) + " " +
            "l" + (+smallSquareSize) + "," + 0 + " " +
            "l" + 0 + "," + (+smallSquareSize) + " " +
            "l" + (-smallSquareSize) + "," + 0 + " " +
            "z"
          }
          fill={"rgb(" + rgb.r + "," + rgb.g + "," +  rgb.b + ")"}
          stroke = "none"
        />);
        val = val -256/n;
      }
      sat = sat -256/n;
    }
    return (<g>{colorSquares}</g>);
  }
})

//---------------------------------------------------------------------------------
var ColorWheel = React.createClass({
  // The state is minumum of the radius sepcified in the props, and the available radius
  getInitialState:function() {
    console.log("ColorWheel.getInitialState", this.props.radius);
    return {radius:this.props.radius, hueIndex:0, hue:0, rgb:{r:255,g:0,b:0}}; // initial hue is 0, inicial color is red
  },

  computeAvailableRadius:function() {
    if (this.elem) {
      // calculate parent's width - padding
      var p = this.elem.parentNode;
      var s= window.getComputedStyle(p);
      var w = p.clientWidth - parseFloat(s.paddingLeft) - parseFloat(s.paddingLeft); // Need parseFloat to get rid of px in 14px
      // Divide width by 2, and leave off an extra pixel
      var r = Math.min(this.props.radius, Math.round(w/2));
      console.log("Computed Radius", r);
      this.setState({radius:r})
    }
  },

  handleResize: function(e) {
    this.computeAvailableRadius();
  },

  componentDidMount: function() {
    this.computeAvailableRadius();
    window.addEventListener('resize', this.handleResize);
    globalColorWheel = this;
  },

  componentWillUnmount: function() {
    window.removeEventListener('resize', this.handleResize);
  },

  selectHue: function(i, hue, rgb) {
    this.setState({hueIndex:i, hue:hue, rgb:rgb});
    this.hueSquare.setState({hue:hue});
  },

  getDefaultProps: function() {
    return { n: 24, radius:100};
  },

  render: function() {
    var n = this.props.n;
    var radius = this.state.radius -1;
    var thickness = Math.round(radius/3);
    // radus is the outer radius

    var radius2 = radius - thickness - thickness/2;
    var radius3 = radius - thickness/2;

    var colorSegments = [];
    for(var i = 0; i < n; i++) {
      var a1 = Math.PI * 2 * i / n;
      var a2 = Math.PI * 2 * (i+1)/n;
      var hue = Math.round(256 * i/n);
      var hsv = {hue:hue, sat:255, val:255};
      var rgb = hsv2rgb(hsv);
      var r = this.state.hueIndex == i ? radius : radius3;

      //console.log(hsv, rgb);
      colorSegments.push(<path
        key={"path" + i}
        id={"path" + i}
        d={
          "M" + (radius + Math.round(Math.cos(a1) * r)) + "," + (radius - Math.round(Math.sin(a1) * r)) + " " +
          "A" + r + "," + r + " 0 0,0 " + (radius + Math.round(Math.cos(a2) * r)) + "," + (radius - Math.round(Math.sin(a2) * r)) + " " +
          "L" + (radius + Math.round(Math.cos(a2) * radius2)) + "," + (radius - Math.round(Math.sin(a2) * radius2)) + " " +
          "A" + radius2 + "," + radius2 + " 0 0,1 " + (radius + Math.round(Math.cos(a1) * radius2)) + "," + (radius - Math.round(Math.sin(a1) * radius2)) + " " +
          "Z"
        }
        fill={"rgb(" + rgb.r + "," + rgb.g + "," +  rgb.b + ")"}
        stroke = "black"
        strokeWidth = {this.state.hueIndex == i ? "1.5" : "1"}
        onClick = {this.selectHue.bind(this, i, hue, rgb)}
      />);
    }
    console.log("ColorWheel", radius);
    var self = this;
    return (<svg height={radius*2} width={radius*2}
      ref={function(input) { self.elem = input; }}
      >
      <g>{colorSegments}</g>
      <HueSquare
        ref={function(input) {self.hueSquare = input }}
        radius={this.state.radius} n={8} thickness={thickness} />
    </svg>);
  }
})

//---------------------------------------------------------------------------------
var LeftRightArrow = React.createClass({
  changeSpeed:function(speedInc) {
    this.setState({speed:(this.state.speed + speedInc)});
  },

  getInitialState: function() {
    return {speed:0};
  },

  render: function() {
    return(

              {this.props.label}
              <button type="button" className="ui compact icon button" onClick={this.changeSpeed.bind(this, -1)}></button>
              {this.state.speed}
              <button type="button" className="ui compact icon button" onClick={this.changeSpeed.bind(this, +1)}></button>

);
  }
})

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

ReactDOM.render(
      <LedWheel radius={200}/>,
      document.getElementById('main')
)

ReactDOM.render(
      <ColorWheel radius={100} n={24}/>,
      document.getElementById('right')
)

ReactDOM.render(
      <form className="ui form">
      <LeftRightArrow label="Outer Circle" wheelObj={outerWheel}/>
      <LeftRightArrow label="Inner Circle" wheelObj={innerWheel}/>
      </form>,
      document.getElementById('left')
)

window.setInterval(callTimerCallbacks, 20);
<|endoftext|>