<commit_before>
// Wait for DOM to be ready!
$(document).ready(function(){
	$.ajax({
		// Get all movies from our database.
    url:"movies/getallmovies",
		dataType:"json",
		cache: false,
		// If successfull, run our renderData function and send the data (a JSON-object) to it.
    success:function (data) {
    		//Adds the movies to the slider
    		//Adds the links
			renderData(data);

			//Load Contact Details
			loadContactDetails();
		},
    // If error.
		error:function(errorData) {
			console.log("There seems to be an error fetching the data." + errorData.error);
		}
	});
});

function renderData (movies) {
  // Loop to add stuff from JSON-data (movies variable) to the DOM.

	//Loads the description from the Machine Title
	loadDescription(movies[0]['machinetitle']);

	for (var i = 0;i < movies.length;i++) {

		// Add only the thumbnail (not the actuall movie) to our div with class bxslider.
		$('.bxslider').append(

			// We give the thumbnail img a #id that is the same as the Youtube ID.
			'

'
		);

		//When the thumbnail is clicked...
		//The thumbnails id looks like this after concatenation: #4Vvd875V (hashtag + YouTube ID)
		$('#' + movies[i].link).click(function(){

			//The movies variable in renderData() is no longer available when this thumbnail is clicked.
			//So we get the Youtube video ID from the ID Hashtag instead of the movie variable!
			var videoID = $(this).attr('id');

			//(this). returns the  that was clicked. We cant put the video into the image....
			//So we replace the content in the parent of  ie the
!
			$(this).parent().html('');

		});
		// Add the titles+author to div with ID bx-pager.
		/* The best solution but the jQuery slider doesn't allow us to change the DOM structure links live in
		if(i < 5) {

			$('.left-column').append(
				'
'+ movies[i].title +' Av '+movies[i].author+'
 '
			);
     	}else{

			$('.right-column').append(
				'
'+ movies[i].title +' Av '+movies[i].author+'
 '
			);
    	}
    	*/

    	/*So were forced to work in a single div instead of a two column div system*/
    	$('#bx-pager').append(
			'
'+ movies[i].title +' Av '+movies[i].author+'
 '
		);

	};

	videoSlider();
	clickhandler();
}

// Activate the videoslider. This has to be done after the videos has been added to our DOM.
function videoSlider(){
	$('.bxslider').bxSlider({
		video: true,
		useCSS: false,
		pagerCustom: '#bx-pager'
	});
}
// makes the anchor scroll on the page smooth as silk
function clickhandler () {
	$('a').click(function(){

		//Get the movie title from the links ID and call loadDescription()
		var machineTitle = $(this).attr('id')
		loadDescription(machineTitle);

		//Slide the correct movie into place
		$('html, body').animate({
			scrollTop: $( $(this).attr('href') ).offset().top
		}, 600);
		return false;
	});
}

//Loads the correct description and fades it in
function loadDescription(machineTitle){

	if(typeof machineTitle === 'undefined' || !machineTitle){
		return false;
	}
	console.log('loadDescription got param data: ' + machineTitle )

	$.ajax({
		// Get all movies from our database.
	    url:"movies/getmovie/" + machineTitle,
			dataType:"json",
			cache: false,
		// If successfull, run our renderData function and send the data (a JSON-object) to it.
	    success:function (data) {
	    	//If ajax call was successfull but no/wrong data was returned show error
	    	if(typeof data[0]['description'] === 'undefined' || !data[0]['description']){
		    	$('#information > p').fadeOut(function(){
					$('#information > p').text('Ingen beskrivning hittades');
					$('#information > p').fadeIn();
		    	})
	    	//Everything good! Show description
	    	}else{
		    	$('#information > p').fadeOut(function(){
					$('#information > p').text(data[0]['description']);
					$('#information > p').fadeIn();
		    	})
	    	}
		},
	    // If error.
		error:function(errorData) {
			console.log("There seems to be an error fetching the description. " + errorData.error);
	    	$('#information > p').fadeOut(function(){
				$('#information > p').text('Ingen beskrivning hittades');
				$('#information > p').fadeIn();
	    	})
		}
	});
}

function loadContactDetails(){
	$.ajax({
		// Get all movies from our database.
	    url:"http://gdata.youtube.com/feeds/api/playlists/SwXUlPkaY_FZ7R9AsTo1yJi7wRthcBtx?v=2&alt=json",
			dataType:"json",
			cache: false,
		// If successfull, run our renderData function and send the data (a JSON-object) to it.
	    success:function (data) {
	    	//If ajax call was successfull but no/wrong data was returned show error
	    	if(typeof data['feed']['media$group']['media$description']['$t'] === 'undefined' || !data['feed']['media$group']['media$description']['$t']){
		    	$('#contact > p').fadeOut(function(){
					$('#contact > p').text('Ingen kontaktinformation hittades');
					$('#contact > p').fadeIn();
		    	})
	    	//Everything good! Show Contact Details
	    	}else{
		    	$('#contact > p').fadeOut(function(){
					$('#contact > p').text(data['feed']['media$group']['media$description']['$t']);
					$('#contact > p').fadeIn();
		    	})
	    	}
		},
	    // If error.
		error:function(errorData) {
			console.log("There seems to be an error fetching the contact details. " + errorData.error);
	    	$('#contact > p').fadeOut(function(){
				$('#contact > p').text('Ingen kontaktinformation hittades');
				$('#contact > p').fadeIn();
	    	})
		}
	});
}

//Returns the YoutubeID of the video currently visible in the slider.
function getMachineTitleFromLink(){
	/*Broken since link no longer get the .active class*/
	return $('#bx-pager > a.active').attr('id');
}
<commit_msg>changed the info-text for when there is no info for ajax to fetch<commit_after>
// Wait for DOM to be ready!
$(document).ready(function(){
	$.ajax({
		// Get all movies from our database.
    url:"movies/getallmovies",
		dataType:"json",
		cache: false,
		// If successfull, run our renderData function and send the data (a JSON-object) to it.
    success:function (data) {
    		//Adds the movies to the slider
    		//Adds the links
			renderData(data);

			//Load Contact Details
			loadContactDetails();
		},
    // If error.
		error:function(errorData) {
			console.log("There seems to be an error fetching the data." + errorData.error);
		}
	});
});

function renderData (movies) {
  // Loop to add stuff from JSON-data (movies variable) to the DOM.

	//Loads the description from the Machine Title
	loadDescription(movies[0]['machinetitle']);

	for (var i = 0;i < movies.length;i++) {

		// Add only the thumbnail (not the actuall movie) to our div with class bxslider.
		$('.bxslider').append(

			// We give the thumbnail img a #id that is the same as the Youtube ID.
			'

'
		);

		//When the thumbnail is clicked...
		//The thumbnails id looks like this after concatenation: #4Vvd875V (hashtag + YouTube ID)
		$('#' + movies[i].link).click(function(){

			//The movies variable in renderData() is no longer available when this thumbnail is clicked.
			//So we get the Youtube video ID from the ID Hashtag instead of the movie variable!
			var videoID = $(this).attr('id');

			//(this). returns the  that was clicked. We cant put the video into the image....
			//So we replace the content in the parent of  ie the
!
			$(this).parent().html('');

		});
		// Add the titles+author to div with ID bx-pager.
		/* The best solution but the jQuery slider doesn't allow us to change the DOM structure links live in
		if(i < 5) {

			$('.left-column').append(
				'
'+ movies[i].title +' Av '+movies[i].author+'
 '
			);
     	}else{

			$('.right-column').append(
				'
'+ movies[i].title +' Av '+movies[i].author+'
 '
			);
    	}
    	*/

    	/*So were forced to work in a single div instead of a two column div system*/
    	$('#bx-pager').append(
			'
'+ movies[i].title +' Av '+movies[i].author+'
 '
		);

	};

	videoSlider();
	clickhandler();
}

// Activate the videoslider. This has to be done after the videos has been added to our DOM.
function videoSlider(){
	$('.bxslider').bxSlider({
		video: true,
		useCSS: false,
		pagerCustom: '#bx-pager'
	});
}
// makes the anchor scroll on the page smooth as silk
function clickhandler () {
	$('a').click(function(){

		//Get the movie title from the links ID and call loadDescription()
		var machineTitle = $(this).attr('id')
		loadDescription(machineTitle);

		//Slide the correct movie into place
		$('html, body').animate({
			scrollTop: $( $(this).attr('href') ).offset().top
		}, 600);
		return false;
	});
}

//Loads the correct description and fades it in
function loadDescription(machineTitle){

	if(typeof machineTitle === 'undefined' || !machineTitle){
		return false;
	}
	console.log('loadDescription got param data: ' + machineTitle )

	$.ajax({
		// Get all movies from our database.
	    url:"movies/getmovie/" + machineTitle,
			dataType:"json",
			cache: false,
		// If successfull, run our renderData function and send the data (a JSON-object) to it.
	    success:function (data) {
	    	//If ajax call was successfull but no/wrong data was returned show error
	    	if(typeof data[0]['description'] === 'undefined' || !data[0]['description']){
		    	$('#information > p').fadeOut(function(){
					$('#information > p').text('Ingen info finns');
					$('#information > p').fadeIn();
		    	})
	    	//Everything good! Show description
	    	}else{
		    	$('#information > p').fadeOut(function(){
					$('#information > p').text(data[0]['description']);
					$('#information > p').fadeIn();
		    	})
	    	}
		},
	    // If error.
		error:function(errorData) {
			console.log("There seems to be an error fetching the description. " + errorData.error);
	    	$('#information > p').fadeOut(function(){
				$('#information > p').text('Ingen beskrivning hittades');
				$('#information > p').fadeIn();
	    	})
		}
	});
}

function loadContactDetails(){
	$.ajax({
		// Get all movies from our database.
	    url:"http://gdata.youtube.com/feeds/api/playlists/SwXUlPkaY_FZ7R9AsTo1yJi7wRthcBtx?v=2&alt=json",
			dataType:"json",
			cache: false,
		// If successfull, run our renderData function and send the data (a JSON-object) to it.
	    success:function (data) {
	    	//If ajax call was successfull but no/wrong data was returned show error
	    	if(typeof data['feed']['media$group']['media$description']['$t'] === 'undefined' || !data['feed']['media$group']['media$description']['$t']){
		    	$('#contact > p').fadeOut(function(){
					$('#contact > p').text('Ingen kontaktinformation hittades');
					$('#contact > p').fadeIn();
		    	})
	    	//Everything good! Show Contact Details
	    	}else{
		    	$('#contact > p').fadeOut(function(){
					$('#contact > p').text(data['feed']['media$group']['media$description']['$t']);
					$('#contact > p').fadeIn();
		    	})
	    	}
		},
	    // If error.
		error:function(errorData) {
			console.log("There seems to be an error fetching the contact details. " + errorData.error);
	    	$('#contact > p').fadeOut(function(){
				$('#contact > p').text('Ingen kontaktinformation hittades');
				$('#contact > p').fadeIn();
	    	})
		}
	});
}

