<commit_before>var currentMode;

(function(){
	var t = $.now();
	if(window.console == null) window.console = {"log" : $.noop};
	var isDev = window.location.host == "localhost";

	var deferred_load = $.get("searchbar.html");

	$.ajaxSetup({
		dataType: "json",
		traditional: true
	});

	$.ajaxPrefilter('json', function(options, orig, jqXHR) {
	    if (options.crossDomain && !$.support.cors) return 'jsonp';
	});

	var deferred_sm = $.Deferred(function( dfd ){
		$.sm("korp_statemachine.xml", dfd.resolve);
	}).promise();

	var deferred_domReady = $.Deferred(function( dfd ){
		$(dfd.resolve);
	}).promise();

	var deferred_mode = $.Deferred();
	if($.deparam.querystring().mode != null && $.deparam.querystring().mode != "default") {
		deferred_mode = $.getScript($.format("modes/%s_mode.js", $.deparam.querystring().mode));
	} else {
		deferred_mode.resolve();
	}

    var chained = deferred_mode.pipe(function() {
        return $.ajax({
			url : settings.cgi_script,
			data : {
				command : "info",
				corpus : $.map($.keys(settings.corpora), function(item) {
					return item.toUpperCase();
				}).join()
			}
		});
    });

	chained.done(function( info_data ) {
		$.each(settings.corpora, function(key){
			settings.corpora[key]["info"] = info_data["corpora"][key.toUpperCase()]["info"];
		});
	});

	$.when(deferred_load, chained, deferred_domReady, deferred_sm, deferred_mode).then(function(searchbar_html) {
		$.revision = parseInt("$Rev$".split(" ")[1]);
		$.log("preloading done, t = ", $.now() - t);
		currentMode = $.deparam.querystring().mode || "default";
		util.browserWarn();

		$("#mode_switch").radioList({
            change : function() {
            	$.log("changed", this);
            	var mode = $(this).data("mode");
    			$.bbq.removeState("corpus");
    			if(mode == "default") {
    				location.search = "";
    			} else {
    				location.search = "?mode=" + mode;
    			}
            },
            selected : $($.format("a[data-mode=%s]", currentMode)).index()
		}).add("#about").vAlign();

		$("#searchbar").html(searchbar_html[0]);

		$("#search_history").change(function(event) {
			$.log("select", $(this).find(":selected"));
			location.href = $(this).find(":selected").val();
		});

		loadCorpora();

		$.sm.start();
		var tab_a_selector = 'ul.ui-tabs-nav a';

		$("#search-tab").tabs({
			event : "change",
			show : function(event, ui) {
				if($("#columns").position().top > 0)
					$("#sidebar").sidebar("updatePlacement"); //place sidebar
				var selected = $(ui.panel).attr("id").split("-")[1];
				$.sm.send("searchtab." + selected);
			}
		});
		$("#result-container").korptabs({
			event : "change",
			show : function(event, ui) {
				if($(ui.tab).parent().is(".custom_tab")) {
					$.sm.send("resultstab.custom");
				} else {
					var currentId = $(ui.panel).attr("id");
//					//				if(currentId == null) return;
					var selected = currentId.split("-")[1];
//					if($("#sidebar").is(":hidden"))
//						$("#rightStatsTable").css({"width": $("#content").innerWidth() - ($("#leftStatsTable").width() + 50)});
//					else {
//						$("#rightStatsTable").css("width", $("#content").innerWidth() - ($("#leftStatsTable").width() +500));
//						$("#rightStatsTable").animate({"width": $("#content").innerWidth() - ($("#leftStatsTable").width() + 50)});
//					}
					$.sm.send("resultstab." + selected);
				}
			},
			panelTemplate : "
" + kwicResults.initHTML + "
",
			tabTemplate : '
#{label}
'
		});

		$("#result-container li.ui-state-disabled").live({
			mouseover : function() {
				nTimeout = setTimeout(function() {
					$("#lemgram_select").highlight();
				}, 750);

			},
			mouseout : function() {
				if(nTimeout)
					clearTimeout(nTimeout);
				$("#lemgram_select").highlight("abort");
			}
		});

		var tabs = $(".ui-tabs");
		tabs.find(tab_a_selector).click(function() {
			if($(this).parent().is(".ui-state-disabled")) return;
			var state = {},
			id = $(this).closest( '.ui-tabs' ).attr( 'id' ),
			// Get the index of this tab.
			idx = $(this).parent().prevAll().length;

			// Set the state!
			state[ id ] = idx;
			$.bbq.pushState( state );
			return false;
		});

		$(".custom_anchor").live("mouseup", function() {
			$.log("custom click");
			$.bbq.removeState("result-container");
			$(this).triggerHandler( 'change' );
		});

		function onHashChange(event, isInit) {
			var prevFragment = $.bbq.prevFragment || {};
			var e = $.bbq;
			function hasChanged(key) {
				return prevFragment[key] != e.getState(key);
			}

			var hpp = e.getState("hpp", true);
			if(hpp)
				kwicResults.$result.find(".num_hits").val(hpp);
			if(!isInit && hasChanged("hpp")) {
				kwicResults.handlePaginationClick(0, null, true);
			}

			var page = e.getState("page", true);
			if(hasChanged("page") && !hasChanged("search")) {
				kwicResults.setPage(page);
			}

			var sort = e.getState("sort");
			if(isInit && sort) {
				kwicResults.$result.find(".sort_select").val(sort);
			}
			if(!isInit && hasChanged("sort")) {
				kwicResults.handlePaginationClick(0, null, true);
			}

			if(isInit) {
				kwicResults.current_page = page;
			}

			var corpus = e.getState("corpus");
			if (corpus && corpus.length != 0 && corpus != prevFragment["corpus"]){
				var corp_array = corpus.split(',');
				corpusChooserInstance.corpusChooser("selectItems",corp_array);
				$("#select_corpus").val(corpus);
				simpleSearch.enableSubmit();
			}

			function showAbout() {
				$("#about_content").dialog({
					beforeClose : function() {
						$.bbq.removeState("display");
						return false;
					}
				}).css("opacity", 0);
				$("#ui-dialog-title-about_content").attr("rel", "localize[about]");
				$("#about_content").fadeTo(400,1);
				$("#about_content").find("a").blur(); // Prevents the focus of the first link in the "dialog"
			}

			if(e.getState("display") == "about") {
				if($("#about_content").is(":empty")) {
					$("#about_content").load("about.html", function() {
						$("#revision").text($.revision);
						showAbout();
					});
				} else {
					showAbout();
				}

			} else  {
				$("#about_content").closest(".ui-dialog").fadeTo(400, 0, function() {
					$("#about_content").dialog("destroy");
				});
			}

			tabs.each(function() {
				var idx = e.getState( this.id, true );
				if(idx === null) return;
				$(this).find( tab_a_selector ).eq( idx ).triggerHandler( 'change' );
			});

			var search = e.getState("search");
			if(search != null && search !== prevFragment["search"]) {
				kwicResults.current_page = page || 0;
				var type = search.split("|")[0];
				var value = search.split("|").slice(1).join("|");

				view.updateSearchHistory(value);

				switch(type) {
				case "word":
					$("#simple_text").val(value);
					simpleSearch.onSimpleChange();
					simpleSearch.setPlaceholder(null, null);
					simpleSearch.makeLemgramSelect();
					$.sm.send("submit.kwic", {value : value, page : page});
					break;
				case "lemgram":
					$.sm.send("submit.lemgram", {value : value, page : page});
					break;
				case "saldo":
					extendedSearch.setOneToken("saldo", value);
					$.sm.send("submit.kwic", {value : value, page : page});
					break;
				case "cqp":
					advancedSearch.setCQP(value);
					$.sm.send("submit.kwic", {value : value, page : page});
					break;
				}
			}

			$.bbq.prevFragment = $.deparam.fragment();
		}
		$(window).bind( 'hashchange', onHashChange);

		$.log("window scroll init");
		$(window).scroll(function() {
			$("#sidebar").sidebar("updatePlacement");
		});

		//setup about link
		$("#about").click(function() {
			if($.bbq.getState("display") == null) {
				$.bbq.pushState({display : "about"});
			} else {
				$.bbq.removeState("display");
			}
		});

		$("#languages").radioList({
			change : function() {
				util.localize();
			}
		}).vAlign();

		$("#sidebar").sidebar().sidebar("hide");

		$("#simple_text")[0].focus();

		$(document).click(function() {
			$("#simple_text").autocomplete("close");
		});

		util.localize();
		onHashChange(null, true);
		$("body").fadeTo(400, 1, function() {
			$(this).css("opacity", "");
		});
		view.updateSearchHistory();
	});

})();

<commit_msg>added log.<commit_after>var currentMode;

