<commit_before>// at the top of the test spec:
var browserLogs = require('protractor-browser-logs'),
    ToolBar = require('./../helper/toolBar'),
    Container = require('./../helper/container');

describe('The Editor', function () {

    var toolBar = new ToolBar(),
        container = new Container();

    var logs;

    beforeEach(function () {
        logs = browserLogs(browser);
        logs.ignore(logs.DEBUG);
        logs.ignore(logs.INFO);
    });

    afterEach(function () {
        return logs.verify();
    });

    it('should loaded', function () {
        browser.driver.get('http://localhost:9001/index.html');
        browser.waitForAngular();

        var editor = element(by.className('sc-prose-editor'));
        expect(editor.isPresent()).toBe(true);
    });

    describe('container', function () {

        it('should display paragraph 1', function () {
            expect(container.getParagraphElement(1).isPresent()).toBe(true);
            expect(container.getContentOfParagraphElement(1).getText()).toEqual('Insert a new image using the image tool.');
        });

        it('should display paragraph 2', function () {
            expect(container.getParagraphElement(2).isPresent()).toBe(true);
            expect(container.getContentOfParagraphElement(2).getText()).toEqual('Please note that images are not actually uploaded in this example. You would need to provide a custom file client that talks to an image store. See FileClientStub which reveals the API you have to implement.');
        });
    });

    describe('save button', function () {

        it('should be present', function () {
            expect(toolBar.getSaveButton().isPresent()).toBe(true);
        });

        it('should switched off', function () {
            expect(toolBar.getSaveButton().isEnabled()).toBe(false);
        });

        it('should activate save handler', function () {
            container.getContentOfParagraphElement(2).click();
            browser.actions().sendKeys('a').perform();
            toolBar.getSaveButton().click();
            logs.expect(/Save from Angular!/);
        });
    });

});
<commit_msg>An other ci try<commit_after>// at the top of the test spec:
var browserLogs = require('protractor-browser-logs'),
    ToolBar = require('./../helper/toolBar'),
    Container = require('./../helper/container');

describe('The Editor', function () {

    var toolBar = new ToolBar(),
        container = new Container();

    var logs;

    beforeEach(function () {
        logs = browserLogs(browser);
        logs.ignore(logs.DEBUG);
        logs.ignore(logs.INFO);
    });

    afterEach(function () {
        return logs.verify();
    });

    it('should loaded', function () {
        browser.driver.get('http://localhost:9001/index.html');
        browser.waitForAngular();
        browser.wait(started, 5 * 1000, 'Server should start within 5 seconds');
        var editor = element(by.className('sc-prose-editor'));
        expect(editor.isPresent()).toBe(true);
    });

    describe('container', function () {

        it('should display paragraph 1', function () {
            expect(container.getParagraphElement(1).isPresent()).toBe(true);
            expect(container.getContentOfParagraphElement(1).getText()).toEqual('Insert a new image using the image tool.');
        });

        it('should display paragraph 2', function () {
            expect(container.getParagraphElement(2).isPresent()).toBe(true);
            expect(container.getContentOfParagraphElement(2).getText()).toEqual('Please note that images are not actually uploaded in this example. You would need to provide a custom file client that talks to an image store. See FileClientStub which reveals the API you have to implement.');
        });
    });

    describe('save button', function () {

        it('should be present', function () {
            expect(toolBar.getSaveButton().isPresent()).toBe(true);
        });

        it('should switched off', function () {
            expect(toolBar.getSaveButton().isEnabled()).toBe(false);
        });

        it('should activate save handler', function () {
            container.getContentOfParagraphElement(2).click();
            browser.actions().sendKeys('a').perform();
            toolBar.getSaveButton().click();
            logs.expect(/Save from Angular!/);
        });
    });

});
<|endoftext|>


<commit_before>const helpers = require("./global-setup");
const request = require("request");
const expect = require("chai").expect;

const describe = global.describe;
const it = global.it;
const before = global.before;
const after = global.after;
const mlog = require("mocha-logger");

describe("Vendors", function () {

	helpers.setupTimeout(this);

	var app = null;

	before(function () {
		process.env.MM_CONFIG_FILE = "tests/configs/env.js";
		return helpers.startApplication({
			args: ["js/electron.js"]
		}).then(function (startedApp) { app = startedApp; });
	});

	after(function () {
		return helpers.stopApplication(app);
	});

	describe("Get list vendors", function () {

		var vendors = require(__dirname + "/../../vendor/vendor.js");
		Object.keys(vendors).forEach(vendor => {
			it(`should return 200 HTTP code for vendor "${vendor}"`, function () {
				urlVendor = "http://localhost:8080/vendor/" + vendors[vendor];
				request.get(urlVendor, function (err, res, body) {
					if (!err)
					{expect(res.statusCode).to.equal(200);}
					else
					{mlog.pending(`There error vendor 200 test ${err}`);}
				});
			});
		});

		Object.keys(vendors).forEach(vendor => {
			it(`should return 404 HTTP code for vendor https://localhost/"${vendor}"`, function() {
				urlVendor = "http://localhost:8080/" + vendors[vendor];
				request.get(urlVendor, function (err, res, body) {
					if (!err)
					{expect(res.statusCode).to.equal(404);}
					else
					{mlog.pending(`There error vendor 404 test ${err}`);}
				});
			});
		});
	});
});
<commit_msg>Revert error logging introduced in 1e97b5c<commit_after>const helpers = require("./global-setup");
const request = require("request");
const expect = require("chai").expect;

const describe = global.describe;
const it = global.it;
const before = global.before;
const after = global.after;
const mlog = require("mocha-logger");

describe("Vendors", function () {

	helpers.setupTimeout(this);

	var app = null;

	before(function () {
		process.env.MM_CONFIG_FILE = "tests/configs/env.js";
		return helpers.startApplication({
			args: ["js/electron.js"]
		}).then(function (startedApp) { app = startedApp; });
	});

	after(function () {
		return helpers.stopApplication(app);
	});

	describe("Get list vendors", function () {

		var vendors = require(__dirname + "/../../vendor/vendor.js");
		Object.keys(vendors).forEach(vendor => {
			it(`should return 200 HTTP code for vendor "${vendor}"`, function () {
				urlVendor = "http://localhost:8080/vendor/" + vendors[vendor];
				request.get(urlVendor, function (err, res, body) {
					expect(res.statusCode).to.equal(200);
				});
			});
		});

		Object.keys(vendors).forEach(vendor => {
			it(`should return 404 HTTP code for vendor https://localhost/"${vendor}"`, function() {
				urlVendor = "http://localhost:8080/" + vendors[vendor];
				request.get(urlVendor, function (err, res, body) {
					expect(res.statusCode).to.equal(404);
				});
			});
		});
	});
});
<|endoftext|>


<commit_before>$(function() {

	/* change these to use a class selector since we added more than one of them */
	if ($('table#manageusers').length) {
		$('#manageusers').DataTable({
        dom: 'Vlfrtip'
  		  });
	}

	if ($('table#manageschools').length) {
		$('#manageschools').DataTable({
        dom: 'Vlfrtip'
    });
	}

	if ($('table#manageschooldetails').length) {
		$('#manageschooldetails').DataTable();
	}

	if ($('table#analyzestudents').length) {
		$('#analyzestudents').DataTable();
	}

	$( "#filter-result" ).change(function() {
		$("#filter-form-result").val($( "#filter-result" ).val());
		$( "#dataGridFormFilter").submit();
	});

	$("[data-toggle='modal']").on('click', function(e) {
		e.preventDefault();
		var $that = $(this);

		var $loading = $(".loading", $that.attr('data-target')).fadeIn();

		if ($(this).attr('data-post-data')) {
			var $form = $($(this).attr('data-post-data'));
			$.ajax({
				url: $(this).attr('data-href'),
				type: 'post',
				data: $form.serialize(),
				dataType: 'json',
				success: function(response) {
					$loading.fadeOut();
					$(".modal-ajax-content", $that.attr('data-target')).html(response.html);
				}
			})
		}
	})

	$('#content-query').focus(function(){
		var query = $(this);
		if (query.val() == 'search text')
			query.val('');
	});

	/* Get the query string into an object for use in the defilter list */
	var urlParams;
	(window.onpopstate = function () {
		var match,
			pl     = /\+/g,  // Regex for replacing addition symbol with a space
			search = /([^&=]+)=?([^&]*)/g,
			decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
			query  = window.location.search.substring(1);

		urlParams = {};
		while (match = search.exec(query))
			urlParams[decode(match[1])] = decode(match[2]);
	})();

	$('.filter_active').click(function () {
		delete urlParams[this.value];
		var newQuery = $.param(urlParams);
		var baseUrl = [location.protocol, '//', location.host, location.pathname].join('');
		window.location = baseUrl+'?'+newQuery;
	})

	/* Sample code for browser extension dev when handling content links */
	var assignmentLink = $('a.extension'), target = 'chrome-extension://maifknjmjnafdaiohogiffkdaebomimn';

	/* Tell the extension what was the last active URL  */
	/*if(window.parent.location.origin === 'chrome-extension://maifknjmjnafdaiohogiffkdaebomimn'){*/
	window.parent.postMessage({operation: 'changeUrl', location: window.location.href}, target);
	/*  }*/

	if (assignmentLink.length) {
		// Hide links if a Google Classroom page is not open
		$(window).on('message', function (event) {
			if (event.originalEvent.origin === target && !event.originalEvent.data.isClassroomOpen) {
				assignmentLink.hide();
			}
		});
		window.parent.postMessage({operation: 'isClassroomOpen'}, target);

		// Click handler for entering fields into the new assignment form
		assignmentLink.click(function(event){
			/*  event.preventDefault();
			 var link   = $(this),
			 title      = link.attr('title'),
			 desc       = link.attr('description'),
			 href       = link.attr('href');*/

			event.preventDefault();
			var link = $(this);
			var message = {title: link.attr('title'), desc: link.attr('description'), href: link.attr('href')};
			window.parent.postMessage(message, target);
		});
	}

    $("#main-menu #management, #main-menu #learning-lab").click(function(event) {
    	event.preventDefault();
    	var submenu = $('ul', $(this).parent());
    	if (submenu.length && submenu.is(':visible')) {
    		submenu.slideUp( "slow", function() {
    		// Animation complete.
    		});
    	} else {
    		submenu.slideDown( "slow", function() {
    		// Animation complete.
    		});
    	}
    });

    if ($('.sublive').length) {
        $('.sublive').parent().show();
    }

	$( "#schoolFilter" ).change(function() {
		var schoolId = $(this).val();

		if (schoolId == 'all') {

			$('select#staffusi option').show();
			$('select#staffusi').val('');

		}else {

			$('select#staffusi option[school != "'+schoolId+'"]').hide();
			$('select#staffusi option[school = "'+schoolId+'"]').show();
			$('select#staffusi option[school = "reset"]').show();
			$('select#staffusi').val('');
		}

	});

	$('a.usermanagement-index-delete').click(function(event) {
		event.preventDefault();
		if (confirm('Are you sure you want to delete this user?')) {
			window.location = this.href;
		}

	})

	if ($('#usermanagement-addedit-authtype input:checkbox').length && $('#usermanagement-addedit-authtype input:checkbox').prop('checked')) {
		$('#usermanagement-addedit-password').hide();
	}

	$('#usermanagement-addedit-authtype input:checkbox').click(function(event) {
		$('#usermanagement-addedit-password').toggle(this.checked == false)
	});
	$('[data-toggle="tooltip"]').tooltip();

});