//Returns the YoutubeID of the video currently visible in the slider.
function getMachineTitleFromLink(){
	/*Broken since link no longer get the .active class*/
	return $('#bx-pager > a.active').attr('id');
}
<|endoftext|>


<commit_before>var showing = 0;
var shades;
var resume;
var orderArr = [
	[0,1,2,3,4,5,6,7,8],
	[1,0,1,2,3,4,5,6,7],
	[2,1,0,1,2,3,4,5,6],
	[3,2,1,0,1,2,3,4,5],
	[4,3,2,1,0,1,2,3,4],
	[5,4,3,2,1,0,1,2,3],
	[6,5,4,3,2,1,0,1,2],
	[7,6,5,4,3,2,1,0,1],
	[8,7,6,5,4,3,2,1,0]
];

var sections = ["general", "school", "diet", "resume", "hacker", "success"];
var currentSection = 0;

var align = function(){
	$.each(paras, function(index, obj){
		var top = $(shades[showing+1]).scrollTop();
		top *= (index+1)*0.5;
		$(obj).css({"top":-top});
	});
}
var order = function(){
    for (var i = 0; i <= currentSection; i++) {
        $('#' + sections[i]).css({"display" : "block"});
    }

    return;
    // Old code below...

	$.each(shades, function(index, obj){
		index -= 1;
		var left, zindex, opacity;

		if($(obj).attr("id") == "footerInner"){
			zindex = -2000;
			opacity = 1;
			if( $(window).width() < 1000 ){
				left = "0px";
			}else{
				left = $(window).width()/2 - $(obj).width()/2 + "px"
			}
		}else{
			zindex = orderArr[showing][index];
			opacity = zindex/5;
			opacity = 1 - opacity;
			if( $(window).width() < 1000 ){
				left = "0px";
			}else{
				left = $(window).width()/2 - $(obj).width()/2;
				left += 40*(index-showing);
				left += "px";
			}
		}

		$(obj).css({"left":left, "z-index":1000-zindex, "opacity":opacity });
	});
	align();
}
$(document).ready(function(){
	shades = $(".inner");
	paras = $(".parallax");
	order();
	$(window).resize(order);
	$.each(shades, function(index, obj){
		$(obj).on("scroll", function(){
			if(index-1 == showing){
				align();
			}
		});
	});
	$(".inner").show(0);
	var moveRight = function(){

        currentSection++;
        order();
        return;
        // Old code below...

		showing = (showing+1) % shades.length;
		order();
	};

	$(".left").click(function(){
		showing = (showing-1) % shades.length;
		order();
	});
	$("#school-attend-school").change(function (){
		$("#school-selector").slideToggle();
		$("#school-school").removeClass("error");
	});
	$("input[name='travel']:radio").change(function () {
		$("#venmo").slideToggle();
		$("#school-venmo").removeClass("error");
	});
	$("#hacker-plan-hardware").change(function (){
		$("#plan-hardware-on").slideToggle();
		$("#hacker-plan-hardware-on").removeClass("error");
	});
	$("#hacker-need-partner, #hacker-plan-mentor").change(function (){
		if( $("#hacker-need-partner").prop('checked')
		 || $("#hacker-plan-mentor").prop('checked') )
			$("#partner").slideDown();
		else{
			$("#partner").slideUp();
			$("#hacker-need-partner-skills").removeClass("error");
		}
	});
	$("#resume-button").click(function (){
		$("#resume-button-shadow").click();
	});
	$("#resume-button-shadow").change(function(e){
		$("#resume-button").find("div").text(e.target.files[0].name);
		resume = e.target.files[0];
		$("#resume-button").addClass("done");
	});
	var validateLength = function ($input){
		if($input.val().length <= 0)
			$input.addClass("error");
	}
	var validateSelect = function ($input){
		if($input.val() == null)
			$input.addClass("error");
	}
	$("#validate-general").click(function(){
		$this = $("#general");
		validateLength($this.find("#general-first-name"));
		validateLength($this.find("#general-last-name"));
		validateLength($this.find("#general-email"));
		var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    	if(!re.test($this.find("#general-email").val()))
			$this.find("#general-email").addClass("error");
		validateLength($this.find("#general-password"));
		validateSelect($this.find("#general-swag-size"));

		if($this.find(".error").length <= 0)
			moveRight();
	});
	$("#validate-school").click(function(){
		$this = $("#school");
		if($this.find("#school-attend-school").prop("checked")){
			validateSelect($this.find("#school-school"));
		}
		validateLength($this.find("#school-city"));
		validateLength($this.find("#school-zip"));
		validateSelect($this.find("#school-state"));
		validateSelect($this.find("#school-country"));
		if($this.find("#school-travel-yes").prop("checked")){
			validateLength($this.find("#school-venmo"));
		}

		if($this.find(".error").length <= 0)
			moveRight();
	});
	$("#validate-diet, #anon-surv").click(function(){
		moveRight();
	});
	$("#validate-resume").click(function(){
		if($("#resume-button-shadow").attr("data-done") == undefined){
			$this = $("#resume");
			var resume = $this.find("#resume-button-shadow");
			if(resume.val().length <= 0){
				resume.addClass("error");
				$("#resume-button").addClass("error");
			}
			if($this.find(".error").length <= 0)
				moveRight();
		}else
			moveRight()
	});

	$("form").on("change", ".error", function (){
		$(this).removeClass("error");
		if($(this).attr("type") == "file")
			$("#resume-button").removeClass("error");
	});
	$("textarea").change(function (){
		var id = $(this).attr("id");
		var text = $(this).val();
		$("#"+id+"-shadow").val(text);
	});
	$("#footerTable td").click(function(){
		document.location = $($(this).children()[0]).attr("href");
	});
	$("#application").submit(function (e){
		e.preventDefault();

		var data = new FormData();
		$.each($("#application input, #application select"), function(index, obj){
			console.log($(obj).attr("type"), $(obj).attr("name"), $(obj).val())

			if( !($(obj).is("select")) && $(obj).attr("type") == "checkbox"){
				data.append($(obj).attr("name"), $(obj).prop("checked"))
			}else{
				data.append($(obj).attr("name"), $(obj).val());
			}
		});
		data.append("travel", $('input[name=travel]:checked').val());

		if(resume == undefined)
			data.append("resume", $("#resume-button-shadow").attr("data-done"));
		else
			data.append("resume", resume);

		var purl = $(this).attr("Action");
		$.ajax({
			url:purl,
			type:"POST",
			data:data,
			dataType:"json",
			processData: false,
			contentType: false,
			beforeSend:function (){
				$("button").attr("disabled", "disabled");
			},
			success:function (result){
				if(result.success == true){
					moveRight();
				}
			},
			error: function(error){
				$("button").removeAttr("disabled", "disabled");
			},
			complete: function(a){
				$("button").removeAttr("disabled", "disabled");
			}
		})
	});
	$("#anon").submit(function (e){
		e.preventDefault();
		$.ajax({
			url:"/users/anon",
			type:"POST",
			data:$(this).serialize(),
			dataType:"json",
			beforeSend:function (){
				$("button").attr("disabled", "disabled");
			},
			success:function (result){
				if(result.success == true){
					moveRight();
				}
			},
			error: function(error){
				if(error.responseJSON.error == "exists"){

				}
			},
			complete: function(a){
				$("button").removeAttr("disabled", "disabled");
			}
		})
	});

});<commit_msg>add navigate previous functionality<commit_after>var showing = 0;
var shades;
var resume;
var orderArr = [
	[0,1,2,3,4,5,6,7,8],
	[1,0,1,2,3,4,5,6,7],
	[2,1,0,1,2,3,4,5,6],
	[3,2,1,0,1,2,3,4,5],
	[4,3,2,1,0,1,2,3,4],
	[5,4,3,2,1,0,1,2,3],
	[6,5,4,3,2,1,0,1,2],
	[7,6,5,4,3,2,1,0,1],
	[8,7,6,5,4,3,2,1,0]
];

var sections = ["general", "school", "diet", "resume", "hacker", "success"];
var currentSection = 0;