(function(){
	var t = $.now();
	if(window.console == null) window.console = {"log" : $.noop};
	var isDev = window.location.host == "localhost";

	var deferred_load = $.get("searchbar.html");

	$.ajaxSetup({
		dataType: "json",
		traditional: true
	});

	$.ajaxPrefilter('json', function(options, orig, jqXHR) {
	    if (options.crossDomain && !$.support.cors) return 'jsonp';
	});

	var deferred_sm = $.Deferred(function( dfd ){
		$.sm("korp_statemachine.xml", dfd.resolve);
	}).promise();

	var deferred_domReady = $.Deferred(function( dfd ){
		$(dfd.resolve);
	}).promise();

	var deferred_mode = $.Deferred();
	if($.deparam.querystring().mode != null && $.deparam.querystring().mode != "default") {
		deferred_mode = $.getScript($.format("modes/%s_mode.js", $.deparam.querystring().mode));
	} else {
		deferred_mode.resolve();
	}

    var chained = deferred_mode.pipe(function() {
        return $.ajax({
			url : settings.cgi_script,
			data : {
				command : "info",
				corpus : $.map($.keys(settings.corpora), function(item) {
					return item.toUpperCase();
				}).join(),
				log : 1
			}
		});
    });

	chained.done(function( info_data ) {
		$.each(settings.corpora, function(key){
			settings.corpora[key]["info"] = info_data["corpora"][key.toUpperCase()]["info"];
		});
	});

	$.when(deferred_load, chained, deferred_domReady, deferred_sm, deferred_mode).then(function(searchbar_html) {
		$.revision = parseInt("$Rev$".split(" ")[1]);
		$.log("preloading done, t = ", $.now() - t);
		currentMode = $.deparam.querystring().mode || "default";
		util.browserWarn();

		$("#mode_switch").radioList({
            change : function() {
            	$.log("changed", this);
            	var mode = $(this).data("mode");
    			$.bbq.removeState("corpus");
    			if(mode == "default") {
    				location.search = "";
    			} else {
    				location.search = "?mode=" + mode;
    			}
            },
            selected : $($.format("a[data-mode=%s]", currentMode)).index()
		}).add("#about").vAlign();

		$("#searchbar").html(searchbar_html[0]);

		$("#search_history").change(function(event) {
			$.log("select", $(this).find(":selected"));
			location.href = $(this).find(":selected").val();
		});

		loadCorpora();

		$.sm.start();
		var tab_a_selector = 'ul.ui-tabs-nav a';

		$("#search-tab").tabs({
			event : "change",
			show : function(event, ui) {
				if($("#columns").position().top > 0)
					$("#sidebar").sidebar("updatePlacement"); //place sidebar
				var selected = $(ui.panel).attr("id").split("-")[1];
				$.sm.send("searchtab." + selected);
			}
		});
		$("#result-container").korptabs({
			event : "change",
			show : function(event, ui) {
				if($(ui.tab).parent().is(".custom_tab")) {
					$.sm.send("resultstab.custom");
				} else {
					var currentId = $(ui.panel).attr("id");
//					//				if(currentId == null) return;
					var selected = currentId.split("-")[1];
//					if($("#sidebar").is(":hidden"))
//						$("#rightStatsTable").css({"width": $("#content").innerWidth() - ($("#leftStatsTable").width() + 50)});
//					else {
//						$("#rightStatsTable").css("width", $("#content").innerWidth() - ($("#leftStatsTable").width() +500));
//						$("#rightStatsTable").animate({"width": $("#content").innerWidth() - ($("#leftStatsTable").width() + 50)});
//					}
					$.sm.send("resultstab." + selected);
				}
			},
			panelTemplate : "
" + kwicResults.initHTML + "
",
			tabTemplate : '
#{label}
'
		});

		$("#result-container li.ui-state-disabled").live({
			mouseover : function() {
				nTimeout = setTimeout(function() {
					$("#lemgram_select").highlight();
				}, 750);

			},
			mouseout : function() {
				if(nTimeout)
					clearTimeout(nTimeout);
				$("#lemgram_select").highlight("abort");
			}
		});

		var tabs = $(".ui-tabs");
		tabs.find(tab_a_selector).click(function() {
			if($(this).parent().is(".ui-state-disabled")) return;
			var state = {},
			id = $(this).closest( '.ui-tabs' ).attr( 'id' ),
			// Get the index of this tab.
			idx = $(this).parent().prevAll().length;

			// Set the state!
			state[ id ] = idx;
			$.bbq.pushState( state );
			return false;
		});

		$(".custom_anchor").live("mouseup", function() {
			$.log("custom click");
			$.bbq.removeState("result-container");
			$(this).triggerHandler( 'change' );
		});

		function onHashChange(event, isInit) {
			var prevFragment = $.bbq.prevFragment || {};
			var e = $.bbq;
			function hasChanged(key) {
				return prevFragment[key] != e.getState(key);
			}

			var hpp = e.getState("hpp", true);
			if(hpp)
				kwicResults.$result.find(".num_hits").val(hpp);
			if(!isInit && hasChanged("hpp")) {
				kwicResults.handlePaginationClick(0, null, true);
			}

			var page = e.getState("page", true);
			if(hasChanged("page") && !hasChanged("search")) {
				kwicResults.setPage(page);
			}

			var sort = e.getState("sort");
			if(isInit && sort) {
				kwicResults.$result.find(".sort_select").val(sort);
			}
			if(!isInit && hasChanged("sort")) {
				kwicResults.handlePaginationClick(0, null, true);
			}

			if(isInit) {
				kwicResults.current_page = page;
			}

			var corpus = e.getState("corpus");
			if (corpus && corpus.length != 0 && corpus != prevFragment["corpus"]){
				var corp_array = corpus.split(',');
				corpusChooserInstance.corpusChooser("selectItems",corp_array);
				$("#select_corpus").val(corpus);
				simpleSearch.enableSubmit();
			}

			function showAbout() {
				$("#about_content").dialog({
					beforeClose : function() {
						$.bbq.removeState("display");
						return false;
					}
				}).css("opacity", 0);
				$("#ui-dialog-title-about_content").attr("rel", "localize[about]");
				$("#about_content").fadeTo(400,1);
				$("#about_content").find("a").blur(); // Prevents the focus of the first link in the "dialog"
			}

			if(e.getState("display") == "about") {
				if($("#about_content").is(":empty")) {
					$("#about_content").load("about.html", function() {
						$("#revision").text($.revision);
						showAbout();
					});
				} else {
					showAbout();
				}

			} else  {
				$("#about_content").closest(".ui-dialog").fadeTo(400, 0, function() {
					$("#about_content").dialog("destroy");
				});
			}

			tabs.each(function() {
				var idx = e.getState( this.id, true );
				if(idx === null) return;
				$(this).find( tab_a_selector ).eq( idx ).triggerHandler( 'change' );
			});

			var search = e.getState("search");
			if(search != null && search !== prevFragment["search"]) {
				kwicResults.current_page = page || 0;
				var type = search.split("|")[0];
				var value = search.split("|").slice(1).join("|");

				view.updateSearchHistory(value);

				switch(type) {
				case "word":
					$("#simple_text").val(value);
					simpleSearch.onSimpleChange();
					simpleSearch.setPlaceholder(null, null);
					simpleSearch.makeLemgramSelect();
					$.sm.send("submit.kwic", {value : value, page : page});
					break;
				case "lemgram":
					$.sm.send("submit.lemgram", {value : value, page : page});
					break;
				case "saldo":
					extendedSearch.setOneToken("saldo", value);
					$.sm.send("submit.kwic", {value : value, page : page});
					break;
				case "cqp":
					advancedSearch.setCQP(value);
					$.sm.send("submit.kwic", {value : value, page : page});
					break;
				}
			}

			$.bbq.prevFragment = $.deparam.fragment();
		}
		$(window).bind( 'hashchange', onHashChange);

		$.log("window scroll init");
		$(window).scroll(function() {
			$("#sidebar").sidebar("updatePlacement");
		});

		//setup about link
		$("#about").click(function() {
			if($.bbq.getState("display") == null) {
				$.bbq.pushState({display : "about"});
			} else {
				$.bbq.removeState("display");
			}
		});

		$("#languages").radioList({
			change : function() {
				util.localize();
			}
		}).vAlign();

		$("#sidebar").sidebar().sidebar("hide");

		$("#simple_text")[0].focus();

		$(document).click(function() {
			$("#simple_text").autocomplete("close");
		});

		util.localize();
		onHashChange(null, true);
		$("body").fadeTo(400, 1, function() {
			$(this).css("opacity", "");
		});
		view.updateSearchHistory();
	});

})();

<|endoftext|>


<commit_before><commit_msg>Making things display onmouseover<commit_after><|endoftext|>


<commit_before>/*! Copyright (c) 2011 Tom Ellis (http://www.webmuse.co.uk)
* User Select cssHook for jQuery 1.4.3+
* Licensed under the MIT License (LICENSE.txt).
*/
(function($) {

	//User Select cssHook

	var div = document.createElement( "div" ),
		divStyle = div.style,
		$.support.userSelect =
		div.style.MozUserSelect === "" ? 'MozUserSelect' :
		(div.style.WebkitUserSelect === "" ? 'WebkitUserSelect' :
		(div.style.userSelect === ""  ? 'userSelect' : false));

	if ( $.support.userSelect && $.support.userSelect !== "userSelect" ){
		$.cssHooks.userSelect = {

			get: function( elem, computed, extra ) {
				return $.css(elem, $.support.userSelect);
			},
			set: function( elem, value ) {
				elem.style[ $.support.userSelect ] = value;
			}
		};
	}

	div = null;

})(jQuery); <commit_msg>Adding missing divStyle<commit_after>/*! Copyright (c) 2011 Tom Ellis (http://www.webmuse.co.uk)
* User Select cssHook for jQuery 1.4.3+
* Licensed under the MIT License (LICENSE.txt).
*/
(function($) {

	//User Select cssHook

	var div = document.createElement( "div" ),
		divStyle = div.style,
		$.support.userSelect =
		div.style.MozUserSelect === "" ? 'MozUserSelect' :
		(div.style.WebkitUserSelect === "" ? 'WebkitUserSelect' :
		(div.style.userSelect === ""  ? 'userSelect' : false));

	if ( $.support.userSelect && $.support.userSelect !== "userSelect" ){
		$.cssHooks.userSelect = {

			get: function( elem, computed, extra ) {
				return $.css(elem, $.support.userSelect);
			},
			set: function( elem, value ) {
				elem.style[ $.support.userSelect ] = value;
			}
		};
	}

	div = divStyle = null;

})(jQuery); <|endoftext|>


<commit_before>function main() {
	for (let i = 0; i < timescale; i++) {
		update();
		render();
	}
}

function update() {

}

function render() {
	ctx.clearRect(0, 0, display.width, display.height);

	for (let i in creatures) {
		ctx.fillStyle = creatures[i].color;
		ctx.strokeStyle = "#ffffff";
		ctx.lineWidth = 5;

		ctx.beginPath();
		ctx.arc(creatures[i].x, creatures[i].y, creatures[i].size, 0, 2 * Math.PI);
		ctx.closePath();

		ctx.fill();
		ctx.stroke();
	}
}

setInterval(main, 1000 / 100);<commit_msg>Delete main.js<commit_after><|endoftext|>


<commit_before>var App = function () {}