/* GOOGLE SIGN IN: https://developers.google.com/identity/sign-in/ */
function onSignIn(googleUser) {
	/*console.log(googleUser);*/
	// Useful data for your client-side scripts:
	var profile = googleUser.getBasicProfile();
	//console.log("ID: " + profile.getId()); // Don't send this directly to your server!
	//console.log("Name: " + profile.getName());
	//console.log("Image URL: " + profile.getImageUrl());
	//console.log("Email: " + profile.getEmail());
	// The ID token you need to pass to your backend:

	var id_token = googleUser.getAuthResponse().id_token;
	var uemail = profile.getEmail();
	var name = profile.getName();

	var localbe = 'http://localhost/easol/';
	var devbe = 'http://easol-dev.azurewebsites.net/';
	var staging = 'http://easol-stage.azurewebsites.net/';
	var livebe = '';
	var gloginPosturl = location.href;

	var xhr = new XMLHttpRequest();
	xhr.open('POST', gloginPosturl);
	xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xhr.onload = function() {
		if(xhr.responseText=="gloginValid") {
			/* GOOD SIGN IN */
			/*console.log('Signed in as: ' + profile.getName() );*/
			/* alert(profile.getName() + ' is now logged in!');  alert(xhr.responseText);*/
			window.location='student';
		} else {
			/* FAILED SIGN IN */
			console.log('Signed In Error: ' + xhr.responseText);
			signOut();
			/*
			 * we set the error message server side in the session for display on the redirect.
			 * we redirect to the current url but without resending the post data like window.location.reload() would do.
			 */
			window.location.href = window.location.href;
		}
	};
	xhr.send('idtoken=' + id_token + '&uemail=' + uemail);
}
//  END SIGN IN
/* GOOGLE LOGIN - WELL WE NEED TO LOGOUT */
/* Login button must be on same page as logout button - but hidden  - for this to work */
function signOut() { console.log('Attempting Google Logout');
	var auth2 = gapi.auth2.getAuthInstance();
	auth2.signOut().then(function () {
		console.log('User signed out.');
	});
	console.log('End Google Logout');
}

