<commit_before>window.daltonTab = {
	subjects: []
};

window.daltonTab.addEventToList = function(ev, list) {
	var tag = window.utils.getPrefix(ev.name);
	var name = ev.name.split(" ");
	name.splice(0, 1);
	name = name.join(" ");
	var done = (ev.done == 1 ? true : false);

	if (name.trim() == "") {
		return;
	}

	var $item = $('

');
		if (done) {
			$item.addClass("daltonTab-done");
		}
		var $name = $('

');
			$name.text(name);
		$item.append($name);

		var $lineTwo = $('

');
			var $tag = $('');
				$tag.addClass("first-word");
				if (tag.toLowerCase() == "read") {
					tag = tag + "ing";
				}
				$tag.addClass(window.utils.getPrefixClass(tag));

				$tag.text(tag);
			$lineTwo.append($tag);

			var $subject = $('');
				$subject.text(" in " + window.daltonTab.subjects[ev.subject].name);
			$lineTwo.append($subject);

			var $due = $('');
				var keyword = "due";
				if (tag.toLowerCase() == "test" || tag.toLowerCase() == "exam" || tag.toLowerCase() == "midterm" || tag.toLowerCase() == "quiz" || tag.toLowerCase() == "ica" || tag.toLowerCase() == "lab") {
					keyword = "on";
				}
				var dueText = window.utils.formatDate_pretty(moment(ev.due).add(1, "day").toDate());
				if (moment(ev.due).add(1, "day").week() == moment().week()) {
					dueText = window.utils.getDayOfWeek(moment(ev.due).add(1, "day").day());
				}
				$due.text(" " + keyword + " " + dueText);
			$lineTwo.append($due);
		$item.append($lineTwo);
	$("#hw" + list).append($item);
};
window.daltonTab.findNextDay = function(offset) {
	var retVal = moment(); //moment().add("days", offset);
	if (retVal.day() == 6) {
		// don't start on Saturday
		retVal.add(1, "day");
	}
	for (var i = 0; i < offset; i++) {
		retVal.add(1, "day"); //add a day
		// is it a Saturday?
		if (retVal.day() == 6) {
			retVal.add(2, "day"); // skip the weekend
		}
	}
	return retVal.toDate();
};
window.daltonTab.loadDate = function(date, list) {
	console.log(date);
	for (var subjectIndex in window.daltonTab.subjects) {
		window.planhub.get("planner/events/get/" + window.utils.formatDate_api(date) + "/" + subjectIndex, function(data) {
			var ev = data.events;
			//window.daltonTab.loadStep();
			if (ev.length == 0) {
				return;
			}
			for (var evIndex in ev) {
				var evObj = {
					name: ev[evIndex].text,
					due: new Date(data.date),
					subject: ev[evIndex].sectionIndex,
					done: ev[evIndex].done
				};
				window.daltonTab.addEventToList(evObj, list);
			};
		});
	}
};

$(document).ready(function() {
	var timeUpdFunc = function() {
		$(".current-time").text(moment().format("h:mm A"));
		$(".current-date").text(moment().format("MMMM Do, YYYY"));
	};
	timeUpdFunc();
	setInterval(timeUpdFunc, 1000);

	chrome.storage.sync.get("backImgTog", function(storage) {
		if (storage.backImgTog != undefined || !storage.backImgTog) {
			$.get("https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US", function(response) {
				var url = "https://www.bing.com" + response.images[0].url;
				$("#par").parallax({ imageSrc: url, bleed: 20, positionY: "0px" });
				$("#par").addClass("imageLoaded");
				$("#section1").addClass("imageLoaded");
				//$("body").css("background-image", "url(" + url + ")");
			});
		}
	});

	$("#settingsBtn").click(function() {
		$("#settingsModal").modal();
	});

	$("#newTabDefault").click(function() {
		window.location.href = "chrome-search://local-ntp/local-ntp.html"
	});
	$("#hwButton").smoothScroll();

	$("#schedulesAccountBtn").click(function() {
		var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left;
		var dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top;

		width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
		height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;

		var w = 600;
		var h = 400;

		var left = ((width / 2) - (w / 2)) + dualScreenLeft;
		var top = ((height / 2) - (h / 2)) + dualScreenTop;
		window.location.href = chrome.runtime.getURL("schedulesSignIn.html");
	});

	chrome.storage.sync.get(["schedulesLogin"], function(response) {
		if (response.schedulesLogin != undefined) {
			$("#schedulesSignIn").addClass("hidden");
			$("#schedulesSignedIn").removeClass("hidden");
			$("#schedulesAccountName").text(response.schedulesLogin.username);
		}
	});

	$("#schedulesLogOut").click(function() {
		chrome.storage.sync.remove("schedulesLogin", function() {
			window.location.reload();
		});
	});

	chrome.storage.sync.get("backImgTog", function(storage) {
		$("#backImgTog").prop("checked", storage.backImgTog);
	});
	$("#backImgTog").change(function() {
		chrome.storage.sync.set("backImgTog", $(this).prop("checked"), function() {

		});
	});

	window.coursesLib.checkLoggedIn(function(response) {
		if (!response.isLoggedIn) {
			$("#classes-warning").html(' Please log in here.');
		} else {
			window.coursesLib.getCourseList(function(response) {
				for (var courseIndex in response.classes) {
					var course = response.classes[courseIndex];
					console.log(course);
					var $element = $("

");
						$element.html('' + course.name + '');
					$("#courses").append($element);
				}
			});
		}

		var easter_egg = new Konami();
		easter_egg.code = function() {
			swal("Unexpected T_PAAMAYIM_NEKUDOTAYIM!", "MWAHHHAHAHAHAHAHAHAH\nConfused? Search on...\n This product uses Sapi, Papi, Capy, Wapi", "warning")
		}
		easter_egg.load();
	});

	window.planhub.get("features/get/", function(data) {
		console.log(data);
		if (data.status == "error") {
			$("#hw-warning").html(' Sign into PlanHub to view your homework.');
			return;
		}
		if (data.features.indexOf("hwView") == -1) {
			$("#hw-warning").html(' Enable Homework View to see your homework here.');
			return;
		}

		window.planhub.get("planner/sections/get/", function(data) {
			for (var i = 0; i < data.sections.length; i++) {
				var itm = data.sections[i];
				window.daltonTab.subjects[itm.sectionIndex] = itm;
			};
			window.daltonTab.loadDate(window.daltonTab.findNextDay(1), "Tomorrow", function() {

			});
			window.daltonTab.loadDate(window.daltonTab.findNextDay(2), "Soon", function() {

			});
			window.daltonTab.loadDate(window.daltonTab.findNextDay(3), "Soon", function() {

			});
			window.daltonTab.loadDate(window.daltonTab.findNextDay(4), "Soon", function() {

			});
			window.daltonTab.loadDate(window.daltonTab.findNextDay(5), "Longterm", function() {

			});
			window.daltonTab.loadDate(window.daltonTab.findNextDay(6), "Longterm", function() {

			});
			window.daltonTab.loadDate(window.daltonTab.findNextDay(7), "Longterm", function() {

			});
			window.daltonTab.loadDate(window.daltonTab.findNextDay(8), "Longterm", function() {

			});
			window.daltonTab.loadDate(window.daltonTab.findNextDay(9), "Longterm", function() {

			});
			window.daltonTab.loadDate(window.daltonTab.findNextDay(10), "Longterm", function() {

			});
			window.daltonTab.loadDate(window.daltonTab.findNextDay(11), "Longterm", function() {

			});
			window.daltonTab.loadDate(window.daltonTab.findNextDay(12), "Longterm", function() {

			});
			window.daltonTab.loadDate(window.daltonTab.findNextDay(13), "Longterm", function() {

			});
			window.daltonTab.loadDate(window.daltonTab.findNextDay(14), "Longterm", function() {

			});
		});
	});
	setTimeout(function() {
		$(window).trigger('resize');
	}, 100)
});

$(document).on("load", function() {

});
<commit_msg>asdfasdfasdf<commit_after>window.daltonTab = {
	subjects: []
};

window.daltonTab.addEventToList = function(ev, list) {
	var tag = window.utils.getPrefix(ev.name);
	var name = ev.name.split(" ");
	name.splice(0, 1);
	name = name.join(" ");
	var done = (ev.done == 1 ? true : false);

	if (name.trim() == "") {
		return;
	}

	var $item = $('

');
		if (done) {
			$item.addClass("daltonTab-done");
		}
		var $name = $('

');
			$name.text(name);
		$item.append($name);

		var $lineTwo = $('

');
			var $tag = $('');
				$tag.addClass("first-word");
				if (tag.toLowerCase() == "read") {
					tag = tag + "ing";
				}
				$tag.addClass(window.utils.getPrefixClass(tag));

				$tag.text(tag);
			$lineTwo.append($tag);

			var $subject = $('');
				$subject.text(" in " + window.daltonTab.subjects[ev.subject].name);
			$lineTwo.append($subject);

			var $due = $('');
				var keyword = "due";
				if (tag.toLowerCase() == "test" || tag.toLowerCase() == "exam" || tag.toLowerCase() == "midterm" || tag.toLowerCase() == "quiz" || tag.toLowerCase() == "ica" || tag.toLowerCase() == "lab") {
					keyword = "on";
				}
				var dueText = window.utils.formatDate_pretty(moment(ev.due).add(1, "day").toDate());
				if (moment(ev.due).add(1, "day").week() == moment().week()) {
					dueText = window.utils.getDayOfWeek(moment(ev.due).add(1, "day").day());
				}
				$due.text(" " + keyword + " " + dueText);
			$lineTwo.append($due);
		$item.append($lineTwo);
	$("#hw" + list).append($item);
};
window.daltonTab.findNextDay = function(offset) {
	var retVal = moment(); //moment().add("days", offset);
	if (retVal.day() == 6) {
		// don't start on Saturday
		retVal.add(1, "day");
	}
	for (var i = 0; i < offset; i++) {
		retVal.add(1, "day"); //add a day
		// is it a Saturday?
		if (retVal.day() == 6) {
			retVal.add(2, "day"); // skip the weekend
		}
	}
	return retVal.toDate();
};
window.daltonTab.loadDate = function(date, list) {
	console.log(date);
	for (var subjectIndex in window.daltonTab.subjects) {
		window.planhub.get("planner/events/get/" + window.utils.formatDate_api(date) + "/" + subjectIndex, function(data) {
			var ev = data.events;
			//window.daltonTab.loadStep();
			if (ev.length == 0) {
				return;
			}
			for (var evIndex in ev) {
				var evObj = {
					name: ev[evIndex].text,
					due: new Date(data.date),
					subject: ev[evIndex].sectionIndex,
					done: ev[evIndex].done
				};
				window.daltonTab.addEventToList(evObj, list);
			};
		});
	}
};

$(document).ready(function() {
	var timeUpdFunc = function() {
		$(".current-time").text(moment().format("h:mm A"));
		$(".current-date").text(moment().format("MMMM Do, YYYY"));
	};
	timeUpdFunc();
	setInterval(timeUpdFunc, 1000);

	chrome.storage.sync.get("backImgTog", function(storage) {
		if (storage.backImgTog != undefined || !storage.backImgTog) {
			$.get("https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US", function(response) {
				var url = "https://www.bing.com" + response.images[0].url;
				$("#par").parallax({ imageSrc: url, bleed: 20, positionY: "0px" });
				$("#par").addClass("imageLoaded");
				$("#section1").addClass("imageLoaded");
				//$("body").css("background-image", "url(" + url + ")");
			});
		}
	});

	$("#settingsBtn").click(function() {
		$("#settingsModal").modal();
	});

	$("#newTabDefault").click(function() {
		window.location.href = "chrome-search://local-ntp/local-ntp.html"
	});
	$("#hwButton").smoothScroll();

	$("#schedulesAccountBtn").click(function() {
		var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left;
		var dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top;

		width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
		height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;

		var w = 600;
		var h = 400;

		var left = ((width / 2) - (w / 2)) + dualScreenLeft;
		var top = ((height / 2) - (h / 2)) + dualScreenTop;
		window.location.href = chrome.runtime.getURL("schedulesSignIn.html");
	});

	chrome.storage.sync.get(["schedulesLogin"], function(response) {
		if (response.schedulesLogin != undefined) {
			$("#schedulesSignIn").addClass("hidden");
			$("#schedulesSignedIn").removeClass("hidden");
			$("#schedulesAccountName").text(response.schedulesLogin.username);
		}
	});

	$("#schedulesLogOut").click(function() {
		chrome.storage.sync.remove("schedulesLogin", function() {
			window.location.reload();
		});
	});

	chrome.storage.sync.get("backImgTog", function(storage) {
		$("#backImgTog").prop("checked", storage.backImgTog);
	});
	$("#backImgTog").change(function() {
		chrome.storage.sync.set({"backImgTog": $(this).prop("checked")}, function() {

		});
	});

	window.coursesLib.checkLoggedIn(function(response) {
		if (!response.isLoggedIn) {
			$("#classes-warning").html(' Please log in here.');
		} else {
			window.coursesLib.getCourseList(function(response) {
				for (var courseIndex in response.classes) {
					var course = response.classes[courseIndex];
					console.log(course);
					var $element = $("

");
						$element.html('' + course.name + '');
					$("#courses").append($element);
				}
			});
		}

		var easter_egg = new Konami();
		easter_egg.code = function() {
			swal("Unexpected T_PAAMAYIM_NEKUDOTAYIM!", "MWAHHHAHAHAHAHAHAHAH\nConfused? Search on...\n This product uses Sapi, Papi, Capy, Wapi", "warning")
		}
		easter_egg.load();
	});

	window.planhub.get("features/get/", function(data) {
		console.log(data);
		if (data.status == "error") {
			$("#hw-warning").html(' Sign into PlanHub to view your homework.');
			return;
		}
		if (data.features.indexOf("hwView") == -1) {
			$("#hw-warning").html(' Enable Homework View to see your homework here.');
			return;
		}

		window.planhub.get("planner/sections/get/", function(data) {
			for (var i = 0; i < data.sections.length; i++) {
				var itm = data.sections[i];
				window.daltonTab.subjects[itm.sectionIndex] = itm;
			};
			window.daltonTab.loadDate(window.daltonTab.findNextDay(1), "Tomorrow", function() {

			});
			window.daltonTab.loadDate(window.daltonTab.findNextDay(2), "Soon", function() {

			});
			window.daltonTab.loadDate(window.daltonTab.findNextDay(3), "Soon", function() {

			});
			window.daltonTab.loadDate(window.daltonTab.findNextDay(4), "Soon", function() {

			});
			window.daltonTab.loadDate(window.daltonTab.findNextDay(5), "Longterm", function() {

			});
			window.daltonTab.loadDate(window.daltonTab.findNextDay(6), "Longterm", function() {

			});
			window.daltonTab.loadDate(window.daltonTab.findNextDay(7), "Longterm", function() {

			});
			window.daltonTab.loadDate(window.daltonTab.findNextDay(8), "Longterm", function() {

			});
			window.daltonTab.loadDate(window.daltonTab.findNextDay(9), "Longterm", function() {

			});
			window.daltonTab.loadDate(window.daltonTab.findNextDay(10), "Longterm", function() {

			});
			window.daltonTab.loadDate(window.daltonTab.findNextDay(11), "Longterm", function() {

			});
			window.daltonTab.loadDate(window.daltonTab.findNextDay(12), "Longterm", function() {

			});
			window.daltonTab.loadDate(window.daltonTab.findNextDay(13), "Longterm", function() {

			});
			window.daltonTab.loadDate(window.daltonTab.findNextDay(14), "Longterm", function() {

			});
		});
	});
	setTimeout(function() {
		$(window).trigger('resize');
	}, 100)
});

$(document).on("load", function() {

});
<|endoftext|>


<commit_before>initData();
initHelpers();

var endpoint = 'https://api.panlex.org/v2';
var currentUrl;

$(document).ready(function () {
  $('#queryList').html(Handlebars.templates.queryList({ queries: queries }));
  $('.queryLink').on('click', clickQuery);

  var queryLink;
  var hash = window.location.hash.replace(/^#/, '');
  if (hash.length && hash.match(/^[a-z]+$/)) {
    var elt = $('#queryLink-'+hash);
    if (elt.length) queryLink = elt;
  }
  if (!queryLink) queryLink = $('#queryLink-langvar');
  queryLink.trigger('click');

  $('#content').show();
});

function initData() {
  // populate queryDefaults
  for (var i in queryDefaults) {
    if (i === 'all') continue;

    // apply "all" values to this query type
    queryDefaults[i] = deepCopyExtend(queryDefaults.all, queryDefaults[i]);

    // apply inherited values
    for (var j in queryDefaults[i]) {
      for (var k in queryDefaults[i][j]) {
        var inherit = queryDefaults[i][j][k].inherit;
        if (inherit) queryDefaults[i][j][k] = queryDefaults[inherit][j][k];
      }
    }
  }

  // populate inherited reqParams and reqParamsRestrictions
  for (var i in queries) {
    var q = queries[i];

    if (q.reqParams.inherit) { // inherit all params
      var f = q.reqParams.filter;
      q.reqParams = deepCopy(queries[q.reqParams.inherit].reqParams);
      if (f) applyObjFilter(q.reqParams, f);
    }
    else {
      for (var j in q.reqParams) {
        if (q.reqParams[j].inherit) { // inherit single param
          var f = q.reqParams[j].filter;
          q.reqParams[j] = deepCopy(queries[q.reqParams[j].inherit].reqParams[j]);
          if (f) applyObjFilter(q.reqParams[j], f);
        }
      }
    }

    if (q.reqParamsRestrictions && q.reqParamsRestrictions.inherit) {
      var f = q.reqParamsRestrictions.filter;
      q.reqParamsRestrictions = queries[q.reqParamsRestrictions.inherit].reqParamsRestrictions.slice();
      if (f) applyArrayFilter(q.reqParamsRestrictions, f);
    }
  }

  // populate query fields:
  // - from queryDefaults
  // - reqTypes and resTypes
  // - include desc
  // - restriction desc
  for (var i in queries) {
    var queryType = queries[i].type;

    // apply default values to queries
    if (queryType && queryDefaults[queryType])
      queries[i] = deepCopyExtend(queryDefaults[queryType], queries[i]);

    // make set of request parameter and response object types requiring documentation
    ['reqParams', 'resFields', 'resFieldsRoot'].forEach(function (j) {
      var types = {};

      for (var k in queries[i][j]) {
        var type = queries[i][j][k].type;
        if (type) {
          type = type.replace(/(?:\[\])+$/, '');
          if (objectTypes[type]) types[type] = objectTypes[type];
        }
      }

      if (Object.keys(types).length) {
        var key = j.replace(/Params|Fields/, 'Types');
        queries[i][key] = types;
      }
    });

    // populate include desc (deleting param if invalid)
    if (queries[i].reqParams.include) {
      var obj = queries[i].reqParams.include;

      if (obj.options) {
        obj.desc += ' Possible values: '
          + obj.options.map(function (p) { return '' + p + '' }).join(', ')
          + '.';
      }
      else delete queries[i].reqParams.include;
    }

    // populate restriction desc
    if (queries[i].reqParamsRestrictions) {
      var desc = [];

      queries[i].reqParamsRestrictions.forEach(function (r) {
        if (r.type === 'atLeastOne') {
          var str = (r.context ? r.context + ', you ' : 'You ');
          var conj;

          if (r.not) {
            str += 'must provide at least one parameter other than ';
            conj = 'and';
          }
          else {
            str += 'must provide at least one of the following parameters: ';
            conj = 'or';
          }

          var value = r.value.map(function (p) { return '' + p + '' });
          if (value.length > 2) {
            value[value.length - 1] = conj + ' ' + value[value.length - 1];
            str += value.join(', ');
          }
          else str += value.join(' ' + conj + ' ');

          desc.push(str + '.');
        }
        else if (r.type === 'comment') {
          desc.push(r.value);
        }
        else if (r.type === 'required') {
          desc.push('The parameter ' + r.value + ' is required.');
        }
      });

      queries[i].reqParamsRestrictions = desc;
    }
  }

  // populate inherited objectTypes
  for (var i in objectTypes) {
    if (objectTypes[i].inherit) {
      var ourFields = objectTypes[i].fields = {};
      var theirFields = queries[objectTypes[i].inherit].resFields;

      for (var j in theirFields) {
        if (!theirFields[j].restriction) ourFields[j] = theirFields[j];
      }
    }
  }
}

function deepCopy(obj) {
  return $.extend(true, {}, obj);
}

function deepCopyExtend(obj1, obj2) {
  return $.extend(true, deepCopy(obj1), obj2);
}

function applyObjFilter(obj, f) {
  var sign =  f.not ? -1 : 1;

  var set = {};
  f.value.forEach(function (i) { set[i] = 1 });

  for (var i in obj) {
    if ((set[i] || -1)*sign === -1) delete obj[i];
  }

  return obj;
}

function applyArrayFilter(array, f) {
  var sign =  f.not ? -1 : 1;

  var set = {};
  f.value.forEach(function (i) { set[i] = 1 });

  if (f.key) {
    for (var i = 0; i < array.length; i++) {
      if ((set[array[i][f.key]] || -1)*sign === -1) array.splice(i--, 1);
    }
  }
  else {
    for (var i = 0; i < array.length; i++) {
      if ((set[array[i]] || -1)*sign === -1) array.splice(i--, 1);
    }
  }
}

function initHelpers() {
  Handlebars.registerHelper('eachSorted', function (context, options) {
    var ret = '';
    Object.keys(context).sort().forEach(function (key) {
      ret += options.fn({ name: key, attr: context[key] });
    });
    return ret;
  });

  Handlebars.registerHelper('urlToId', function (url) {
    return url.replace(/[/<>|_]/g, '');
  });
}

function clickQuery(e) {
  $('.queryLink').removeClass('active');
  setQuery($(this).addClass('active').data('url'));
  window.location.hash = this.id.replace(/^queryLink-/, '');
}

function setQuery(url) {
  var info = queries[url];

  $('#summary').html(Handlebars.templates.summary({ url: url, summary: info.summary }));

  $('#error').empty();

  $('#description').html(Handlebars.templates.description({ desc: info.desc }));

  var reqUrlParams = url.match(/<[^>]+>/g);
  if (reqUrlParams) {
    reqUrlParams = reqUrlParams.map(function (item) {
      var param = item.replace(/[<>]/g, '');
      return { name: param, attr: urlParams[param] };
    });
  }

  $('#reqParams').html(Handlebars.templates.reqParams({
    params: info.reqParams,
    paramsGlobal: info.reqParamsGlobal,
    restrictions: info.reqParamsRestrictions,
    urlParams: reqUrlParams,
    types: info.reqTypes
  }));

  $('#submit').on('click', submitRequest);

  $('#resFields').html(Handlebars.templates.resFields({
    fields: info.resFields,
    fieldsRoot: info.resFieldsRoot,
    types: info.resTypes,
    typesRoot: info.resTypesRoot
  }));

  currentUrl = url.replace(/\/<.+$/, '');
}

function submitRequest(e) {
  $('#error').empty();

  var p = getReqParams();
  if (!p) return;

  $('#queryResultBody').html('
Running…
');
  $('#queryResult').modal('show');

  var options = {
    url: endpoint + currentUrl,
    complete: receiveResult(p.body)
  };

  if (p.url.length) {
    options.method = 'GET';
    options.url += '/' + p.url.join('/');
    options.data = p.body;
  }
  else {
    options.method = 'POST';
    options.data = JSON.stringify(p.body);
  }

  $.ajax(options);
}

function getReqParams() {
  var p = { body: {}, url: [] };
  var error;

  $('#reqParams input').each(function () {
    var val = this.value.trim();
    var match = this.name.match(/^url_(\d)$/);

    if (match) {
      if (val.length) p.url[match[1]] = val;
      else {
        setError($(this).data('name'), 'is required');
      }
    }
    else if (val.length) {
      try {
        val = JSON.parse(val);
        p.body[this.name] = val;
      } catch (e) {
        setError(this.name, 'has invalid JSON');
      }
    }
  });

  return error ? null : p;

  function setError(param, message) {
    error = true;
    $('#error').append(Handlebars.templates.error({ param: param, message: message }));
  }
}

function receiveResult(body) {
  return function(jqXHR, textStatus) {
    if (textStatus === 'success' || textStatus === 'error') {
      try {
        var response = $.parseJSON(jqXHR.responseText);

        $('#queryResultBody').html(Handlebars.templates.queryResult({
          url: this.url,
          method: this.method,
          body: this.method === 'POST' ? canonicalJson(body, null, 2) : null,
          status: jqXHR.status !== 200 ? jqXHR.status : null,
          response: canonicalJson(response, null, 2)
        }));
      } catch (e) {
        $('#queryResultBody').html('
API response contained invalid JSON
');
      }
    }
    else $('#queryResultBody').html('
Unexpected error occurred
');
  }
}

function canonicalJson(object, replacer, space) {
  return JSON.stringify(copyObjectWithSortedKeys(object), replacer, space)
}

function copyObjectWithSortedKeys(object) {
  if (isObject(object)) {
    var newObj = {}
    var keysSorted = Object.keys(object).sort()
    var key
    for (var i = 0, len = keysSorted.length; i < len; i++) {
      key = keysSorted[i]
      newObj[key] = copyObjectWithSortedKeys(object[key])
    }
    return newObj
  } else if (Array.isArray(object)) {
    return object.map(copyObjectWithSortedKeys)
  } else {
    return object
  }
}

function isObject(a) {
  return Object.prototype.toString.call(a) === '[object Object]'
}

<commit_msg>put #submit click event in more logical place<commit_after>initData();
initHelpers();

var endpoint = 'https://api.panlex.org/v2';
var currentUrl;

$(document).ready(function () {
  $('#queryList').html(Handlebars.templates.queryList({ queries: queries }));
  $('.queryLink').on('click', clickQuery);

  var queryLink;
  var hash = window.location.hash.replace(/^#/, '');
  if (hash.length && hash.match(/^[a-z]+$/)) {
    var elt = $('#queryLink-'+hash);
    if (elt.length) queryLink = elt;
  }
  if (!queryLink) queryLink = $('#queryLink-langvar');
  queryLink.trigger('click');

  $('#content').show();
});

function initData() {
  // populate queryDefaults
  for (var i in queryDefaults) {
    if (i === 'all') continue;

    // apply "all" values to this query type
    queryDefaults[i] = deepCopyExtend(queryDefaults.all, queryDefaults[i]);

    // apply inherited values
    for (var j in queryDefaults[i]) {
      for (var k in queryDefaults[i][j]) {
        var inherit = queryDefaults[i][j][k].inherit;
        if (inherit) queryDefaults[i][j][k] = queryDefaults[inherit][j][k];
      }
    }
  }

  // populate inherited reqParams and reqParamsRestrictions
  for (var i in queries) {
    var q = queries[i];

    if (q.reqParams.inherit) { // inherit all params
      var f = q.reqParams.filter;
      q.reqParams = deepCopy(queries[q.reqParams.inherit].reqParams);
      if (f) applyObjFilter(q.reqParams, f);
    }
    else {
      for (var j in q.reqParams) {
        if (q.reqParams[j].inherit) { // inherit single param
          var f = q.reqParams[j].filter;
          q.reqParams[j] = deepCopy(queries[q.reqParams[j].inherit].reqParams[j]);
          if (f) applyObjFilter(q.reqParams[j], f);
        }
      }
    }

    if (q.reqParamsRestrictions && q.reqParamsRestrictions.inherit) {
      var f = q.reqParamsRestrictions.filter;
      q.reqParamsRestrictions = queries[q.reqParamsRestrictions.inherit].reqParamsRestrictions.slice();
      if (f) applyArrayFilter(q.reqParamsRestrictions, f);
    }
  }

  // populate query fields:
  // - from queryDefaults
  // - reqTypes and resTypes
  // - include desc
  // - restriction desc
  for (var i in queries) {
    var queryType = queries[i].type;

    // apply default values to queries
    if (queryType && queryDefaults[queryType])
      queries[i] = deepCopyExtend(queryDefaults[queryType], queries[i]);

    // make set of request parameter and response object types requiring documentation
    ['reqParams', 'resFields', 'resFieldsRoot'].forEach(function (j) {
      var types = {};

      for (var k in queries[i][j]) {
        var type = queries[i][j][k].type;
        if (type) {
          type = type.replace(/(?:\[\])+$/, '');
          if (objectTypes[type]) types[type] = objectTypes[type];
        }
      }

      if (Object.keys(types).length) {
        var key = j.replace(/Params|Fields/, 'Types');
        queries[i][key] = types;
      }
    });

    // populate include desc (deleting param if invalid)
    if (queries[i].reqParams.include) {
      var obj = queries[i].reqParams.include;

      if (obj.options) {
        obj.desc += ' Possible values: '
          + obj.options.map(function (p) { return '' + p + '' }).join(', ')
          + '.';
      }
      else delete queries[i].reqParams.include;
    }

    // populate restriction desc
    if (queries[i].reqParamsRestrictions) {
      var desc = [];

      queries[i].reqParamsRestrictions.forEach(function (r) {
        if (r.type === 'atLeastOne') {
          var str = (r.context ? r.context + ', you ' : 'You ');
          var conj;

          if (r.not) {
            str += 'must provide at least one parameter other than ';
            conj = 'and';
          }
          else {
            str += 'must provide at least one of the following parameters: ';
            conj = 'or';
          }

          var value = r.value.map(function (p) { return '' + p + '' });
          if (value.length > 2) {
            value[value.length - 1] = conj + ' ' + value[value.length - 1];
            str += value.join(', ');
          }
          else str += value.join(' ' + conj + ' ');

          desc.push(str + '.');
        }
        else if (r.type === 'comment') {
          desc.push(r.value);
        }
        else if (r.type === 'required') {
          desc.push('The parameter ' + r.value + ' is required.');
        }
      });

      queries[i].reqParamsRestrictions = desc;
    }
  }

  // populate inherited objectTypes
  for (var i in objectTypes) {
    if (objectTypes[i].inherit) {
      var ourFields = objectTypes[i].fields = {};
      var theirFields = queries[objectTypes[i].inherit].resFields;

      for (var j in theirFields) {
        if (!theirFields[j].restriction) ourFields[j] = theirFields[j];
      }
    }
  }
}

function deepCopy(obj) {
  return $.extend(true, {}, obj);
}

function deepCopyExtend(obj1, obj2) {
  return $.extend(true, deepCopy(obj1), obj2);
}

function applyObjFilter(obj, f) {
  var sign =  f.not ? -1 : 1;

  var set = {};
  f.value.forEach(function (i) { set[i] = 1 });

  for (var i in obj) {
    if ((set[i] || -1)*sign === -1) delete obj[i];
  }

  return obj;
}

function applyArrayFilter(array, f) {
  var sign =  f.not ? -1 : 1;

  var set = {};
  f.value.forEach(function (i) { set[i] = 1 });

  if (f.key) {
    for (var i = 0; i < array.length; i++) {
      if ((set[array[i][f.key]] || -1)*sign === -1) array.splice(i--, 1);
    }
  }
  else {
    for (var i = 0; i < array.length; i++) {
      if ((set[array[i]] || -1)*sign === -1) array.splice(i--, 1);
    }
  }
}

function initHelpers() {
  Handlebars.registerHelper('eachSorted', function (context, options) {
    var ret = '';
    Object.keys(context).sort().forEach(function (key) {
      ret += options.fn({ name: key, attr: context[key] });
    });
    return ret;
  });

  Handlebars.registerHelper('urlToId', function (url) {
    return url.replace(/[/<>|_]/g, '');
  });
}

function clickQuery(e) {
  $('.queryLink').removeClass('active');
  setQuery($(this).addClass('active').data('url'));
  window.location.hash = this.id.replace(/^queryLink-/, '');
}

function setQuery(url) {
  var info = queries[url];

  $('#summary').html(Handlebars.templates.summary({ url: url, summary: info.summary }));

  $('#submit').on('click', submitRequest);

  $('#error').empty();

  $('#description').html(Handlebars.templates.description({ desc: info.desc }));

  var reqUrlParams = url.match(/<[^>]+>/g);
  if (reqUrlParams) {
    reqUrlParams = reqUrlParams.map(function (item) {
      var param = item.replace(/[<>]/g, '');
      return { name: param, attr: urlParams[param] };
    });
  }

  $('#reqParams').html(Handlebars.templates.reqParams({
    params: info.reqParams,
    paramsGlobal: info.reqParamsGlobal,
    restrictions: info.reqParamsRestrictions,
    urlParams: reqUrlParams,
    types: info.reqTypes
  }));

  $('#resFields').html(Handlebars.templates.resFields({
    fields: info.resFields,
    fieldsRoot: info.resFieldsRoot,
    types: info.resTypes,
    typesRoot: info.resTypesRoot
  }));

  currentUrl = url.replace(/\/<.+$/, '');
}

function submitRequest(e) {
  $('#error').empty();

  var p = getReqParams();
  if (!p) return;

  $('#queryResultBody').html('
Running…
');
  $('#queryResult').modal('show');

  var options = {
    url: endpoint + currentUrl,
    complete: receiveResult(p.body)
  };

  if (p.url.length) {
    options.method = 'GET';
    options.url += '/' + p.url.join('/');
    options.data = p.body;
  }
  else {
    options.method = 'POST';
    options.data = JSON.stringify(p.body);
  }

  $.ajax(options);
}

function getReqParams() {
  var p = { body: {}, url: [] };
  var error;

  $('#reqParams input').each(function () {
    var val = this.value.trim();
    var match = this.name.match(/^url_(\d)$/);

    if (match) {
      if (val.length) p.url[match[1]] = val;
      else {
        setError($(this).data('name'), 'is required');
      }
    }
    else if (val.length) {
      try {
        val = JSON.parse(val);
        p.body[this.name] = val;
      } catch (e) {
        setError(this.name, 'has invalid JSON');
      }
    }
  });

  return error ? null : p;

  function setError(param, message) {
    error = true;
    $('#error').append(Handlebars.templates.error({ param: param, message: message }));
  }
}

function receiveResult(body) {
  return function(jqXHR, textStatus) {
    if (textStatus === 'success' || textStatus === 'error') {
      try {
        var response = $.parseJSON(jqXHR.responseText);

        $('#queryResultBody').html(Handlebars.templates.queryResult({
          url: this.url,
          method: this.method,
          body: this.method === 'POST' ? canonicalJson(body, null, 2) : null,
          status: jqXHR.status !== 200 ? jqXHR.status : null,
          response: canonicalJson(response, null, 2)
        }));
      } catch (e) {
        $('#queryResultBody').html('
API response contained invalid JSON
');
      }
    }
    else $('#queryResultBody').html('
Unexpected error occurred
');
  }
}

function canonicalJson(object, replacer, space) {
  return JSON.stringify(copyObjectWithSortedKeys(object), replacer, space)
}

function copyObjectWithSortedKeys(object) {
  if (isObject(object)) {
    var newObj = {}
    var keysSorted = Object.keys(object).sort()
    var key
    for (var i = 0, len = keysSorted.length; i < len; i++) {
      key = keysSorted[i]
      newObj[key] = copyObjectWithSortedKeys(object[key])
    }
    return newObj
  } else if (Array.isArray(object)) {
    return object.map(copyObjectWithSortedKeys)
  } else {
    return object
  }
}

function isObject(a) {
  return Object.prototype.toString.call(a) === '[object Object]'
}

<|endoftext|>


<commit_before>
document.addEventListener('DOMContentLoaded', () => {

  // Getting data info from the browser
  const date = new Date();
  date.month = date.getMonth();
  date.year = date.getFullYear();
  date.hour = date.getHours();

  // Setting the general styles, at-dat, at-night or terminal class
  const body = document.getElementsByTagName('body')[0];

  // Add at-day or at-night class depending on the current hour
  date.hour >= 8 && date.hour < 21 ? body.classList.add('at-day') : body.classList.add('at-night');

  // Mounts set
  const month = ['January', 'February', 'March', 'April', 'March', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

  // Format the string for display the mount on time HTML tag
  let space = '';
  date.month < 10 ? space = '-0' : space = '-';
  const currentDate = `${month[date.month]} ${date.year}`;
  const attDate = `${date.year}${space}${date.month+1}`;

  // Adding the attribute and the text on <time> element
  const time = document.getElementsByTagName('time')[0];
  time.setAttribute('datatime', attDate);
  time.textContent = currentDate;

  // Hides browser address bar when load
  setTimeout(() => { window.scroll(0, 1) }, 0);

});

console.log("👋 HELLO PARTNET. Feel free to fork it on https://github.com/pablorgarcia/pablorgarcia.github.io :)");
<commit_msg>Hides browser address bar when load, deleted<commit_after>
document.addEventListener('DOMContentLoaded', () => {

  // Getting data info from the browser
  const date = new Date();
  date.month = date.getMonth();
  date.year = date.getFullYear();
  date.hour = date.getHours();

  // Setting the general styles, at-dat, at-night or terminal class
  const body = document.getElementsByTagName('body')[0];

  // Add at-day or at-night class depending on the current hour
  date.hour >= 8 && date.hour < 21 ? body.classList.add('at-day') : body.classList.add('at-night');

  // Mounts set
  const month = ['January', 'February', 'March', 'April', 'March', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

  // Format the string for display the mount on time HTML tag
  let space = '';
  date.month < 10 ? space = '-0' : space = '-';
  const currentDate = `${month[date.month]} ${date.year}`;
  const attDate = `${date.year}${space}${date.month+1}`;

  // Adding the attribute and the text on <time> element
  const time = document.getElementsByTagName('time')[0];
  time.setAttribute('datatime', attDate);
  time.textContent = currentDate;

});

console.log("👋 HELLO PARTNET. Feel free to fork it on https://github.com/pablorgarcia/pablorgarcia.github.io :)");
<|endoftext|>


<commit_before>
$(function(){
	play();
});

var bk_table = [];
function play(){
	//初始化UI
	createUI();
	//初始化随机number
	//移动随机数
	//合并碰撞
	//检测add
	//终止条件
}

function createUI(){
	//bk_cell init
	for(var i = 0; i < 4; i++){
		bk_table[i] = [];
		for(var j = 0; j <4; j++){
			bk_table[i][j] = 0;
			var bk_cell = $('#bk_cell_'+ i + '_' + j);
			bk_cell.css('top', getTop(i, j));
			bk_cell.css('left', getLeft(i, j));
		}
	}

	//show number
	bk_table[1][2] = 8;
	bk_table[2][0] = 4;
	showNumber(bk_table);
	console.log(bk_table);

}

function showNumber(bk_table){
	//fr_cell init
	$('.fr_cell').remove();
	for(var i = 0; i < 4; i++){
		for(var j = 0; j < 4; j++){
			var fr_cell_str = '
' + '
';
			$('#main_ui_cell').append(fr_cell_str);
			var fr_cell = $('#fr_cell'+ i + '_' + j);
			if(bk_table[i][j] == 0){
				fr_cell.css('width', '10px');
				fr_cell.css('height', '10px');
				fr_cell.css('top', getTop(i, j) + 50);
				fr_cell.css('left', getLeft(i, j) + 50);
			}else{
				fr_cell.css('width', '100px');
				fr_cell.css('height', '100px');
				fr_cell.css('top', getTop(i, j));
				fr_cell.css('left', getLeft(i, j));
				fr_cell.css('backgroundColor', getBackColor(bk_table[i][j])); //设置背景色
				fr_cell.css('color', getTextColor(bk_table[i][j])); //设置文字颜色
				fr_cell.text(bk_table[i][j]);
			}
		}
	}
}

function getBackColor(number){
	switch(number){
		case 2: return '#EEE4DA'; break;
		case 4: return '#EEE4DA'; break;
		case 8: return '#F3B079'; break;
		case 16: return '#EB8E53'; break;
		case 32: return '#FB795F'; break;
		case 64: return '#EB573B'; break;
		case 128: return '#00C6E5'; break;
		case 256: return '#EDCA62'; break;
		case 512: return '#FCD209'; break;
		case 1024: return '#E12D2D'; break;
		case 2048: return '#4CB649'; break;
	}
}

function getTextColor(number){
	if(number <= 4)
		return '#665C52';

	return '#FFF';
}

function getTop(i , j){
	return i*110 + 10;
}

function getLeft(i, j){
	return j*110 + 10;
}<commit_msg>show number<commit_after>
$(function(){
	play();
});

var bk_table = [];
function play(){
	//初始化UI
	createUI();
	//初始化随机number
	//移动随机数
	//合并碰撞
	//检测add
	//终止条件
}

function createUI(){
	//bk_cell init
	for(var i = 0; i < 4; i++){
		bk_table[i] = [];
		for(var j = 0; j <4; j++){
			bk_table[i][j] = 0;
			var bk_cell = $('#bk_cell_'+ i + '_' + j);
			bk_cell.css('top', getTop(i, j));
			bk_cell.css('left', getLeft(i, j));
		}
	}

	//show number
	bk_table[1][2] = 8;
	bk_table[2][0] = 4;
	showNumber(bk_table);

}

function showNumber(bk_table){
	console.log(bk_table);
	//fr_cell init
	$('.fr_cell').remove();
	for(var i = 0; i < 4; i++){
		for(var j = 0; j < 4; j++){
			var fr_cell_str = '
' + '
';
			$('#main_ui_cell').append(fr_cell_str);
			var fr_cell = $('#fr_cell_'+ i + '_' + j);
			if(bk_table[i][j] == 0){
				fr_cell.css('width', '10px');
				fr_cell.css('height', '10px');
				fr_cell.css('top', getTop(i, j) + 50);
				fr_cell.css('left', getLeft(i, j) + 50);
			}else{
				fr_cell.css('width', '100px');
				fr_cell.css('height', '100px');
				fr_cell.css('top', getTop(i, j));
				fr_cell.css('left', getLeft(i, j));
				fr_cell.css('backgroundColor', getBackColor(bk_table[i][j])); //设置背景色
				fr_cell.css('color', getTextColor(bk_table[i][j])); //设置文字颜色
				fr_cell.text(bk_table[i][j]);
			}
		}
	}
}

function getBackColor(number){
	switch(number){
		case 2: return '#EEE4DA'; break;
		case 4: return '#EEE4DA'; break;
		case 8: return '#F3B079'; break;
		case 16: return '#EB8E53'; break;
		case 32: return '#FB795F'; break;
		case 64: return '#EB573B'; break;
		case 128: return '#00C6E5'; break;
		case 256: return '#EDCA62'; break;
		case 512: return '#FCD209'; break;
		case 1024: return '#E12D2D'; break;
		case 2048: return '#4CB649'; break;
		default: break;
	}
}

function getTextColor(number){
	if(number <= 4)
		return '#665C52';

	return '#FFF';
}

function getTop(i , j){
	return i*110 + 10;
}

function getLeft(i, j){
	return j*110 + 10;
}<|endoftext|>


<commit_before>(function() {
  "use strict";
  var btn = document.getElementById('btn');
  btn.addEventListener("click", function() {
    var n = Math.floor(Math.random() * 3);
    switch (n) {
      case 0:
        this.textContent = "大吉";
        break;
      case 1:
        this.textContent = "中吉";
        break;
      case 2:
        this.textContent = "凶";
        break;
      default:
    }
    // if (n === 0) {
    //   this.textContent = "大吉";
    // } else if (n === 1) {
    //   this.textContent = "中吉";
    // } else {
    //   this.textContent = "凶";
    // }
  });
  btn.addEventListener("mousedown", function() {
    this.className = "pushed";
  });
  btn.addEventListener("mouseup", function() {
    this.className = "";
  });
})();
<commit_msg>use array to show results<commit_after>(function() {
  "use strict";
  var btn = document.getElementById('btn');
  btn.addEventListener("click", function() {
    var results = ["大吉", "吉", "末吉", "凶"];
    var n = Math.floor(Math.random() * results.length);
    this.textContent = results[n];
  });
  btn.addEventListener("mousedown", function() {
    this.className = "pushed";
  });
  btn.addEventListener("mouseup", function() {
    this.className = "";
  });
})();
<|endoftext|>


<commit_before>// Init background image
$.backstretch(["img/bg.jpg"], {fade: 200});

// To the global namespace just for now
var theme = new Soundgun("sounds/theme.ogg");

$(function () {

    // Music & Sounds
    var hit = new Soundgun("sounds/hit.ogg");
    theme.setVolume(0);
    theme.play();
    theme.fadeIn(70, 0.5);
    theme.loop();

    // Text
    var score = new Textgun("#score");
    score.useTransition(1);
    score.setValue('0');
    var time = new Textgun("#time");

    engine = new PongEngine();
    engine.startEngine();

    // Start timer
    var timer = new Timer();
    timer.start();
    var timeInterval = setInterval(function() {time.setValue(timer.getFormattedTime(timer.getCurrentTime()));}, 100);

    var upPressed = function() {
        console.log("up");
        engine.ball.movingVector.elements[1]--;
    },
        downPressed = function() {
            console.log("down");
            engine.ball.movingVector.elements[1]++;
        },
        rightPressed = function() {
            // for now, move paddle 10 times right
            for(var i =  0; i < 10; i++) {
                engine.paddle.movePaddleRight();
            }
        },
        leftPressed = function() {
            for(var i = 0; i < 10; i++) {
                engine.paddle.movePaddleLeft();
            }
        };

    var keyHandlers = {39: rightPressed, 38: upPressed, 37: leftPressed, 40: downPressed};

    $(document).keydown(function(e, v) {
        var isArrowkey = function(keycode) {
            return keycode >= 37 && keycode <= 40;
        },
            forwardKeyPress = true;

        if (!isArrowkey(e.keyCode)) {
            forwardKeyPress = true;
        }  else {
            try {
                keyHandlers[e.keyCode]();
            } catch(e) {
                // Do nothing
            }
            forwardKeyPress = false;
        }
        return forwardKeyPress;
    });

    // Bind all game events. Game engine triggers them to canvas
    $('#main-canvas').bind('collision', function() {
        console.log("there was a collision!");
        hit.play();
        score.setValue(Number(score.getValue()) + 150);
    });
    $('#main-canvas').bind('gameOver', function() {
        console.log("Game is over! Restarting the engine!");
        engine.stopEngine();
        timer.stop();
        clearInterval(timeInterval);
        console.log(timer.getFinalTime());

        // Display the nameModal
        $('#nameModal').fadeIn();

    });

    // When user submits scoreform
    $('#yes-button').click(function(){
        var nick = $('#nick').val();
        var dataString = 'nick=' + nick + '&time=' + timer.getFormattedTime() + '&score=' + score.getValue();
        $.ajax({
            type: 'POST',
            url: 'commit.php',
            data: dataString,
            success: function(data) {
                alert(data); // testing
            }
        });
    });

});
<commit_msg>Fixes to usage logic<commit_after>// Init background image
$.backstretch(["img/bg.jpg"], {fade: 200});

// To the global namespace just for now
var theme = new Soundgun("sounds/theme.ogg");

$(function () {

    // Music & Sounds
    var hit = new Soundgun("sounds/hit.ogg");
    theme.setVolume(0);
    theme.play();
    theme.fadeIn(70, 0.5);
    theme.loop();

    // Text
    var score = new Textgun("#score");
    score.useTransition(1);
    score.setValue('0');
    var time = new Textgun("#time");

    engine = new PongEngine();
    engine.startEngine();

    // Start timer
    var timer = new Timer();
    timer.start();
    var timeInterval = setInterval(function() {time.setValue(timer.getFormattedTime(timer.getCurrentTime()));}, 100);

    var upPressed = function() {
        console.log("up");
        engine.ball.movingVector.elements[1]--;
    },
        downPressed = function() {
            console.log("down");
            engine.ball.movingVector.elements[1]++;
        },
        rightPressed = function() {
            // for now, move paddle 10 times right
            for(var i =  0; i < 10; i++) {
                engine.paddle.movePaddleRight();
            }
        },
        leftPressed = function() {
            for(var i = 0; i < 10; i++) {
                engine.paddle.movePaddleLeft();
            }
        };

    var keyHandlers = {39: rightPressed, 38: upPressed, 37: leftPressed, 40: downPressed};

    $(document).keydown(function(e, v) {
        var isArrowkey = function(keycode) {
            return keycode >= 37 && keycode <= 40;
        },
            forwardKeyPress = true;

        if (!isArrowkey(e.keyCode)) {
            forwardKeyPress = true;
        }  else {
            try {
                keyHandlers[e.keyCode]();
            } catch(e) {
                // Do nothing
            }
            forwardKeyPress = false;
        }
        return forwardKeyPress;
    });

    // Bind all game events. Game engine triggers them to canvas
    $('#main-canvas').bind('collision', function() {
        console.log("there was a collision!");
        hit.play();
        score.setValue(Number(score.getValue()) + 150);
    });
    $('#main-canvas').bind('gameOver', function() {
        console.log("Game is over! Restarting the engine!");
        engine.stopEngine();
        timer.stop();
        time.setValue(timer.getFormattedTime(timer.getFinalTime()));
        clearInterval(timeInterval);
        console.log(timer.getFormattedTime(timer.getFinalTime()));

        // Display the nameModal
        $('#nameModal').fadeIn();

    });

    // When user submits scoreform
    $('#yes-button').click(function(){
        var nick = $('#nick').val();
        var dataString = 'nick=' + nick + '&time=' + timer.getFormattedTime() + '&score=' + score.getValue();
        $.ajax({
            type: 'POST',
            url: 'commit.php',
            data: dataString,
            success: function(data) {
                alert(data); // testing
            }
        });
    });

});
<|endoftext|>


<commit_before>'use strict';
(function(){

var balls = [], worldObjects = [];

function startGame(){
	// set the scene size
	var WIDTH = window.innerWidth,
		HEIGHT = window.innerHeight;

	// set some camera attributes
	var VIEW_ANGLE = 45,
		ASPECT = WIDTH / HEIGHT,
		NEAR = 0.1,
		FAR = 10000;

	// get the DOM element to attach to
	// - assume we've got jQuery to hand
	var $container = $('#container');

	// create a WebGL renderer, camera
	// and a scene
	var renderer = new THREE.WebGLRenderer();
	var camera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR);
	var scene = new THREE.Scene();

	// the camera starts at 0,0,0 so pull it back
	camera.position.z = 300;
	camera.position.y = 200;
	camera.rotation.x = 100;

	// start the renderer
	renderer.setSize(WIDTH, HEIGHT);
	// enable shadows on the renderer
	//renderer.shadowMapEnabled = true;

	// attach the render-supplied DOM element
	$container.append(renderer.domElement);

	// create the sphere's material
	var sphereMaterial = new THREE.MeshLambertMaterial(
	{
		color: 0xCC0000
	});

	// set up the sphere vars
	var radius = 50, segments = 16, rings = 16;

	// create a new mesh with sphere geometry -
	// we will cover the sphereMaterial next!
	var sphere = new THREE.Mesh(
		new THREE.SphereGeometry(radius, segments, rings),
		sphereMaterial);

	// create the sphere's material
	var cubeMaterial = new THREE.MeshLambertMaterial(
	{
		color: 0xCC0000
	});

	// set up the cube vars
	var width = 50, height = 50, depth = 100;

	var cube = new THREE.Mesh(
		new THREE.CubeGeometry(width, height, depth),
		cubeMaterial);

	// enable shadows for an object
	//cube.castShadow = true;
	//cube.receiveShadow = true;

	// add the sphere to the scene
	scene.add(cube);

	// sphere geometry
	sphere.geometry

	// it's attributes
	sphere.position.x = 0;
	sphere.rotation.x = 50;
	sphere.scale.y = .5;

	var planeGeo = new THREE.PlaneGeometry(1000, 1000, 10, 10);
	var planeMat = new THREE.MeshLambertMaterial({color: 0xFFFFFF});
	var plane = new THREE.Mesh(planeGeo, planeMat);
	plane.rotation.x = -Math.PI/2;
	plane.position.y = -25;
	plane.receiveShadow = true;
	scene.add(plane);
	worldObjects.push(plane);

	// add the sphere to the scene
	scene.add(sphere);

	// and the camera
	scene.add(camera);

	// create a point light
	var pointLight = new THREE.PointLight( 0xFFFFFF );

	// set its position
	pointLight.position.x = 10;
	pointLight.position.y = 40;
	pointLight.position.z = 130;

	// enable shadows for a light
	//pointLight.castShadow = true;

	// add to the scene
	scene.add(pointLight);

	// model
	var loader = new THREE.ColladaLoader();
	loader.load('worldData/glMap.dae', function (result) {
	  scene.add(result.scene);
	});

	/*
	var loader = new THREE.OBJMTLLoader();
	loader.addEventListener( 'load', function ( event ) {

		modelObject = event.content;

		modelObject.position.y = - 80;
		scene.add( modelObject );

	});
	loader.load( 'http://localhost/Dodgeball/objData/glMap.obj', 'http://localhost/Dodgeball/objData/glMap.mtl' );
	*/

	var controls = new THREE.FirstPersonControls(camera);
	controls.movementSpeed = 100;
	controls.lookSpeed = 0.1;
	controls.lon = -70; //Make camera look towards initial objects.
	//controls.noFly = true;
	var clock = new THREE.Clock();

	// Stop moving around when the window is unfocused
	$(window).bind('focus', function() {
		if (controls) controls.freeze = false;
	});
	$(window).bind('blur', function() {
		if (controls) controls.freeze = true;
	});

	// Draw
	function renderLoop() {
		requestAnimationFrame(renderLoop);
		var clockDelta = clock.getDelta();

		if (controls.fire){
			controls.fire = false;
			scene.add(fireBall(balls, camera));
		}

		var ballsToRemove = moveBalls(balls, clockDelta);
		for (var i in ballsToRemove){
			var ball = ballsToRemove[i];
			scene.remove(ball.obj);
		}

		controls.update(clockDelta);
		applyGravity(camera, clockDelta);

		cube.rotation.x += 0.05;
		cube.rotation.y += 0.05;
		renderer.render(scene, camera);
	}
	renderLoop();
}

function applyGravity(object, delta){
	var floor = 25;
	if (object.position.y <= floor){
		return;
	}

	var gravityRate = 100;
	object.translateY((-gravityRate) * delta);
}

function fireBall(balls, camera){
	var sphereMaterial = new THREE.MeshLambertMaterial(
	{
		color: 0x0000CC
	});

	var radius = 20, segments = 16, rings = 16;

	var sphere = new THREE.Mesh(
		new THREE.SphereGeometry(radius, segments, rings),
		sphereMaterial
	);

	sphere.position.x = camera.position.x;
	sphere.position.y = camera.position.y;
	sphere.position.z = camera.position.z;

	var vDirection = new THREE.Vector3( 0, 0, -1 );
	vDirection.applyQuaternion( camera.quaternion );

	var ball = game.createEntity(
	{
		name: 		"Ball",
		obj:		sphere,
		direction:	vDirection,
		age:		0
	},
	[
		game.component.entity,
        game.component.takesGravity
	]);

	balls.push(ball);

	return sphere;
}

function moveBalls(balls, delta){
	var removeBalls = [];
	var ballspeed = 2;

	for (var i in balls){
		var ball = balls[i];

		ball.obj.translateOnAxis(ball.direction, ballspeed);
		ball.applyGravity(delta);

		for (var vertexIndex = 0; vertexIndex < ball.obj.geometry.vertices.length; vertexIndex++)
		{
			var localVertex = ball.obj.geometry.vertices[vertexIndex].clone();
			var globalVertex = localVertex.applyMatrix4(ball.obj.matrix);
			var directionVector = globalVertex.sub( ball.obj.position );

			var raycaster = new THREE.Raycaster();
			raycaster.set(ball.obj.position, directionVector.clone().normalize());
			var collisions = raycaster.intersectObjects(worldObjects);
			if ( collisions.length > 0 && collisions[0].distance < directionVector.length() )
			{
				console.log('collision!');
			}
		}
		ball.age += delta;

		if (ball.obj.position.y < 0 || ball.age > 15){
			delete balls[i];
			removeBalls.push(ball);
		}
	}

	return removeBalls;
}

// componentSystem.js
(function() {

    window.game = {};
    game.component = {};

    game.createEntity = function(properties, components) {

        var prop;
        var entity = {};

        for (prop in properties) {
            entity[prop] = properties[prop];
        }

        components.forEach(function(component) {
            for (prop in component) {
                if (entity.hasOwnProperty(prop)) {
                    throw "Entity property conflict! " + prop;
                }
                entity[prop] = component[prop];
            }
        });

        return entity;

    }

}());

// entity.js
(function() {

    game.component.entity = {
        distanceTo: function(x, y) {
            return Math.sqrt(Math.pow(x - this.x, 2) +
                             Math.pow(y - this.y, 2));
        }
    }

}());

// moveable.js
(function() {

    game.component.moveable = {
        move: function(x, y) {
            this.x = x;
            this.y = y;
        }
    }

}());

(function() {
	var gravityRate = 50;

    game.component.takesGravity = {
        applyGravity: function(delta) {
			this.obj.translateY((-gravityRate) * delta);
        }
    }

}());

$(document).ready(startGame);
})();<commit_msg>Woot! Collision detection via ray casting is working!<commit_after>'use strict';
(function(){

var balls = [], worldObjects = [];

function startGame(){
	// set the scene size
	var WIDTH = window.innerWidth,
		HEIGHT = window.innerHeight;

	// set some camera attributes
	var VIEW_ANGLE = 45,
		ASPECT = WIDTH / HEIGHT,
		NEAR = 0.1,
		FAR = 10000;

	// get the DOM element to attach to
	// - assume we've got jQuery to hand
	var $container = $('#container');

	// create a WebGL renderer, camera
	// and a scene
	var renderer = new THREE.WebGLRenderer();
	var camera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR);
	var scene = new THREE.Scene();

	// the camera starts at 0,0,0 so pull it back
	camera.position.z = 300;
	camera.position.y = 200;
	camera.rotation.x = 100;

	// start the renderer
	renderer.setSize(WIDTH, HEIGHT);
	// enable shadows on the renderer
	//renderer.shadowMapEnabled = true;

	// attach the render-supplied DOM element
	$container.append(renderer.domElement);

	// create the sphere's material
	var sphereMaterial = new THREE.MeshLambertMaterial(
	{
		color: 0xCC0000
	});

	// set up the sphere vars
	var radius = 50, segments = 16, rings = 16;

	// create a new mesh with sphere geometry -
	// we will cover the sphereMaterial next!
	var sphere = new THREE.Mesh(
		new THREE.SphereGeometry(radius, segments, rings),
		sphereMaterial);

	// create the sphere's material
	var cubeMaterial = new THREE.MeshLambertMaterial(
	{
		color: 0xCC0000
	});

	// set up the cube vars
	var width = 50, height = 50, depth = 100;

	var cube = new THREE.Mesh(
		new THREE.CubeGeometry(width, height, depth),
		cubeMaterial);

	// enable shadows for an object
	//cube.castShadow = true;
	//cube.receiveShadow = true;

	// add the sphere to the scene
	scene.add(cube);

	// sphere geometry
	sphere.geometry

	// it's attributes
	sphere.position.x = 0;
	sphere.rotation.x = 50;
	sphere.scale.y = .5;

	var planeGeo = new THREE.PlaneGeometry(1000, 1000, 10, 10);
	var planeMat = new THREE.MeshLambertMaterial({color: 0xFFFFFF});
	var plane = new THREE.Mesh(planeGeo, planeMat);
	plane.rotation.x = -Math.PI/2;
	plane.position.y = -25;
	plane.receiveShadow = true;
	scene.add(plane);
	worldObjects.push(plane);

	// add the sphere to the scene
	scene.add(sphere);

	// and the camera
	scene.add(camera);

	// create a point light
	var pointLight = new THREE.PointLight( 0xFFFFFF );

	// set its position
	pointLight.position.x = 10;
	pointLight.position.y = 40;
	pointLight.position.z = 130;

	// enable shadows for a light
	//pointLight.castShadow = true;

	// add to the scene
	scene.add(pointLight);

	// model
	var loader = new THREE.ColladaLoader();
	loader.load('worldData/glMap.dae', function (result) {
	  scene.add(result.scene);
	});

	/*
	var loader = new THREE.OBJMTLLoader();
	loader.addEventListener( 'load', function ( event ) {

		modelObject = event.content;

		modelObject.position.y = - 80;
		scene.add( modelObject );

	});
	loader.load( 'http://localhost/Dodgeball/objData/glMap.obj', 'http://localhost/Dodgeball/objData/glMap.mtl' );
	*/

	var controls = new THREE.FirstPersonControls(camera);
	controls.movementSpeed = 100;
	controls.lookSpeed = 0.1;
	controls.lon = -70; //Make camera look towards initial objects.
	//controls.noFly = true;
	var clock = new THREE.Clock();

	// Stop moving around when the window is unfocused
	$(window).bind('focus', function() {
		if (controls) controls.freeze = false;
	});
	$(window).bind('blur', function() {
		if (controls) controls.freeze = true;
	});

	// Draw
	function renderLoop() {
		requestAnimationFrame(renderLoop);
		var clockDelta = clock.getDelta();

		if (controls.fire){
			controls.fire = false;
			scene.add(fireBall(balls, camera));
		}

		var ballsToRemove = moveBalls(balls, clockDelta);
		for (var i in ballsToRemove){
			var ball = ballsToRemove[i];
			scene.remove(ball.obj);
		}

		controls.update(clockDelta);
		applyGravity(camera, clockDelta);

		cube.rotation.x += 0.05;
		cube.rotation.y += 0.05;
		renderer.render(scene, camera);
	}
	renderLoop();
}

function applyGravity(object, delta){
	var floor = 25;
	if (object.position.y <= floor){
		return;
	}

	var gravityRate = 100;
	object.translateY((-gravityRate) * delta);
}

function fireBall(balls, camera){
	var sphereMaterial = new THREE.MeshLambertMaterial(
	{
		color: 0x0000CC
	});

	var radius = 20, segments = 16, rings = 16;

	var sphere = new THREE.Mesh(
		new THREE.SphereGeometry(radius, segments, rings),
		sphereMaterial
	);

	sphere.position.x = camera.position.x;
	sphere.position.y = camera.position.y;
	sphere.position.z = camera.position.z;

	var vDirection = new THREE.Vector3( 0, 0, -1 );
	vDirection.applyQuaternion( camera.quaternion );

	var ball = game.createEntity(
	{
		name: 		"Ball",
		obj:		sphere,
		direction:	vDirection,
		age:		0
	},
	[
		game.component.entity,
        game.component.takesGravity
	]);

	balls.push(ball);

	return sphere;
}

function moveBalls(balls, delta){
	var removeBalls = [];
	var ballspeed = 5;

	for (var i in balls){
		var ball = balls[i];

		ball.obj.translateOnAxis(ball.direction, ballspeed);
		ball.applyGravity(delta);

		thisBallCheck: for (var vertexIndex = 0; vertexIndex < ball.obj.geometry.vertices.length; vertexIndex++)
		{
			var localVertex = ball.obj.geometry.vertices[vertexIndex].clone();
			var globalVertex = localVertex.applyMatrix4(ball.obj.matrix);
			var directionVector = globalVertex.sub( ball.obj.position );

			var raycaster = new THREE.Raycaster();
			raycaster.set(ball.obj.position, directionVector.clone().normalize());
			var collisions = raycaster.intersectObjects(worldObjects);
			if ( collisions.length > 0 && collisions[0].distance < directionVector.length() )
			{
				console.log('collision!');
				delete balls[i];
				removeBalls.push(ball);
				break thisBallCheck;
			}
		}
	}

	return removeBalls;
}

// componentSystem.js
(function() {

    window.game = {};
    game.component = {};

    game.createEntity = function(properties, components) {

        var prop;
        var entity = {};

        for (prop in properties) {
            entity[prop] = properties[prop];
        }

        components.forEach(function(component) {
            for (prop in component) {
                if (entity.hasOwnProperty(prop)) {
                    throw "Entity property conflict! " + prop;
                }
                entity[prop] = component[prop];
            }
        });

        return entity;

    }

}());

// entity.js
(function() {

    game.component.entity = {
        distanceTo: function(x, y) {
            return Math.sqrt(Math.pow(x - this.x, 2) +
                             Math.pow(y - this.y, 2));
        }
    }

}());

// moveable.js
(function() {

    game.component.moveable = {
        move: function(x, y) {
            this.x = x;
            this.y = y;
        }
    }

}());

(function() {
	var gravityRate = 50;

    game.component.takesGravity = {
        applyGravity: function(delta) {
			this.obj.translateY((-gravityRate) * delta);
        }
    }

}());

$(document).ready(startGame);
})();<|endoftext|>


<commit_before>
var public_spreadsheet_url = 'https://docs.google.com/spreadsheets/d/1ZBKNxsXDaNGrP63jYHISp3ckbsxvV0SUwD8VNbllVC4/pubhtml';

var tabletop = Tabletop.init({
  key: "https://docs.google.com/spreadsheets/d/1ZBKNxsXDaNGrP63jYHISp3ckbsxvV0SUwD8VNbllVC4/pubhtml",
  callback: sheetLoad,
  simpleSheet: false
})

function sheetLoad( data, tabletop ){
  render( data )
  console.log( data )
  console.log('something')
}

function render( context ){
  var template = $("#guilds-template").html()
  var compile = Handlebars.compile( template )
  var html = compile( { guild: context } )
  $(".guild-profiles").html( html ).show()
}

// render(tabletop.data().Details.all());

// $(document).ready( function() {
//   Tabletop.init( { key: public_spreadsheet_url,
//                    callback: showInfo,
//                    debug: true
//                    } );
// });
//
// function showInfo(data, tabletop) {
//   console.log('ANyTHING!');
//   var source   = $("#guilds-template").html();
//   var template = Handlebars.compile(source);
//
//   $.each( tabletop.sheets("Details").all(), function(i, guild) {
//     var html = template(guild);
//     $(".guild-profiles").append(html);
//   });
// }
<commit_msg>it works?<commit_after>
var public_spreadsheet_url = 'https://docs.google.com/spreadsheets/d/1ZBKNxsXDaNGrP63jYHISp3ckbsxvV0SUwD8VNbllVC4/pubhtml';

var tabletop = Tabletop.init({
  key: "https://docs.google.com/spreadsheets/d/1ZBKNxsXDaNGrP63jYHISp3ckbsxvV0SUwD8VNbllVC4/pubhtml",
  callback: sheetLoad,
  simpleSheet: false
})

function sheetLoad( data, tabletop ){
  console.log( data )
  console.log(tabletop.data())
  console.log('something')
  render(data.Details.all())
}

function render( context ){
  var template = $("#guilds-template").html()
  var compile = Handlebars.compile( template )
  var html = compile( { guild: context } )
  $(".guild-profiles").html( html ).show()
}

// $(document).ready( function() {
//   Tabletop.init( { key: public_spreadsheet_url,
//                    callback: showInfo,
//                    debug: true
//                    } );
// });
//
// function showInfo(data, tabletop) {
//   console.log('ANyTHING!');
//   var source   = $("#guilds-template").html();
//   var template = Handlebars.compile(source);
//
//   $.each( tabletop.sheets("Details").all(), function(i, guild) {
//     var html = template(guild);
//     $(".guild-profiles").append(html);
//   });
// }
<|endoftext|>


<commit_before>/*
 * Copyright 2016 Joa Ebert
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/** @const @type !Array<!string> */
const selectors = [
  // ---------------------------- // ---------------------------
  // Selector                     // Website / Script
  // ---------------------------- // ---------------------------
  "#cookieChoiceInfo",            // BlogSpot
  "#cookie-banner",               // Random guess
  ".cookie-banner",               // Random guess
  "#cookiebanner",                // Random guess
  ".cookiebanner",                // https://github.com/dobarkod/cookie-banner
  "#cookies-eu-banner",           // https://github.com/Alex-D/Cookies-EU-banner
  "cc_banner-wrapper",            // https://silktide.com/tools/cookie-consent/
  "#cookie-bar",                  // http://www.primebox.co.uk/projects/jquery-cookiebar/
  ".cookie-bar",                  // Random guess
  "#cookiebar",                   // Random guess
  ".cookiebar",                   // Random guess
  "#cookie-law",                  // Random guess
  "#cookielaw",                   // Random guess
  ".cookie-law",                  // Random guess
  ".cookielaw",                   // Random guess
  // ---------------------------- // ---------------------------
];

/** @const @type !string */
const cssClass = "banned-by-cookie-banner";

for(let selector of selectors) {
  /** @const @type ?Element */
  const element = document.querySelector(selector);

  if(typeof Element !== "undefined" && element instanceof Element) {
    /** @const @type ?string */
    const klass = element.getAttribute("class");

    element.setAttribute("class", (klass ? klass + " " : "") + cssClass);

    break;
  }
}
<commit_msg>Block more cookie banners<commit_after>/*
 * Copyright 2016 Joa Ebert
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/** @const @type !Array<!string> */
const selectors = [
  // ---------------------------- // ---------------------------
  // Selector                     // Website / Script
  // ---------------------------- // ---------------------------
  "#cookieChoiceInfo",            // BlogSpot
  "#cookie-banner",               // Random guess
  ".cookie-banner",               // Random guess
  "#cookiebanner",                // Random guess
  ".cookiebanner",                // https://github.com/dobarkod/cookie-banner
  "#cookies-eu-banner",           // https://github.com/Alex-D/Cookies-EU-banner
  "cc_banner-wrapper",            // https://silktide.com/tools/cookie-consent/
  "#cookie-bar",                  // http://www.primebox.co.uk/projects/jquery-cookiebar/
  ".cookie-bar",                  // Random guess
  "#cookiebar",                   // Random guess
  ".cookiebar",                   // Random guess
  "#cookie-law",                  // Random guess
  "#cookielaw",                   // Random guess
  ".cookie-law",                  // Random guess
  ".cookielaw",                   // Random guess
  ".cookies-dialog",              // Unity3D
  "#cookies-dialog",              // Random guess
  ".cookiesdialog",               // Random guess
  "#cookiesdialog",               // Random guess
  ".cookie-dialog",               // Random guess
  "#cookie-dialog",               // Random guess
  ".cookiedialog",                // Random guess
  "#cookiedialog",                // Random guess
  // ---------------------------- // ---------------------------
];

/** @const @type !string */
const cssClass = "banned-by-cookie-banner";

for(let selector of selectors) {
  /** @const @type ?Element */
  const element = document.querySelector(selector);

  if(typeof Element !== "undefined" && element instanceof Element) {
    /** @const @type ?string */
    const klass = element.getAttribute("class");

    element.setAttribute("class", (klass ? klass + " " : "") + cssClass);

    break;
  }
}
<|endoftext|>


<commit_before>$(function(){
	var getSolved = function(username, callback){
		var apiUrl = "http://judge.u-aizu.ac.jp/onlinejudge/webservice/user?id=";
		$.ajax({
			url: apiUrl + username,
			type: 'get',
			dataType: 'xml',
			success: function(xml, status){
				var username_ = $(xml).find("user > id").text();
				var solved_ = $(xml).find("user > status > solved").text();
				callback(username_, solved_, status);
			}
		});
	}

	var users = ["raimei10130", "kagamiz", "orisano", "li_saku", "marin72_com", "shogo1996"];
	var users_ = [];
	var solved_ = [];
	var count = 0;
	var userTemplate = _.template("
<%= name %>	<%= solved %>
");
	_.each(users, function(user){ getSolved(user, function(username, solved){
		count++;
		users_.push({name: username, solved: solved});
	});});

	var waitComplete = function(span, callback){
		if (count == users.length){
			callback();
		}
		else {
			setTimeout(function(){
				waitComplete(span, callback);
			}, span);
		}
	};

	waitComplete(100, function(){
		var ctx = document.getElementById("solved-graph").getContext("2d");
		users_.sort(function(a, b){
				return a.solved - b.solved;
		});
		_.each(users_, function(item){ $("table#watch-table").append(userTemplate(item)); });
		new Chart(ctx).Bar({
			labels: _.map(users_, function(usr){ return (usr.name) }),
			datasets : [{ data : _.map(users_, function(usr){ return (usr.solved)}) }]
		});
	});
});<commit_msg>不要ファイルの削除<commit_after><|endoftext|>


<commit_before>'use strict';

function repo_init(){
    core_repo_init({
      'events': {
        'file-to-uri': {
          'onclick': function(){
              const files = document.getElementById('file').files;
              if(files.length === 0){
                  return;
              }

              core_file({
                'file': files[0],
                'todo': function(event){
                    document.getElementById('uri').value = event.target.result;
                },
              });
          },
        },
        'fill': {
          'onclick': fill,
        },
        'grid-remake': {
          'onclick': function(){
              if(!globalThis.confirm('Remake grid?')){
                  return;
              }

              core_storage_save();
              setup_dimensions();
          },
        },
        'grid-toggle': {
          'onclick': grid_toggle,
        },
        'uri-to-grid': {
          'onclick': function(){
              if(!globalThis.confirm('Set grid to URI?')){
                  return;
              }

              core_storage_save();
              uri_to_grid();
          },
        },
      },
      'globals': {
        'pixelcount': 0,
        'view': false,
      },
      'info': '<textarea id=uri></textarea>
<canvas id=canvas></canvas>
'
        + '<input id=file type=file><input id=file-to-uri type=button value="Convert File to URI">
'
        + '<input id=grid-remake type=button value="Remake Grid"><input id=grid-toggle type=button value="Toggle Borders"><input id=uri-to-grid type=button value="Set Grid to URI">
'
        + '<input id=color type=color value=#ffffff><input id=fill type=button value=Fill>'
        + '   <input id=color-hover readonly>',
      'menu': true,
      'menu-block-events': false,
      'storage': {
        'height': 32,
        'mode': 0,
        'quality': 1,
        'size': 25,
        'type': 'image/png',
        'uri': '',
        'width': 32,
      },
      'storage-menu': '

<input id=height min=1 type=number>Height'
        + '
<select id=mode><option value=1>Color Picking</option><option value=0>Set Pixel Color</option><option value=2>Transparency</option></select>Mode'
        + '
<input id=quality max=1 min=0 step=0.01 type=number>Quality'
        + '
<input id=size min=1 type=number>px Size'
        + '
<input id=type>Type'
        + '
<input id=width min=1 type=number>Width
',
      'title': 'PixelEditor.htm',
    });

    setup_dimensions();
    document.getElementById('edit').style.userSelect = 'none';
}
<commit_msg>removed step due to validation<commit_after>'use strict';

function repo_init(){
    core_repo_init({
      'events': {
        'file-to-uri': {
          'onclick': function(){
              const files = document.getElementById('file').files;
              if(files.length === 0){
                  return;
              }

              core_file({
                'file': files[0],
                'todo': function(event){
                    document.getElementById('uri').value = event.target.result;
                },
              });
          },
        },
        'fill': {
          'onclick': fill,
        },
        'grid-remake': {
          'onclick': function(){
              if(!globalThis.confirm('Remake grid?')){
                  return;
              }

              core_storage_save();
              setup_dimensions();
          },
        },
        'grid-toggle': {
          'onclick': grid_toggle,
        },
        'uri-to-grid': {
          'onclick': function(){
              if(!globalThis.confirm('Set grid to URI?')){
                  return;
              }

              core_storage_save();
              uri_to_grid();
          },
        },
      },
      'globals': {
        'pixelcount': 0,
        'view': false,
      },
      'info': '<textarea id=uri></textarea>
<canvas id=canvas></canvas>
'
        + '<input id=file type=file><input id=file-to-uri type=button value="Convert File to URI">
'
        + '<input id=grid-remake type=button value="Remake Grid"><input id=grid-toggle type=button value="Toggle Borders"><input id=uri-to-grid type=button value="Set Grid to URI">
'
        + '<input id=color type=color value=#ffffff><input id=fill type=button value=Fill>'
        + '   <input id=color-hover readonly>',
      'menu': true,
      'menu-block-events': false,
      'storage': {
        'height': 32,
        'mode': 0,
        'quality': 1,
        'size': 25,
        'type': 'image/png',
        'uri': '',
        'width': 32,
      },
      'storage-menu': '

<input id=height min=1 type=number>Height'
        + '
<select id=mode><option value=1>Color Picking</option><option value=0>Set Pixel Color</option><option value=2>Transparency</option></select>Mode'
        + '
<input id=quality max=1 min=0 type=number>Quality'
        + '
<input id=size min=1 type=number>px Size'
        + '
<input id=type>Type'
        + '
<input id=width min=1 type=number>Width
',
      'title': 'PixelEditor.htm',
    });

    setup_dimensions();
    document.getElementById('edit').style.userSelect = 'none';
}
<|endoftext|>


<commit_before>var validateCommandOptions = require('./validateCommandOptions'),
    shellQuote = require('shell-quote'),
    optimist = require('optimist'),
    extend = require('extend'),
    shellHelpers = require('./shellHelpers');

module.exports = exports = function (cmdStr, context, options) {
    var shell = this;

    // Initialize shell helper methods.
    if (context) shellHelpers.updateContext(context);

    var prompt = shell.getVar('prompt');

    // If no command string was supplied then write an error message.
    if (!cmdStr || /^\s*$/.test(cmdStr))
        return shell.error('You must supply a value.');

    // Parse the command string into an argument array and set the command name to the first item.
    var args = cmdStr,
        cmdName = cmdStr;
    if (cmdStr.length > 0) {
        args = shellQuote.parse(cmdStr);
        cmdName = args[0];
    }

    if (cmdStr.toLowerCase() !== 'cancel') {
        // If a prompt context exists then override command and options with those stored in the context...
        if (prompt) {
            cmdName = prompt.cmd;
            options = prompt.options;
            options[prompt.option] = cmdStr;
            shell.clearPrompt();
        }
        // ...otherwise remove the command name from the args array and build our options object.
        else {
            args.splice(0, 1);
            options = extend({}, optimist(args).argv, options);
        }

        // Get reference to the command module by name.
        var cmd = shell.cmds[cmdName.toLowerCase()];
        // If the command module exists then process it's options and invoke the module.
        if (cmd && cmd.access(shell, cmdName)) {
            if (options.hasOwnProperty('?') || options.hasOwnProperty('help'))
                shell.execute('help', context, { command: cmdName });
            else if (validateCommandOptions(options, cmd, shell))
                cmd.invoke(shell, options);
        }
        else
            shell.error('"' + cmdName + '" is not a valid command');
    }
    else {
        // If prompt exists then cancel it...
        if (prompt){
            shell.warn('prompt canceled');
            shell.clearPrompt();
        }
        // ...otherwise inform user there is no active prompt.
        else
            shell.error('there are no active prompts');

    }

    return shell;
};<commit_msg>Fixed case sensitive cmd name.<commit_after>var validateCommandOptions = require('./validateCommandOptions'),
    shellQuote = require('shell-quote'),
    optimist = require('optimist'),
    extend = require('extend'),
    shellHelpers = require('./shellHelpers');

module.exports = exports = function (cmdStr, context, options) {
    var shell = this;

    // Initialize shell helper methods.
    if (context) shellHelpers.updateContext(context);

    var prompt = shell.getVar('prompt');

    // If no command string was supplied then write an error message.
    if (!cmdStr || /^\s*$/.test(cmdStr))
        return shell.error('You must supply a value.');

    // Parse the command string into an argument array and set the command name to the first item.
    var args = cmdStr,
        cmdName = cmdStr;
    if (cmdStr.length > 0) {
        args = shellQuote.parse(cmdStr);
        cmdName = args[0];
    }

    if (cmdStr.toLowerCase() !== 'cancel') {
        // If a prompt context exists then override command and options with those stored in the context...
        if (prompt) {
            cmdName = prompt.cmd;
            options = prompt.options;
            options[prompt.option] = cmdStr;
            shell.clearPrompt();
        }
        // ...otherwise remove the command name from the args array and build our options object.
        else {
            args.splice(0, 1);
            options = extend({}, optimist(args).argv, options);
        }

        // Get reference to the command module by name.
        var cmd = shell.cmds[cmdName.toLowerCase()];
        // If the command module exists then process it's options and invoke the module.
        if (cmd && cmd.access(shell, cmdName.toLowerCase())) {
            if (options.hasOwnProperty('?') || options.hasOwnProperty('help'))
                shell.execute('help', context, { command: cmdName });
            else if (validateCommandOptions(options, cmd, shell))
                cmd.invoke(shell, options);
        }
        else
            shell.error('"' + cmdName + '" is not a valid command');
    }
    else {
        // If prompt exists then cancel it...
        if (prompt){
            shell.warn('prompt canceled');
            shell.clearPrompt();
        }
        // ...otherwise inform user there is no active prompt.
        else
            shell.error('there are no active prompts');

    }

    return shell;
};<|endoftext|>


<commit_before>/* jshint browser: true, devel: true, indent: 2, curly: true, eqeqeq: true, futurehostile: true, latedef: true, undef: true, unused: true */
/* global $, jQuery, document, Site, Modernizr */

Site = {
  mobileThreshold: 601,
  init: function() {
    var _this = this;

    $(window).resize(function(){
      _this.onResize();
    });

    $(document).ready(function () {

      _this.Layout.init();

      if ($('body').hasClass('post-type-archive-collection')) {
        _this.Collection.Archive.init();
      }
      if ($('body').hasClass('home')) {
        _this.Home.init();
      }

    });

  },

  onResize: function() {
    var _this = this;

    _this.Layout.windowWidth = $(window).width();
    _this.Layout.windowHeight = $(window).height();

    if ($('body').hasClass('single-collection')) {
      _this.Layout.convertScroll();
    }

    if ($('body').hasClass('home')) {
      _this.Home.sizeHomeElements();
    }
  },

  fixWidows: function() {
    // utility class mainly for use on headines to avoid widows [single words on a new line]
    $('.js-fix-widows').each(function(){
      var string = $(this).html();
      string = string.replace(/ ([^ ]*)$/,' $1');
      $(this).html(string);
    });
  },
};

Site.Collection = {

  Archive: {
    randPos: 0,
    randFlip: 0,
    init: function() {
      _this = this;

      _this.bindItemHover();
    },

    bindItemHover: function() {
      _this = this;

      $('.archive-collection-link').hover( function() {
        _this.randPos = Math.round(Math.random() * 3);
        _this.randFlip = Math.round(Math.random() * 3);

        $(this).parent().siblings('.archive-collection-image-holder').addClass('visible pos-' + _this.randPos + ' flip-' + _this.randFlip);
      }, function() {
        $(this).parent().siblings('.archive-collection-image-holder').removeClass('visible pos-' + _this.randPos + ' flip-' + _this.randFlip);
      });
    }
  },
};

Site.Home = {
  init: function() {
    var _this = this;

    _this.sizeHomeElements();
    _this.bindHomeBgImages();
    Site.Layout.toggleOverlay();
  },

  sizeHomeElements: function() {
    var _this = this,
      videoWidth = $('.home-video').width(),
      videoHeight = ( videoWidth / videoAspect['width'] ) * videoAspect['height'];

    var videoTop = (Site.Layout.windowHeight - videoHeight) / 2,
      videoLeft = (Site.Layout.windowWidth - videoWidth) / 2;

    $('.home-video').css({
      'height': videoHeight,
      'top': videoTop,
      'left': videoLeft,
    });

    if ($('#home-video-player').length) {
      $('#home-video-player').css({
        'width': videoWidth,
        'height': videoHeight + 300,
        'top': '-150px'
      });
    }

    if ($('.home-image').length) {
      $('.home-image-top, .home-image-bottom').css({
        'height': videoTop,
        'width': Site.Layout.windowWidth - videoLeft,
      });

      $('.home-image-left, .home-image-right').css({
        'height': Site.Layout.windowHeight - videoTop,
        'width': videoLeft,
      });
    }
  },

  bindHomeBgImages: function() {
    if (window.DeviceOrientationEvent) {
       window.addEventListener('deviceorientation', function(event) {
        var mouseX = ( ( ( event.beta / 180 ) * 100 ) + 100 ) / 2,
          mouseY = ( ( ( event.gamma / 90 ) * 100 ) + 100 ) / 2;

        $('.home-image-bg-left').css({
          'transform': 'translateX(' + ( - mouseY / 2) + '%)',
        });

        $('.home-image-bg-right').css({
          'transform': 'translateX(' + ( mouseY / 2) + '%)',
        });

        $('.home-image-bg-top').css({
          'transform': 'translateY(' + ( - mouseX / 2) + '%)',
        });

        $('.home-image-bg-bottom').css({
          'transform': 'translateY(' + ( mouseX / 2) + '%)',
        });
      });
    }

    $(document).bind('mousemove', function(e){
        var mouseX = ( e.pageX / Site.Layout.windowWidth ) * 100,
          mouseY = ( e.pageY / Site.Layout.windowHeight ) * 100;

        $('.home-image-bg-left').css({
          'transform': 'translateX(' + ( - mouseY / 2) + '%)',
        });

        $('.home-image-bg-right').css({
          'transform': 'translateX(' + ( mouseY / 2) + '%)',
        });

        $('.home-image-bg-top').css({
          'transform': 'translateY(' + ( - mouseX / 2) + '%)',
        });

        $('.home-image-bg-bottom').css({
          'transform': 'translateY(' + ( mouseX / 2) + '%)',
        });
    });
  }
};

Site.Layout = {
  windowWidth: $(window).width(),
  windowHeight: $(window).height(),
  init: function() {
    var _this = this;

    if ($('body').hasClass('single-collection')) {
      _this.convertScroll();
    }
  },

  convertScroll: function() {
    if ($('body').css('overflow-x') == 'scroll') {
      scrollConverter.activate();
    } else {
      scrollConverter.deactivate();
    }
  },

  toggleOverlay: function() {
    if ($('.site-overlay').length) {
      $('.site-overlay').toggleClass('hide');
    }
  }
};

Site.init();
<commit_msg>add temporary disable device orientation<commit_after>/* jshint browser: true, devel: true, indent: 2, curly: true, eqeqeq: true, futurehostile: true, latedef: true, undef: true, unused: true */
/* global $, jQuery, document, Site, Modernizr */

Site = {
  mobileThreshold: 601,
  init: function() {
    var _this = this;

    $(window).resize(function(){
      _this.onResize();
    });

    $(document).ready(function () {

      _this.Layout.init();

      if ($('body').hasClass('post-type-archive-collection')) {
        _this.Collection.Archive.init();
      }
      if ($('body').hasClass('home')) {
        _this.Home.init();
      }

    });

  },

  onResize: function() {
    var _this = this;

    _this.Layout.windowWidth = $(window).width();
    _this.Layout.windowHeight = $(window).height();

    if ($('body').hasClass('single-collection')) {
      _this.Layout.convertScroll();
    }

    if ($('body').hasClass('home')) {
      _this.Home.sizeHomeElements();
    }
  },

  fixWidows: function() {
    // utility class mainly for use on headines to avoid widows [single words on a new line]
    $('.js-fix-widows').each(function(){
      var string = $(this).html();
      string = string.replace(/ ([^ ]*)$/,' $1');
      $(this).html(string);
    });
  },
};

Site.Collection = {

  Archive: {
    randPos: 0,
    randFlip: 0,
    init: function() {
      _this = this;

      _this.bindItemHover();
    },

    bindItemHover: function() {
      _this = this;

      $('.archive-collection-link').hover( function() {
        _this.randPos = Math.round(Math.random() * 3);
        _this.randFlip = Math.round(Math.random() * 3);

        $(this).parent().siblings('.archive-collection-image-holder').addClass('visible pos-' + _this.randPos + ' flip-' + _this.randFlip);
      }, function() {
        $(this).parent().siblings('.archive-collection-image-holder').removeClass('visible pos-' + _this.randPos + ' flip-' + _this.randFlip);
      });
    }
  },
};

Site.Home = {
  init: function() {
    var _this = this;

    _this.sizeHomeElements();
    _this.bindHomeBgImages();
    Site.Layout.toggleOverlay();
  },

  sizeHomeElements: function() {
    var _this = this,
      videoWidth = $('.home-video').width(),
      videoHeight = ( videoWidth / videoAspect['width'] ) * videoAspect['height'];

    var videoTop = (Site.Layout.windowHeight - videoHeight) / 2,
      videoLeft = (Site.Layout.windowWidth - videoWidth) / 2;

    $('.home-video').css({
      'height': videoHeight,
      'top': videoTop,
      'left': videoLeft,
    });

    if ($('#home-video-player').length) {
      $('#home-video-player').css({
        'width': videoWidth,
        'height': videoHeight + 300,
        'top': '-150px'
      });
    }

    if ($('.home-image').length) {
      $('.home-image-top, .home-image-bottom').css({
        'height': videoTop,
        'width': Site.Layout.windowWidth - videoLeft,
      });

      $('.home-image-left, .home-image-right').css({
        'height': Site.Layout.windowHeight - videoTop,
        'width': videoLeft,
      });
    }
  },

  bindHomeBgImages: function() {
    /*
    if (window.DeviceOrientationEvent) {
       window.addEventListener('deviceorientation', function(event) {
        var mouseX = ( ( ( event.beta / 180 ) * 100 ) + 100 ) / 2,
          mouseY = ( ( ( event.gamma / 90 ) * 100 ) + 100 ) / 2;

        $('.home-image-bg-left').css({
          'transform': 'translateX(' + ( - mouseY / 2) + '%)',
        });

        $('.home-image-bg-right').css({
          'transform': 'translateX(' + ( mouseY / 2) + '%)',
        });

        $('.home-image-bg-top').css({
          'transform': 'translateY(' + ( - mouseX / 2) + '%)',
        });

        $('.home-image-bg-bottom').css({
          'transform': 'translateY(' + ( mouseX / 2) + '%)',
        });
      });
    }
    */

    $(document).bind('mousemove', function(e){
        var mouseX = ( e.pageX / Site.Layout.windowWidth ) * 100,
          mouseY = ( e.pageY / Site.Layout.windowHeight ) * 100;

        $('.home-image-bg-left').css({
          'transform': 'translateX(' + ( - mouseY / 2) + '%)',
        });

        $('.home-image-bg-right').css({
          'transform': 'translateX(' + ( mouseY / 2) + '%)',
        });

        $('.home-image-bg-top').css({
          'transform': 'translateY(' + ( - mouseX / 2) + '%)',
        });

        $('.home-image-bg-bottom').css({
          'transform': 'translateY(' + ( mouseX / 2) + '%)',
        });
    });
  }
};

Site.Layout = {
  windowWidth: $(window).width(),
  windowHeight: $(window).height(),
  init: function() {
    var _this = this;

    if ($('body').hasClass('single-collection')) {
      _this.convertScroll();
    }
  },

  convertScroll: function() {
    if ($('body').css('overflow-x') == 'scroll') {
      scrollConverter.activate();
    } else {
      scrollConverter.deactivate();
    }
  },

  toggleOverlay: function() {
    if ($('.site-overlay').length) {
      $('.site-overlay').toggleClass('hide');
    }
  }
};

Site.init();
<|endoftext|>