//  binds the sidebar menu links
App.bindMenuLinks = function(){
	$(".sideBar_link").click(function (e) {
		e.preventDefault();
		link = $(this).attr("href");
		parent_el = $(this).parent()
		is_active = parent_el.hasClass("active")

		if(is_active){
			parent_el.removeClass("active")
			subnav = parent_el.find("ul.subnav")
			subnav.addClass("hidden");
			return
		}

		$(".active_small").removeClass("active_small");
		var selector = $(".container")
		var url = "gender_clothes.html"
		var callback = false

		switch(link){
			case "#catalog":
				subnav = $(link).find("ul.subnav")
				$(".nav.navbar-nav li").removeClass("active")
				subnav.removeClass("hidden");
				$(link).addClass("active")
				url = "gender_clothes.html"
				break;

			case "#about":
				subnav = $(link).find("ul.subnav")
				$(".nav.navbar-nav li").removeClass("active")
				subnav.removeClass("hidden");
				$(link).addClass("active")
				url = "about.html"
				break;

			case "#male":
				selector = $(".container")
				url = "MaleClothes.html"
				callback = false
				break;
			case "#female":
			selector = $(".container")
				url = "FemaleClothes.html"
				callback = false
				break;
			case "#child":
				selector = $(".container")
				url = "ChildClothes.html"
				callback = false
				break;

			default:
				$(".nav.navbar-nav li").removeClass("active")
				$("ul.subnav").addClass("hidden")
				$(link).addClass("active")
				break;
		}
		$(".container").focus();
		App.load(selector , url , callback)
	})
}

// shows the menus
App.showMenu = function(type) {
	$("#sideBar").load("side_bar.html");

	bind_links = function () {
		App.resizeMenu();
		App.bindMenuLinks();
	}

	App.load($("#sideBar") , "side_bar.html" , bind_links)

}

// binds the button for resizing the sidebar menu
App.resizeMenu = function(type) {

	$('#collapse-sidebar').click(function(){
		$('.navbar-side').toggleClass('navbar-side-closed');
	    $('#wrapper').toggleClass('wrapper-full');
    });

}

// loads an HTML in the selector and then runs the callback
App.load = function (selector , url , callback) {
	$.ajax({
		url: url,
		dataType: "html"
	}).done(function(data){
		selector.html(data)
		if(callback){
			callback()
		}
	})
}

// get the data from the needed json
App.getData = function (url ,callback) {
	var json_url = "";
	switch(url){
		case "clothes/men":
			json_url = "data/men.json"
		break;

		case "clothes/women":
			json_url = "data/women.json"
		break;

		case "clothes/dresses":
			json_url = "data/dresses.json"
		break;

		case "clothes/shirts":
			json_url = "data/shirts.json"
		break;

		case "clothes/jeans":
			json_url = "data/jeans.json"
		break;

		case "clothes/tops":
			json_url = "data/tops.json"
		break;
		default:
			alert("FATAL ERROR");

	}
	var result = []
	console.log("start ajax")
	$.ajax({
		url: json_url,
		dataType: "json"
	}).done(callback)

}<commit_msg>"Files<commit_after>var App = function () {}

//  binds the sidebar menu links
App.bindMenuLinks = function(){
	$(".sideBar_link").click(function (e) {
		e.preventDefault();
		link = $(this).attr("href");
		parent_el = $(this).parent()
		is_active = parent_el.hasClass("active")

		if(is_active){
			parent_el.removeClass("active")
			subnav = parent_el.find("ul.subnav")
			subnav.addClass("hidden");
			return
		}

		$(".active_small").removeClass("active_small");
		var selector = $(".container")
		var url = "gender_clothes.html"
		var callback = false

		switch(link){
			case "#catalog":
				subnav = $(link).find("ul.subnav")
				$(".nav.navbar-nav li").removeClass("active")
				subnav.removeClass("hidden");
				$(link).addClass("active")
				url = "gender_clothes.html"
				break;

			case "#about":
				subnav = $(link).find("ul.subnav")
				$(".nav.navbar-nav li").removeClass("active")
				subnav.removeClass("hidden");
				$(link).addClass("active")
				url = "about.html"
				break;

			case "#male":
				selector = $(".container")
				url = "MaleClothes.html"
				callback = false
				break;
			case "#female":
				selector = $(".container")
				url = "FemaleClothes.html"
				callback = false
				break;
			case "#child":
				selector = $(".container")
				url = "ChildClothes.html"
				callback = false
				break;

			default:
				$(".nav.navbar-nav li").removeClass("active")
				$("ul.subnav").addClass("hidden")
				$(link).addClass("active")
				break;
		}
		$(".container").focus();
		App.load(selector , url , callback)
	})
}

// shows the menus
App.showMenu = function(type) {
	$("#sideBar").load("side_bar.html");

	bind_links = function () {
		App.resizeMenu();
		App.bindMenuLinks();
	}

	App.load($("#sideBar") , "side_bar.html" , bind_links)

}

// binds the button for resizing the sidebar menu
App.resizeMenu = function(type) {

	$('#collapse-sidebar').click(function(){
		$('.navbar-side').toggleClass('navbar-side-closed');
	    $('#wrapper').toggleClass('wrapper-full');
    });

}

// loads an HTML in the selector and then runs the callback
App.load = function (selector , url , callback) {
	$.ajax({
		url: url,
		dataType: "html"
	}).done(function(data){
		selector.html(data)
		if(callback){
			callback()
		}
	})
}

// get the data from the needed json
App.getData = function (url ,callback) {
	var json_url = "";
	switch(url){
		case "clothes/men":
			json_url = "data/men.json"
		break;

		case "clothes/women":
			json_url = "data/women.json"
		break;

		case "clothes/dresses":
			json_url = "data/dresses.json"
		break;

		case "clothes/shirts":
			json_url = "data/shirts.json"
		break;

		case "clothes/jeans":
			json_url = "data/jeans.json"
		break;

		case "clothes/tops":
			json_url = "data/tops.json"
		break;
		default:
			alert("FATAL ERROR");

	}
	var result = []
	console.log("start ajax")
	$.ajax({
		url: json_url,
		dataType: "json"
	}).done(callback)

}<|endoftext|>


<commit_before>var stage           = null;
var penguinTextures = [];
var renderer        = null;
var penguin         = null;
var snowStage       = null;
var snowTexture     = null;
var meter           = null;
function init()
{
  var konami      = new Konami();
  konami.code     = surprise;
  konami.load();
  stage           = new PIXI.Stage(0x5bb5ff,true);
	renderer        = PIXI.autoDetectRenderer(800,330);
	document.getElementById("page").appendChild(renderer.view);

  meter =  new FPSMeter(document.getElementById("fps"));

  snowTexture     = new PIXI.Texture.fromImage("images/bg-snow.png");
  snowStage       = new PIXI.Stage(0xFFFFFF);

  addGroundSnow();

  penguin         = new Penguin();

  stage.addChild(snowStage);
  stage.addChild(penguin.stage);
  requestAnimFrame( animate );

  window.onkeydown = function(e){
    if(!penguin.movement.surprise){
      if(e.keyCode == 37){
        //left
        penguin.movement.left  = true;
        penguin.movement.right = false;
      }
      if(e.keyCode == 39){
        //right
        penguin.movement.left  = false;
        penguin.movement.right = true;
      }
    }
    if(e.metaKey==true){
      return true;
    }
    return false;
  };

  window.onkeyup = function(e){
    if(!penguin.movement.surprise){
      if(e.keyCode == 38){
        //up
        penguin.movement.up   = false;
      }
      if(e.keyCode == 40){
        //down
        penguin.movement.down = false;
      }
      if(e.keyCode == 37){
        //left
        penguin.movement.left  = false;
      }
      if(e.keyCode == 39){
        //right
        penguin.movement.right = false;
      }
    }
  };

  renderer.view.onmousedown = function(e){
    e.preventDefault();
    if((e.clientX - this.getBoundingClientRect().left) > penguin.position.x){
      penguin.movement.right = true;
      penguin.movement.left  = false;
    }
    else {
      penguin.movement.right = false;
      penguin.movement.left  = true;
    }
  };
  renderer.view.onmouseup   = function(e){
      penguin.movement.right = false;
      penguin.movement.left  = false;
  };

  var touchstart = function(e){
    e.preventDefault();
    if(e.clientX){
      renderer.view.onmousedown.call(self,e);
    }
    else{
      var i=0;
      var len = e.targetTouches.length;
      var touch;
      var self = this;
      for(;i<len;i++){
        touch = e.targetTouches[i];
        touch.preventDefault = function(){};
        renderer.view.onmousedown.call(self,touch);
      }
    }
  };
  var touchend = function(e){
    e.preventDefault();
    renderer.view.onmouseup.call(this,e);
  };
  renderer.view.addEventListener("touchstart",touchstart,false);
  renderer.view.addEventListener("touchend",touchend,false);
  renderer.view.addEventListener("touchcancel",touchend,false);
}

function animate() {
  meter.tickStart();
  requestAnimFrame( animate );
  renderer.render(stage);
  var movePerFrame = 3;
  var rotatePerFrame = 0.015;
  var rotateMax      = 0.05;
  var center         = renderer.view.width/2;

  if(penguin.movement.surprise){
    penguin.getSurprised();
  }
  if(penguin.movement.left){
    penguin.position.x -= movePerFrame;
    penguin.scale.x = -0.35;
  }
  if(penguin.movement.right){
    penguin.position.x += movePerFrame;
    penguin.scale.x = 0.35;
  }
  if(penguin.movement.left || penguin.movement.right){
    if(penguin.movement.waddleRight ){
      penguin.rotation += rotatePerFrame;
      if(penguin.rotation >= rotateMax){
        penguin.movement.waddleRight = false;
      }
    }
    else{
      penguin.rotation -= rotatePerFrame;
      if(penguin.rotation <= -rotateMax){
        penguin.movement.waddleRight = true;
      }
    }
  }
  meter.tick();
}
function addGroundSnow()
{
  var i=0;
  for(i=0; i< snowStage.children.length; i++){
    snowStage.removeChild(snowStage.children[i]);
  }
  for(i = 0; i < window.innerWidth / 400; i++){
    var snow            = new PIXI.Sprite(snowTexture,{x:0,y:0,width:400,height:100});
    snow.position.x = i * 400;
    snow.position.y = 230;
    snowStage.addChild(snow);
  }
}