var align = function(){
	$.each(paras, function(index, obj){
		var top = $(shades[showing+1]).scrollTop();
		top *= (index+1)*0.5;
		$(obj).css({"top":-top});
	});
}
var order = function(){
    // Hide things that aren't the current section.
    for (var i = 0; i <= sections.length; i++) {
        if (i !== currentSection) {
            $('#' + sections[i]).css({"display" : "none"});
        } else {
            $('#' + sections[i]).css({"display": "block"});
        }
    }

    return;
    // Old code below...

	$.each(shades, function(index, obj){
		index -= 1;
		var left, zindex, opacity;

		if($(obj).attr("id") == "footerInner"){
			zindex = -2000;
			opacity = 1;
			if( $(window).width() < 1000 ){
				left = "0px";
			}else{
				left = $(window).width()/2 - $(obj).width()/2 + "px"
			}
		}else{
			zindex = orderArr[showing][index];
			opacity = zindex/5;
			opacity = 1 - opacity;
			if( $(window).width() < 1000 ){
				left = "0px";
			}else{
				left = $(window).width()/2 - $(obj).width()/2;
				left += 40*(index-showing);
				left += "px";
			}
		}

		$(obj).css({"left":left, "z-index":1000-zindex, "opacity":opacity });
	});
	align();
}
$(document).ready(function(){
	shades = $(".inner");
	paras = $(".parallax");
	order();
	$(window).resize(order);
	$.each(shades, function(index, obj){
		$(obj).on("scroll", function(){
			if(index-1 == showing){
				align();
			}
		});
	});
	$(".inner").show(0);
	var moveRight = function(){

        currentSection++;
        order();
        return;
        // Old code below...

		showing = (showing+1) % shades.length;
		order();
	};
    var moveLeft = function(){

        currentSection--;
        currentSection = currentSection < 0 ? 0 : currentSection;

        order();
        return;
    };

    $(".previous").click(function(){
		moveLeft();
	});
	$("#school-attend-school").change(function (){
		$("#school-selector").slideToggle();
		$("#school-school").removeClass("error");
	});
	$("input[name='travel']:radio").change(function () {
		$("#venmo").slideToggle();
		$("#school-venmo").removeClass("error");
	});
	$("#hacker-plan-hardware").change(function (){
		$("#plan-hardware-on").slideToggle();
		$("#hacker-plan-hardware-on").removeClass("error");
	});
	$("#hacker-need-partner, #hacker-plan-mentor").change(function (){
		if( $("#hacker-need-partner").prop('checked')
		 || $("#hacker-plan-mentor").prop('checked') )
			$("#partner").slideDown();
		else{
			$("#partner").slideUp();
			$("#hacker-need-partner-skills").removeClass("error");
		}
	});
	$("#resume-button").click(function (){
		$("#resume-button-shadow").click();
	});
	$("#resume-button-shadow").change(function(e){
		$("#resume-button").find("div").text(e.target.files[0].name);
		resume = e.target.files[0];
		$("#resume-button").addClass("done");
	});
	var validateLength = function ($input){
		if($input.val().length <= 0)
			$input.addClass("error");
	}
	var validateSelect = function ($input){
		if($input.val() == null)
			$input.addClass("error");
	}
	$("#validate-general").click(function(){
		$this = $("#general");
		validateLength($this.find("#general-first-name"));
		validateLength($this.find("#general-last-name"));
		validateLength($this.find("#general-email"));
		var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    	if(!re.test($this.find("#general-email").val()))
			$this.find("#general-email").addClass("error");
		validateLength($this.find("#general-password"));
		validateSelect($this.find("#general-swag-size"));

		if($this.find(".error").length <= 0)
			moveRight();
	});
	$("#validate-school").click(function(){
		$this = $("#school");
		if($this.find("#school-attend-school").prop("checked")){
			validateSelect($this.find("#school-school"));
		}
		validateLength($this.find("#school-city"));
		validateLength($this.find("#school-zip"));
		validateSelect($this.find("#school-state"));
		validateSelect($this.find("#school-country"));
		if($this.find("#school-travel-yes").prop("checked")){
			validateLength($this.find("#school-venmo"));
		}

		if($this.find(".error").length <= 0)
			moveRight();
	});
	$("#validate-diet, #anon-surv").click(function(){
		moveRight();
	});
	$("#validate-resume").click(function(){
		if($("#resume-button-shadow").attr("data-done") == undefined){
			$this = $("#resume");
			var resume = $this.find("#resume-button-shadow");
			if(resume.val().length <= 0){
				resume.addClass("error");
				$("#resume-button").addClass("error");
			}
			if($this.find(".error").length <= 0)
				moveRight();
		}else
			moveRight()
	});

	$("form").on("change", ".error", function (){
		$(this).removeClass("error");
		if($(this).attr("type") == "file")
			$("#resume-button").removeClass("error");
	});
	$("textarea").change(function (){
		var id = $(this).attr("id");
		var text = $(this).val();
		$("#"+id+"-shadow").val(text);
	});
	$("#footerTable td").click(function(){
		document.location = $($(this).children()[0]).attr("href");
	});
	$("#application").submit(function (e){
		e.preventDefault();

		var data = new FormData();
		$.each($("#application input, #application select"), function(index, obj){
			console.log($(obj).attr("type"), $(obj).attr("name"), $(obj).val())

			if( !($(obj).is("select")) && $(obj).attr("type") == "checkbox"){
				data.append($(obj).attr("name"), $(obj).prop("checked"))
			}else{
				data.append($(obj).attr("name"), $(obj).val());
			}
		});
		data.append("travel", $('input[name=travel]:checked').val());

		if(resume == undefined)
			data.append("resume", $("#resume-button-shadow").attr("data-done"));
		else
			data.append("resume", resume);

		var purl = $(this).attr("Action");
		$.ajax({
			url:purl,
			type:"POST",
			data:data,
			dataType:"json",
			processData: false,
			contentType: false,
			beforeSend:function (){
				$("button").attr("disabled", "disabled");
			},
			success:function (result){
				if(result.success == true){
					moveRight();
				}
			},
			error: function(error){
				$("button").removeAttr("disabled", "disabled");
			},
			complete: function(a){
				$("button").removeAttr("disabled", "disabled");
			}
		})
	});
	$("#anon").submit(function (e){
		e.preventDefault();
		$.ajax({
			url:"/users/anon",
			type:"POST",
			data:$(this).serialize(),
			dataType:"json",
			beforeSend:function (){
				$("button").attr("disabled", "disabled");
			},
			success:function (result){
				if(result.success == true){
					moveRight();
				}
			},
			error: function(error){
				if(error.responseJSON.error == "exists"){

				}
			},
			complete: function(a){
				$("button").removeAttr("disabled", "disabled");
			}
		})
	});

});<|endoftext|>


<commit_before>$(document).ready(function () {
  bindListeners();
});

var bindListeners = function(){
  $("#url").on("submit", getWebsite)
  $("#start-button").on("click", runArticle)
  $("#pause").on("click", pressPause)
  $("#stop").on("click", pressStop)
}

var CreateSpeedReedObject = function(response){
  this.title = response["title"];
  this.text = response["text_array"];
  this.i = 0;
  this.pause = false;
}

var getWebsite = function(e){
  e.preventDefault();
  $.ajax({
    method: "post",
    url: "/websites",
    data: $(this).serialize(),
    dataType: 'json',
  }).done(function(response){
    speedReedObject = new CreateSpeedReedObject(response);
    addTitle(speedReedObject);
    $("#reading").removeClass("hidden");
    $("#website-input").addClass("hidden")
  })
}

var addTitle = function(speedReedObject){
 $("#title").html('Ready to Read "'+speedReedObject.title+'"?');
}

function intervalLoop(speedReedObject, speed){
  setInterval(function(){
    if ((speedReedObject.i <= speedReedObject.text.length) && (speedReedObject.pause != true)){
      $("#text-object").html(speedReedObject.text[speedReedObject.i++])
    } else setTimeout(function(){},1)
  }, speed);
}

function runArticle(){
  var speed = $('input[name=amountRange]').val()
  var WPM = 60000 / speed;
  $("#slider").addClass("hidden");
  $("#start-button").addClass("hidden")
  $("#pause").removeClass("hidden");
  $("#stop").removeClass("hidden")
  intervalLoop(speedReedObject, WPM);
  switchButton()
}

function pressPause(){
  speedReedObject.pause = !speedReedObject.pause;
  switchButton()
}

function switchButton(){
  if (speedReedObject.pause == false){
    $("#pause").html("Pause")
  }
  else{
    $("#pause").html("Resume")
  }
}

function clearObject(){
  speedReedObject.text = [];
  speedReedObject.title = [];
  speedReedObject.i = 0;
  speedReedObject.pause = false
}

function pressStop(){
  $(".amountRange").removeClass("hidden");
  $("#slider").removeClass("hidden");
  $("#start-button").removeClass("hidden")
  $("#stop").addClass("hidden")
  $("#pause").addClass("hidden")
  $("#reading").addClass("hidden");
  $(".panel-body").html("");
  $("#website-input").removeClass("hidden")
  switchButton();
  clearObject();
}
<commit_msg>Add final formatting touches to JS<commit_after>$(document).ready(function () {
  bindListeners();
});

function bindListeners(){
  $("#url").on("submit", getWebsite)
  $("#start-button").on("click", runArticle)
  $("#pause").on("click", pressPause)
  $("#stop").on("click", pressStop)
}

function CreateSpeedReedObject(response){
  this.title = response["title"];
  this.text = response["text_array"];
  this.i = 0;
  this.pause = false;
}

function getWebsite(e){
  e.preventDefault();
  $.ajax({
    method: "post",
    url: "/websites",
    data: $(this).serialize(),
    dataType: 'json',
  }).done(function(response){
    speedReedObject = new CreateSpeedReedObject(response);
    addTitle(speedReedObject);
    $("#reading").removeClass("hidden");
    $("#website-input").addClass("hidden")
  })
}

function addTitle(speedReedObject){
 $("#title").html('Ready to Read "'+speedReedObject.title+'"?');
}

function intervalLoop(speedReedObject, speed){
  setInterval(function(){
    if ((speedReedObject.i <= speedReedObject.text.length) && (speedReedObject.pause != true)){
      $("#text-object").html(speedReedObject.text[speedReedObject.i++])
    } else setTimeout(function(){},1)
  }, speed);
}

function runArticle(){
  var speed = $('input[name=amountRange]').val()
  var WPM = 60000 / speed;
  $("#slider").addClass("hidden");
  $("#start-button").addClass("hidden")
  $("#pause").removeClass("hidden");
  $("#stop").removeClass("hidden")
  intervalLoop(speedReedObject, WPM);
  switchButton()
}

function pressPause(){
  speedReedObject.pause = !speedReedObject.pause;
  switchButton()
}

function switchButton(){
  if (speedReedObject.pause == false){
    $("#pause").html("Pause")
  }
  else{
    $("#pause").html("Resume")
  }
}

function clearObject(){
  speedReedObject.text = [];
  speedReedObject.title = [];
  speedReedObject.i = 0;
  speedReedObject.pause = false;
  $("#text-object").html("");
}

function pressStop(){
  $(".amountRange").removeClass("hidden");
  $("#slider").removeClass("hidden");
  $("#start-button").removeClass("hidden")
  $("#stop").addClass("hidden")
  $("#pause").addClass("hidden")
  $("#reading").addClass("hidden");
  $(".panel-body").html("");
  $("#website-input").removeClass("hidden")
  switchButton();
  clearObject();
}
<|endoftext|>


<commit_before>$(document).ready(function() {
  var map; // declaring map globally for later
  var infowindow; // declaring globally for later
  var marker; // declaring globally for later
  navigator.geolocation.getCurrentPosition(initialize);
  // finds user's current position and creates map and marker showing them
  $('.search-form').on('submit', function(e){
    addNewMarker(e);
  });

  $('#friend-list').on('click', ".delete", function(e) {
    deleteFriend(e);
  });

  // click listener for info window
});