function loading($node) {

	var $box = $node.closest('.loading-box');
	if ($box.length == 0) $box = $node.css('position', 'relative');
	if ($box.find('.loading-img').length == 0) $box.append('

');

	$box.find('.loading-img').fadeIn();
}
function unloading($node) {
	var $box = $node.closest('.loading-box');
	$box.find('.loading-img').fadeOut();
}

<commit_msg>Removed URLs from custom.js<commit_after>$(function() {

	/* change these to use a class selector since we added more than one of them */
	if ($('table#manageusers').length) {
		$('#manageusers').DataTable({
        dom: 'Vlfrtip'
  		  });
	}

	if ($('table#manageschools').length) {
		$('#manageschools').DataTable({
        dom: 'Vlfrtip'
    });
	}

	if ($('table#manageschooldetails').length) {
		$('#manageschooldetails').DataTable();
	}

	if ($('table#analyzestudents').length) {
		$('#analyzestudents').DataTable();
	}

	$( "#filter-result" ).change(function() {
		$("#filter-form-result").val($( "#filter-result" ).val());
		$( "#dataGridFormFilter").submit();
	});

	$("[data-toggle='modal']").on('click', function(e) {
		e.preventDefault();
		var $that = $(this);

		var $loading = $(".loading", $that.attr('data-target')).fadeIn();

		if ($(this).attr('data-post-data')) {
			var $form = $($(this).attr('data-post-data'));
			$.ajax({
				url: $(this).attr('data-href'),
				type: 'post',
				data: $form.serialize(),
				dataType: 'json',
				success: function(response) {
					$loading.fadeOut();
					$(".modal-ajax-content", $that.attr('data-target')).html(response.html);
				}
			})
		}
	})

	$('#content-query').focus(function(){
		var query = $(this);
		if (query.val() == 'search text')
			query.val('');
	});

	/* Get the query string into an object for use in the defilter list */
	var urlParams;
	(window.onpopstate = function () {
		var match,
			pl     = /\+/g,  // Regex for replacing addition symbol with a space
			search = /([^&=]+)=?([^&]*)/g,
			decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
			query  = window.location.search.substring(1);

		urlParams = {};
		while (match = search.exec(query))
			urlParams[decode(match[1])] = decode(match[2]);
	})();

	$('.filter_active').click(function () {
		delete urlParams[this.value];
		var newQuery = $.param(urlParams);
		var baseUrl = [location.protocol, '//', location.host, location.pathname].join('');
		window.location = baseUrl+'?'+newQuery;
	})

	/* Sample code for browser extension dev when handling content links */
	var assignmentLink = $('a.extension'), target = 'chrome-extension://maifknjmjnafdaiohogiffkdaebomimn';

	/* Tell the extension what was the last active URL  */
	/*if(window.parent.location.origin === 'chrome-extension://maifknjmjnafdaiohogiffkdaebomimn'){*/
	window.parent.postMessage({operation: 'changeUrl', location: window.location.href}, target);
	/*  }*/

	if (assignmentLink.length) {
		// Hide links if a Google Classroom page is not open
		$(window).on('message', function (event) {
			if (event.originalEvent.origin === target && !event.originalEvent.data.isClassroomOpen) {
				assignmentLink.hide();
			}
		});
		window.parent.postMessage({operation: 'isClassroomOpen'}, target);

		// Click handler for entering fields into the new assignment form
		assignmentLink.click(function(event){
			/*  event.preventDefault();
			 var link   = $(this),
			 title      = link.attr('title'),
			 desc       = link.attr('description'),
			 href       = link.attr('href');*/

			event.preventDefault();
			var link = $(this);
			var message = {title: link.attr('title'), desc: link.attr('description'), href: link.attr('href')};
			window.parent.postMessage(message, target);
		});
	}

    $("#main-menu #management, #main-menu #learning-lab").click(function(event) {
    	event.preventDefault();
    	var submenu = $('ul', $(this).parent());
    	if (submenu.length && submenu.is(':visible')) {
    		submenu.slideUp( "slow", function() {
    		// Animation complete.
    		});
    	} else {
    		submenu.slideDown( "slow", function() {
    		// Animation complete.
    		});
    	}
    });

    if ($('.sublive').length) {
        $('.sublive').parent().show();
    }

	$( "#schoolFilter" ).change(function() {
		var schoolId = $(this).val();

		if (schoolId == 'all') {

			$('select#staffusi option').show();
			$('select#staffusi').val('');

		}else {

			$('select#staffusi option[school != "'+schoolId+'"]').hide();
			$('select#staffusi option[school = "'+schoolId+'"]').show();
			$('select#staffusi option[school = "reset"]').show();
			$('select#staffusi').val('');
		}

	});

	$('a.usermanagement-index-delete').click(function(event) {
		event.preventDefault();
		if (confirm('Are you sure you want to delete this user?')) {
			window.location = this.href;
		}

	})

	if ($('#usermanagement-addedit-authtype input:checkbox').length && $('#usermanagement-addedit-authtype input:checkbox').prop('checked')) {
		$('#usermanagement-addedit-password').hide();
	}

	$('#usermanagement-addedit-authtype input:checkbox').click(function(event) {
		$('#usermanagement-addedit-password').toggle(this.checked == false)
	});
	$('[data-toggle="tooltip"]').tooltip();

});

/* GOOGLE SIGN IN: https://developers.google.com/identity/sign-in/ */
function onSignIn(googleUser) {
	/*console.log(googleUser);*/
	// Useful data for your client-side scripts:
	var profile = googleUser.getBasicProfile();
	//console.log("ID: " + profile.getId()); // Don't send this directly to your server!
	//console.log("Name: " + profile.getName());
	//console.log("Image URL: " + profile.getImageUrl());
	//console.log("Email: " + profile.getEmail());
	// The ID token you need to pass to your backend:

	var id_token = googleUser.getAuthResponse().id_token;
	var uemail = profile.getEmail();
	var name = profile.getName();

	var gloginPosturl = location.href;

	var xhr = new XMLHttpRequest();
	xhr.open('POST', gloginPosturl);
	xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xhr.onload = function() {
		if(xhr.responseText=="gloginValid") {
			/* GOOD SIGN IN */
			/*console.log('Signed in as: ' + profile.getName() );*/
			/* alert(profile.getName() + ' is now logged in!');  alert(xhr.responseText);*/
			window.location='student';
		} else {
			/* FAILED SIGN IN */
			console.log('Signed In Error: ' + xhr.responseText);
			signOut();
			/*
			 * we set the error message server side in the session for display on the redirect.
			 * we redirect to the current url but without resending the post data like window.location.reload() would do.
			 */
			window.location.href = window.location.href;
		}
	};
	xhr.send('idtoken=' + id_token + '&uemail=' + uemail);
}
//  END SIGN IN
/* GOOGLE LOGIN - WELL WE NEED TO LOGOUT */
/* Login button must be on same page as logout button - but hidden  - for this to work */
function signOut() { console.log('Attempting Google Logout');
	var auth2 = gapi.auth2.getAuthInstance();
	auth2.signOut().then(function () {
		console.log('User signed out.');
	});
	console.log('End Google Logout');
}

function loading($node) {

	var $box = $node.closest('.loading-box');
	if ($box.length == 0) $box = $node.css('position', 'relative');
	if ($box.find('.loading-img').length == 0) $box.append('

');

	$box.find('.loading-img').fadeIn();
}
function unloading($node) {
	var $box = $node.closest('.loading-box');
	$box.find('.loading-img').fadeOut();
}

<|endoftext|>


<commit_before>'use strict';

require('should');
var benv = require('benv');

describe('pluginbase', function ( ) {
  this.timeout(30000); // TODO: see why this test takes longer on Travis to complete

  var headless = require('./fixtures/headless')(benv, this);

  before(function (done) {
    done( );
  });

  after(function (done) {
    done( );
  });

  beforeEach(function (done) {
    headless.setup({ }, done);
  });

  afterEach(function (done) {
    headless.teardown( );
    done( );
  });

  it('does stuff', function() {

    function div (clazz) {
      return $('

');
    }

    var container = div('container')
      , bgStatus = div('bgStatus').appendTo(container)
      , majorPills = div('majorPills').appendTo(bgStatus)
      , minorPills = div('minorPills').appendTo(bgStatus)
      , statusPills = div('statusPills').appendTo(bgStatus)
      , tooltip = div('tooltip').appendTo(container)
      ;

    var fake = {
      name: 'fake'
      , label: 'Insulin-on-Board'
      , pluginType: 'pill-major'
    };

    var pluginbase = require('../lib/plugins/pluginbase')(majorPills, minorPills, statusPills, bgStatus, tooltip);

    pluginbase.updatePillText(fake, {
      value: '123'
      , label: 'TEST'
      , info: [{label: 'Label', value: 'Value'}]
    });

    majorPills.length.should.equal(1);
  });

});
<commit_msg>pluginbase.test.js fails with 30 sec. upping to 40 sec timeout<commit_after>'use strict';

require('should');
var benv = require('benv');

describe('pluginbase', function ( ) {
  this.timeout(40000); // TODO: see why this test takes longer on Travis to complete

  var headless = require('./fixtures/headless')(benv, this);

  before(function (done) {
    done( );
  });

  after(function (done) {
    done( );
  });

  beforeEach(function (done) {
    headless.setup({ }, done);
  });

  afterEach(function (done) {
    headless.teardown( );
    done( );
  });

  it('does stuff', function() {

    function div (clazz) {
      return $('

');
    }

    var container = div('container')
      , bgStatus = div('bgStatus').appendTo(container)
      , majorPills = div('majorPills').appendTo(bgStatus)
      , minorPills = div('minorPills').appendTo(bgStatus)
      , statusPills = div('statusPills').appendTo(bgStatus)
      , tooltip = div('tooltip').appendTo(container)
      ;

    var fake = {
      name: 'fake'
      , label: 'Insulin-on-Board'
      , pluginType: 'pill-major'
    };

    var pluginbase = require('../lib/plugins/pluginbase')(majorPills, minorPills, statusPills, bgStatus, tooltip);

    pluginbase.updatePillText(fake, {
      value: '123'
      , label: 'TEST'
      , info: [{label: 'Label', value: 'Value'}]
    });

    majorPills.length.should.equal(1);
  });

});
<|endoftext|>


<commit_before>import LayoutFactory from './layout-factory';

export default {
	/**
	 * Shows the previous month on the calendar.
	 * @param {Event} e Click event.
	 * @param {Date} date Current date of calendar.js, the instance them self gets modified.
	 */
	previous: (e, date) => {
		date.setMonth(date.getMonth() - 1);

		LayoutFactory.rebuildCalendar(date);
	},

	/**
	 * Shows the next month on the calendar.
	 * @param {Event} e Click event.
	 * @param {Date} date Current date of calendar.js, the instance them self gets modified.
	 */
	next: (e, date) => {
		date.setMonth(date.getMonth() + 1);

		LayoutFactory.rebuildCalendar(date);
	},

	/**
	 * Sets the event handler to close the calendar widget.
	 * @param overlay
	 * @param wrapper
	 */
	close: (overlay, wrapper) => {
		overlay.addEventListener('click', e => {
			e.target === wrapper || e.target === overlay ? overlay.remove() : null;
		});
	},

	selectDate: date => {
		const days = document.getElementsByClassName('day');
		let i = 0;

		for (; i < days.length; i++) {
			days[i].addEventListener('click', e => {
				LayoutFactory.selectDate(e.target.innerText, date);
			})
		}
	}
}
<commit_msg>events.js - events to reset current date and validate the time values<commit_after>import LayoutFactory from './layout-factory';

export default {
	/**
	 * Shows the previous month on the calendar.
	 * @param {Event} e Click event.
	 * @param {Date} date Current date of calendar.js, the instance them self gets modified.
	 */
	previous: (e, date) => {
		date.setMonth(date.getMonth() - 1);

		LayoutFactory.rebuildCalendar(date);
	},

	/**
	 * Shows the next month on the calendar.
	 * @param {Event} e Click event.
	 * @param {Date} date Current date of calendar.js, the instance them self gets modified.
	 */
	next: (e, date) => {
		date.setMonth(date.getMonth() + 1);

		LayoutFactory.rebuildCalendar(date);
	},

	/**
	 * Sets the event handler to close the calendar widget.
	 * @param overlay
	 * @param wrapper
	 */
	close: (overlay, wrapper) => {
		overlay.addEventListener('click', e => {
			e.target === wrapper || e.target === overlay ? overlay.remove() : null;
		});
	},

	/**
	 * Resets the current date of the picker
	 */
	reset: () => {
		document.querySelector('.reset button').addEventListener('click', LayoutFactory.reset);
	},

	/**
	 * Sets the event listener for picking a date.
	 * @param date
	 */
	selectDate: date => {
		const days = document.getElementsByClassName('day');
		let i = 0;

		for (; i < days.length; i++) {
			days[i].addEventListener('click', e => {
				LayoutFactory.selectDate(e.target.innerText, date);
			})
		}
	},

	/**
	 * Set event listener to validate the hours input field.
	 * Only integers between 0 and 23 are allowed.
	 */
	hoursValidator: () => {
		document.querySelector('input.hours').addEventListener('keyup', e => {
			if (!Number.isInteger(Number(e.target.value))) {
				e.target.value = '';
			}

			if (Number(e.target.value) > 23) {
				e.target.value = '23';
			}

			if (Number(e.target.value) < 0) {
				e.target.value = '0';
			}
		})
	},

	/**
	 * Set event listener to validate the hours input field.
	 * Only integers between 0 and 59 are allowed.
	 */
	minutesValidator: () => {
		document.querySelector('input.minutes').addEventListener('keyup', e => {
			if (!Number.isInteger(Number(e.target.value))) {
				e.target.value = '';
			}

			if (Number(e.target.value) > 59) {
				e.target.value = '59';
			}

			if (Number(e.target.value) < 0) {
				e.target.value = '0';
			}
		})
	}
}
<|endoftext|>


<commit_before>Ppulse = {}

Ppulse.colors = ['green', 'blue', 'amber', 'orange', 'purple'];

Ppulse.formatTime = function(time, format) {
	if (format == undefined) {
		format = 'hms';
	}

	var hours = Math.floor(time / 3600);
	var minutes = Math.floor((time - hours*3600) / 60 );
	var seconds = Math.floor((time - hours*3600 - minutes*60));

	if (minutes < 10) { minutes = '0' + minutes; }
	if (seconds < 10) { seconds = '0' + seconds; }

	if (format == 'hms') {
		return hours + ':' + minutes + ':' + seconds;
	} else {
		return hours + ':' + minutes;
	}
}

Ppulse.updateTimer = function(start_time, offset_time) {
	var d = new Date().getTime()/1000;
	return d - start_time + offset_time;
}

Ppulse.dayOffset = function(day) {
	var nday = Math.floor(new Date().getTime()/(1000*3600*24));
	return nday - day;
}

function Pproject(container)
{
	var self = this;

	var color = 0;
	var init = 0;
	var times = [0, 0, 0];
	var timer = false;

	// html
	var project = container.addClass('clockin');
	var p = Pproject.prototype.build(project);

	// sortable logic
	var sort = new Sortable(p.tasks[0], {
		animation: 0, // ms, animation speed moving items when sorting, `0` — without animation
		handle: ".clockin_task", // Restricts sort start click/touch to the specified element
	  	draggable: ".clockin_task", // Specifies which items inside the element should be sortable
	  	ghostClass: "sortable_ghost",
	});

	// logic
	project.on('stoptimer', function() {
		if (timer)
		{
			$(this).removeClass('running');
			p.runtimers.removeClass('animate-spin');
			self.stopTimer();
		}
	});

	p.colors.on('click touchstart', function() { self.cycleColor(); })
	p.trash.on('click touchstart', function() {
		clockin_dialog(
			'Delete project',
			'
Are you sure you wan\'t to delete this project?
',
			'prompt',
			{
				cancel: 'Abort',
				affirm: ' Delete',
				fcn: function(){ project.remove(); }
			}
		);
	});
	p.runtimers.on('click touchstart', function() {
		if (timer) {
			$(this).removeClass('animate-spin');
			self.stopTimer();
		} else {
			$(this).addClass('animate-spin');
			self.startTimer();
		}
	});
	p.addtask.on('click touchstart', function() { self.addTask('', 0); })

	// simple functions
	this.getTitle = function() { return p.title.val(); }
	this.setTitle = function(value) { p.title.val(value) }

	this.getDescription = function() { return p.description.text(); }
	this.setDescription = function(value) { p.description.text(value); }

	this.cycleColor = function() { var value = (color + 1) % Ppulse.colors.length; this.setColor(value); }
	this.getColor = function() { return color; }
	this.setColor = function(value) { project.removeClass(Ppulse.colors[color]).addClass(Ppulse.colors[value]); color = value; }
	this.setColor(color);

	this.appendTo = function(container) { $(container).append(project); }
	this.remove = function() { project.remove(); }

	this.updateInit = function() {
		init = Math.floor(new Date().getTime()/(3600*1000*24));
		return init;
	}

	if (init === 0) {
		this.updateInit();
	}

	this.addTime = function(value)   { times = $.map( times, function(time, i) { return value + time; }); this.updateTimer(); }
	this.setTime = function(value)   { times = $.map( times, function(time, i) { return value; });        this.updateTimer(); }
	this.setTimes = function(values) { times = $.map( times, function(time, i) { return values[i]; });    this.updateTimer(); }
	this.loopTimes = function(times, init) {
		var off = Ppulse.dayOffset(init);
		var day = new Date().getDay();

		if (off > 0) { times[2] = 0; }
		if (off > day) { times[1] = 0; }

		return times;
	}

	this.updateLoopTimes = function() {
		setTimeout(function() {
			times = self.loopTimes(times, init);
			self.updateInit();
			self.updateLoopTimes();
		}, (init + 1)*3600*1000 + 5000 - new Date().getTime());
	}
	this.updateLoopTimes();

	this.addTask = function(title, state) {
		var oc = 'open', icon = 'icon-check-empty'; if (state == 1) { oc = 'closed'; icon = 'icon-check'; }

		var task = $('

')
			.append($('<input type="text" value="' + title + '"/>'))
			.append($(''))
			.append($(''));

		p.tasks.append(task);
	}

	this.setTimer = function(times) {
		p.totaltimer.text(Ppulse.formatTime(times[0], 'hm'));
		p.weektimer.text(Ppulse.formatTime(times[1], 'hm'));
		p.todaytimer.text(Ppulse.formatTime(times[2]));
	}

	this.updateTimer = function() { this.setTimer(times); }
	this.updateTimer();

	this.startTimer = function() {
		stopAllTimers();
		$('body').addClass('dim');
		project.addClass('running');

		var starttime = new Date().getTime()/1000;
		var offsettimes = times.slice(0);

		var updater = function() {
			times = $.map( times, function(time, i) { return Ppulse.updateTimer( starttime, offsettimes[i]); });
			self.setTimer(times);
		}

		timer =  setInterval(updater, 1000);
	}

	this.stopTimer = function() {
		$('body').removeClass('dim');
		project.removeClass('running');

		clearInterval(timer);
		timer = false;
	}

	this.exportToObject = function() {
		var dump = {};
		dump.title = this.getTitle();
		dump.color = this.getColor();
		dump.time = Math.floor(times[2]);
		dump.week = Math.floor(times[1]);
		dump.total = Math.floor(times[0]);
		dump.desc = this.getDescription();

		var tasks = [];
		$('.clockin_task', p.tasks).each(function(){
			tasks.push([$('input', this).val(), $(this).attr('data-state')]);
		});
		dump.tasks = tasks;
		// dump.offset = self.offset;

		return dump;
	}

	this.loadFromObject = function(dump) {

		times = this.loopTimes([dump.total, dump.week, dump.time], dump.offset)

		this.setTitle(dump.title);
		this.setColor(dump.color);
		this.setDescription(dump.desc);
		this.setTimes(times);

		if ('tasks' in dump)
		{
			for (var i = 0; i < dump.tasks.length; i++)
			{
				this.addTask(dump.tasks[i][0], dump.tasks[i][1]);
			}
		}
	}

	this.loadFromString = function(str) {
		this.loadFromObject($.parseJSON(str));
	}
}

Pproject.prototype.build = function(project) {
	var p = {};

	p.title = $('<input class="clockin_title" type="text" value="" placeholder="Project"/>');
	p.colors = $('');
	p.trash = $('');

	p.description = $('<textarea class="clockin_desc"></textarea>');

	p.totaltimer = $('

');
	p.weektimer = $('

');
	p.todaytimer = $('

');
	p.runtimers = $('');

	p.tasks = $('

');
	p.addtask = $('add task')

	project.append(
			$('

')
				.append(p.title).append(p.colors).append(p.trash))
	.append(p.description)
	.append(
		$('

')
			.append($('
Total
')
				.append(p.totaltimer))
			.append($('
This week
')
				.append(p.weektimer))
			.append($('
Today
')
				.append(p.todaytimer))
			.append($('

')
				.append(p.runtimers)))
	.append(p.tasks)
	.append(p.addtask);

	return p;
}

// delete task
$( document ).on( "click touchstart", ".clockin_task_delete", function( e ) {
	var container = $(this).parent('.clockin_task');
	if ($(this).siblings('input').val() == false) {
		container.remove();
	} else {
		clockin_dialog(
			'Delete task',
			'
Are you sure you wan\'t to delete this task?
',
			'prompt',
			{
				cancel: 'Abort',
			 	affirm: ' Delete',
			 	fcn: function(){ container.remove(); }
			}
		);
	}
} );

// switch state
$( document ).on('click touchstart', '.clockin_task_state', function( e ){
	var container = $(this).parent('.clockin_task');

	if (container.attr('data-state') == 0) {
		container.attr('data-state', 1);
		container.removeClass('clockin_task_open').addClass('clockin_task_closed');
		$(this).removeClass('icon-check-empty').addClass('icon-check')
	} else {
		container.attr('data-state', 0);
		container.removeClass('clockin_task_closed').addClass('clockin_task_open');
		$(this).removeClass('icon-check').addClass('icon-check-empty')
	}
});

function stopAllTimers() {
	$('.clockin').each(function() {
		$(this).trigger('stoptimer');
	});
}

function clockin_dialog(title, content, dtype, options) {
	switch(dtype) {
		case 'warning':
			var ddtype = ' icon-attention';
			break;
		case 'error':
			var ddtype = ' icon-attention';
			break;
		default:
			var ddtype = ''
	}

	var viewport_width = $(window).width();
	var viewport_height = $(window).height();

	var modal_y = Math.round(Math.max(viewport_height/2.5-100, 0));
	var modal_w = Math.min(viewport_width, 400);

	var popup = $('

');

	var blur = $('

')
		.on('click touchstart', function(e){
			e.stopPropagation();
			e.preventDefault();
			e.cancelBubble = true;
			popup.remove();
		});

	var dialog = $('

')
		.css('margin-top', modal_y - 50 + 'px')
		.css('width', modal_w + 'px');

	var addendum = '';
	switch(dtype) {
		case 'prompt':
			addendum =  $('

')
					.append($('' + options.affirm + '')
						.on('click touchstart', function(){
							options.fcn();
							$('#clockin_popup').remove();
						})
					)
					.append(' ')
					.append($('' + options.cancel +'')
						.on('click touchstart', function(){
							$('#clockin_popup').remove();
						})
					);
			break;
		default:
			addendum = ''
	}

	dialog.append($('
✖
')
			.on('click touchstart', function(){
				popup.remove();
			})
		)
		.append($('

')
			.append($('

').append(title))
			.append($('

').append(content).append(addendum))
		)

	$('body').append(popup.append(blur).append(dialog));

	window.setTimeout(function(){
		blur.css('opacity', .6);
		dialog.css('opacity', 1).css('margin-top', modal_y + 'px')
	}, 50);
}<commit_msg>Stupid bracket error<commit_after>Ppulse = {}

Ppulse.colors = ['green', 'blue', 'amber', 'orange', 'purple'];

Ppulse.formatTime = function(time, format) {
	if (format == undefined) {
		format = 'hms';
	}

	var hours = Math.floor(time / 3600);
	var minutes = Math.floor((time - hours*3600) / 60 );
	var seconds = Math.floor((time - hours*3600 - minutes*60));

	if (minutes < 10) { minutes = '0' + minutes; }
	if (seconds < 10) { seconds = '0' + seconds; }

	if (format == 'hms') {
		return hours + ':' + minutes + ':' + seconds;
	} else {
		return hours + ':' + minutes;
	}
}

Ppulse.updateTimer = function(start_time, offset_time) {
	var d = new Date().getTime()/1000;
	return d - start_time + offset_time;
}

Ppulse.dayOffset = function(day) {
	var nday = Math.floor(new Date().getTime()/(1000*3600*24));
	return nday - day;
}

function Pproject(container)
{
	var self = this;

	var color = 0;
	var init = 0;
	var times = [0, 0, 0];
	var timer = false;

	// html
	var project = container.addClass('clockin');
	var p = Pproject.prototype.build(project);

	// sortable logic
	var sort = new Sortable(p.tasks[0], {
		animation: 0, // ms, animation speed moving items when sorting, `0` — without animation
		handle: ".clockin_task", // Restricts sort start click/touch to the specified element
	  	draggable: ".clockin_task", // Specifies which items inside the element should be sortable
	  	ghostClass: "sortable_ghost",
	});

	// logic
	project.on('stoptimer', function() {
		if (timer)
		{
			$(this).removeClass('running');
			p.runtimers.removeClass('animate-spin');
			self.stopTimer();
		}
	});

	p.colors.on('click touchstart', function() { self.cycleColor(); })
	p.trash.on('click touchstart', function() {
		clockin_dialog(
			'Delete project',
			'
Are you sure you wan\'t to delete this project?
',
			'prompt',
			{
				cancel: 'Abort',
				affirm: ' Delete',
				fcn: function(){ project.remove(); }
			}
		);
	});
	p.runtimers.on('click touchstart', function() {
		if (timer) {
			$(this).removeClass('animate-spin');
			self.stopTimer();
		} else {
			$(this).addClass('animate-spin');
			self.startTimer();
		}
	});
	p.addtask.on('click touchstart', function() { self.addTask('', 0); })

	// simple functions
	this.getTitle = function() { return p.title.val(); }
	this.setTitle = function(value) { p.title.val(value) }

	this.getDescription = function() { return p.description.text(); }
	this.setDescription = function(value) { p.description.text(value); }

	this.cycleColor = function() { var value = (color + 1) % Ppulse.colors.length; this.setColor(value); }
	this.getColor = function() { return color; }
	this.setColor = function(value) {
		value = parseInt(value);
		if (isNaN(value) || value < 0) { value = 0; }
		project.removeClass(Ppulse.colors[color]).addClass(Ppulse.colors[value]);
		color = value;
	}
	this.setColor(color);

	this.appendTo = function(container) { $(container).append(project); }
	this.remove = function() { project.remove(); }

	this.updateInit = function() {
		init = Math.floor(new Date().getTime()/(3600*1000*24));
		return init;
	}

	if (init === 0) {
		this.updateInit();
	}

	this.addTime = function(value)   { times = $.map( times, function(time, i) { return value + time; }); this.updateTimer(); }
	this.setTime = function(value)   { times = $.map( times, function(time, i) { return value; });        this.updateTimer(); }
	this.setTimes = function(values) { times = $.map( times, function(time, i) { return values[i]; });    this.updateTimer(); }
	this.loopTimes = function(times, init) {
		var off = Ppulse.dayOffset(init);
		var day = new Date().getDay();

		if (off > 0) { times[2] = 0; }
		if (off > day) { times[1] = 0; }

		return times;
	}

	this.updateLoopTimes = function() {
		setTimeout(function() {
			times = self.loopTimes(times, init);
			self.updateInit();
			self.updateLoopTimes();
		}, (init + 1)*3600*1000 + 5000 - new Date().getTime());
	}
	this.updateLoopTimes();

	this.addTask = function(title, state) {
		var oc = 'open', icon = 'icon-check-empty'; if (state == 1) { oc = 'closed'; icon = 'icon-check'; }

		var task = $('

')
			.append($('<input type="text" value="' + title + '"/>'))
			.append($(''))
			.append($(''));

		p.tasks.append(task);
	}

	this.setTimer = function(times) {
		p.totaltimer.text(Ppulse.formatTime(times[0], 'hm'));
		p.weektimer.text(Ppulse.formatTime(times[1], 'hm'));
		p.todaytimer.text(Ppulse.formatTime(times[2]));
	}

	this.updateTimer = function() { this.setTimer(times); }
	this.updateTimer();

	this.startTimer = function() {
		stopAllTimers();
		$('body').addClass('dim');
		project.addClass('running');

		var starttime = new Date().getTime()/1000;
		var offsettimes = times.slice(0);

		var updater = function() {
			times = $.map( times, function(time, i) { return Ppulse.updateTimer( starttime, offsettimes[i]); });
			self.setTimer(times);
		}

		timer =  setInterval(updater, 1000);
	}

	this.stopTimer = function() {
		$('body').removeClass('dim');
		project.removeClass('running');

		clearInterval(timer);
		timer = false;
	}

	this.exportToObject = function() {
		var dump = {};
		dump.title = this.getTitle();
		dump.color = this.getColor();
		dump.time = Math.floor(times[2]);
		dump.week = Math.floor(times[1]);
		dump.total = Math.floor(times[0]);
		dump.desc = this.getDescription();

		var tasks = [];
		$('.clockin_task', p.tasks).each(function(){
			tasks.push([$('input', this).val(), $(this).attr('data-state')]);
		});
		dump.tasks = tasks;
		// dump.offset = self.offset;

		return dump;
	}

	this.loadFromObject = function(dump) {

		times = this.loopTimes([dump.total, dump.week, dump.time], dump.offset)

		this.setTitle(dump.title);
		this.setColor(dump.color);
		this.setDescription(dump.desc);
		this.setTimes(times);

		if ('tasks' in dump)
		{
			for (var i = 0; i < dump.tasks.length; i++)
			{
				this.addTask(dump.tasks[i][0], dump.tasks[i][1]);
			}
		}
	}

	this.loadFromString = function(str) {
		this.loadFromObject($.parseJSON(str));
	}
}

Pproject.prototype.build = function(project) {
	var p = {};

	p.title = $('<input class="clockin_title" type="text" value="" placeholder="Project"/>');
	p.colors = $('');
	p.trash = $('');

	p.description = $('<textarea class="clockin_desc"></textarea>');

	p.totaltimer = $('

');
	p.weektimer = $('

');
	p.todaytimer = $('

');
	p.runtimers = $('');

	p.tasks = $('

');
	p.addtask = $('add task')

	project.append(
			$('

')
				.append(p.title).append(p.colors).append(p.trash))
	.append(p.description)
	.append(
		$('

')
			.append($('
Total
')
				.append(p.totaltimer))
			.append($('
This week
')
				.append(p.weektimer))
			.append($('
Today
')
				.append(p.todaytimer))
			.append($('

')
				.append(p.runtimers)))
	.append(p.tasks)
	.append(p.addtask);

	return p;
}

// delete task
$( document ).on( "click touchstart", ".clockin_task_delete", function( e ) {
	var container = $(this).parent('.clockin_task');
	if ($(this).siblings('input').val() == false) {
		container.remove();
	} else {
		clockin_dialog(
			'Delete task',
			'
Are you sure you wan\'t to delete this task?
',
			'prompt',
			{
				cancel: 'Abort',
			 	affirm: ' Delete',
			 	fcn: function(){ container.remove(); }
			}
		);
	}
} );

// switch state
$( document ).on('click touchstart', '.clockin_task_state', function( e ){
	var container = $(this).parent('.clockin_task');

	if (container.attr('data-state') == 0) {
		container.attr('data-state', 1);
		container.removeClass('clockin_task_open').addClass('clockin_task_closed');
		$(this).removeClass('icon-check-empty').addClass('icon-check')
	} else {
		container.attr('data-state', 0);
		container.removeClass('clockin_task_closed').addClass('clockin_task_open');
		$(this).removeClass('icon-check').addClass('icon-check-empty')
	}
});

function stopAllTimers() {
	$('.clockin').each(function() {
		$(this).trigger('stoptimer');
	});
}

function clockin_dialog(title, content, dtype, options) {
	switch(dtype) {
		case 'warning':
			var ddtype = ' icon-attention';
			break;
		case 'error':
			var ddtype = ' icon-attention';
			break;
		default:
			var ddtype = ''
	}

	var viewport_width = $(window).width();
	var viewport_height = $(window).height();

	var modal_y = Math.round(Math.max(viewport_height/2.5-100, 0));
	var modal_w = Math.min(viewport_width, 400);

	var popup = $('

');

	var blur = $('

')
		.on('click touchstart', function(e){
			e.stopPropagation();
			e.preventDefault();
			e.cancelBubble = true;
			popup.remove();
		});

	var dialog = $('

')
		.css('margin-top', modal_y - 50 + 'px')
		.css('width', modal_w + 'px');

	var addendum = '';
	switch(dtype) {
		case 'prompt':
			addendum =  $('

')
					.append($('' + options.affirm + '')
						.on('click touchstart', function(){
							options.fcn();
							$('#clockin_popup').remove();
						})
					)
					.append(' ')
					.append($('' + options.cancel +'')
						.on('click touchstart', function(){
							$('#clockin_popup').remove();
						})
					);
			break;
		default:
			addendum = ''
	}

	dialog.append($('
✖
')
			.on('click touchstart', function(){
				popup.remove();
			})
		)
		.append($('

')
			.append($('

').append(title))
			.append($('

').append(content).append(addendum))
		)

	$('body').append(popup.append(blur).append(dialog));

	window.setTimeout(function(){
		blur.css('opacity', .6);
		dialog.css('opacity', 1).css('margin-top', modal_y + 'px')
	}, 50);
}<|endoftext|>


<commit_before>$(document).ready(function() {
    'use strict';

    var slideout;

    function initSlideout() {
        slideout = new Slideout({
            'panel': document.getElementById('slideout-content'),
            'menu': document.getElementById('slideout-nav'),
            'padding': 256,
            'tolerance': 70,
            'side': 'right'
        });
        $('.mobile-nav__icon').on('click', function() {
            slideout.toggle();
        });
    }

    var options = {
            prefetch: true,
            cacheLength: 2,
            onStart: {
                duration: 1300,
                render: function($container) {
                    $container.addClass('is-exiting');
                    smoothState.restartCSSAnimations();
                    slideout.close();
                }
            },
            onReady: {
                duration: 0,
                render: function($container, $newContent) {
                    $container.removeClass('is-exiting');
                    $container.html($newContent);
                    if ($(window).width() < 768) {
                        initSlideout();
                    }
                    if(document.getElementById("particles-js")!=null){
                        initParticles();
                    }
                    window.retinajs();
                }
            }
        },
        smoothState = $('#animate-wrapper').smoothState(options).data('smoothState');

    var resizeId;

    if ($(window).width() < 768) {
        initSlideout();
    }

    $(window).resize(function() {
        clearTimeout(resizeId);
        resizeId = setTimeout(doneResizing, 500);
    });

    function doneResizing() {
        if ($(window).width() < 768) {
            initSlideout();
        }
        if ($(window).width() >= 768) {
            slideout.close();
        }
    }

    function initParticles() {
        particlesJS.load('particles-js', '/assets/json/particles.json');
    }

    if(document.getElementById("particles-js")!=null){
        initParticles();
    }

    window.retinajs();

});
<commit_msg>Fix slide out errors.<commit_after>$(document).ready(function() {
    'use strict';

    var slideout;

    function initSlideout() {
        slideout = new Slideout({
            'panel': document.getElementById('slideout-content'),
            'menu': document.getElementById('slideout-nav'),
            'padding': 256,
            'tolerance': 70,
            'side': 'right'
        });
        $('.mobile-nav__icon').on('click', function() {
            slideout.toggle();
        });
    }

    var options = {
            prefetch: true,
            cacheLength: 2,
            onStart: {
                duration: 1300,
                render: function($container) {
                    $container.addClass('is-exiting');
                    smoothState.restartCSSAnimations();
                    if ($(window).width() < 768) {
                        slideout.close();
                    }
                }
            },
            onReady: {
                duration: 0,
                render: function($container, $newContent) {
                    $container.removeClass('is-exiting');
                    $container.html($newContent);
                    if ($(window).width() < 768) {
                        initSlideout();
                    }
                    if(document.getElementById("particles-js")!=null){
                        initParticles();
                    }
                    window.retinajs();
                }
            }
        },
        smoothState = $('#animate-wrapper').smoothState(options).data('smoothState');

    var resizeId;

    if ($(window).width() < 768) {
        initSlideout();
    }

    $(window).resize(function() {
        clearTimeout(resizeId);
        resizeId = setTimeout(doneResizing, 500);
    });

    function doneResizing() {
        if ($(window).width() < 768) {
            initSlideout();
        }
        if ($('#slideout-nav').hasClass('slideout-menu') && $(window).width() >= 768) {
            slideout.close();
        }
    }

    function initParticles() {
        particlesJS.load('particles-js', '/assets/json/particles.json');
    }

    if(document.getElementById("particles-js")!=null){
        initParticles();
    }

    window.retinajs();

});
<|endoftext|>


<commit_before>
/*!--------------------------------*\
   3-Jekyll Theme
   @author Peiwen Lu (P233)
   https://github.com/P233/3-Jekyll
\*---------------------------------*/

// Detect window size, if less than 1280px add class 'mobile' to sidebar therefore it will be auto hide when trigger the pjax request in small screen devices.
if ($(window).width() <= 1280) {
  $('#sidebar').addClass('mobile')
}

// Variables
    tag1       = $('.pl__all'),
    tag2       = $('.start'),
    tag3       = $('.resume'),
    tag4       = $('.leetcode'),
    tag5       = $('.job'),
    tag6       = $('.note');
var sidebar    = $('#sidebar'),
    container  = $('#post'),
    content    = $('#pjax'),
    button     = $('#icon-arrow');

// Tags switcher
var clickHandler = function(k) {
  return function() {
    $(this).addClass('active').siblings().removeClass('active');
    tag1.hide();
    window['tag'+k].delay(50).fadeIn(350);
  }
};
for (var i = 1; i <= 6; i++) {
  $('#js-label' + i).on('click', clickHandler(i));
}

// If sidebar has class 'mobile', hide it after clicking.
tag1.on('click', function() {
  $(this).addClass('active').siblings().removeClass('active');
  if (sidebar.hasClass('mobile')) {
    $('#sidebar, #pjax, #icon-arrow').addClass('fullscreen');
  }
});

// Enable fullscreen.
$('#js-fullscreen').on('click', function() {
  if (button.hasClass('fullscreen')) {
    sidebar.removeClass('fullscreen');
    button.removeClass('fullscreen');
    content.delay(300).queue(function(){
      $(this).removeClass('fullscreen').dequeue();
    });
  } else {
    sidebar.addClass('fullscreen');
    button.addClass('fullscreen');
    content.delay(200).queue(function(){
      $(this).addClass('fullscreen').dequeue();
    });
  }
});

$('#mobile-avatar').on('click', function(){
  $('#sidebar, #pjax, #icon-arrow').addClass('fullscreen');
});

//tr hover event by weiier
$('.trProject').hover(function(e){
		for(i in e){
			console.log(i);
		}
		$('.trDetail').show();
	},function(){
		$('.trDetail').hide();
	}
)

// Pjax
$(document).pjax('#avatar, #mobile-avatar, .pl__all', '#pjax', { fragment: '#pjax', timeout: 10000 });
$(document).on({
  'pjax:click': function() {
    content.removeClass('fadeIn').addClass('fadeOut');
    NProgress.start();
  },
  'pjax:start': function() {
    content.css({'opacity':0});
  },
  'pjax:end': function() {
    NProgress.done();
    container.scrollTop(0);
    content.css({'opacity':1}).removeClass('fadeOut').addClass('fadeIn');
    afterPjax();
  }
});

// Codepen embed js
// http://codepen.io/assets/embed/ei.js
// Added on 17 Nov 2013
var CodePenEmbed={width:"100%",init:function(){this.showCodePenEmbeds(),this.listenToParentPostMessages()},showCodePenEmbeds:function(){var e=document.getElementsByClassName("codepen");for(var t=e.length-1;t>-1;t--){var n=this._getParamsFromAttributes(e[t]);n=this._convertOldDataAttributesToNewDataAttributes(n);var r=this._buildURL(n),i=this._buildIFrame(n,r);this._addIFrameToPage(e[t],i)}},_getParamsFromAttributes:function(e){var t={},n=e.attributes;for(var r=0,i=n.length;r<i;r++)name=n[r].name,name.indexOf("data-")===0&&(t[name.replace("data-","")]=n[r].value);return t},_convertOldDataAttributesToNewDataAttributes:function(e){return e.href&&(e["slug-hash"]=e.href),e.type&&(e["default-tab"]=e.type),e.safe&&(e["safe"]=="true"?e.animations="run":e.animations="stop-after-5"),e},_buildURL:function(e){var t=this._getHost(e),n=e.user?e.user:"anon",r="?"+this._getGetParams(e),i=[t,n,"embed",e["slug-hash"]+r].join("/");return i.replace(/\/\//g,"//")},_getHost:function(e){return e.host?e.host:document.location.protocol=="file:"?"http://codepen.io":"//codepen.io"},_getGetParams:function(e){var t="",n=0;for(var r in e)t!==""&&(t+="&"),t+=r+"="+encodeURIComponent(e[r]);return t},_buildIFrame:function(e,t){var n={id:"cp_embed_"+e["slug-hash"].replace("/","_"),src:t,scrolling:"no",frameborder:"0",height:this._getHeight(e),allowTransparency:"true","class":"cp_embed_iframe",style:"width: "+this.width+"; overflow: hidden;"},r="",r},_getHeight:function(e){return e.height?e["height"]=="auto"?300:e.height:300},_addIFrameToPage:function(e,t){if(e.parentNode){var n=document.createElement("div");n.innerHTML=t,e.parentNode.replaceChild(n,e)}else e.innerHTML=t},listenToParentPostMessages:function(){var eventMethod=window.addEventListener?"addEventListener":"attachEvent",eventListener=window[eventMethod],messageEvent=eventMethod=="attachEvent"?"onmessage":"message";eventListener(messageEvent,function(e){try{var dataObj=eval("("+e.data+")"),iframe=document.getElementById("cp_embed_"+dataObj.hash);iframe&&(iframe.height=dataObj.height)}catch(err){}},!1)}};

// Re-run scripts for post content after pjax
function afterPjax() {
  // Open links in new tab
  $('#post__content a').attr('target','_blank');

  // Embed codepen after pjax
  CodePenEmbed.init();

  // Generate post TOC for h1 h2 and h3
  var toc = $('#post__toc-ul');
  // Empty TOC and generate an entry for h1
  toc.empty().append('
' + $('#post__title').text() + '
');

  // Generate entries for h2 and h3
  $('#post__content').children('h2,h3').each(function() {
    // Generate random ID for each heading
    $(this).attr('id', function() {
      var ID = "",
          alphabet = "abcdefghijklmnopqrstuvwxyz";

      for(var i=0; i < 5; i++) {
        ID += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
      }
      return ID;
    });

    if ($(this).prop("tagName") == 'H2') {
      toc.append('
' + $(this).text() + '
');
    } else {
      toc.append('
' + $(this).text() + '
');
    }
  });

  // Smooth scrolling
  $('.js-anchor-link').on('click', function() {
    var target = $(this.hash);
    container.animate({scrollTop: target.offset().top + container.scrollTop() - 70}, 500, function() {
      target.addClass('flash').delay(700).queue(function() {
        $(this).removeClass('flash').dequeue();
      });
    });
  });

  // Lazy Loading Disqus
  // http://jsfiddle.net/dragoncrew/SHGwe/1/
  var ds_loaded = false,
      top = $('#disqus_thread').offset().top;
      identifier = $('#post__title').data('identifier');
  window.disqus_shortname = 'weiier';
  window.disqus_identifier = identifier;

  function check() {
    if ( !ds_loaded && container.scrollTop() + container.height() > top ) {
      $.ajax({
        type: 'GET',
        url: 'http://' + disqus_shortname + '.disqus.com/embed.js',
        dataType: 'script',
        cache: true
      });
      ds_loaded = true;
    }
  }check();
  container.scroll(check);
}afterPjax();

<commit_msg>resume<commit_after>
/*!--------------------------------*\
   3-Jekyll Theme
   @author Peiwen Lu (P233)
   https://github.com/P233/3-Jekyll
\*---------------------------------*/

// Detect window size, if less than 1280px add class 'mobile' to sidebar therefore it will be auto hide when trigger the pjax request in small screen devices.
if ($(window).width() <= 1280) {
  $('#sidebar').addClass('mobile')
}

// Variables
    tag1       = $('.pl__all'),
    tag2       = $('.start'),
    tag3       = $('.resume'),
    tag4       = $('.leetcode'),
    tag5       = $('.job'),
    tag6       = $('.note');
var sidebar    = $('#sidebar'),
    container  = $('#post'),
    content    = $('#pjax'),
    button     = $('#icon-arrow');

// Tags switcher
var clickHandler = function(k) {
  return function() {
    $(this).addClass('active').siblings().removeClass('active');
    tag1.hide();
    window['tag'+k].delay(50).fadeIn(350);
  }
};
for (var i = 1; i <= 6; i++) {
  $('#js-label' + i).on('click', clickHandler(i));
}

// If sidebar has class 'mobile', hide it after clicking.
tag1.on('click', function() {
  $(this).addClass('active').siblings().removeClass('active');
  if (sidebar.hasClass('mobile')) {
    $('#sidebar, #pjax, #icon-arrow').addClass('fullscreen');
  }
});

// Enable fullscreen.
$('#js-fullscreen').on('click', function() {
  if (button.hasClass('fullscreen')) {
    sidebar.removeClass('fullscreen');
    button.removeClass('fullscreen');
    content.delay(300).queue(function(){
      $(this).removeClass('fullscreen').dequeue();
    });
  } else {
    sidebar.addClass('fullscreen');
    button.addClass('fullscreen');
    content.delay(200).queue(function(){
      $(this).addClass('fullscreen').dequeue();
    });
  }
});

$('#mobile-avatar').on('click', function(){
  $('#sidebar, #pjax, #icon-arrow').addClass('fullscreen');
});

//tr hover event by weiier
$('.trProject').hover(function(e){
		$target =$(e.target);
		for(i in $target){
			console.log(i);
		}
		$('.trDetail').show();
	},function(){
		$('.trDetail').hide();
	}
)

// Pjax
$(document).pjax('#avatar, #mobile-avatar, .pl__all', '#pjax', { fragment: '#pjax', timeout: 10000 });
$(document).on({
  'pjax:click': function() {
    content.removeClass('fadeIn').addClass('fadeOut');
    NProgress.start();
  },
  'pjax:start': function() {
    content.css({'opacity':0});
  },
  'pjax:end': function() {
    NProgress.done();
    container.scrollTop(0);
    content.css({'opacity':1}).removeClass('fadeOut').addClass('fadeIn');
    afterPjax();
  }
});

// Codepen embed js
// http://codepen.io/assets/embed/ei.js
// Added on 17 Nov 2013
var CodePenEmbed={width:"100%",init:function(){this.showCodePenEmbeds(),this.listenToParentPostMessages()},showCodePenEmbeds:function(){var e=document.getElementsByClassName("codepen");for(var t=e.length-1;t>-1;t--){var n=this._getParamsFromAttributes(e[t]);n=this._convertOldDataAttributesToNewDataAttributes(n);var r=this._buildURL(n),i=this._buildIFrame(n,r);this._addIFrameToPage(e[t],i)}},_getParamsFromAttributes:function(e){var t={},n=e.attributes;for(var r=0,i=n.length;r<i;r++)name=n[r].name,name.indexOf("data-")===0&&(t[name.replace("data-","")]=n[r].value);return t},_convertOldDataAttributesToNewDataAttributes:function(e){return e.href&&(e["slug-hash"]=e.href),e.type&&(e["default-tab"]=e.type),e.safe&&(e["safe"]=="true"?e.animations="run":e.animations="stop-after-5"),e},_buildURL:function(e){var t=this._getHost(e),n=e.user?e.user:"anon",r="?"+this._getGetParams(e),i=[t,n,"embed",e["slug-hash"]+r].join("/");return i.replace(/\/\//g,"//")},_getHost:function(e){return e.host?e.host:document.location.protocol=="file:"?"http://codepen.io":"//codepen.io"},_getGetParams:function(e){var t="",n=0;for(var r in e)t!==""&&(t+="&"),t+=r+"="+encodeURIComponent(e[r]);return t},_buildIFrame:function(e,t){var n={id:"cp_embed_"+e["slug-hash"].replace("/","_"),src:t,scrolling:"no",frameborder:"0",height:this._getHeight(e),allowTransparency:"true","class":"cp_embed_iframe",style:"width: "+this.width+"; overflow: hidden;"},r="",r},_getHeight:function(e){return e.height?e["height"]=="auto"?300:e.height:300},_addIFrameToPage:function(e,t){if(e.parentNode){var n=document.createElement("div");n.innerHTML=t,e.parentNode.replaceChild(n,e)}else e.innerHTML=t},listenToParentPostMessages:function(){var eventMethod=window.addEventListener?"addEventListener":"attachEvent",eventListener=window[eventMethod],messageEvent=eventMethod=="attachEvent"?"onmessage":"message";eventListener(messageEvent,function(e){try{var dataObj=eval("("+e.data+")"),iframe=document.getElementById("cp_embed_"+dataObj.hash);iframe&&(iframe.height=dataObj.height)}catch(err){}},!1)}};

// Re-run scripts for post content after pjax
function afterPjax() {
  // Open links in new tab
  $('#post__content a').attr('target','_blank');

  // Embed codepen after pjax
  CodePenEmbed.init();

  // Generate post TOC for h1 h2 and h3
  var toc = $('#post__toc-ul');
  // Empty TOC and generate an entry for h1
  toc.empty().append('
' + $('#post__title').text() + '
');

  // Generate entries for h2 and h3
  $('#post__content').children('h2,h3').each(function() {
    // Generate random ID for each heading
    $(this).attr('id', function() {
      var ID = "",
          alphabet = "abcdefghijklmnopqrstuvwxyz";

      for(var i=0; i < 5; i++) {
        ID += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
      }
      return ID;
    });

    if ($(this).prop("tagName") == 'H2') {
      toc.append('
' + $(this).text() + '
');
    } else {
      toc.append('
' + $(this).text() + '
');
    }
  });

  // Smooth scrolling
  $('.js-anchor-link').on('click', function() {
    var target = $(this.hash);
    container.animate({scrollTop: target.offset().top + container.scrollTop() - 70}, 500, function() {
      target.addClass('flash').delay(700).queue(function() {
        $(this).removeClass('flash').dequeue();
      });
    });
  });

  // Lazy Loading Disqus
  // http://jsfiddle.net/dragoncrew/SHGwe/1/
  var ds_loaded = false,
      top = $('#disqus_thread').offset().top;
      identifier = $('#post__title').data('identifier');
  window.disqus_shortname = 'weiier';
  window.disqus_identifier = identifier;

  function check() {
    if ( !ds_loaded && container.scrollTop() + container.height() > top ) {
      $.ajax({
        type: 'GET',
        url: 'http://' + disqus_shortname + '.disqus.com/embed.js',
        dataType: 'script',
        cache: true
      });
      ds_loaded = true;
    }
  }check();
  container.scroll(check);
}afterPjax();

<|endoftext|>


<commit_before>describe("Menu Navigation", function() {

    var testGM;

    beforeEach(function() {
        testGM = new GameManager();
        testGM.screenmanager.root = new MainMenuScreen("home");
        testGM.screenmanager.root.start();
    });

    it("should be able to navigate from home to user-login", function() {
        testGM.screenmanager.changePage("user-login");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("user-login");
    });

    it("should navigate back a page correctly", function() {
        testGM.screenmanager.changePage("user-login");
        testGM.screenmanager.changePage("back");

        expect(testGM.screenmanager.topScreen.menuName).toEqual("home");
    });

    it("should be able to navigate from home screen to guest login", function(){
        testGM.screenmanager.changePage("guest-login");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("guest-login");
    });

    it("should be able to navigate from home screen to teacher login", function(){
        testGM.screenmanager.changePage("teacher-login");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("teacher-login");
    });

    it("should be able to navigate from home screen to creator login", function(){
        testGM.screenmanager.changePage("creator-login");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("creator-login");
    });

});

describe("User Management", function() {

    var testGM;

    beforeEach(function() {
        testGM = new GameManager();
        testGM.screenmanager.root = new MainMenuScreen("home");
        testGM.screenmanager.root.start();
    });

    it("should be able to add a new user", function() {
        var testUser = new User(5);
        testGM.addUser(testUser);

        expect(testGM.users.length).toEqual(1);
    });

    it("should initialize a user's id correctly", function() {
        var testUser = new User(42);
        testGM.addUser(testUser);

        expect(testGM.getUser(42).id).toEqual(42);
    });

    it("should be able to remove a user", function() {
        var testUser1 = new User(1);
        var testUser2 = new User(2);
        testGM.addUser(testUser1);
        testGM.addUser(testUser2);
        testGM.removeUser(1);

        expect(testGM.users.length).toEqual(1);
    });
});

describe("In Game Menu Navigation", function(){

    var testGM;

    beforeEach(function() {
        testGM = new GameManager();
        testGM.screenmanager.root = new MainMenuScreen("home");
        testGM.screenmanager.root.start();
    });

    it("should be able to start a single player game", function(){
        testGM.screenmanager.changePage("levels");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("levels");
    });

    it("should be able to start a multiplayer player game", function(){
        testGM.screenmanager.changePage("levels");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("levels");
    });

    it("should be able to go to settings", function(){
        testGM.screenmanager.changePage("settings");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("settings");
    });

    it("should be able to logout", function(){
        testGM.screenmanager.changePage("logout");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("logout");
    });
});

describe("Teacher Options Menu Navigation", function(){

    var testGM;

    beforeEach(function() {
        testGM = new GameManager();
        testGM.screenmanager.root = new MainMenuScreen("home");
        testGM.screenmanager.root.start();
    });

    it("should be able to navigate to view students", function(){
        testGM.screenmanager.changePage("view-students");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("view-students");
    });

    it("should be able to navigate to assign students page", function(){
        testGM.screenmanager.changePage("assign-students");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("assign-students");
    });

    it("should be able to navigate to send reminders", function(){
        testGM.screenmanager.changePage("send-reminders");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("send-reminders");
    });

});

<commit_msg>added settings menu navigation tests<commit_after>describe("Menu Navigation", function() {

    var testGM;

    beforeEach(function() {
        testGM = new GameManager();
        testGM.screenmanager.root = new MainMenuScreen("home");
        testGM.screenmanager.root.start();
    });

    it("should be able to navigate from home to user-login", function() {
        testGM.screenmanager.changePage("user-login");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("user-login");
    });

    it("should navigate back a page correctly", function() {
        testGM.screenmanager.changePage("user-login");
        testGM.screenmanager.changePage("back");

        expect(testGM.screenmanager.topScreen.menuName).toEqual("home");
    });

    it("should be able to navigate from home screen to guest login", function(){
        testGM.screenmanager.changePage("guest-login");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("guest-login");
    });

    it("should be able to navigate from home screen to teacher login", function(){
        testGM.screenmanager.changePage("teacher-login");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("teacher-login");
    });

    it("should be able to navigate from home screen to creator login", function(){
        testGM.screenmanager.changePage("creator-login");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("creator-login");
    });

});

describe("User Management", function() {

    var testGM;

    beforeEach(function() {
        testGM = new GameManager();
        testGM.screenmanager.root = new MainMenuScreen("home");
        testGM.screenmanager.root.start();
    });

    it("should be able to add a new user", function() {
        var testUser = new User(5);
        testGM.addUser(testUser);

        expect(testGM.users.length).toEqual(1);
    });

    it("should initialize a user's id correctly", function() {
        var testUser = new User(42);
        testGM.addUser(testUser);

        expect(testGM.getUser(42).id).toEqual(42);
    });

    it("should be able to remove a user", function() {
        var testUser1 = new User(1);
        var testUser2 = new User(2);
        testGM.addUser(testUser1);
        testGM.addUser(testUser2);
        testGM.removeUser(1);

        expect(testGM.users.length).toEqual(1);
    });
});

describe("In Game Menu Navigation", function(){

    var testGM;

    beforeEach(function() {
        testGM = new GameManager();
        testGM.screenmanager.root = new MainMenuScreen("home");
        testGM.screenmanager.root.start();
    });

    it("should be able to start a single player game", function(){
        testGM.screenmanager.changePage("levels");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("levels");
    });

    it("should be able to start a multiplayer player game", function(){
    testGM.screenmanager.changePage("levels");
    expect(testGM.screenmanager.topScreen.menuName).toEqual("levels");
    });

    it("should be able to go to settings", function(){
    testGM.screenmanager.changePage("settings");
    expect(testGM.screenmanager.topScreen.menuName).toEqual("settings");
    });

    it("should be able to logout", function(){
        testGM.screenmanager.changePage("logout");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("logout");
    });
});

describe("Teacher Options Menu Navigation", function(){

    var testGM;

    beforeEach(function() {
        testGM = new GameManager();
        testGM.screenmanager.root = new MainMenuScreen("home");
        testGM.screenmanager.root.start();
    });

    it("should be able to navigate to the list of student names", function(){
        testGM.screenmanager.changePage("view-students");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("view-students");
    });

    it("should be able to navigate to assign students page", function(){
    testGM.screenmanager.changePage("assign-students");
    expect(testGM.screenmanager.topScreen.menuName).toEqual("assign-students");
    });

    it("should be able navigate to remind student page ", function(){
    testGM.screenmanager.changePage("send-reminder");
    expect(testGM.screenmanager.topScreen.menuName).toEqual("send-reminder");
    });

});

describe("Settings Menu Navigation", function(){

    var testGM;

    beforeEach(function() {
        testGM = new GameManager();
        testGM.screenmanager.root = new MainMenuScreen("home");
        testGM.screenmanager.root.start();
    });

    it("should be able to navigate difficulty page", function(){
        testGM.screenmanager.changePage("chosen");
        expect(testGM.screenmanager.topScreen.menuName).toEqual("chosen");
    });

    it("should be able to navigate to sound page", function(){
    testGM.screenmanager.changePage("nothing");
    expect(testGM.screenmanager.topScreen.menuName).toEqual("nothing");
    });

});
<|endoftext|>