function surprise()
{
  penguin.movement.surprise = true;
}

init();
<commit_msg>Var defs changed, spacing updates<commit_after>var stage           = null,
    penguinTextures = [],
    renderer        = null,
    penguin         = null,
    snowStage       = null,
    snowTexture     = null,
    meter           = null,
    showMeter       = false;

function init()
{
  var konami      = new Konami();
  konami.code     = surprise;
  konami.load();
  stage           = new PIXI.Stage(0x5bb5ff,true);
	renderer        = PIXI.autoDetectRenderer(800,330);
	document.getElementById("page").appendChild(renderer.view);

  if(showMeter){
    meter         =  new FPSMeter(document.getElementById("fps"));
  }

  snowTexture     = new PIXI.Texture.fromImage("images/bg-snow.png");
  snowStage       = new PIXI.Stage(0xFFFFFF);

  addGroundSnow();

  penguin         = new Penguin();

  stage.addChild(snowStage);
  stage.addChild(penguin.stage);
  requestAnimFrame( animate );

  window.onkeydown = function(e){
    if(!penguin.movement.surprise){
      if(e.keyCode == 37){
        //left
        penguin.movement.left  = true;
        penguin.movement.right = false;
      }
      if(e.keyCode == 39){
        //right
        penguin.movement.left  = false;
        penguin.movement.right = true;
      }
    }
    if(e.metaKey==true){
      return true;
    }
    return false;
  };

  window.onkeyup = function(e){
    if(!penguin.movement.surprise){
      if(e.keyCode == 38){
        //up
        penguin.movement.up   = false;
      }
      if(e.keyCode == 40){
        //down
        penguin.movement.down = false;
      }
      if(e.keyCode == 37){
        //left
        penguin.movement.left  = false;
      }
      if(e.keyCode == 39){
        //right
        penguin.movement.right = false;
      }
    }
  };

  renderer.view.onmousedown = function(e){
    e.preventDefault();
    if((e.clientX - this.getBoundingClientRect().left) > penguin.position.x){
      penguin.movement.right = true;
      penguin.movement.left  = false;
    }
    else {
      penguin.movement.right = false;
      penguin.movement.left  = true;
    }
  };
  renderer.view.onmouseup   = function(e){
      penguin.movement.right = false;
      penguin.movement.left  = false;
  };

  var touchstart = function(e){
    e.preventDefault();
    if(e.clientX){
      renderer.view.onmousedown.call(self,e);
    }
    else{
      var i=0;
      var len = e.targetTouches.length;
      var touch;
      var self = this;
      for(;i<len;i++){
        touch = e.targetTouches[i];
        touch.preventDefault = function(){};
        renderer.view.onmousedown.call(self,touch);
      }
    }
  };
  var touchend = function(e){
    e.preventDefault();
    renderer.view.onmouseup.call(this,e);
  };
  renderer.view.addEventListener("touchstart",touchstart,false);
  renderer.view.addEventListener("touchend",touchend,false);
  renderer.view.addEventListener("touchcancel",touchend,false);
}

function animate() {
  if(showMeter){ meter.tickStart(); }

  requestAnimFrame( animate );
  renderer.render(stage);
  var movePerFrame   = 3,
      rotatePerFrame = 0.015,
      rotateMax      = 0.05,
      center         = renderer.view.width/2;

  if(penguin.movement.surprise){
    penguin.getSurprised();
  }
  if(penguin.movement.left){
    penguin.position.x -= movePerFrame;
    penguin.scale.x     = -0.35;
  }
  if(penguin.movement.right){
    penguin.position.x += movePerFrame;
    penguin.scale.x     = 0.35;
  }
  if(penguin.movement.left || penguin.movement.right){
    if(penguin.movement.waddleRight ){
      penguin.rotation += rotatePerFrame;
      if(penguin.rotation >= rotateMax){
        penguin.movement.waddleRight = false;
      }
    }
    else{
      penguin.rotation -= rotatePerFrame;
      if(penguin.rotation <= -rotateMax){
        penguin.movement.waddleRight = true;
      }
    }
  }
  if(showMeter){ meter.tick(); }
}
function addGroundSnow()
{
  var i=0;
  for(i=0; i< snowStage.children.length; i++){
    snowStage.removeChild(snowStage.children[i]);
  }
  for(i = 0; i < window.innerWidth / 400; i++){
    var snow        = new PIXI.Sprite(snowTexture,{x:0,y:0,width:400,height:100});
    snow.position.x = i * 400;
    snow.position.y = 230;
    snowStage.addChild(snow);
  }
}

function surprise()
{
  penguin.movement.surprise = true;
}

init();
<|endoftext|>