function initialize(location) {
  // Create the map
  createMapWithUserMarker(location);
  // Initialize autocomplete form
  setUpAutocompleteForm();
  // Add database locations to map
  populateLocations();
};

// Adds marker to map (and saves friend to database) via AJAX form
function addNewMarker(e){
  e.preventDefault();

  var data = $(e.target).serialize();

  var request = $.ajax({
    type: 'POST',
    url: '/',
    data: data,
    dataType: 'json'
  });

  request.done(function(data){
    console.log("in addNewMarker done callback")
    console.log(data);
    // navigator.geolocation.getCurrentPosition(codeAddress);
    codeAddress(data);
    // Makes the new marker based on address in form submission
    $("#friend-list").append("

" + "" + data.name + "" + " in " + "" + data.location + "" + "
" + "<button>Delete</button>
");
    console.log("form should clear");
    clearFriendForm();
  });
}

function deleteFriend(e) {
  e.preventDefault();

  var id = e.target.closest('li').id;
  var friend = e.target.closest('li');
  console.log(id);
  console.log(friend);

  var request = $.ajax({
    type: 'delete',
    url: '/friends/' + id + "/delete"
  });

  request.done(function(data) {
    console.log("in done function")
    friend.remove();
  })
}

function clearFriendForm() {
  $('.search-form .friend').val("");
  $('.search-form #address').val("");
}

// Creates a initial map with marker location of current user
function createMapWithUserMarker(location){
  var currentLocation = new google.maps.LatLng(location.coords.latitude, location.coords.longitude)

  var mapCanvas = document.getElementById('map-canvas');

  var mapOptions = {
    center: currentLocation,
    zoom: 3,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }

  map = new google.maps.Map(mapCanvas, mapOptions);

  var marker = new google.maps.Marker({
    position: currentLocation,
    map: map,
    title: "You are here"
  });

  var infowindow = new google.maps.InfoWindow({
    content: "Hey Username!" // Add user information here
  });

  google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map, marker);
    setTimeout(function() {
        infowindow.close();
      }, 3000)
  });
}

// Defines search form based on Places library, biases LatLong bounds
function setUpAutocompleteForm(){
  var defaultBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(33.695441, -117.805632),
    new google.maps.LatLng(45.250434, -69.377900));

  var options = {
    bounds: defaultBounds,
    types: ['(cities)']
  };

  var input = document.getElementById('address');

  var autocomplete = new google.maps.places.Autocomplete(input, options);

  function fillInAddress() {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();

  for (var component in componentForm) {
    document.getElementById(component).value = '';
    document.getElementById(component).disabled = false;
  }

    // Get each component of the address from the place details
    // and fill the corresponding field on the form.
    for (var i = 0; i < place.address_components.length; i++) {
      var addressType = place.address_components[i].types[0];
      if (componentForm[addressType]) {
        var val = place.address_components[i][componentForm[addressType]];
        document.getElementById(addressType).value = val;
      }
    }
  }
}

// Used in addNewMarker AJAX call
var codeAddress = function(data) {
  // var address = document.getElementById("address").value;
  // console.log(address)
  console.log("in codeAddress before geoCode")
  console.log(data)
  geoCode(data);
}

// Used in populateLocations AJAX call
var addMarkerFromDatabase = function(data) {
  console.log("in addMarkerFromDatabase before geoCode")
  geoCode(data);
}

// Finds LatLong of provided address and makes a marker at that location
var geoCode = function(data) {
  console.log("in geoCode")
  console.log(data);
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode( { 'address': data.location }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location,
        title: data.name
      });
    } else {
      alert("Geocode was not successful for the following reason: " + status);
    }

    var infowindow = new google.maps.InfoWindow({
      // content: data.name // Add user info with HTML action
      content: "

" + data.name +"

"
    });

    google.maps.event.addListener(marker, 'click', function() {
      infowindow.open(map,marker);
      setTimeout(function() {
        infowindow.close();
      }, 3000)
    });
  });
}

// gets all locations from server
function populateLocations() {
  var request = $.ajax({
    type: 'GET',
    url: '/locations'
  });

  request.done(function(data){
    for (var i = 0; i < data.length; i++) {
      console.log(data);
      addMarkerFromDatabase(data[i]);

      // $("#friend-list").append("

" + "" + data[i].name + "" + " in " + "" + data[i].location + "" + "
" + "<button>Delete</button>
"
        // );

    };
  });

  request.error(function(response){
    console.log("errors retrieving or processing data from server", response);
  });
}

// makes an infowindow
// function createInfoWindow(data) {
//   var infoToDisplay = data.name + " in " + data.location
//   infoWindowOptions = {
//     content: infoToDisplay
//   }
//   var infowindow = new google.maps.InfoWindow(infoWindowOptions)
//   return infowindow
// }

// adds listener to marker
// function addInfoWindowListener(marker, infowindow) {
//   var marker = marker
//   console.log(marker); // undefined
//   google.maps.event.addListener(map, 'click', function() {
//     showInfoWindow(infowindow, marker);
//   });
// }

// // calls infowindow.open
// function showInfoWindow(infowindow, marker) {
//   infowindow.open(map,marker);
// }
<commit_msg>fix append id on list item<commit_after>$(document).ready(function() {
  var map; // declaring map globally for later
  var infowindow; // declaring globally for later
  var marker; // declaring globally for later
  navigator.geolocation.getCurrentPosition(initialize);
  // finds user's current position and creates map and marker showing them
  $('.search-form').on('submit', function(e){
    addNewMarker(e);
  });

  $('#friend-list').on('click', ".delete", function(e) {
    deleteFriend(e);
  });

  // click listener for info window
});

function initialize(location) {
  // Create the map
  createMapWithUserMarker(location);
  // Initialize autocomplete form
  setUpAutocompleteForm();
  // Add database locations to map
  populateLocations();
};

// Adds marker to map (and saves friend to database) via AJAX form
function addNewMarker(e){
  e.preventDefault();

  var data = $(e.target).serialize();

  var request = $.ajax({
    type: 'POST',
    url: '/',
    data: data,
    dataType: 'json'
  });

  request.done(function(data){
    console.log("in addNewMarker done callback")
    console.log(data);
    // navigator.geolocation.getCurrentPosition(codeAddress);
    codeAddress(data);
    // Makes the new marker based on address in form submission
    $("#friend-list").append("

" + "" + data.name + "" + " in " + "" + data.location + "" + "
" + "<button><a class='delete' href=/friend/" + data.id + "</delete>Delete</button>
");
    console.log("form should clear");
    clearFriendForm();
  });
}

function deleteFriend(e) {
  e.preventDefault();

  var id = e.target.closest('li').id;
  var friend = e.target.closest('li');
  console.log(id);
  console.log(friend);

  var request = $.ajax({
    type: 'delete',
    url: '/friends/' + id + "/delete"
  });

  request.done(function(data) {
    console.log("in done function")
    friend.remove();
  })
}

function clearFriendForm() {
  $('.search-form .friend').val("");
  $('.search-form #address').val("");
}

// Creates a initial map with marker location of current user
function createMapWithUserMarker(location){
  var currentLocation = new google.maps.LatLng(location.coords.latitude, location.coords.longitude)

  var mapCanvas = document.getElementById('map-canvas');

  var mapOptions = {
    center: currentLocation,
    zoom: 3,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }

  map = new google.maps.Map(mapCanvas, mapOptions);

  var marker = new google.maps.Marker({
    position: currentLocation,
    map: map,
    title: "You are here"
  });

  var infowindow = new google.maps.InfoWindow({
    content: "Hey Username!" // Add user information here
  });

  google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map, marker);
    setTimeout(function() {
        infowindow.close();
      }, 3000)
  });
}

// Defines search form based on Places library, biases LatLong bounds
function setUpAutocompleteForm(){
  var defaultBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(33.695441, -117.805632),
    new google.maps.LatLng(45.250434, -69.377900));

  var options = {
    bounds: defaultBounds,
    types: ['(cities)']
  };

  var input = document.getElementById('address');

  var autocomplete = new google.maps.places.Autocomplete(input, options);

  function fillInAddress() {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();

  for (var component in componentForm) {
    document.getElementById(component).value = '';
    document.getElementById(component).disabled = false;
  }

    // Get each component of the address from the place details
    // and fill the corresponding field on the form.
    for (var i = 0; i < place.address_components.length; i++) {
      var addressType = place.address_components[i].types[0];
      if (componentForm[addressType]) {
        var val = place.address_components[i][componentForm[addressType]];
        document.getElementById(addressType).value = val;
      }
    }
  }
}

// Used in addNewMarker AJAX call
var codeAddress = function(data) {
  // var address = document.getElementById("address").value;
  // console.log(address)
  console.log("in codeAddress before geoCode")
  console.log(data)
  geoCode(data);
}

// Used in populateLocations AJAX call
var addMarkerFromDatabase = function(data) {
  console.log("in addMarkerFromDatabase before geoCode")
  geoCode(data);
}

// Finds LatLong of provided address and makes a marker at that location
var geoCode = function(data) {
  console.log("in geoCode")
  console.log(data);
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode( { 'address': data.location }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location,
        title: data.name
      });
    } else {
      alert("Geocode was not successful for the following reason: " + status);
    }

    var infowindow = new google.maps.InfoWindow({
      // content: data.name // Add user info with HTML action
      content: "

" + data.name +"

"
    });

    google.maps.event.addListener(marker, 'click', function() {
      infowindow.open(map,marker);
      setTimeout(function() {
        infowindow.close();
      }, 3000)
    });
  });
}

// gets all locations from server
function populateLocations() {
  var request = $.ajax({
    type: 'GET',
    url: '/locations'
  });

  request.done(function(data){
    for (var i = 0; i < data.length; i++) {
      console.log(data);
      addMarkerFromDatabase(data[i]);

      // $("#friend-list").append("

" + "" + data[i].name + "" + " in " + "" + data[i].location + "" + "
" + "<button>Delete</button>
"
        // );

    };
  });

  request.error(function(response){
    console.log("errors retrieving or processing data from server", response);
  });
}

// makes an infowindow
// function createInfoWindow(data) {
//   var infoToDisplay = data.name + " in " + data.location
//   infoWindowOptions = {
//     content: infoToDisplay
//   }
//   var infowindow = new google.maps.InfoWindow(infoWindowOptions)
//   return infowindow
// }

// adds listener to marker
// function addInfoWindowListener(marker, infowindow) {
//   var marker = marker
//   console.log(marker); // undefined
//   google.maps.event.addListener(map, 'click', function() {
//     showInfoWindow(infowindow, marker);
//   });
// }

// // calls infowindow.open
// function showInfoWindow(infowindow, marker) {
//   infowindow.open(map,marker);
// }
<|endoftext|>


<commit_before>(function($){
    $.fn.disableSelection = function() {
        return this
                 .attr('unselectable', 'on')
                 .css('user-select', 'none')
                 .on('selectstart', false);
    };
})(jQuery);

$(document).ready(function () {
	var canvas = $('canvas')[0],
		ctx = canvas.getContext('2d'),
		h = window.innerHeight - 60,
		w = window.innerWidth,
		balls = [],
		bugs = [],
		bullets = 20,
		level = 1,
		curAngle = 45,
		cannon = {
			angle: degToRad(curAngle),
			x0: 40,
			y0: h - 20,
			power: 0.4
		},
		time_interval = 30,
		acceleration = 0.0001,

		levels = [
		{
			num_bugs: 3,
			bullets: 20,
			radius: 30
		},
		{
			num_bugs: 3,
			bullets: 20,
			radius: 20
		},
		{
			num_bugs: 5,
			bullets: 20,
			radius: 15		},
		{
			num_bugs: 8,
			bullets: 20,
			radius: 20		},
		{
			num_bugs: 5,
			bullets: 15,
			radius: 15		},
		{
			num_bugs: 3,
			bullets: 15,
			radius: 20		},
		{
			num_bugs: 3,
			bullets: 10,
			radius: 10		},
		{
			num_bugs: 5,
			bullets: 10,
			radius: 10		},
		{
			num_bugs: 3,
			bullets: 10,
			radius: 10		},
		{
			num_bugs: 3,
			bullets: 10,
			radius: 7		},
		{
			num_bugs: 3,
			bullets: 5,
			radius: 7
		}
		];

	canvas.height = h;
	canvas.width = w;

	function degToRad(deg) {
		return deg * Math.PI / 180;
	}

	function paintScreen() {
		ctx.clearRect(0, 0, w, h);

		drawCannon();
		drawBalls();
		drawBugs();
		checkKills();
		updateStats();

		setTimeout(paintScreen, 30);
	}

	function updateCannon() {
		cannon.x = 80 * Math.sin(cannon.angle);
		cannon.y = 80 * Math.cos(cannon.angle);
	}

	function drawCannon () {
		ctx.fillStyle = '#34def5'
		ctx.strokeStyle = '#0898ab'
		ctx.beginPath();
		ctx.lineWidth = 40;
		ctx.moveTo(cannon.x0, cannon.y0);
		ctx.lineTo(cannon.x0 + cannon.x , cannon.y0 - cannon.y);
		ctx.stroke();
		ctx.closePath();

		ctx.beginPath();
		ctx.arc(cannon.x0, cannon.y0, 20, 0, 2 * Math.PI);
		ctx.fill();
		ctx.closePath();

		updateCannon();
	}

	function Ball(x, y, angle, v0) {
		this.x = x;
		this.y = y;
		this.x0 = x;
		this.y0 = y;
		this.v0 = v0;
		this.angle = angle;
		this.time = 0;
		this.r = 5;
	};

	function drawBalls() {
		ctx.fillStyle = '#e61c23'
		_.each(balls, function (ball) {
			ctx.beginPath();
			ctx.arc(ball.x, ball.y, ball.r, 0, 2 * Math.PI);
			ctx.fill();
			ctx.closePath();
		});
		evolveBalls();
	};

	function evolveBalls() {
		_.each(balls, function (ball) {
			var v0x = ball.v0 * Math.sin(ball.angle);
			var v0y = ball.v0 * Math.cos(ball.angle);

			ball.time += time_interval;

			ball.x = ball.x0 + v0x * ball.time;
			ball.y = ball.y0 - v0y * ball.time + acceleration * Math.pow(ball.time, 2);

			if (ball.y > h + ball.r) {
				balls.splice(ball, 1);
			}
		});
	};

	function checkKills() {
		_.each(balls, function (ball) {
			_.each(bugs, function (bug, i) {
				if (ball.x + ball.r >= bug.x - bug.r && ball.x - ball.r <= bug.x + bug.r && ball.y + ball.r >= bug.y - bug.r && ball.y - ball.r <= bug.y + bug.r ) {
					bugs.splice(i, 1);

					if (bugs.length == 0) {
						if (level < 10) {
							level++;

							setLevel();
							$('.level_up').text('Next Level: ' + level);
							$('.level_up').show();

							setTimeout(function () {
								$('.level_up').fadeOut('700');
							}, 800);
						} else {
						$('.win').show();
						}
					}
				}
			});
		});

		if (bullets == 0 && bugs.length != 0 && balls.length == 0) {
			$('.game_over').show();
		}
	};

	function setLevel() {
		for (var i = 0; i < levels[level].num_bugs; i++) {
			bugs.push(new Bug(levels[level].radius));
		}
		balls = []
		bullets = levels[level].bullets;
	};

	function Bug(radius) {
		this.x = Math.random() * (w - radius*2) + radius;
		this.y = Math.random() * (h - radius*2) + radius;
		this.r = radius;
	};

	function drawBugs() {
		_.each(bugs, function (bug) {
			ctx.fillStyle = '#172729';
			ctx.beginPath();
			ctx.arc(bug.x, bug.y, bug.r, 0, 2 * Math.PI);
			ctx.fill();
			ctx.closePath();

			ctx.beginPath();
			ctx.lineWidth = 3;
			ctx.moveTo(bug.x, bug.y);
			ctx.lineTo(bug.x + bug.r*1.75, bug.y);
			ctx.moveTo(bug.x, bug.y);
			ctx.lineTo(bug.x - bug.r*1.75, bug.y);

			ctx.moveTo(bug.x, bug.y);
			ctx.lineTo(bug.x + bug.r*1.75, bug.y + bug.r * 0.65);
			ctx.moveTo(bug.x, bug.y);
			ctx.lineTo(bug.x - bug.r*1.75, bug.y + bug.r * 0.65);

			ctx.moveTo(bug.x, bug.y);
			ctx.lineTo(bug.x + bug.r*1.75, bug.y - bug.r * 0.65);
			ctx.moveTo(bug.x, bug.y);
			ctx.lineTo(bug.x - bug.r*1.75, bug.y - bug.r * 0.65);
			ctx.strokeStyle = '#172729';
			ctx.stroke();
			ctx.closePath();

			ctx.beginPath();
			ctx.fillStyle = 'white'
			ctx.arc(bug.x + bug.r*0.4, bug.y + bug.r*0.5, bug.r * 0.2, 0, 2 * Math.PI);
			ctx.arc(bug.x - bug.r*0.4, bug.y + bug.r*0.5, bug.r * 0.2, 0, 2 * Math.PI);
			ctx.fill();
			ctx.closePath();
		});
	};

	function updateStats() {
		$('.power').text('Power Level: ' + Math.round(cannon.power * 100));
		$('.bullets').text('Bullets: ' + bullets);
		$('.level_stat').text('Level: ' + level);
	};

	$('#start').on('click', function () {
		setLevel();
		$('.info').fadeOut('fast');
		paintScreen();
	});

	$(document).on('keydown', function (e) {
		if (e.keyCode == 32 && bullets != 0) {
			balls.push(new Ball(cannon.x0 + cannon.x , cannon.y0 - cannon.y, cannon.angle, cannon.power));
			bullets--;
		}

		if (e.keyCode == 38) {
			cannon.angle -= degToRad(2);
		}

		if (e.keyCode == 40) {
			cannon.angle += degToRad(2);
		}

		if (e.keyCode == 37) {
			cannon.power -= 0.02;
			if (cannon.power <= 0) {
				cannon.power = 0;
			}
		}

		if (e.keyCode == 39) {
			cannon.power += 0.02;
			if (cannon.power >= 100) {
				cannon.power = 100;
			}
		}

	});

	$('body').disableSelection();

});
<commit_msg>bug fix<commit_after>(function($){
    $.fn.disableSelection = function() {
        return this
                 .attr('unselectable', 'on')
                 .css('user-select', 'none')
                 .on('selectstart', false);
    };
})(jQuery);