<commit_before>(function (Q, $) {
/**
 * @module Q-tools
 */

/**
 * Implements lazy-loading for various types of elements.
 * By default, has implementations for "img" and "Q_tool" selectors.
 * The "Q_tool" handler only works with tools whose elements have a "data-q-lazyload" attribute .
 * Note that the elements must have a stable, nonzero width height set in the CSS even
 * if they are empty, otherwise they might not be lazy-loaded, and they might
 * thrash back and forth if removed.
 * @class Q lazyload
 * @constructor
 * @param {Object} [options] Override various options for this tool
 * @param {Array} [options.handle] Set this to
 * @param {Object} [options.handlers] You can modify the defaults by passing an object
 *    that looks like {handlerName: { selector: String, entering: Function, exiting: Function, preparing: Function}}
 *    Function "entering" receives (element, intersectionObserverEntry)
 *    Function "exiting" receives (element, intersectionObserverEntry)
 *    Function "preparing" receives (element) and is used the first time to prepare the element
 *    Both functions must return true if the element was modified.
 * @param {Element} [root=tool.element] The container inside which to watch for intesections
 * @param {Object} [observerOptions] Override any options to pass to IntersectionObserver
 * @param {Element} [observerOptions.root=tool.element.scrollingParent(true)]
 * @param {String} [observerOptions.rootMargin='0px']
 * @param {String} [observerOptions.threshold=0]
 * @return {Q.Tool}
 */
Q.Tool.define('Q/lazyload', function (options) {

	var tool = this;
	var state = this.state;
	state.root = state.root || this.element;

	var Elp = Element.prototype;

	Q.ensure('IntersectionObserver', function () {
		// Observe whatever is on the page already
		var p = tool.element.scrollingParent(true);
		if (p === document.body) {
			p = document.documentElement;
		}
		tool.observer = _createObserver(tool, p);
		tool.observe(tool.prepare(tool.element, false));

		// Override innerHTML

		var originalSet = Object.getOwnPropertyDescriptor(Elp, 'innerHTML').set;
		var originalGet = Object.getOwnPropertyDescriptor(Elp, 'innerHTML').get;

		Object.defineProperty(Elp, 'innerHTML', {
			set: function (html) {
				var element = document.createElement('div');
				var root = state.root || document.documentElement;
				var inside = (root === this) || root.contains(this);
				if (!inside) {
					originalSet.call(this, html);
					return html;
				}
				originalSet.call(element, html);
				var found = false;
				Q.each(state.handlers, function (name, info) {
					var elements = element.querySelectorAll
						? Array.from(element.querySelectorAll(info.selector))
						: [];
					if (elements.length) {
						found = true;
						return false;
					}
				});
				if (found) {
					html = originalGet.call(element);
				}
				originalSet.call(this, html);
				if (found) {
					tool.observe(tool.prepare(this, true));
				}
				return html;
			},
			get: originalGet
		});

		Q.each(['insertBefore', 'appendChild'], function (i, fn) {
			var orig = Elp[fn];
			Elp[fn] = function (element) {
				if (!(element instanceof HTMLElement)) {
					return orig.apply(this, arguments);
				}
				var root = state.root || document.documentElement;
				var inside = (root === this) || root.contains(this);
				if (!inside) {
					return orig.apply(this, arguments);
				}
				var found = false;
				Q.each(state.handlers, function (name, info) {
					if (element.matches && element.matches(info.selector)) {
						found = true;
						return false;
					}
					var elements = element.querySelectorAll
						? Array.from(element.querySelectorAll(info.selector))
						: [];
					if (elements.length) {
						found = true;
						return false;
					}
				});
				if (found) {
					tool.observe(tool.prepare(element, true));
				}
				return orig.apply(this, arguments);
			};
		});
	});

},

{
	handlers: {
		img: {
			selector: 'img',
			entering: function (img, entry) {
				function _loaded() {
					img.addClass('Q_lazy_loaded');
				}
				var src = img.getAttribute('data-lazyload-src');
				if (src) {
					img.setAttribute('src', Q.url(src));
					img.removeAttribute('data-lazyload-src');
					img.addClass('Q_lazy_load');
					if (img.complete) {
						_loaded();
					}
					img.addEventListener('load', _loaded);
				}
				return true;
			},
			exiting: function (img) {
				// no need to do anything
				return true;
			},
			preparing: function (img, beingInsertedIntoDOM) {
				if (!beingInsertedIntoDOM) {
					return true; // too late anyway, browser will load image
				}
				if (img.hasClass('Q_lazy_load') || img.hasClass('Q_lazy_loaded')) {
					return true; // this was already processed by lazy-loading
				}
				var src = img.getAttribute('src');
				if (src && src.substr(0, 5) !== 'data:'
				&& !img.hasAttribute('data-lazyload-src')) {
					img.setAttribute('data-lazyload-src', Q.url(src));
					img.setAttribute('src', Q.url(
						Q.getObject('Q.images.lazyload.loadingSrc')
						|| "{{Q}}/img/throbbers/transparent.gif"
					));
				}
				return true;
			}
		},
		tool: {
			selector: '.Q_tool',
			entering: function (element, entry) {
				if (element.hasAttribute('data-q-lazyload')
				&& (!element.Q || !element.Q.tool)) {
					element.addClass('Q_lazy_load');
					element.setAttribute('data-q-lazyload', 'activating');
					Q.activate(element, function () {
						element.setAttribute('data-q-lazyload', 'activated');
						element.addClass('Q_lazy_loaded');
					}, {}, true);
					return true;
				}
			},
			exiting: function (element, entry) {
				if (element.hasAttribute('data-q-lazyload')
				&& element.Q.tool) {
					Q.Tool.remove(element);
					element.removeClass('Q_lazy_loading');
					element.removeClass('Q_lazy_loaded');
					element.setAttribute('data-q-lazyload', 'removed');
					if (this.state.handlers.tool.exitingRemoveHTML) {
						element.innerHTML = '';
					}
				}
				return true;
			},
			preparing: function (element) {
				return true;
			},
			exitingRemoveHTML: true
		}
	},
	root: undefined,
	observerOptions: {
		root: undefined,
		rootMargin: '0px',
		threshold: 0
	}
},

{
	prepare: function (container, beingInsertedIntoDOM) {
		var tool = this;
		var found = [];
		Q.each(tool.state.handlers, function (name, info) {
			var elements = container.querySelectorAll
				? Array.from(container.querySelectorAll(info.selector))
				: [];
			if (container.matches && container.matches(info.selector)) {
				elements.push(container);
			}
			Q.each(elements, function (i, element) {
				if (info.preparing.call(tool, element, beingInsertedIntoDOM) === true) {
					found.push(element);
				}
			});
		});
		return found;
	},
	observe: function (elements) {
		var tool = this;
		tool.observer && Q.each(elements, function (i, element) {
			tool.observer.observe(element);
		});
	},
	unobserve: function (elements) {
		var tool = this;
		tool.observer && Q.each(elements, function (i, element) {
			tool.observer.unobserve(element);
		});
	},
	Q: {
		beforeRemove: function () {
			this.observer && this.observer.disconnect();
		}
	}
});

function _createObserver(tool, container) {
	var o = Q.copy(tool.state.observerOptions);
	if (o.root === undefined) {
		o.root = (container === document.documentElement) ? null : (container || null);
	}
	return new IntersectionObserver(function (entries, observer) {
		Q.each(entries, function (i, entry) {
			Q.each(tool.state.handlers, function (name, info) {
				if (entry.target.matches && entry.target.matches(info.selector)) {
					if (entry.isIntersecting) {
						info.entering.call(tool, entry.target, entry);
					} else  {
						var rect = entry.target.getBoundingClientRect();
						if (rect.width > 0 && rect.height > 0) {
							// also covers !document.body.contains(entry.target)
							info.exiting.call(tool, entry.target, entry);
						} // otherwise it might get a false positive
					}
				}
			});
		});
	}, o);
}

})(Q, jQuery);<commit_msg>Added debounce to lazyload<commit_after>(function (Q, $) {
/**
 * @module Q-tools
 */

/**
 * Implements lazy-loading for various types of elements.
 * By default, has implementations for "img" and "Q_tool" selectors.
 * The "Q_tool" handler only works with tools whose elements have a "data-q-lazyload" attribute .
 * Note that the elements must have a stable, nonzero width height set in the CSS even
 * if they are empty, otherwise they might not be lazy-loaded, and they might
 * thrash back and forth if removed.
 * @class Q lazyload
 * @constructor
 * @param {Object} [options] Override various options for this tool
 * @param {Array} [options.handle] Set this to
 * @param {Object} [options.handlers] You can modify the defaults by passing an object
 *    that looks like {handlerName: { selector: String, entering: Function, exiting: Function, preparing: Function}}
 *    Function "entering" receives (element, intersectionObserverEntry)
 *    Function "exiting" receives (element, intersectionObserverEntry)
 *    Function "preparing" receives (element) and is used the first time to prepare the element
 *    Both functions must return true if the element was modified.
 * @param {Element} [root=tool.element] The container inside which to watch for intesections
 * @param {Object} [debounce]
 * @param {Number} [debounce.milliseconds] How many milliseconds to wait before starting the lazyload, to avoid loading during fast scrolling
 * @param {Object} [observerOptions] Override any options to pass to IntersectionObserver
 * @param {Element} [observerOptions.root=tool.element.scrollingParent(true)]
 * @param {String} [observerOptions.rootMargin='0px']
 * @param {String} [observerOptions.threshold=0]
 * @return {Q.Tool}
 */
Q.Tool.define('Q/lazyload', function (options) {

	var tool = this;
	var state = this.state;
	state.root = state.root || this.element;

	var Elp = Element.prototype;

	Q.ensure('IntersectionObserver', function () {
		// Observe whatever is on the page already
		var p = tool.element.scrollingParent(true);
		if (p === document.body) {
			p = document.documentElement;
		}
		tool.observer = _createObserver(tool, p);
		tool.observe(tool.prepare(tool.element, false));

		// Override innerHTML

		var originalSet = Object.getOwnPropertyDescriptor(Elp, 'innerHTML').set;
		var originalGet = Object.getOwnPropertyDescriptor(Elp, 'innerHTML').get;

		Object.defineProperty(Elp, 'innerHTML', {
			set: function (html) {
				var element = document.createElement('div');
				var root = state.root || document.documentElement;
				var inside = (root === this) || root.contains(this);
				if (!inside) {
					originalSet.call(this, html);
					return html;
				}
				originalSet.call(element, html);
				var found = false;
				Q.each(state.handlers, function (name, info) {
					var elements = element.querySelectorAll
						? Array.from(element.querySelectorAll(info.selector))
						: [];
					if (elements.length) {
						found = true;
						return false;
					}
				});
				if (found) {
					html = originalGet.call(element);
				}
				originalSet.call(this, html);
				if (found) {
					tool.observe(tool.prepare(this, true));
				}
				return html;
			},
			get: originalGet
		});

		Q.each(['insertBefore', 'appendChild'], function (i, fn) {
			var orig = Elp[fn];
			Elp[fn] = function (element) {
				if (!(element instanceof HTMLElement)) {
					return orig.apply(this, arguments);
				}
				var root = state.root || document.documentElement;
				var inside = (root === this) || root.contains(this);
				if (!inside) {
					return orig.apply(this, arguments);
				}
				var found = false;
				Q.each(state.handlers, function (name, info) {
					if (element.matches && element.matches(info.selector)) {
						found = true;
						return false;
					}
					var elements = element.querySelectorAll
						? Array.from(element.querySelectorAll(info.selector))
						: [];
					if (elements.length) {
						found = true;
						return false;
					}
				});
				if (found) {
					tool.observe(tool.prepare(element, true));
				}
				return orig.apply(this, arguments);
			};
		});
	});

},

{
	handlers: {
		img: {
			selector: 'img',
			entering: function (img, entry) {
				function _loaded() {
					img.addClass('Q_lazy_loaded');
				}
				element.Q_lazyload_timeout = setTimeout(function () {
					if (element.hasAttribute('data-q-lazyload')
					&& (!element.Q || !element.Q.tool)) {
						var src = img.getAttribute('data-lazyload-src');
						if (src) {
							img.setAttribute('src', Q.url(src));
							img.removeAttribute('data-lazyload-src');
							img.addClass('Q_lazy_load');
							if (img.complete) {
								_loaded();
							}
							img.addEventListener('load', _loaded);
						}
					}
				}, state.debounce.milliseconds);
				return true;
			},
			exiting: function (img) {
				if (element.Q_lazyload_timeout) {
					clearTimeout(element.Q_lazyload_timeout);
					delete element.Q_lazyload_timeout;
				}
				return true; // no need to do anything else
			},
			preparing: function (img, beingInsertedIntoDOM) {
				if (!beingInsertedIntoDOM) {
					return true; // too late anyway, browser will load image
				}
				if (img.hasClass('Q_lazy_load') || img.hasClass('Q_lazy_loaded')) {
					return true; // this was already processed by lazy-loading
				}
				var src = img.getAttribute('src');
				if (src && src.substr(0, 5) !== 'data:'
				&& !img.hasAttribute('data-lazyload-src')) {
					img.setAttribute('data-lazyload-src', Q.url(src));
					img.setAttribute('src', Q.url(
						Q.getObject('Q.images.lazyload.loadingSrc')
						|| "{{Q}}/img/throbbers/transparent.gif"
					));
				}
				return true;
			}
		},
		tool: {
			selector: '.Q_tool',
			entering: function (element, entry) {
				element.Q_lazyload_timeout = setTimeout(function () {
					if (element.hasAttribute('data-q-lazyload')
					&& (!element.Q || !element.Q.tool)) {
						element.addClass('Q_lazy_load');
						element.setAttribute('data-q-lazyload', 'activating');
						Q.activate(element, function () {
							element.setAttribute('data-q-lazyload', 'activated');
							element.addClass('Q_lazy_loaded');
						}, {}, true);
						delete element.Q_lazyload_timeout;
					}
				}, state.debounce.milliseconds);
				return true;
			},
			exiting: function (element, entry) {
				if (element.hasAttribute('data-q-lazyload')
				&& element.Q.tool) {
					Q.Tool.remove(element);
					element.removeClass('Q_lazy_loading');
					element.removeClass('Q_lazy_loaded');
					element.setAttribute('data-q-lazyload', 'removed');
					if (this.state.handlers.tool.exitingRemoveHTML) {
						element.innerHTML = '';
					}
				}
				if (element.Q_lazyload_timeout) {
					clearTimeout(element.Q_lazyload_timeout);
					delete element.Q_lazyload_timeout;
				}
				return true;
			},
			preparing: function (element) {
				return true;
			},
			exitingRemoveHTML: true
		}
	},
	root: undefined,
	observerOptions: {
		root: undefined,
		rootMargin: '0px',
		threshold: 0
	},
	debounce: {
		milliseconds: 300
	}
},

{
	prepare: function (container, beingInsertedIntoDOM) {
		var tool = this;
		var found = [];
		Q.each(tool.state.handlers, function (name, info) {
			var elements = container.querySelectorAll
				? Array.from(container.querySelectorAll(info.selector))
				: [];
			if (container.matches && container.matches(info.selector)) {
				elements.push(container);
			}
			Q.each(elements, function (i, element) {
				if (info.preparing.call(tool, element, beingInsertedIntoDOM) === true) {
					found.push(element);
				}
			});
		});
		return found;
	},
	observe: function (elements) {
		var tool = this;
		tool.observer && Q.each(elements, function (i, element) {
			tool.observer.observe(element);
		});
	},
	unobserve: function (elements) {
		var tool = this;
		tool.observer && Q.each(elements, function (i, element) {
			tool.observer.unobserve(element);
		});
	},
	Q: {
		beforeRemove: function () {
			this.observer && this.observer.disconnect();
		}
	}
});

function _createObserver(tool, container) {
	var o = Q.copy(tool.state.observerOptions);
	if (o.root === undefined) {
		o.root = (container === document.documentElement) ? null : (container || null);
	}
	return new IntersectionObserver(function (entries, observer) {
		Q.each(entries, function (i, entry) {
			Q.each(tool.state.handlers, function (name, info) {
				if (entry.target.matches && entry.target.matches(info.selector)) {
					if (entry.isIntersecting) {
						info.entering.call(tool, entry.target, entry);
					} else  {
						var rect = entry.target.getBoundingClientRect();
						if (rect.width > 0 && rect.height > 0) {
							// also covers !document.body.contains(entry.target)
							info.exiting.call(tool, entry.target, entry);
						} // otherwise it might get a false positive
					}
				}
			});
		});
	}, o);
}

})(Q, jQuery);<|endoftext|>