$(document).ready(function () {
	var canvas = $('canvas')[0],
		ctx = canvas.getContext('2d'),
		h = window.innerHeight - 60,
		w = window.innerWidth,
		balls = [],
		bugs = [],
		bullets = 20,
		level = 1,
		curAngle = 45,
		cannon = {
			angle: degToRad(curAngle),
			x0: 40,
			y0: h - 20,
			power: 0.4
		},
		time_interval = 30,
		acceleration = 0.0001,

		levels = [
		{
			num_bugs: 3,
			bullets: 20,
			radius: 30
		},
		{
			num_bugs: 3,
			bullets: 20,
			radius: 20
		},
		{
			num_bugs: 5,
			bullets: 20,
			radius: 15		},
		{
			num_bugs: 8,
			bullets: 20,
			radius: 20		},
		{
			num_bugs: 5,
			bullets: 15,
			radius: 15		},
		{
			num_bugs: 3,
			bullets: 15,
			radius: 20		},
		{
			num_bugs: 3,
			bullets: 10,
			radius: 10		},
		{
			num_bugs: 5,
			bullets: 10,
			radius: 10		},
		{
			num_bugs: 3,
			bullets: 10,
			radius: 10		},
		{
			num_bugs: 3,
			bullets: 10,
			radius: 7		},
		{
			num_bugs: 3,
			bullets: 5,
			radius: 7
		}
		];

	canvas.height = h;
	canvas.width = w;

	function degToRad(deg) {
		return deg * Math.PI / 180;
	}

	function paintScreen() {
		ctx.clearRect(0, 0, w, h);

		drawCannon();
		drawBalls();
		drawBugs();
		checkKills();
		updateStats();

		setTimeout(paintScreen, 30);
	}

	function updateCannon() {
		cannon.x = 80 * Math.sin(cannon.angle);
		cannon.y = 80 * Math.cos(cannon.angle);
	}

	function drawCannon () {
		ctx.fillStyle = '#34def5'
		ctx.strokeStyle = '#0898ab'
		ctx.beginPath();
		ctx.lineWidth = 40;
		ctx.moveTo(cannon.x0, cannon.y0);
		ctx.lineTo(cannon.x0 + cannon.x , cannon.y0 - cannon.y);
		ctx.stroke();
		ctx.closePath();

		ctx.beginPath();
		ctx.arc(cannon.x0, cannon.y0, 20, 0, 2 * Math.PI);
		ctx.fill();
		ctx.closePath();

		updateCannon();
	}

	function Ball(x, y, angle, v0) {
		this.x = x;
		this.y = y;
		this.x0 = x;
		this.y0 = y;
		this.v0 = v0;
		this.angle = angle;
		this.time = 0;
		this.r = 5;
	};

	function drawBalls() {
		ctx.fillStyle = '#e61c23'
		_.each(balls, function (ball) {
			ctx.beginPath();
			ctx.arc(ball.x, ball.y, ball.r, 0, 2 * Math.PI);
			ctx.fill();
			ctx.closePath();
		});
		evolveBalls();
	};

	function evolveBalls() {
		_.each(balls, function (ball) {
			var v0x = ball.v0 * Math.sin(ball.angle);
			var v0y = ball.v0 * Math.cos(ball.angle);

			ball.time += time_interval;

			ball.x = ball.x0 + v0x * ball.time;
			ball.y = ball.y0 - v0y * ball.time + acceleration * Math.pow(ball.time, 2);

			if (ball.y > h + ball.r) {
				balls.splice(ball, 1);
			}
		});
	};

	function checkKills() {
		_.each(balls, function (ball) {
			_.each(bugs, function (bug, i) {
				if (ball.x + ball.r >= bug.x - bug.r && ball.x - ball.r <= bug.x + bug.r && ball.y + ball.r >= bug.y - bug.r && ball.y - ball.r <= bug.y + bug.r ) {
					bugs.splice(i, 1);

					if (bugs.length == 0) {
						if (level < 10) {
							level++;

							setLevel();
							$('.level_up').text('Next Level: ' + level);
							$('.level_up').show();

							setTimeout(function () {
								$('.level_up').fadeOut('700');
							}, 800);
						} else {
						$('.win').show();
						}
					}
				}
			});
		});

		if (bullets == 0 && bugs.length != 0 && balls.length == 0) {
			$('.game_over').show();
		}
	};

	function setLevel() {
		for (var i = 0; i < levels[level].num_bugs; i++) {
			bugs.push(new Bug(levels[level].radius));
		}
		balls = []
		bullets = levels[level].bullets;
	};

	function Bug(radius) {
		this.x = Math.random() * (w - radius*2) + radius;
		this.y = Math.random() * (h - radius*2) + radius;
		this.r = radius;
	};

	function drawBugs() {
		_.each(bugs, function (bug) {
			ctx.fillStyle = '#172729';
			ctx.beginPath();
			ctx.arc(bug.x, bug.y, bug.r, 0, 2 * Math.PI);
			ctx.fill();
			ctx.closePath();

			ctx.beginPath();
			ctx.lineWidth = 3;
			ctx.moveTo(bug.x, bug.y);
			ctx.lineTo(bug.x + bug.r*1.75, bug.y);
			ctx.moveTo(bug.x, bug.y);
			ctx.lineTo(bug.x - bug.r*1.75, bug.y);

			ctx.moveTo(bug.x, bug.y);
			ctx.lineTo(bug.x + bug.r*1.75, bug.y + bug.r * 0.65);
			ctx.moveTo(bug.x, bug.y);
			ctx.lineTo(bug.x - bug.r*1.75, bug.y + bug.r * 0.65);

			ctx.moveTo(bug.x, bug.y);
			ctx.lineTo(bug.x + bug.r*1.75, bug.y - bug.r * 0.65);
			ctx.moveTo(bug.x, bug.y);
			ctx.lineTo(bug.x - bug.r*1.75, bug.y - bug.r * 0.65);
			ctx.strokeStyle = '#172729';
			ctx.stroke();
			ctx.closePath();

			ctx.beginPath();
			ctx.fillStyle = 'white'
			ctx.arc(bug.x + bug.r*0.4, bug.y + bug.r*0.5, bug.r * 0.2, 0, 2 * Math.PI);
			ctx.arc(bug.x - bug.r*0.4, bug.y + bug.r*0.5, bug.r * 0.2, 0, 2 * Math.PI);
			ctx.fill();
			ctx.closePath();
		});
	};

	function updateStats() {
		$('.power').text('Power Level: ' + Math.round(cannon.power * 100));
		$('.bullets').text('Bullets: ' + bullets);
		$('.level_stat').text('Level: ' + level);
	};

	$('#start').on('click', function () {
		setLevel();
		$('.info').fadeOut('fast');
		paintScreen();
	});

	$(document).on('keydown', function (e) {
		if (e.keyCode == 32 && bullets != 0) {
			balls.push(new Ball(cannon.x0 + cannon.x , cannon.y0 - cannon.y, cannon.angle, cannon.power));
			bullets--;
		}

		if (e.keyCode == 38) {
			cannon.angle -= degToRad(2);
		}

		if (e.keyCode == 40) {
			cannon.angle += degToRad(2);
		}

		if (e.keyCode == 37) {
			cannon.power -= 0.02;
			if (cannon.power <= 0) {
				cannon.power = 0;
			}
		}

		if (e.keyCode == 39) {
			cannon.power += 0.02;
			if (cannon.power >= 1) {
				cannon.power = 1;
			}
		}

	});

	$('body').disableSelection();

});
<|endoftext|>


<commit_before>
import CONST from '../const';
import currentLocale from 'current-locale';
import langs from 'langs';
import format from 'math.format';

export default class Locale {
    static getLocale() {
        let locale = currentLocale({ fallbackLocale: 'en' }).substr(0, 2);

        if (CONST.availableLocales.indexOf(locale) === -1) {
            locale = 'en';
        }

        return locale;
    }

    static buildLocalesCompletion(themeModel) {
        const localesCompletion = [];

        for (const localeCode of CONST.availableLocales) {
            const isoInfos = langs.where('1', localeCode);

            const layers = themeModel.get('layers');
            const presets = themeModel.get('presets');
            const presetCategories = themeModel.get('presetCategories');
            const tags = themeModel.get('tags');

            const localeCompletions = [
                themeModel.getLocaleCompletion(localeCode),
                Locale._buildLocaleCompletionFromCollection(layers, localeCode),
                Locale._buildLocaleCompletionFromCollection(presets, localeCode),
                Locale._buildLocaleCompletionFromCollection(presetCategories, localeCode),
                Locale._buildLocaleCompletionFromCollection(tags, localeCode),
            ];

            /* eslint-disable no-unused-vars */
            let itemsCount = 0;
            let completedItemsCount = 0;
            /* eslint-enable */
            for (const localeCompletion of localeCompletions) {
                itemsCount += localeCompletion.items;
                completedItemsCount += localeCompletion.completed;
            }

            const totalCompletion = format(
                (completedItemsCount / itemsCount) * 100,
                {
                    floor: 1,
                    ifInfinity: 0,
                }
            );

            localesCompletion.push({
                code: localeCode,
                label: isoInfos.name,
                description: isoInfos.local,
                completion: totalCompletion,
            });
        }

        return localesCompletion;
    }

    static buildItemsLocaleCompletion(themeModel, localeCode) {
        const layers = themeModel.get('layers');
        const presets = themeModel.get('presets');
        const presetCategories = themeModel.get('presetCategories');
        const tags = themeModel.get('tags');

        const presetData = Locale._buildLocaleCompletionFromCollection(presets, localeCode);
        const categoriesData = Locale._buildLocaleCompletionFromCollection(
            presetCategories,
            localeCode
        );

        const localesCompletion = [
            {
                id: 'theme',
                label: document.l10n.getSync('mainSettings'),
                data: themeModel.getLocaleCompletion(localeCode),
            },
            {
                id: 'layer',
                label: document.l10n.getSync('layers'),
                data: Locale._buildLocaleCompletionFromCollection(layers, localeCode),
            },
            {
                id: 'tag',
                label: document.l10n.getSync('tags'),
                data: Locale._buildLocaleCompletionFromCollection(tags, localeCode),
            },
            {
                id: 'preset',
                label: document.l10n.getSync('presets'),
                data: {
                    items: presetData.items + categoriesData.items,
                    completed: presetData.completed + categoriesData.completed,
                },
            },
        ];

        for (const locale of localesCompletion) {
            locale.completion = format(
                (locale.data.completed / locale.data.items) * 100,
                {
                    floor: 1,
                    ifInfinity: 0,
                }
            );
        }

        return localesCompletion;
    }

    static _buildLocaleCompletionFromCollection(collection, localeCode) {
        const data = {
            items: 0,
            completed: 0,
        };

        for (const model of collection.models) {
            const { items, completed } = model.getLocaleCompletion(localeCode);

            data.items += items;
            data.completed += completed;
        }

        return data;
    }

    static getLocalized(model, attributeName) {
        const locale = Locale.getLocale();
        const modelLocales = model.get('locales');

        if (!modelLocales || !modelLocales[locale]) {
            return model.get(attributeName);
        }

        const attributes = modelLocales[locale];

        if (attributes && attributes[attributeName]) {
            return attributes[attributeName];
        }

        return model.get(attributeName);
    }

    static findLocalizedTagValue(customTags, key, optionName) {
        const options = Locale.findLocalizedOptions(customTags, key);

        return options[optionName] ? options[optionName] : optionName;
    }

    static findLocalizedOptions(customTags, key) {
        for (const customTag of customTags) {
            if (customTag.get('key') === key) {
                return Locale.getLocalizedOptions(customTag);
            }
        }

        return {};
    }

    static getLocalizedOptions(model) {
        const locale = Locale.getLocale();
        const options = model.get('options');
        const attributes = model.get('locales')[locale];
        let localizedOptions = {};

        if (attributes && attributes.options) {
            localizedOptions = attributes.options;
        }

        for (const option of options) {
            if (!localizedOptions[option]) {
                localizedOptions[option] = option;
            }
        }

        return localizedOptions;
    }
}
<commit_msg>Better return<commit_after>
import CONST from '../const';
import currentLocale from 'current-locale';
import langs from 'langs';
import format from 'math.format';

export default class Locale {
    static getLocale() {
        let locale = currentLocale({ fallbackLocale: 'en' }).substr(0, 2);

        if (CONST.availableLocales.indexOf(locale) === -1) {
            locale = 'en';
        }

        return locale;
    }