<commit_before>(function() {
  var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
                              window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  window.requestAnimationFrame = requestAnimationFrame;
})();

function step()
{
  var ctx = step.ctx;
  ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);

  step.land.draw(ctx);

  requestAnimationFrame(step);
}

function init()
{
  var canvas;
  var ctx;
  var land;

  canvas = document.getElementById("wave-sim");
  ctx    = canvas.getContext("2d");
  land   = new Land();

  step.ctx  = ctx;
  step.land = land;

  // start animation
  requestAnimationFrame(step);
}

<commit_msg>Add another island<commit_after>(function() {
  var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
                              window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  window.requestAnimationFrame = requestAnimationFrame;
})();

function step()
{
  var ctx = step.ctx;
  var i   = 0;
  var len = step.lands.length;

  ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);

  for(;i<len;i++){
    step.lands[i].draw(ctx);
  }

  requestAnimationFrame(step);
}

function init()
{
  var canvas;
  var ctx;
  var land;
  var land2;

  canvas       = document.getElementById("wave-sim");
  ctx          = canvas.getContext("2d");
  land         = new Land();
  land2        = new Land();
  land2.x      = land.x+150;
  land2.y      = land.y-80;
  land2.width  = 50;
  land2.height = 50;

  step.ctx     = ctx;
  step.lands   = [];
  step.lands.push(land);
  step.lands.push(land2);

  // start animation
  requestAnimationFrame(step);
}

<|endoftext|>


<commit_before>(function (Q, $) {
/**
 * @module Q-tools
 */

/**
 * Implements lazy-loading for various types of elements.
 * By default, has implementations for "img" and "Q_tool" selectors.
 * The "Q_tool" handler only works with tools whose elements have a "data-q-lazyload" attribute .
 * Note that the elements must have a stable, nonzero width height set in the CSS even
 * if they are empty, otherwise they might not be lazy-loaded, and they might
 * thrash back and forth if removed.
 * @class Q lazyload
 * @constructor
 * @param {Object} [options] Override various options for this tool
 * @param {Array} [options.handle] Set this to
 * @param {Object} [options.handlers] You can modify the defaults by passing an object
 *    that looks like {handlerName: { selector: String, entering: Function, exiting: Function, preparing: Function}}
 *    Function "entering" receives (element, intersectionObserverEntry)
 *    Function "exiting" receives (element, intersectionObserverEntry)
 *    Function "preparing" receives (element) and is used the first time to prepare the element
 *    Both functions must return true if the element was modified.
 * @param {Object} [observerOptions] Override any options to pass to IntersectionObserver
 * @param {Element} [observerOptions.root=tool.scrollingParent]
 * @param {String} [observerOptions.rootMargin='0px']
 * @param {String} [observerOptions.threshold=0]
 * @return {Q.Tool}
 */
Q.Tool.define('Q/lazyload', function (options) {

	var tool = this;
	var state = this.state;

	var Elp = Element.prototype;

	Q.ensure(window.IntersectionObserver, _polyfill, function () {
		// Observe whatever is on the page already
		tool.observer = _createObserver(tool, tool.element.scrollingParent(true));
		tool.observe(tool.prepare(tool.element, false));

		// Override innerHTML

		var originalSet = Object.getOwnPropertyDescriptor(Elp, 'innerHTML').set;
		var originalGet = Object.getOwnPropertyDescriptor(Elp, 'innerHTML').get;

		Object.defineProperty(Elp, 'innerHTML', {
			set: function (html) {
				var element = document.createElement('div');
				var root = tool.observer.root || document.documentElement;
				var inside = (root === this) || root.contains(this);
				if (!inside) {
					originalSet.call(this, html);
					return html;
				}
				originalSet.call(element, html);
				var found = false;
				Q.each(state.handlers, function (name, info) {
					var elements = element.querySelectorAll
						? Array.from(element.querySelectorAll(info.selector))
						: [];
					if (elements.length) {
						found = true;
						return false;
					}
				});
				if (found) {
					html = originalGet.call(element);
				}
				originalSet.call(this, html);
				if (found) {
					tool.observe(tool.prepare(this, true));
				}
				return html;
			},
			get: originalGet
		});

		Q.each(['insertBefore', 'appendChild'], function (i, fn) {
			var orig = Elp[fn];
			Elp[fn] = function (element) {
				if (!(element instanceof HTMLElement)) {
					return orig.apply(this, arguments);
				}
				var root = tool.observer.root || document.documentElement;
				var inside = (root === this) || root.contains(this);
				if (!inside) {
					return orig.apply(this, arguments);
				}
				var found = false;
				Q.each(state.handlers, function (name, info) {
					if (element.matches && element.matches(info.selector)) {
						found = true;
						return false;
					}
					var elements = element.querySelectorAll
						? Array.from(element.querySelectorAll(info.selector))
						: [];
					if (elements.length) {
						found = true;
						return false;
					}
				});
				if (found) {
					tool.observe(tool.prepare(element, true));
				}
				return orig.apply(this, arguments);
			};
		});
	});

},

{
	handlers: {
		img: {
			selector: 'img',
			entering: function (img, entry) {
				function _loaded() {
					img.addClass('Q_lazy_loaded');
				}
				var src = img.getAttribute('data-lazyload-src');
				if (src) {
					img.setAttribute('src', Q.url(src));
					img.removeAttribute('data-lazyload-src');
					img.addClass('Q_lazy_load');
					if (img.complete) {
						_loaded();
					}
					img.addEventListener('load', _loaded);
				}
				return true;
			},
			exiting: function (img) {
				// no need to do anything
				return true;
			},
			preparing: function (img, beingInsertedIntoDOM) {
				if (!beingInsertedIntoDOM) {
					return true; // too late anyway, browser will load image
				}
				if (img.hasClass('Q_lazy_load') || img.hasClass('Q_lazy_loaded')) {
					return true; // this was already processed by lazy-loading
				}
				var src = img.getAttribute('src');
				if (src && src.substr(0, 5) !== 'data:'
				&& !img.hasAttribute('data-lazyload-src')) {
					img.setAttribute('data-lazyload-src', Q.url(src));
					img.setAttribute('src', Q.url(
						Q.getObject('Q.images.lazyload.loadingSrc')
						|| "{{Q}}/img/throbbers/transparent.gif"
					));
				}
				return true;
			}
		},
		tool: {
			selector: '.Q_tool',
			entering: function (element, entry) {
				if (element.hasAttribute('data-q-lazyload')
				&& (!element.Q || !element.Q.tool)) {
					element.addClass('Q_lazy_load');
					element.setAttribute('data-q-lazyload', 'activating');
					Q.activate(element, function () {
						element.setAttribute('data-q-lazyload', 'activated');
						element.addClass('Q_lazy_loaded');
					}, {}, true);
					return true;
				}
			},
			exiting: function (element, entry) {
				if (element.hasAttribute('data-q-lazyload')
				&& element.Q.tool) {
					Q.Tool.remove(element);
					element.removeClass('Q_lazy_loading');
					element.removeClass('Q_lazy_loaded');
					element.setAttribute('data-q-lazyload', 'removed');
					if (this.state.handlers.tool.exitingRemoveHTML) {
						element.innerHTML = '';
					}
				}
				return true;
			},
			preparing: function (element) {
				return true;
			},
			exitingRemoveHTML: true
		}
	},
	observerOptions: {
		root: undefined,
		rootMargin: '0px',
		threshold: 0
	}
},

{
	prepare: function (container, beingInsertedIntoDOM) {
		var tool = this;
		var found = [];
		Q.each(tool.state.handlers, function (name, info) {
			var elements = container.querySelectorAll
				? Array.from(container.querySelectorAll(info.selector))
				: [];
			if (container.matches && container.matches(info.selector)) {
				elements.push(container);
			}
			Q.each(elements, function (i, element) {
				if (info.preparing.call(tool, element, beingInsertedIntoDOM) === true) {
					found.push(element);
				}
			});
		});
		return found;
	},
	observe: function (elements) {
		var tool = this;
		tool.observer && Q.each(elements, function (i, element) {
			tool.observer.observe(element);
		});
	},
	unobserve: function (elements) {
		var tool = this;
		tool.observer && Q.each(elements, function (i, element) {
			tool.observer.unobserve(element);
		});
	},
	Q: {
		beforeRemove: function () {
			this.observer && this.observer.disconnect();
		}
	}
});

function _createObserver(tool, container) {
	var o = Q.copy(tool.state.observerOptions);
	if (o.root === undefined) {
		o.root = container || null;
	}
	return new IntersectionObserver(function (entries, observer) {
		Q.each(entries, function (i, entry) {
			Q.each(tool.state.handlers, function (name, info) {
				if (entry.target.matches && entry.target.matches(info.selector)) {
					if (entry.isVisible) {
						info.entering.call(tool, entry.target, entry);
					} else  {
						var rect = entry.target.getBoundingClientRect();
						if (rect.width > 0 && rect.height > 0) {
							// also covers !document.body.contains(entry.target)
							info.exiting.call(tool, entry.target, entry);
						} // otherwise it might get a false positive
					}
				}
			});
		});
	}, o);
}

function _polyfill(callback) {
	// Exit early if all IntersectionObserver and IntersectionObserverEntry
	// features are natively supported.
	if ('IntersectionObserver' in window &&
	    'IntersectionObserverEntry' in window &&
	    'intersectionRatio' in window.IntersectionObserverEntry.prototype) {

	  // Minimal polyfill for Edge 15's lack of `isIntersecting`
	  // See: https://github.com/w3c/IntersectionObserver/issues/211
	  if (!('isIntersecting' in window.IntersectionObserverEntry.prototype)) {
	    Object.defineProperty(window.IntersectionObserverEntry.prototype,
	      'isIntersecting', {
	      get: function () {
	        return this.intersectionRatio > 0;
	      }
	    });
	  }
	  return Q.handle(callback);
	}
	Q.addScript('{{Q}}/js/polyfills/IntersectionObserver.js', callback);
}

_polyfill();

})(Q, jQuery);<commit_msg>Worked on Q/lazyload tool<commit_after>(function (Q, $) {
/**
 * @module Q-tools
 */

/**
 * Implements lazy-loading for various types of elements.
 * By default, has implementations for "img" and "Q_tool" selectors.
 * The "Q_tool" handler only works with tools whose elements have a "data-q-lazyload" attribute .
 * Note that the elements must have a stable, nonzero width height set in the CSS even
 * if they are empty, otherwise they might not be lazy-loaded, and they might
 * thrash back and forth if removed.
 * @class Q lazyload
 * @constructor
 * @param {Object} [options] Override various options for this tool
 * @param {Array} [options.handle] Set this to
 * @param {Object} [options.handlers] You can modify the defaults by passing an object
 *    that looks like {handlerName: { selector: String, entering: Function, exiting: Function, preparing: Function}}
 *    Function "entering" receives (element, intersectionObserverEntry)
 *    Function "exiting" receives (element, intersectionObserverEntry)
 *    Function "preparing" receives (element) and is used the first time to prepare the element
 *    Both functions must return true if the element was modified.
 * @param {Element} [root=tool.element] The container inside which to watch for intesections
 * @param {Object} [observerOptions] Override any options to pass to IntersectionObserver
 * @param {Element} [observerOptions.root=tool.element.scrollingParent(true)]
 * @param {String} [observerOptions.rootMargin='0px']
 * @param {String} [observerOptions.threshold=0]
 * @return {Q.Tool}
 */
Q.Tool.define('Q/lazyload', function (options) {

	var tool = this;
	var state = this.state;

	var Elp = Element.prototype;

	Q.ensure(window.IntersectionObserver, _polyfill, function () {
		// Observe whatever is on the page already
		tool.observer = _createObserver(tool, tool.element.scrollingParent(true));
		tool.observe(tool.prepare(tool.element, false));

		// Override innerHTML

		var originalSet = Object.getOwnPropertyDescriptor(Elp, 'innerHTML').set;
		var originalGet = Object.getOwnPropertyDescriptor(Elp, 'innerHTML').get;

		Object.defineProperty(Elp, 'innerHTML', {
			set: function (html) {
				var element = document.createElement('div');
				var root = state.root || document.documentElement;
				var inside = (root === this) || root.contains(this);
				if (!inside) {
					originalSet.call(this, html);
					return html;
				}
				originalSet.call(element, html);
				var found = false;
				Q.each(state.handlers, function (name, info) {
					var elements = element.querySelectorAll
						? Array.from(element.querySelectorAll(info.selector))
						: [];
					if (elements.length) {
						found = true;
						return false;
					}
				});
				if (found) {
					html = originalGet.call(element);
				}
				originalSet.call(this, html);
				if (found) {
					tool.observe(tool.prepare(this, true));
				}
				return html;
			},
			get: originalGet
		});

		Q.each(['insertBefore', 'appendChild'], function (i, fn) {
			var orig = Elp[fn];
			Elp[fn] = function (element) {
				if (!(element instanceof HTMLElement)) {
					return orig.apply(this, arguments);
				}
				var root = state.root || document.documentElement;
				var inside = (root === this) || root.contains(this);
				if (!inside) {
					return orig.apply(this, arguments);
				}
				var found = false;
				Q.each(state.handlers, function (name, info) {
					if (element.matches && element.matches(info.selector)) {
						found = true;
						return false;
					}
					var elements = element.querySelectorAll
						? Array.from(element.querySelectorAll(info.selector))
						: [];
					if (elements.length) {
						found = true;
						return false;
					}
				});
				if (found) {
					tool.observe(tool.prepare(element, true));
				}
				return orig.apply(this, arguments);
			};
		});
	});

},

{
	handlers: {
		img: {
			selector: 'img',
			entering: function (img, entry) {
				function _loaded() {
					img.addClass('Q_lazy_loaded');
				}
				var src = img.getAttribute('data-lazyload-src');
				if (src) {
					img.setAttribute('src', Q.url(src));
					img.removeAttribute('data-lazyload-src');
					img.addClass('Q_lazy_load');
					if (img.complete) {
						_loaded();
					}
					img.addEventListener('load', _loaded);
				}
				return true;
			},
			exiting: function (img) {
				// no need to do anything
				return true;
			},
			preparing: function (img, beingInsertedIntoDOM) {
				if (!beingInsertedIntoDOM) {
					return true; // too late anyway, browser will load image
				}
				if (img.hasClass('Q_lazy_load') || img.hasClass('Q_lazy_loaded')) {
					return true; // this was already processed by lazy-loading
				}
				var src = img.getAttribute('src');
				if (src && src.substr(0, 5) !== 'data:'
				&& !img.hasAttribute('data-lazyload-src')) {
					img.setAttribute('data-lazyload-src', Q.url(src));
					img.setAttribute('src', Q.url(
						Q.getObject('Q.images.lazyload.loadingSrc')
						|| "{{Q}}/img/throbbers/transparent.gif"
					));
				}
				return true;
			}
		},
		tool: {
			selector: '.Q_tool',
			entering: function (element, entry) {
				if (element.hasAttribute('data-q-lazyload')
				&& (!element.Q || !element.Q.tool)) {
					element.addClass('Q_lazy_load');
					element.setAttribute('data-q-lazyload', 'activating');
					Q.activate(element, function () {
						element.setAttribute('data-q-lazyload', 'activated');
						element.addClass('Q_lazy_loaded');
					}, {}, true);
					return true;
				}
			},
			exiting: function (element, entry) {
				if (element.hasAttribute('data-q-lazyload')
				&& element.Q.tool) {
					Q.Tool.remove(element);
					element.removeClass('Q_lazy_loading');
					element.removeClass('Q_lazy_loaded');
					element.setAttribute('data-q-lazyload', 'removed');
					if (this.state.handlers.tool.exitingRemoveHTML) {
						element.innerHTML = '';
					}
				}
				return true;
			},
			preparing: function (element) {
				return true;
			},
			exitingRemoveHTML: true
		}
	},
	root: undefined,
	observerOptions: {
		root: undefined,
		rootMargin: '0px',
		threshold: 0
	}
},

{
	prepare: function (container, beingInsertedIntoDOM) {
		var tool = this;
		var found = [];
		Q.each(tool.state.handlers, function (name, info) {
			var elements = container.querySelectorAll
				? Array.from(container.querySelectorAll(info.selector))
				: [];
			if (container.matches && container.matches(info.selector)) {
				elements.push(container);
			}
			Q.each(elements, function (i, element) {
				if (info.preparing.call(tool, element, beingInsertedIntoDOM) === true) {
					found.push(element);
				}
			});
		});
		return found;
	},
	observe: function (elements) {
		var tool = this;
		tool.observer && Q.each(elements, function (i, element) {
			tool.observer.observe(element);
		});
	},
	unobserve: function (elements) {
		var tool = this;
		tool.observer && Q.each(elements, function (i, element) {
			tool.observer.unobserve(element);
		});
	},
	Q: {
		beforeRemove: function () {
			this.observer && this.observer.disconnect();
		}
	}
});

function _createObserver(tool, container) {
	var o = Q.copy(tool.state.observerOptions);
	if (o.root === undefined) {
		o.root = (container === document.documentElement) ? null : (container || null);
	}
	return new IntersectionObserver(function (entries, observer) {
		Q.each(entries, function (i, entry) {
			Q.each(tool.state.handlers, function (name, info) {
				if (entry.target.matches && entry.target.matches(info.selector)) {
					if (entry.isVisible) {
						info.entering.call(tool, entry.target, entry);
					} else  {
						var rect = entry.target.getBoundingClientRect();
						if (rect.width > 0 && rect.height > 0) {
							// also covers !document.body.contains(entry.target)
							info.exiting.call(tool, entry.target, entry);
						} // otherwise it might get a false positive
					}
				}
			});
		});
	}, o);
}

function _polyfill(callback) {
	// Exit early if all IntersectionObserver and IntersectionObserverEntry
	// features are natively supported.
	if ('IntersectionObserver' in window &&
	    'IntersectionObserverEntry' in window &&
	    'intersectionRatio' in window.IntersectionObserverEntry.prototype) {

	  // Minimal polyfill for Edge 15's lack of `isIntersecting`
	  // See: https://github.com/w3c/IntersectionObserver/issues/211
	  if (!('isIntersecting' in window.IntersectionObserverEntry.prototype)) {
	    Object.defineProperty(window.IntersectionObserverEntry.prototype,
	      'isIntersecting', {
	      get: function () {
	        return this.intersectionRatio > 0;
	      }
	    });
	  }
	  return Q.handle(callback);
	}
	Q.addScript('{{Q}}/js/polyfills/IntersectionObserver.js', callback);
}

_polyfill();

})(Q, jQuery);<|endoftext|>


<commit_before>var globalColorWheel;