    static buildLocalesCompletion(themeModel) {
        const localesCompletion = [];

        for (const localeCode of CONST.availableLocales) {
            const isoInfos = langs.where('1', localeCode);

            const layers = themeModel.get('layers');
            const presets = themeModel.get('presets');
            const presetCategories = themeModel.get('presetCategories');
            const tags = themeModel.get('tags');

            const localeCompletions = [
                themeModel.getLocaleCompletion(localeCode),
                Locale._buildLocaleCompletionFromCollection(layers, localeCode),
                Locale._buildLocaleCompletionFromCollection(presets, localeCode),
                Locale._buildLocaleCompletionFromCollection(presetCategories, localeCode),
                Locale._buildLocaleCompletionFromCollection(tags, localeCode),
            ];

            /* eslint-disable no-unused-vars */
            let itemsCount = 0;
            let completedItemsCount = 0;
            /* eslint-enable */
            for (const localeCompletion of localeCompletions) {
                itemsCount += localeCompletion.items;
                completedItemsCount += localeCompletion.completed;
            }

            const totalCompletion = format(
                (completedItemsCount / itemsCount) * 100,
                {
                    floor: 1,
                    ifInfinity: 0,
                }
            );

            localesCompletion.push({
                code: localeCode,
                label: isoInfos.name,
                description: isoInfos.local,
                completion: totalCompletion,
            });
        }

        return localesCompletion;
    }

    static buildItemsLocaleCompletion(themeModel, localeCode) {
        const layers = themeModel.get('layers');
        const presets = themeModel.get('presets');
        const presetCategories = themeModel.get('presetCategories');
        const tags = themeModel.get('tags');

        const presetData = Locale._buildLocaleCompletionFromCollection(presets, localeCode);
        const categoriesData = Locale._buildLocaleCompletionFromCollection(
            presetCategories,
            localeCode
        );

        const localesCompletion = [
            {
                id: 'theme',
                label: document.l10n.getSync('mainSettings'),
                data: themeModel.getLocaleCompletion(localeCode),
            },
            {
                id: 'layer',
                label: document.l10n.getSync('layers'),
                data: Locale._buildLocaleCompletionFromCollection(layers, localeCode),
            },
            {
                id: 'tag',
                label: document.l10n.getSync('tags'),
                data: Locale._buildLocaleCompletionFromCollection(tags, localeCode),
            },
            {
                id: 'preset',
                label: document.l10n.getSync('presets'),
                data: {
                    items: presetData.items + categoriesData.items,
                    completed: presetData.completed + categoriesData.completed,
                },
            },
        ];

        for (const locale of localesCompletion) {
            locale.completion = format(
                (locale.data.completed / locale.data.items) * 100,
                {
                    floor: 1,
                    ifInfinity: 0,
                }
            );
        }

        return localesCompletion;
    }

    static _buildLocaleCompletionFromCollection(collection, localeCode) {
        const data = {
            items: 0,
            completed: 0,
        };

        for (const model of collection.models) {
            const { items, completed } = model.getLocaleCompletion(localeCode);

            data.items += items;
            data.completed += completed;
        }

        return data;
    }

    static getLocalized(model, attributeName) {
        const locale = Locale.getLocale();
        const modelLocales = model.get('locales');

        if (!modelLocales || !modelLocales[locale]) {
            return model.get(attributeName);
        }

        const attributes = modelLocales[locale];

        if (attributes && attributes[attributeName]) {
            return attributes[attributeName];
        }

        return model.get(attributeName);
    }

    static findLocalizedTagValue(customTags, key, optionName) {
        const options = Locale.findLocalizedOptions(customTags, key);

        return options[optionName] || optionName;
    }

    static findLocalizedOptions(customTags, key) {
        for (const customTag of customTags) {
            if (customTag.get('key') === key) {
                return Locale.getLocalizedOptions(customTag);
            }
        }

        return {};
    }

    static getLocalizedOptions(model) {
        const locale = Locale.getLocale();
        const options = model.get('options');
        const attributes = model.get('locales')[locale];
        let localizedOptions = {};

        if (attributes && attributes.options) {
            localizedOptions = attributes.options;
        }

        for (const option of options) {
            if (!localizedOptions[option]) {
                localizedOptions[option] = option;
            }
        }

        return localizedOptions;
    }
}
<|endoftext|>


<commit_before>if (typeof console == 'undefined') {
    window.console = {
        log: function (msg) {
            alert(msg);
        },
        dir: function () {}
    }
}

microXTag = (function ($) {
    function loadImports(importList, loaded) {
        var loadqueue = [];
        $.each(importList, function (index, importFile) {
            var componentPath = importFile.replace(/[^\/]*$/, '');
            function adjustPath(el, attr) {
                var src = el.getAttribute(attr);
                if (!/^\//.test(src)) {
                    el.setAttribute(attr, componentPath + src);
                }
            };
            $.get(importFile)
                .done(function (html) {
                    var $elements = $(html);
                    var $scripts = $elements.filter('script[src]');
                    $scripts.each(function (index, script) {
                        adjustPath(script, 'src');
                    });
                    var $links = $elements.filter('link[rel="stylesheet"]');
                    var $nonlinks = $elements.not('link[rel="stylesheet"]');
                    $links.each(function (index, link) {
                        adjustPath(link, 'href');
                    });
                    $('body').append($nonlinks);
                    $('head').append($links);
                    loadqueue[index] = true;
                    if (loadqueue.length == importList.length) {
                        for (var i = 0; i < loadqueue.length &&
                             loadqueue[i] == true; i++);
                        if (i >= loadqueue.length) {
                            loaded();
                        }
                    };
                })
            loadqueue[index] = false; // request has been made but response not received
        });
    };

    var registry = {};

    function register(componentName, templateID, config) {
        var name = componentName.toUpperCase();
        if (registry[name]) {
            var errorMsg = "component already registered with name " + componentName;
            console.log(errorMsg);
            return;
        }
        registry[name] = {
            config: config,
            elementList: [],
            fragment: getFragmentFromTemplate(templateID)
        }
    }

    function getComponent(name, el) {
        var regname = name.toUpperCase();
        var registryItem = registry[regname];
        if (typeof registryItem == 'undefined') {
            throw Error("no tag " + name + " registered");
        };
        var component = new mxtElement(regname, registryItem, el);
        registryItem.elementList.push(component);
        var config = component.registryListing.config;
        if (config.lifecycle && config.lifecycle.created) {
            config.lifecycle.created.apply(component);
        };

        return component;
    }

    function standUpTag(el) {
        var tagName = el.nodeName,
            mxt = getComponent(tagName, el);
            parentEl = el.parentNode;
        parentEl.replaceChild(mxt.el, el);
        triggerChildrenInserted(mxt.el);
        return mxt;
    }

    // micro-x-taggify the DOM elements passed in
    function standUpTags(tagList) {
        for (var i = 0, len = tagList.length; i < len; i++) {
            el = tagList[i];
            standUpTag(el);
        }
    }

    function mxtElement (name, registryListing, origElement) {
        this.registryListing = registryListing;
        var newElement = document.createElement(name);
        this.el = newElement;
        if (origElement) {
            var attrs = $(origElement).prop("attributes");
            $.each(attrs, function() {
                newElement.setAttribute(this.name, this.value);
            });
        }
        this.el.setAttribute('x-micro-tags', true);
        this.el.appendChild(this.registryListing.fragment.cloneNode(true));
        // Support the methods in the "methods" property of the config
        $.extend(this, registryListing.config.methods);
        this._microx = {
            accessorLookup: {}
        };
        var accessors = registryListing.config.accessors;
        if (accessors) {
            for (var name in accessors) {
                if (accessors[name].attribute) {
                    if (accessors[name].attribute.name) {
                        this._microx.accessorLookup[accessors[name].attribute.name] = accessors[name];
                    }
                }
            }
        }
        var childXTags = microXTag.query(this, '[x-micro-tags=true]');
        $.each(childXTags || [], function (index, el) {
            var c = microXTag.getComponent(el.nodeName, el);
            var p = el.parentNode;
            p.replaceChild(c.el, el);
        });
        this.xtag = {}; //ease backward compatibility
    };

    mxtElement.prototype = {
        appendTo: function (newParent) {
            newParent.appendChild(this.el);
            this.onInsert();
        },
        getElement: function () {
            return this.el;
        },
        onInsert: function () {
            var config = this.registryListing.config;
            if (config.lifecycle && config.lifecycle.inserted) {
                config.lifecycle.inserted.apply(this);
            };
            this._microx.inserted = true;
        },
        setAttribute: function (name, value) {
            //return;
            var accessor = this._microx.accessorLookup[name] || (function(accessors) {
                return accessors && accessors[name];
            })(this.registryListing.config.accessors);

            if (accessor && accessor.set) {
                accessor.set.call(this, value);
            }
            return this.el.setAttribute(name, value);
        },
        getAttribute: function (name) {
            //return "foo";
            var accessors = this.registryListing.config.accessors;
            if (accessors && accessors[name] && accessors[name].get) {
                console.log("Hey, we're using get accessor!");
                return accessors[name].get.call(this);
            } else {
                return this.el.getAttribute(name);
            }
        },
        addClass: function (classname) {
            $(this.el).addClass(classname);
        }
    };

    $.each(['getElementsByTagName'], function (index, methodName) {
        mxtElement.prototype[methodName] = function () {
            return this.el[methodName].apply(this.el, arguments);
        };
    });

    function getFragmentFromTemplate(templateID) {
        var text = $("#" + templateID).html();
        var div = document.createElement('div');
        div.innerHTML = text;
        var df = document.createDocumentFragment();
        while (div.firstChild) {
            df.appendChild(div.firstChild);
        }
        return df;
    };

    function queryNative(mxtag, selector) {
        return mxtag.el.querySelectorAll(selector);
    }

    function queryAssisted(mxtag, selector) {
        var $result = $(mxtag.el).find(selector);
        return $result.get();
    }

    // Append newEl to parent, the micro-xtag way
    function appendChild(parent, newItem) {
        var newNodeList = [],
            i, len, newEl;

        if (newItem._microx) {
            newEl = newItem.el;
        } else {
            newEl = newItem;
        }
        if (newEl.nodeName == "#document-fragment") {
            for (i = 0, len = newEl.childNodes.length; i < len; i++) {
                newNodeList.push(newEl.childNodes[i]);
            };
        } else {
            newNodeList = [newEl];
        }
        parent.appendChild(newEl);
        if (newItem._microx && newItem._microx.inserted == true) return;
        for (var i = 0, len = newNodeList.length; i < len; i++) {
            triggerChildrenInserted(newNodeList[i]);
        };
    }

    // given a tag name and a DOM element, look up the mxtElement
    // object that is the wrapper for the DOM element
    function getMxtFromElement(el) {
        var registryItem = registry[el.nodeName];
        if (!registryItem) {
            console.log("Expected a registered tag named " + el.nodeName);
            return null;
        };
        var list = registryItem.elementList;
        var item = null;
        for (var i = 0, len = list.length; i < len; i++) {
            if (list[i].el == el) {
                item =  list[i];
            }
        };
        if (item == null) {
            console.log("Warning: mxtElement for " + el.nodeName + " not found");
        };
        return item;
    }

    function getMxtById(doc, id) {
        if (arguments.length < 2) {
            id = doc;
            doc = document;
        }
        var el = doc.getElementById(id);
        return getMxtFromElement(el);
    };

    function triggerChildrenInserted(el) {
        if (el.getAttribute('x-micro-tags') == 'true') {
            var mxt = getMxtFromElement(el);
            if (mxt) {
                mxt.onInsert();
            } else {
                console.log("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA!!!!!!!!!!!!!!!!");
            }
            for (i = 0, len = el.children.length; i < len; i++) {
                triggerChildrenInserted(el.children[i]);
            };
        }
    }

    return {
        loadImports: loadImports,
        register: register,
        query: document.querySelector ? queryNative : queryAssisted,
        appendChild: appendChild,
        triggerChildrenInserted: triggerChildrenInserted,
        getMxtFromElement: getMxtFromElement,
        getMxtById: getMxtById,
        standUpTag: standUpTag,
        standUpTags: standUpTags,
        getComponent: getComponent
    }
})(jQuery);
<commit_msg>Ease error finding by throwing an exception if the template ID is invalid.<commit_after>if (typeof console == 'undefined') {
    window.console = {
        log: function (msg) {
            alert(msg);
        },
        dir: function () {}
    }
}