//---------------------------------------------------------------------------------
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 LedWheel = React.createClass({
  // The state is minumum of the radius sepcified in the props, and the available radius
  getInitialState:function() {
    return {radius: this.props.radius};
  },

  computeAvailableRadius:function() {
    if (this.elem) {
      // calculate parent's width - padding
      var p = this.elem.parentNode;
      var w = p.clientWidth - window.getComputedStyle(p).borderLeftWidth - window.getComputedStyle(p).borderRightWidth;
      // 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);
  },

  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 leds = [];
    var circs = [{n:24, r: r1}, {n:12, r:r2}];
    for(var j = 0; j < 2; j++) {
      var n = circs[j].n;
      var r = circs[j].r;
      var r2 = r - thickness;
      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={j+"_"+i} circleIndex={j} ledIndex={i} angle={a1} thickness={thickness-2} x={x} y={y}/>);
      }
    }
    var self = this;
    return (<svg
      ref={function(input) { self.elem = input; }}
      height={radius*2} width={radius*2}>{leds}</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({
  componentDidMount: function() {
    globalColorWheel = this;
  },

  getInitialState: function() {
    return {hueIndex:0, hue:0, rgb:{r:255,g:0,b:0}}; // initial hue is 0, inicial color is red
  },

  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, thickness:30 };
  },

  render: function() {
    var n = this.props.n;
    var radius = this.props.radius;
    var thickness = this.props.thickness;
    // 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)}
      />);
    }

    var self = this;
    return (<svg height={radius*2+2} width={radius*2+2}>
      <g>{colorSegments}</g>
      <HueSquare
        ref={function(input) {self.hueSquare = input }}
        radius={this.props.radius} n={8} thickness={this.props.thickness} />
    </svg>);
  }
})

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

ReactDOM.render(
      <ColorWheel radius={100} n={24} thickness={30}/>,
      document.getElementById('right')
)
<commit_msg>Update main.js<commit_after>var globalColorWheel;

//---------------------------------------------------------------------------------
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 LedWheel = React.createClass({
  // The state is minumum of the radius sepcified in the props, and the available radius
  getInitialState:function() {
    return {radius: this.props.radius};
  },

  computeAvailableRadius:function() {
    if (this.elem) {
      // calculate parent's width - padding
      var p = this.elem.parentNode;
      console.log(window.getComputedStyle(p));
      var w = p.clientWidth - window.getComputedStyle(p).borderLeftWidth - window.getComputedStyle(p).borderRightWidth;
      // 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);
  },

  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 leds = [];
    var circs = [{n:24, r: r1}, {n:12, r:r2}];
    for(var j = 0; j < 2; j++) {
      var n = circs[j].n;
      var r = circs[j].r;
      var r2 = r - thickness;
      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={j+"_"+i} circleIndex={j} ledIndex={i} angle={a1} thickness={thickness-2} x={x} y={y}/>);
      }
    }
    var self = this;
    return (<svg
      ref={function(input) { self.elem = input; }}
      height={radius*2} width={radius*2}>{leds}</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({
  componentDidMount: function() {
    globalColorWheel = this;
  },

  getInitialState: function() {
    return {hueIndex:0, hue:0, rgb:{r:255,g:0,b:0}}; // initial hue is 0, inicial color is red
  },

  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, thickness:30 };
  },

  render: function() {
    var n = this.props.n;
    var radius = this.props.radius;
    var thickness = this.props.thickness;
    // 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)}
      />);
    }

    var self = this;
    return (<svg height={radius*2+2} width={radius*2+2}>
      <g>{colorSegments}</g>
      <HueSquare
        ref={function(input) {self.hueSquare = input }}
        radius={this.props.radius} n={8} thickness={this.props.thickness} />
    </svg>);
  }
})

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

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


<commit_before>/* Main code */

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

/* 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.appendTo('#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)); });
				} 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 update_events(from_id) {
	require(["jquery"], function(jquery) {
		jquery.get('backend.php', {'msgs':'1', 'start':''+from_id}, function(data) {
			var events = JSON.parse(data);
			for(i in events) if(events.hasOwnProperty(i)) {
				dialog = jquery('#elements .event_container').clone();
				dialog.find('.date').text(data.date);
				dialog.find('.msg').text(data.msg);
				dialog.appendTo('#events');
			}
		});
	}, function(err) { add_error(JSON.stringify(err)); });
}

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

	// TODO: Setup simple clock on control form

	// TODO: Setup previous event history
	update_events(0);

	// TODO: Start fetching new events

};

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

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

/* 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.appendTo('#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)); });
				} 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 update_events(from_id) {
	require(["jquery"], function(jquery) {
		jquery.get('backend.php', {'msgs':'1', 'start':''+from_id}, function(data) {
			alert('got data: ' . data);
			var events = JSON.parse(data);
			for(i in events) if(events.hasOwnProperty(i)) {
				dialog = jquery('#elements .event_container').clone();
				dialog.find('.date').text(data.date);
				dialog.find('.msg').text(data.msg);
				dialog.appendTo('#events');
			}
		});
	}, function(err) { add_error(JSON.stringify(err)); });
}

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

	// TODO: Setup simple clock on control form

	// TODO: Setup previous event history
	update_events(0);

	// TODO: Start fetching new events

};

/* EOF */
<|endoftext|>


<commit_before>AFRAME.registerComponent('click-listener', {
		  init: function () {

		var el = this.el;
	    	const mdl = document.querySelector('#ModelId');
		const txt = document.querySelector('#ModelTxt');
                const sTxt = document.querySelector('#StartTxt');
		const _mdlCnt = 3;

		window.addEventListener('click', function () {
			var MI = document.getElementById('ModelIndex');
                    	sTxt.setAttribute('text-geometry', 'value:');

			    var i = 0;
			    i += parseFloat(MI.innerHTML);
				i += 1;
			    if (i > _mdlCnt)
				i = 1;
			    MI.innerHTML = i;
			    if (i==1) {
				mdl.setAttribute('obj-model', 'obj: #bear-obj;');
				mdl.setAttribute('scale', '0.01 0.01 0.01');
				//mdl.setAttribute('position', '0 0 0');
			    	mdl.innerHTML = "<a-animation attribute='rotation' dur='8000' easing='linear' repeat='indefinite' to='0 360 0'></a-animation><a-entity position='0 2 0' particle-system='preset: rain; color: #EF0000,#44CC00'></a-entity>";
				txt.setAttribute('text-geometry', 'value: Bear Lancer');
				txt.setAttribute('position', '-1.5 0 1.5');
			    }
			    else if (i==2) {
				mdl.setAttribute('obj-model', 'obj: #brawler-obj;');
				mdl.setAttribute('scale', '0.25 0.25 0.25');
				//mdl.setAttribute('position', '0 0 0');
				mdl.innerHTML = "<a-animation attribute='rotation' dur='8000' easing='linear' repeat='indefinite' to='0 360 0'></a-animation><a-entity position='0 0 0' particle-system='preset: rain; color: #EF0000,#44CC00'></a-entity>";
				txt.setAttribute('text-geometry', 'value: The Brawler');
				txt.setAttribute('position', '-1.8 0 1.5');
			    }
			    else if (i==3) {
				mdl.setAttribute('obj-model', 'obj: #cube-obj; mtl: #cube-mtl;');
				mdl.setAttribute('scale', '0.05 0.05 0.05');
				txt.setAttribute('text-geometry', 'value: The Cube');
				txt.setAttribute('position', '-1.4 0 1.5');
			    	mdl.innerHTML = "<a-animation attribute='rotation' dur='8000' easing='linear' repeat='indefinite' to='0 360 0'></a-animation><a-entity position='0 0 0' particle-system='preset: rain; color: #EF0000,#44CC00'></a-entity><a-entity position='0 0 0' particle-system='color: #EF0000,#44CC00'></a-entity>";
			    }
		    });
		  }
		});
<commit_msg>Update BattleRockAR.js<commit_after>AFRAME.registerComponent('click-listener', {
		  init: function () {

		var el = this.el;
	    	const mdl = document.querySelector('#ModelId');
		const txt = document.querySelector('#ModelTxt');
                const sTxt = document.querySelector('#StartTxt');
		const _mdlCnt = 3;

		window.addEventListener('click', function () {
			var MI = document.getElementById('ModelIndex');
                    	sTxt.setAttribute('text-geometry', 'value:');

			    var i = 0;
			    i += parseFloat(MI.innerHTML);
				i += 1;
			    if (i > _mdlCnt)
				i = 1;
			    MI.innerHTML = i;
			    if (i==1) {
				mdl.setAttribute('obj-model', 'obj: #bear-obj;');
				//mdl.setAttribute('scale', '0.01 0.01 0.01');
				//mdl.setAttribute('position', '0 0 0');
			    	mdl.innerHTML = "<a-animation attribute='rotation' dur='8000' easing='linear' repeat='indefinite' to='0 360 0'></a-animation><a-entity position='0 2 0' particle-system='preset: rain; color: #EF0000,#44CC00'></a-entity>";
				txt.setAttribute('text-geometry', 'value: Bear Lancer');
				txt.setAttribute('position', '-1.5 0 1.5');
			    }
			    else if (i==2) {
				mdl.setAttribute('obj-model', 'obj: #brawler-obj;');
				//mdl.setAttribute('scale', '0.25 0.25 0.25');
				//mdl.setAttribute('position', '0 0 0');
				mdl.innerHTML = "<a-animation attribute='rotation' dur='8000' easing='linear' repeat='indefinite' to='0 360 0'></a-animation><a-entity position='0 0 0' particle-system='preset: rain; color: #EF0000,#44CC00'></a-entity>";
				txt.setAttribute('text-geometry', 'value: The Brawler');
				txt.setAttribute('position', '-1.8 0 1.5');
			    }
			    else if (i==3) {
				mdl.setAttribute('obj-model', 'obj: #cube-obj; mtl: #cube-mtl;');
				//mdl.setAttribute('scale', '0.05 0.05 0.05');
				txt.setAttribute('text-geometry', 'value: The Cube');
				txt.setAttribute('position', '-1.4 0 1.5');
			    	mdl.innerHTML = "<a-animation attribute='rotation' dur='8000' easing='linear' repeat='indefinite' to='0 360 0'></a-animation><a-entity position='0 0 0' particle-system='preset: rain; color: #EF0000,#44CC00'></a-entity><a-entity position='0 0 0' particle-system='color: #EF0000,#44CC00'></a-entity>";
			    }
		    });
		  }
		});
<|endoftext|>