microXTag = (function ($) {
    function loadImports(importList, loaded) {
        var loadqueue = [];
        $.each(importList, function (index, importFile) {
            var componentPath = importFile.replace(/[^\/]*$/, '');
            function adjustPath(el, attr) {
                var src = el.getAttribute(attr);
                if (!/^\//.test(src)) {
                    el.setAttribute(attr, componentPath + src);
                }
            };
            $.get(importFile)
                .done(function (html) {
                    var $elements = $(html);
                    var $scripts = $elements.filter('script[src]');
                    $scripts.each(function (index, script) {
                        adjustPath(script, 'src');
                    });
                    var $links = $elements.filter('link[rel="stylesheet"]');
                    var $nonlinks = $elements.not('link[rel="stylesheet"]');
                    $links.each(function (index, link) {
                        adjustPath(link, 'href');
                    });
                    $('body').append($nonlinks);
                    $('head').append($links);
                    loadqueue[index] = true;
                    if (loadqueue.length == importList.length) {
                        for (var i = 0; i < loadqueue.length &&
                             loadqueue[i] == true; i++);
                        if (i >= loadqueue.length) {
                            loaded();
                        }
                    };
                })
            loadqueue[index] = false; // request has been made but response not received
        });
    };

    var registry = {};

    function register(componentName, templateID, config) {
        var name = componentName.toUpperCase();
        if (registry[name]) {
            var errorMsg = "component already registered with name " + componentName;
            console.log(errorMsg);
            return;
        }
        registry[name] = {
            config: config,
            elementList: [],
            fragment: getFragmentFromTemplate(templateID)
        }
    }

    function getComponent(name, el) {
        var regname = name.toUpperCase();
        var registryItem = registry[regname];
        if (typeof registryItem == 'undefined') {
            throw Error("no tag " + name + " registered");
        };
        var component = new mxtElement(regname, registryItem, el);
        registryItem.elementList.push(component);
        var config = component.registryListing.config;
        if (config.lifecycle && config.lifecycle.created) {
            config.lifecycle.created.apply(component);
        };

        return component;
    }

    function standUpTag(el) {
        var tagName = el.nodeName,
            mxt = getComponent(tagName, el);
            parentEl = el.parentNode;
        parentEl.replaceChild(mxt.el, el);
        triggerChildrenInserted(mxt.el);
        return mxt;
    }

    // micro-x-taggify the DOM elements passed in
    function standUpTags(tagList) {
        for (var i = 0, len = tagList.length; i < len; i++) {
            el = tagList[i];
            standUpTag(el);
        }
    }

    function mxtElement (name, registryListing, origElement) {
        this.registryListing = registryListing;
        var newElement = document.createElement(name);
        this.el = newElement;
        if (origElement) {
            var attrs = $(origElement).prop("attributes");
            $.each(attrs, function() {
                newElement.setAttribute(this.name, this.value);
            });
        }
        this.el.setAttribute('x-micro-tags', true);
        this.el.appendChild(this.registryListing.fragment.cloneNode(true));
        // Support the methods in the "methods" property of the config
        $.extend(this, registryListing.config.methods);
        this._microx = {
            accessorLookup: {}
        };
        var accessors = registryListing.config.accessors;
        if (accessors) {
            for (var name in accessors) {
                if (accessors[name].attribute) {
                    if (accessors[name].attribute.name) {
                        this._microx.accessorLookup[accessors[name].attribute.name] = accessors[name];
                    }
                }
            }
        }
        var childXTags = microXTag.query(this, '[x-micro-tags=true]');
        $.each(childXTags || [], function (index, el) {
            var c = microXTag.getComponent(el.nodeName, el);
            var p = el.parentNode;
            p.replaceChild(c.el, el);
        });
        this.xtag = {}; //ease backward compatibility
    };

    mxtElement.prototype = {
        appendTo: function (newParent) {
            newParent.appendChild(this.el);
            this.onInsert();
        },
        getElement: function () {
            return this.el;
        },
        onInsert: function () {
            var config = this.registryListing.config;
            if (config.lifecycle && config.lifecycle.inserted) {
                config.lifecycle.inserted.apply(this);
            };
            this._microx.inserted = true;
        },
        setAttribute: function (name, value) {
            //return;
            var accessor = this._microx.accessorLookup[name] || (function(accessors) {
                return accessors && accessors[name];
            })(this.registryListing.config.accessors);

            if (accessor && accessor.set) {
                accessor.set.call(this, value);
            }
            return this.el.setAttribute(name, value);
        },
        getAttribute: function (name) {
            //return "foo";
            var accessors = this.registryListing.config.accessors;
            if (accessors && accessors[name] && accessors[name].get) {
                console.log("Hey, we're using get accessor!");
                return accessors[name].get.call(this);
            } else {
                return this.el.getAttribute(name);
            }
        },
        addClass: function (classname) {
            $(this.el).addClass(classname);
        }
    };

    $.each(['getElementsByTagName'], function (index, methodName) {
        mxtElement.prototype[methodName] = function () {
            return this.el[methodName].apply(this.el, arguments);
        };
    });

    function getFragmentFromTemplate(templateID) {
        var $template = $("#" + templateID);
        if (!$template || $template.length == 0) {
            throw "No template with id=" + templateID + " found."
        }
        var text = $template.html();
        var div = document.createElement('div');
        div.innerHTML = text;
        var df = document.createDocumentFragment();
        while (div.firstChild) {
            df.appendChild(div.firstChild);
        }
        return df;
    };

    function queryNative(mxtag, selector) {
        return mxtag.el.querySelectorAll(selector);
    }

    function queryAssisted(mxtag, selector) {
        var $result = $(mxtag.el).find(selector);
        return $result.get();
    }

    // Append newEl to parent, the micro-xtag way
    function appendChild(parent, newItem) {
        var newNodeList = [],
            i, len, newEl;

        if (newItem._microx) {
            newEl = newItem.el;
        } else {
            newEl = newItem;
        }
        if (newEl.nodeName == "#document-fragment") {
            for (i = 0, len = newEl.childNodes.length; i < len; i++) {
                newNodeList.push(newEl.childNodes[i]);
            };
        } else {
            newNodeList = [newEl];
        }
        parent.appendChild(newEl);
        if (newItem._microx && newItem._microx.inserted == true) return;
        for (var i = 0, len = newNodeList.length; i < len; i++) {
            triggerChildrenInserted(newNodeList[i]);
        };
    }

    // given a tag name and a DOM element, look up the mxtElement
    // object that is the wrapper for the DOM element
    function getMxtFromElement(el) {
        var registryItem = registry[el.nodeName];
        if (!registryItem) {
            console.log("Expected a registered tag named " + el.nodeName);
            return null;
        };
        var list = registryItem.elementList;
        var item = null;
        for (var i = 0, len = list.length; i < len; i++) {
            if (list[i].el == el) {
                item =  list[i];
            }
        };
        if (item == null) {
            console.log("Warning: mxtElement for " + el.nodeName + " not found");
        };
        return item;
    }

    function getMxtById(doc, id) {
        if (arguments.length < 2) {
            id = doc;
            doc = document;
        }
        var el = doc.getElementById(id);
        return getMxtFromElement(el);
    };

    function triggerChildrenInserted(el) {
        if (el.getAttribute('x-micro-tags') == 'true') {
            var mxt = getMxtFromElement(el);
            if (mxt) {
                mxt.onInsert();
            } else {
                console.log("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA!!!!!!!!!!!!!!!!");
            }
            for (i = 0, len = el.children.length; i < len; i++) {
                // Avoid processing iframe, at least for now, because it kills performance
                //if (el.children[i].nodeName == "IFRAME") continue;
                triggerChildrenInserted(el.children[i]);
            };
        }
    }

    return {
        loadImports: loadImports,
        register: register,
        query: document.querySelector ? queryNative : queryAssisted,
        appendChild: appendChild,
        triggerChildrenInserted: triggerChildrenInserted,
        getMxtFromElement: getMxtFromElement,
        getMxtById: getMxtById,
        standUpTag: standUpTag,
        standUpTags: standUpTags,
        getComponent: getComponent
    }
})(jQuery);
<|endoftext|>