<commit_before>/* globals UTILS */

/*================================================
AJAX NOTIFICATION.
================================================*/

// Display an ajax notification using UTILS.ajax.
UTILS.ajax('../Web-App/data/notification.txt', {
	method: 'GET',
	done: function (response) {
		if (response && response !== '') {
			var message = UTILS.qs('.notifications');
			message.innerHTML = response;
			message.style.display = 'block';
		}
	},
	fail: function (err) {
		console.log(err.message);
	}
});

/*================================================
TABS BEHAVIOR.
================================================*/

// Get a panel connected to a tab.
var getPanel = function(tab) {
	var anchor = tab.getAttribute('href');
	var panel = document.getElementById(anchor.replace('#', '') + '-panel');
	return panel;
};

// Add activeTab class, connect it with a panel (activePanel), show the panel and disable other tabs.
var activate = function(tab) {
	// If another tab is activated, and it's equal to the new tab, break the function.
	if (UTILS.qs('.activeTab') && tab === UTILS.qs('.activeTab')) {
		return;
	}
	else {
		// Get the panel related to this tab.
		var panel = getPanel(tab);
		// Check if another tab has an active state and remove it.
		if (UTILS.qs('.activeTab')) {
			var activeTab = UTILS.qs('.activeTab');
			// Remove activeTab class.
			UTILS.removeClass(activeTab, 'activeTab');
			// Remove aria-selected attribute from previously active tab.
			activeTab.removeAttribute('aria-selected');
			// Set aria-selected='false' to previously active tab.
			activeTab.setAttribute('aria-selected', 'false');
			// Get the active panel.
			var activePanel = getPanel(activeTab);
			// Remove activePanel class.
			UTILS.removeClass(activePanel, 'activePanel');
			// Remove aria-hidden attribute from previously active panel.
			activePanel.removeAttribute('aria-hidden');
			// Set aria-hidden='true' to previously active panel.
			activePanel.setAttribute('aria-hidden', 'true');
		}
		// Activate new tab.
		UTILS.addClass(tab, 'activeTab');
		// Add aria-selected='true' attribute.
		tab.setAttribute('aria-selected', 'true');
		// Activate new Panel.
		UTILS.addClass(panel, 'activePanel');
		// Add aria-hidden='false' attribute.
		panel.setAttribute('aria-hidden', 'false');
	}
};

// This function triggers tab activation on 2 cases:
// 1. On hash change.
// 2. On page load according to hash.
var hash = function() {
	var count = 0;
	var hashVal = window.location.hash;
	// Get all tabs.
	var tabs = UTILS.qsa('.tab');
	// Iterate on tabs and trigger activation.
	for (var i = 0; i < tabs.length; i++) {
		var tab = tabs[i];
		var anchor = tab.getAttribute('href');
		if (anchor === hashVal) {
			activate(tab);
			count = count + 1;
		}
	}
	// If no tab was activated, activate default.
	if (count === 0) {
		window.location.hash = 'quick-reports';
		activate(tabs[0]);
	}
};

// Hash change event listener.
UTILS.addEvent(window, 'hashchange', hash);
// On page load.
hash();

/*================================================
DROPDOWNS BEHAVIOR.
================================================*/

// Close a key activated dropdown while hovering on other dropdowns.
var closeDropdown = function() {
    if (UTILS.qs('.active-menu')) {
	    var activeMenu = UTILS.qs('.active-menu');
	    UTILS.removeClass(activeMenu, 'active-menu');
   	}
   	return activeMenu;
};

// Open a dropdown on key press, or close an already active one.
var openDropdown = function(e) {
	var target = e.target || e.srcElement;
    // Check that it's a nav-section and not a container.
    if (UTILS.hasClass(target, 'nav-section')) {
    	UTILS.preventEvent(e);
	    var activeMenu = closeDropdown();
		if (activeMenu !== target) {
			UTILS.addClass(target, 'active-menu');
		}
	}
};

// Get dropdowns' wrapper.
var nav = document.getElementById('navigation');

// Attach listeners to dropdowns using UTILS.addEvent.
UTILS.addEvent(nav, 'keypress', UTILS.isEnterOrSpace(openDropdown));
UTILS.addEvent(nav, 'mouseover', closeDropdown);

/*================================================
TAB PANELS INTERACTIVITY.
================================================*/

// Add / remove a 'visible-form' class to display / hide a form.
var displayForm = function(e) {
	if (UTILS.hasClass(e.target, 'form-control-img')) {
		UTILS.preventEvent(e);
		var control = e.target;
		var connectedFormId = control.getAttribute('aria-controls');
		var connectedForm = document.getElementById(connectedFormId);
		if (UTILS.hasClass(connectedForm, 'visible-form')) {
			UTILS.removeClass(connectedForm, 'visible-form');
		}
		else {
			UTILS.addClass(connectedForm, 'visible-form');
		}
	}
};

// Get form controls.
var controls = UTILS.qsa('.form-control');
// Iterate on form controls.
for (var i = 0; i < controls.length; i++) {
	var control = controls[i];
	// 'click' event (connect to 'displayForm' function).
	UTILS.addEvent(control, 'click', displayForm);
	// 'keypress' event (connect to 'displayForm' function). Use DRY code (UTILS.isEnterOrSpace(func) function).
	UTILS.addEvent(control, 'keypress', UTILS.isEnterOrSpace(displayForm));
}

// Validate a fieldset (name and URL). Mark invalid fields with a red border.
var validateFieldset = function(e, name, url, siteArray) {
	// If invalid name.
	if (name.value === '') {
		// Prevent form submission.
		UTILS.preventEvent(e);
		// Add invalid class if it doesn't already exist.
		if (!UTILS.hasClass(name, 'invalid')) {
			UTILS.addClass(name, 'invalid');
		}
	}
	else {
		if (UTILS.hasClass(name, 'invalid')) {
			UTILS.removeClass(name, 'invalid');
		}
	}
	// If invalid URL (later with regex).
	if (url.value === '') {
		// Prevent form submission.
		UTILS.preventEvent(e);
		// Add invalid class if it doesn't already exist.
		if (!UTILS.hasClass(url, 'invalid')) {
			UTILS.addClass(url, 'invalid');
		}
	}
	else {
		if (UTILS.hasClass(url, 'invalid')) {
			UTILS.removeClass(url, 'invalid');
		}
	}
	// If fields are filled and validated, make an object with name and url.
	if (!UTILS.hasClass(name, 'invalid') && !UTILS.hasClass(url, 'invalid')) {
		var obj = {
			siteName: name.value,
			siteUrl: url.value
		};
		siteArray.push(obj);
	}
};

// Gets the relevant form and siteArray, displays / hides iframe/select/button and updates site list based on changes.
var displayWebsites = function(form, siteArray) {
	// Get form ID and use it as a class selector.
	var selector = '.' + UTILS.qs('.activePanel').querySelector('.form-wrap').id;
	// Get iframe/select/button connected to this ID with a class of the same name.
	var elements = UTILS.qsa(selector);
	// Iterate on all elements connected to form.
	for (var i = 0; i < elements.length; i++) {
		var elm = elements[i];
		console.log(elm);
		// If the array is empty, hide the element if it's not hidden and remove all attributes.
		if (!siteArray[0] && !UTILS.hasClass(elm, 'hidden')) {
			// If element is an iframe.
			if (elm.removeAttribute('src')) {
				console.log(elm.tagName);
				elm.removeAttribute('src', siteArray[0].siteUrl);
			}
			// If element is a button.
			if (elm.removeAttribute('href')) {
				elm.removeAttribute('href', siteArray[0].siteUrl);
			}
			// If element is a dropdown.
			if (elm.tagName === 'SELECT') {
				// init.
				while (elm.firstChild) {
				    elm.removeChild(elm.firstChild);
				}
			}
			// Hide all.
			UTILS.addClass(elm, 'hidden');
		}
		// If array is empty on first iteration.
		else if (!siteArray[0]) {
			console.log('do nothing!');
		}
		// If array is not empty, display elements and add attributes.
		else {
			// Display element.
			if (UTILS.hasClass(elm, 'hidden')) {
				UTILS.removeClass(elm, 'hidden');
			}
			// If element is an iframe
			if (elm.tagName === 'IFRAME') {
				console.log(elm.tagName);
				elm.setAttribute('src', siteArray[0].siteUrl);
			}
			// If element is a button.
			if (UTILS.hasClass(elm, 'to-website')) {
				elm.setAttribute('href', siteArray[0].siteUrl);
			}

			// If element is a dropdown.
			if (elm.tagName === 'SELECT') {
				// init.
				while (elm.firstChild) {
				    elm.removeChild(elm.firstChild);
				}
				// Create an option for each object in siteArray, with a name and a value.
				for (var j = 0; j < siteArray.length; j ++) {
					var option = document.createElement('OPTION');
					var text = document.createTextNode(siteArray[j].siteName);
					option.appendChild(text);
					option.setAttribute('value', siteArray[j].siteUrl);
					elm.appendChild(option);
				}
			}
			// Hide form if valid.
			UTILS.removeClass(form.parentNode, 'visible-form');
		}
	}
};

// Validate form input using HTML5 'required'.
// Validate URL if a site name was entered.
var validateForm = function(form) {
	return function(e) {
		// Contains name + URL objects.
		var siteArray = [];
		// Get all child fieldsets.
		var sets = form.getElementsByTagName('FIELDSET');
		// Inside each fieldset, if any of the fieldset's fields is not empty, activate validations.
		// Validations are: Name must not be empty, URL must be a legal URL.
		for (var i = 0; i < sets.length; i++) {
			var set = sets[i];
			var name = set.getElementsByTagName('INPUT')[0];
			var url = set.getElementsByTagName('INPUT')[1];
			// Only if one of the fields is not empty, start a fieldset validation process.
			if (name.value !== '' || url.value !== '') {
				console.log('start validation!');
				validateFieldset(e, name, url, siteArray);
			}
			else {
				if (UTILS.hasClass(name, 'invalid')) {
					UTILS.removeClass(name, 'invalid');
				}
				if (UTILS.hasClass(url, 'invalid')) {
					UTILS.removeClass(url, 'invalid');
				}
			}
		}

		// Find if the form is valid.
		if (form.querySelectorAll('.invalid')[0]) {
			// Focus on the first invalid field.
			console.log('some invalid');
			form.querySelectorAll('.invalid')[0].focus();
		}
		else {
			UTILS.preventEvent(e);
			// Catch valid objects containing site name and site URL (inside of siteArray).
			displayWebsites(form, siteArray);
		}
	};
};

// Get forms.
var forms = UTILS.qsa('.enterSite');
// Iterate forms.
for (var i = 0; i < forms.length; i++) {
	var form = forms[i];
	// 'submit' event (connect to 'validateForm' function).
	UTILS.addEvent(form, 'submit', validateForm(form));
}

// Select a website from the dropdown, display in an iframe and make the arrow button point at it.
var selectHandler = function(e) {
	if (e.target.tagName === 'SELECT') {
		var target = e.target;
		// Get selected value.
		var getValue = target.options[target.selectedIndex].value;
		console.log(getValue);
		// Get the active panel.
		var panel = UTILS.qs('.activePanel');
		// Get the iframe.
		var iframe = panel.querySelector('iframe');
		// Get the button.
		var button = panel.querySelector('.to-website');
		// CHange atributes.
		iframe.setAttribute('src', getValue);
		button.setAttribute('href', getValue);
	}
};

// 'change' event (connect to 'select' function).
var selects = document.getElementsByTagName('SELECT');
// Iterate on selects.
for (var i = 0; i < selects.length; i++) {
	var select = selects[i];
	console.log(select);
	UTILS.addEvent(select, 'change', selectHandler);
}

<commit_msg>minor changes<commit_after>/* globals UTILS */

/*================================================
AJAX NOTIFICATION.
================================================*/

// Display an ajax notification using UTILS.ajax.
UTILS.ajax('../Web-App/data/notification.txt', {
	method: 'GET',
	done: function (response) {
		if (response && response !== '') {
			var message = UTILS.qs('.notifications');
			message.innerHTML = response;
			message.style.display = 'block';
		}
	},
	fail: function (err) {
		console.log(err.message);
	}
});

/*================================================
TABS BEHAVIOR.
================================================*/

// Get a panel connected to a tab.
var getPanel = function(tab) {
	var anchor = tab.getAttribute('href');
	var panel = document.getElementById(anchor.replace('#', '') + '-panel');
	return panel;
};

// Add activeTab class, connect it with a panel (activePanel), show the panel and disable other tabs.
var activate = function(tab) {
	// If another tab is activated, and it's equal to the new tab, break the function.
	if (UTILS.qs('.activeTab') && tab === UTILS.qs('.activeTab')) {
		return;
	}
	else {
		// Get the panel related to this tab.
		var panel = getPanel(tab);
		// Check if another tab has an active state and remove it.
		if (UTILS.qs('.activeTab')) {
			var activeTab = UTILS.qs('.activeTab');
			// Remove activeTab class.
			UTILS.removeClass(activeTab, 'activeTab');
			// Remove aria-selected attribute from previously active tab.
			activeTab.removeAttribute('aria-selected');
			// Set aria-selected='false' to previously active tab.
			activeTab.setAttribute('aria-selected', 'false');
			// Get the active panel.
			var activePanel = getPanel(activeTab);
			// Remove activePanel class.
			UTILS.removeClass(activePanel, 'activePanel');
			// Remove aria-hidden attribute from previously active panel.
			activePanel.removeAttribute('aria-hidden');
			// Set aria-hidden='true' to previously active panel.
			activePanel.setAttribute('aria-hidden', 'true');
		}
		// Activate new tab.
		UTILS.addClass(tab, 'activeTab');
		// Add aria-selected='true' attribute.
		tab.setAttribute('aria-selected', 'true');
		// Activate new Panel.
		UTILS.addClass(panel, 'activePanel');
		// Add aria-hidden='false' attribute.
		panel.setAttribute('aria-hidden', 'false');
	}
};

// This function triggers tab activation on 2 cases:
// 1. On hash change.
// 2. On page load according to hash.
var hash = function() {
	var count = 0;
	var hashVal = window.location.hash;
	// Get all tabs.
	var tabs = UTILS.qsa('.tab');
	// Iterate on tabs and trigger activation.
	for (var i = 0; i < tabs.length; i++) {
		var tab = tabs[i];
		var anchor = tab.getAttribute('href');
		if (anchor === hashVal) {
			activate(tab);
			count = count + 1;
		}
	}
	// If no tab was activated, activate default.
	if (count === 0) {
		window.location.hash = 'quick-reports';
		activate(tabs[0]);
	}
};

// Hash change event listener.
UTILS.addEvent(window, 'hashchange', hash);
// On page load.
hash();

/*================================================
DROPDOWNS BEHAVIOR.
================================================*/

// Close a key activated dropdown while hovering on other dropdowns.
var closeDropdown = function() {
    if (UTILS.qs('.active-menu')) {
	    var activeMenu = UTILS.qs('.active-menu');
	    UTILS.removeClass(activeMenu, 'active-menu');
   	}
   	return activeMenu;
};

// Open a dropdown on key press, or close an already active one.
var openDropdown = function(e) {
	var target = e.target;
    // Check that it's a nav-section and not a container.
    if (UTILS.hasClass(target, 'nav-section')) {
    	UTILS.preventEvent(e);
	    var activeMenu = closeDropdown();
		if (activeMenu !== target) {
			UTILS.addClass(target, 'active-menu');
		}
	}
};

// Get dropdowns' wrapper.
var nav = document.getElementById('navigation');

// Attach listeners to dropdowns using UTILS.addEvent.
UTILS.addEvent(nav, 'keypress', UTILS.isEnterOrSpace(openDropdown));
UTILS.addEvent(nav, 'mouseover', closeDropdown);

/*================================================
TAB PANELS INTERACTIVITY.
================================================*/

// Add / remove a 'visible-form' class to display / hide a form.
var displayForm = function(e) {
	if (UTILS.hasClass(e.target, 'form-control-img')) {
		UTILS.preventEvent(e);
		var control = e.target;
		var connectedFormId = control.getAttribute('aria-controls');
		var connectedForm = document.getElementById(connectedFormId);
		if (UTILS.hasClass(connectedForm, 'visible-form')) {
			UTILS.removeClass(connectedForm, 'visible-form');
		}
		else {
			UTILS.addClass(connectedForm, 'visible-form');
		}
	}
};

// Get form controls.
var controls = UTILS.qsa('.form-control');
// Iterate on form controls.
for (var i = 0; i < controls.length; i++) {
	var control = controls[i];
	// 'click' event (connect to 'displayForm' function).
	UTILS.addEvent(control, 'click', displayForm);
	// 'keypress' event (connect to 'displayForm' function). Use DRY code (UTILS.isEnterOrSpace(func) function).
	UTILS.addEvent(control, 'keypress', UTILS.isEnterOrSpace(displayForm));
}

// Validate a fieldset (name and URL). Mark invalid fields with a red border.
var validateFieldset = function(e, name, url, siteArray) {
	// If invalid name.
	if (name.value === '') {
		// Prevent form submission.
		UTILS.preventEvent(e);
		// Add invalid class if it doesn't already exist.
		if (!UTILS.hasClass(name, 'invalid')) {
			UTILS.addClass(name, 'invalid');
		}
	}
	else {
		if (UTILS.hasClass(name, 'invalid')) {
			UTILS.removeClass(name, 'invalid');
		}
	}
	// If invalid URL (later with regex).
	if (url.value === '') {
		// Prevent form submission.
		UTILS.preventEvent(e);
		// Add invalid class if it doesn't already exist.
		if (!UTILS.hasClass(url, 'invalid')) {
			UTILS.addClass(url, 'invalid');
		}
	}
	else {
		if (UTILS.hasClass(url, 'invalid')) {
			UTILS.removeClass(url, 'invalid');
		}
	}
	// If fields are filled and validated, make an object with name and url.
	if (!UTILS.hasClass(name, 'invalid') && !UTILS.hasClass(url, 'invalid')) {
		var obj = {
			siteName: name.value,
			siteUrl: url.value
		};
		siteArray.push(obj);
	}
};

// Gets the relevant form and siteArray, displays / hides iframe/select/button and updates site list based on changes.
var displayWebsites = function(form, siteArray) {
	// Get form ID and use it as a class selector.
	var selector = '.' + UTILS.qs('.activePanel').querySelector('.form-wrap').id;
	// Get iframe/select/button connected to this ID with a class of the same name.
	var elements = UTILS.qsa(selector);
	// Iterate on all elements connected to form.
	for (var i = 0; i < elements.length; i++) {
		var elm = elements[i];
		console.log(elm);
		// If the array is empty, hide the element if it's not hidden and remove all attributes.
		if (!siteArray[0] && !UTILS.hasClass(elm, 'hidden')) {
			// If element is an iframe.
			if (elm.removeAttribute('src')) {
				console.log(elm.tagName);
				elm.removeAttribute('src', siteArray[0].siteUrl);
			}
			// If element is a button.
			if (elm.removeAttribute('href')) {
				elm.removeAttribute('href', siteArray[0].siteUrl);
			}
			// If element is a dropdown.
			if (elm.tagName === 'SELECT') {
				// init.
				while (elm.firstChild) {
				    elm.removeChild(elm.firstChild);
				}
			}
			// Hide all.
			UTILS.addClass(elm, 'hidden');
		}
		// If array is empty on first iteration.
		else if (!siteArray[0]) {
			console.log('do nothing!');
		}
		// If array is not empty, display elements and add attributes.
		else {
			// Display element.
			if (UTILS.hasClass(elm, 'hidden')) {
				UTILS.removeClass(elm, 'hidden');
			}
			// If element is an iframe
			if (elm.tagName === 'IFRAME') {
				console.log(elm.tagName);
				elm.setAttribute('src', siteArray[0].siteUrl);
			}
			// If element is a button.
			if (UTILS.hasClass(elm, 'to-website')) {
				elm.setAttribute('href', siteArray[0].siteUrl);
			}

			// If element is a dropdown.
			if (elm.tagName === 'SELECT') {
				// init.
				while (elm.firstChild) {
				    elm.removeChild(elm.firstChild);
				}
				// Create an option for each object in siteArray, with a name and a value.
				for (var j = 0; j < siteArray.length; j ++) {
					var option = document.createElement('OPTION');
					var text = document.createTextNode(siteArray[j].siteName);
					option.appendChild(text);
					option.setAttribute('value', siteArray[j].siteUrl);
					elm.appendChild(option);
				}
			}
			// Hide form if valid.
			UTILS.removeClass(form.parentNode, 'visible-form');
		}
	}
};

// Validate form input using HTML5 'required'.
// Validate URL if a site name was entered.
var validateForm = function(form) {
	return function(e) {
		// Contains name + URL objects.
		var siteArray = [];
		// Get all child fieldsets.
		var sets = form.getElementsByTagName('FIELDSET');
		// Inside each fieldset, if any of the fieldset's fields is not empty, activate validations.
		// Validations are: Name must not be empty, URL must be a legal URL.
		for (var i = 0; i < sets.length; i++) {
			var set = sets[i];
			var name = set.getElementsByTagName('INPUT')[0];
			var url = set.getElementsByTagName('INPUT')[1];
			// Only if one of the fields is not empty, start a fieldset validation process.
			if (name.value !== '' || url.value !== '') {
				console.log('start validation!');
				validateFieldset(e, name, url, siteArray);
			}
			else {
				if (UTILS.hasClass(name, 'invalid')) {
					UTILS.removeClass(name, 'invalid');
				}
				if (UTILS.hasClass(url, 'invalid')) {
					UTILS.removeClass(url, 'invalid');
				}
			}
		}

		// Find if the form is valid.
		if (form.querySelectorAll('.invalid')[0]) {
			// Focus on the first invalid field.
			console.log('some invalid');
			form.querySelectorAll('.invalid')[0].focus();
		}
		else {
			UTILS.preventEvent(e);
			// Catch valid objects containing site name and site URL (inside of siteArray).
			displayWebsites(form, siteArray);
		}
	};
};

// Get forms.
var forms = UTILS.qsa('.enterSite');
// Iterate forms.
for (var i = 0; i < forms.length; i++) {
	var form = forms[i];
	// 'submit' event (connect to 'validateForm' function).
	UTILS.addEvent(form, 'submit', validateForm(form));
}

// Select a website from the dropdown, display in an iframe and make the arrow button point at it.
var selectHandler = function(e) {
	if (e.target.tagName === 'SELECT') {
		var target = e.target;
		// Get selected value.
		var getValue = target.options[target.selectedIndex].value;
		console.log(getValue);
		// Get the active panel.
		var panel = UTILS.qs('.activePanel');
		// Get the iframe.
		var iframe = panel.querySelector('iframe');
		// Get the button.
		var button = panel.querySelector('.to-website');
		// CHange atributes.
		iframe.setAttribute('src', getValue);
		button.setAttribute('href', getValue);
	}
};

// 'change' event (connect to 'select' function).
var selects = document.getElementsByTagName('SELECT');
// Iterate on selects.
for (var i = 0; i < selects.length; i++) {
	var select = selects[i];
	console.log(select);
	UTILS.addEvent(select, 'change', selectHandler);
}

<|endoftext|>


<commit_before>data = [
    {
        "question_number": "0",
        "question_value": "V2hhdCBpcyAxICsxPw==",
        "question_type": "text",
        "answer_value": "Mg==",
        "answer_type": "text",
        "story_value": "T25jZSB1cG9uIGEgdGltZS4uLg",
        "story_type": "text"
    },
    {
        "question_number": "1",
        "question_value": "V2hhdCBpcyAxICsxPw==", //always add '==' at the end
        "question_type": "text",
        "answer_value": "Mg==", //always add '==' at the end
        "answer_type": "text",
        "story_value": "PHA+TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gRG9uZWMgbm9uIGdyYXZpZGEgZXJhdC4gQWVuZWFuIG5vbiBsaWJlcm8gZGFwaWJ1cywgdGluY2lkdW50IGFudGUgZXVpc21vZCwgZWZmaWNpdHVyIHRlbGx1cy4gRnVzY2UgZXUgcGVsbGVudGVzcXVlIG5pYmguIFNlZCBzZW1wZXIgbWF4aW11cyBvZGlvLCBpZCBjb25kaW1lbnR1bSBtYWduYSBzb2xsaWNpdHVkaW4gdXQuIEFlbmVhbiBtb2xsaXMgbnVuYyBkaWN0dW0gY3Vyc3VzIHNvbGxpY2l0dWRpbi4gUHJvaW4gZmV1Z2lhdCBtYXNzYSBldSByaG9uY3VzIHJ1dHJ1bS4gTnVsbGEgcXVpcyBsaWJlcm8gYWMgYW50ZSBwb3J0YSBmaW5pYnVzIHZlbCB2ZWwgZXJhdC4gVmVzdGlidWx1bSBlZ2V0IHJpc3VzIHNpdCBhbWV0IG51bGxhIGxvYm9ydGlzIGN1cnN1cy4gU3VzcGVuZGlzc2Ugc2l0IGFtZXQgaW1wZXJkaWV0IHVybmEsIHNlZCBtb2xsaXMgZXJhdC4gQWxpcXVhbSBldSBkdWkgbm9uIGxhY3VzIGxvYm9ydGlzIGxhb3JlZXQuIFZlc3RpYnVsdW0gZXUganVzdG8gZGljdHVtLCBzdXNjaXBpdCBuaXNsIHF1aXMsIGdyYXZpZGEgc2VtLiBNb3JiaSBlZmZpY2l0dXIgcGxhY2VyYXQgZXgsIGV0IGxhY2luaWEgbGFjdXMgdmVzdGlidWx1bSBub24uIFZpdmFtdXMgdmVoaWN1bGEsIGlwc3VtIHZlbCBmaW5pYnVzIHZlc3RpYnVsdW0sIG5pYmggYXVndWUgZ3JhdmlkYSBuaXNpLCBzZWQgY29uc2VxdWF0IG1pIHVybmEgdXQgbWV0dXMuPC9wPg0KDQo8cD5WZXN0aWJ1bHVtIGRpY3R1bSBkYXBpYnVzIG5pYmggc2l0IGFtZXQgZWZmaWNpdHVyLiBBZW5lYW4gZWZmaWNpdHVyIG1hdXJpcyBxdWlzIGVzdCBmZXVnaWF0LCBlZ2V0IGNvbnZhbGxpcyByaXN1cyBtYWxlc3VhZGEuIEludGVnZXIgdGVtcG9yIHZhcml1cyBpcHN1bSwgaW4gY29uZ3VlIGlwc3VtIHB1bHZpbmFyIHZlaGljdWxhLiBJbiBzZWQgdG9ydG9yIG5lYyBqdXN0byB2ZXN0aWJ1bHVtIGFsaXF1YW0gYWMgdXQgdXJuYS4gQ3VyYWJpdHVyIG5pYmggZXN0LCBiaWJlbmR1bSBpZCBuZXF1ZSBncmF2aWRhLCBncmF2aWRhIHZpdmVycmEgbGliZXJvLiBDcmFzIGNvbmd1ZSB0ZWxsdXMgaW4gZXggZXVpc21vZCwgZXUgZXVpc21vZCBwdXJ1cyBtb2xsaXMuIFBoYXNlbGx1cyB1bGxhbWNvcnBlciBlcmF0IHNhcGllbiwgYWMgY29uZ3VlIG5pYmggcG9ydHRpdG9yIGEuIFV0IG5vbiBsaWJlcm8gdXJuYS4gU2VkIHN1c2NpcGl0IGxvcmVtIGFjY3Vtc2FuIGVsaXQgcG9zdWVyZSwgdml0YWUgdGluY2lkdW50IGVsaXQgZGljdHVtLiBOdWxsYSBlbGVtZW50dW0gc2VtIHF1aXMgaXBzdW0gZWxlbWVudHVtIHVsdHJpY2VzLiBQcmFlc2VudCBldCBpbnRlcmR1bSBqdXN0by4gQWVuZWFuIGlkIG1hZ25hIG1pLiBWZXN0aWJ1bHVtIGEgc3VzY2lwaXQgbGlndWxhLCBzZWQgZWxlbWVudHVtIGVyYXQuPC9wPg0KDQo8cD5BbGlxdWFtIGVyYXQgdm9sdXRwYXQuIEFlbmVhbiBoZW5kcmVyaXQgbWFzc2EgYWMgYXVndWUgbWF0dGlzLCBpZCBkaWN0dW0gdHVycGlzIHNjZWxlcmlzcXVlLiBGdXNjZSBuZWMgbWkgZW5pbS4gRG9uZWMgYmxhbmRpdCB2ZXN0aWJ1bHVtIHN1c2NpcGl0LiBOdWxsYSBvcm5hcmUgbGVvIHNlZCBwdWx2aW5hciBhbGlxdWFtLiBDbGFzcyBhcHRlbnQgdGFjaXRpIHNvY2lvc3F1IGFkIGxpdG9yYSB0b3JxdWVudCBwZXIgY29udWJpYSBub3N0cmEsIHBlciBpbmNlcHRvcyBoaW1lbmFlb3MuIE51bmMgc2FnaXR0aXMgc2VkIGxvcmVtIGV1IHNlbXBlci48L3A+",
        "story_type": "html"
    }
];

var questionIndex = data.length - 1;
var wrongAnswer = "
Not quite there...
";

// this function decides which data item to show
function render(){
    if data[questionIndex]["question_type"] = "text" {
        $('#question').text(atob(data[questionIndex]["question_value"]));
    }
    else if data[questionIndex]["question_type"] = "html" {
        $('#question').html(atob(data[questionIndex]["question_value"]));
    }
}

// this function checks if an answer is correct
function toggleFields(){
    var userAnswer = $('#answer-input').val();
    var comparisonAnswer = atob(data[questionIndex]["answer_value"]);
    if (userAnswer == comparisonAnswer) {
        $('#story').html(atob(data[questionIndex]["story_value"]));
        $('#story').show();
    }
    else {
        $('#story').html(wrongAnswer);
        $('#story').show();
    }

}

// this function sets up things so the page actually does things
$(document).ready(function () {

    render();

    toggleFields(); //call this first so we start out with the correct visibility depending on the selected form values
    //this will call our toggleFields function every time the answer changes
    $('#answer button').click(function () {
        toggleFields();
    });

    $('#story').hide();

});
<commit_msg>changed ==<commit_after>data = [
    {
        "question_number": "0",
        "question_value": "V2hhdCBpcyAxICsxPw==",
        "question_type": "text",
        "answer_value": "Mg==",
        "answer_type": "text",
        "story_value": "T25jZSB1cG9uIGEgdGltZS4uLg",
        "story_type": "text"
    },
    {
        "question_number": "1",
        "question_value": "V2hhdCBpcyAxICsxPw==", //always add '==' at the end
        "question_type": "text",
        "answer_value": "Mg==", //always add '==' at the end
        "answer_type": "text",
        "story_value": "PHA+TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gRG9uZWMgbm9uIGdyYXZpZGEgZXJhdC4gQWVuZWFuIG5vbiBsaWJlcm8gZGFwaWJ1cywgdGluY2lkdW50IGFudGUgZXVpc21vZCwgZWZmaWNpdHVyIHRlbGx1cy4gRnVzY2UgZXUgcGVsbGVudGVzcXVlIG5pYmguIFNlZCBzZW1wZXIgbWF4aW11cyBvZGlvLCBpZCBjb25kaW1lbnR1bSBtYWduYSBzb2xsaWNpdHVkaW4gdXQuIEFlbmVhbiBtb2xsaXMgbnVuYyBkaWN0dW0gY3Vyc3VzIHNvbGxpY2l0dWRpbi4gUHJvaW4gZmV1Z2lhdCBtYXNzYSBldSByaG9uY3VzIHJ1dHJ1bS4gTnVsbGEgcXVpcyBsaWJlcm8gYWMgYW50ZSBwb3J0YSBmaW5pYnVzIHZlbCB2ZWwgZXJhdC4gVmVzdGlidWx1bSBlZ2V0IHJpc3VzIHNpdCBhbWV0IG51bGxhIGxvYm9ydGlzIGN1cnN1cy4gU3VzcGVuZGlzc2Ugc2l0IGFtZXQgaW1wZXJkaWV0IHVybmEsIHNlZCBtb2xsaXMgZXJhdC4gQWxpcXVhbSBldSBkdWkgbm9uIGxhY3VzIGxvYm9ydGlzIGxhb3JlZXQuIFZlc3RpYnVsdW0gZXUganVzdG8gZGljdHVtLCBzdXNjaXBpdCBuaXNsIHF1aXMsIGdyYXZpZGEgc2VtLiBNb3JiaSBlZmZpY2l0dXIgcGxhY2VyYXQgZXgsIGV0IGxhY2luaWEgbGFjdXMgdmVzdGlidWx1bSBub24uIFZpdmFtdXMgdmVoaWN1bGEsIGlwc3VtIHZlbCBmaW5pYnVzIHZlc3RpYnVsdW0sIG5pYmggYXVndWUgZ3JhdmlkYSBuaXNpLCBzZWQgY29uc2VxdWF0IG1pIHVybmEgdXQgbWV0dXMuPC9wPg0KDQo8cD5WZXN0aWJ1bHVtIGRpY3R1bSBkYXBpYnVzIG5pYmggc2l0IGFtZXQgZWZmaWNpdHVyLiBBZW5lYW4gZWZmaWNpdHVyIG1hdXJpcyBxdWlzIGVzdCBmZXVnaWF0LCBlZ2V0IGNvbnZhbGxpcyByaXN1cyBtYWxlc3VhZGEuIEludGVnZXIgdGVtcG9yIHZhcml1cyBpcHN1bSwgaW4gY29uZ3VlIGlwc3VtIHB1bHZpbmFyIHZlaGljdWxhLiBJbiBzZWQgdG9ydG9yIG5lYyBqdXN0byB2ZXN0aWJ1bHVtIGFsaXF1YW0gYWMgdXQgdXJuYS4gQ3VyYWJpdHVyIG5pYmggZXN0LCBiaWJlbmR1bSBpZCBuZXF1ZSBncmF2aWRhLCBncmF2aWRhIHZpdmVycmEgbGliZXJvLiBDcmFzIGNvbmd1ZSB0ZWxsdXMgaW4gZXggZXVpc21vZCwgZXUgZXVpc21vZCBwdXJ1cyBtb2xsaXMuIFBoYXNlbGx1cyB1bGxhbWNvcnBlciBlcmF0IHNhcGllbiwgYWMgY29uZ3VlIG5pYmggcG9ydHRpdG9yIGEuIFV0IG5vbiBsaWJlcm8gdXJuYS4gU2VkIHN1c2NpcGl0IGxvcmVtIGFjY3Vtc2FuIGVsaXQgcG9zdWVyZSwgdml0YWUgdGluY2lkdW50IGVsaXQgZGljdHVtLiBOdWxsYSBlbGVtZW50dW0gc2VtIHF1aXMgaXBzdW0gZWxlbWVudHVtIHVsdHJpY2VzLiBQcmFlc2VudCBldCBpbnRlcmR1bSBqdXN0by4gQWVuZWFuIGlkIG1hZ25hIG1pLiBWZXN0aWJ1bHVtIGEgc3VzY2lwaXQgbGlndWxhLCBzZWQgZWxlbWVudHVtIGVyYXQuPC9wPg0KDQo8cD5BbGlxdWFtIGVyYXQgdm9sdXRwYXQuIEFlbmVhbiBoZW5kcmVyaXQgbWFzc2EgYWMgYXVndWUgbWF0dGlzLCBpZCBkaWN0dW0gdHVycGlzIHNjZWxlcmlzcXVlLiBGdXNjZSBuZWMgbWkgZW5pbS4gRG9uZWMgYmxhbmRpdCB2ZXN0aWJ1bHVtIHN1c2NpcGl0LiBOdWxsYSBvcm5hcmUgbGVvIHNlZCBwdWx2aW5hciBhbGlxdWFtLiBDbGFzcyBhcHRlbnQgdGFjaXRpIHNvY2lvc3F1IGFkIGxpdG9yYSB0b3JxdWVudCBwZXIgY29udWJpYSBub3N0cmEsIHBlciBpbmNlcHRvcyBoaW1lbmFlb3MuIE51bmMgc2FnaXR0aXMgc2VkIGxvcmVtIGV1IHNlbXBlci48L3A+",
        "story_type": "html"
    }
];

var questionIndex = data.length - 1;
var wrongAnswer = "
Not quite there...
";

// this function decides which data item to show
function render(){
    if data[questionIndex]["question_type"] == "text" {
        $('#question').text(atob(data[questionIndex]["question_value"]));
    }
    else if data[questionIndex]["question_type"] == "html" {
        $('#question').html(atob(data[questionIndex]["question_value"]));
    }
}

// this function checks if an answer is correct
function toggleFields(){
    var userAnswer = $('#answer-input').val();
    var comparisonAnswer = atob(data[questionIndex]["answer_value"]);
    if (userAnswer == comparisonAnswer) {
        $('#story').html(atob(data[questionIndex]["story_value"]));
        $('#story').show();
    }
    else {
        $('#story').html(wrongAnswer);
        $('#story').show();
    }

}

// this function sets up things so the page actually does things
$(document).ready(function () {

    render();

    toggleFields(); //call this first so we start out with the correct visibility depending on the selected form values
    //this will call our toggleFields function every time the answer changes
    $('#answer button').click(function () {
        toggleFields();
    });

    $('#story').hide();

});
<|endoftext|>


<commit_before>var require = (function() {
    var appVersion = '4.0.0';
    return {
        config: {
            'config/config': {
                'appVersion' : appVersion
            }
        },
        baseUrl: 'js',
        paths: {
            'vie' : '../lib/VIE/vie',
            'backbone' : '../lib/backbone/backbone-min',
            'underscore' : '../lib/underscore/underscore-min',
            'jquery' : '../lib/jquery/js/jquery-1.9.1',
            'jquery-ui' : '../lib/jquery/js/jquery-ui-1.10.3.custom.min',
            'jquery-cookie' : '../lib/jquery-cookie/jquery.cookie',
            'logger' : '../lib/logger',
            'chap-timeline' : '../lib/chap-links-library/timeline',
            'svg' : '../lib/svgjs/svg',
            'svg.draggable' : '../lib/svgjs/svg.draggable',
            'svg.foreignobject' : '../lib/svgjs/svg.foreignobject',
            'organize' : '../lib/organize/organize',
            'text' : '../lib/text',
            'bootstrap' : '../lib/bootstrap/js/bootstrap',
            'spin' : '../lib/spinjs/spin.min'
        },
        shim: {
            'logger' : {
                'exports' : 'Logger'
            },
            'vie' : {
                'deps' : ['backbone', 'jquery', 'underscore'],
                'exports' : 'VIE'
            },
            'backbone' : {
                'deps': ['underscore', 'jquery'],
                'exports' : 'Backbone'
            },
            'underscore' : {
                'exports' : '_'
            },
            'organize' : {
                'deps' : ['svg', 'svg.draggable', 'svg.foreignobject', 'jquery'],
                'exports' : 'Organize'
            },
            'chap-timeline' : {
                'exports': 'links.Timeline'
            },
            'svg.draggable' : ['svg'],
            'svg.foreignobject' : ['svg'],
            'jquery-cookie' : {
                'deps' : ['jquery']
            },
            'jquery-ui' : {
                'deps' : ['jquery']
            },
            'bootstrap' : {
                'deps' : ['jquery']
            },
            'spin' : {
                'exports' : 'Spinner'
            }
        },
        urlArgs: "bust=" + (new Date()).getTime()
    };
}());

<commit_msg>Bumped version to 4.0.1<commit_after>var require = (function() {
    var appVersion = '4.0.1';
    return {
        config: {
            'config/config': {
                'appVersion' : appVersion
            }
        },
        baseUrl: 'js',
        paths: {
            'vie' : '../lib/VIE/vie',
            'backbone' : '../lib/backbone/backbone-min',
            'underscore' : '../lib/underscore/underscore-min',
            'jquery' : '../lib/jquery/js/jquery-1.9.1',
            'jquery-ui' : '../lib/jquery/js/jquery-ui-1.10.3.custom.min',
            'jquery-cookie' : '../lib/jquery-cookie/jquery.cookie',
            'logger' : '../lib/logger',
            'chap-timeline' : '../lib/chap-links-library/timeline',
            'svg' : '../lib/svgjs/svg',
            'svg.draggable' : '../lib/svgjs/svg.draggable',
            'svg.foreignobject' : '../lib/svgjs/svg.foreignobject',
            'organize' : '../lib/organize/organize',
            'text' : '../lib/text',
            'bootstrap' : '../lib/bootstrap/js/bootstrap',
            'spin' : '../lib/spinjs/spin.min'
        },
        shim: {
            'logger' : {
                'exports' : 'Logger'
            },
            'vie' : {
                'deps' : ['backbone', 'jquery', 'underscore'],
                'exports' : 'VIE'
            },
            'backbone' : {
                'deps': ['underscore', 'jquery'],
                'exports' : 'Backbone'
            },
            'underscore' : {
                'exports' : '_'
            },
            'organize' : {
                'deps' : ['svg', 'svg.draggable', 'svg.foreignobject', 'jquery'],
                'exports' : 'Organize'
            },
            'chap-timeline' : {
                'exports': 'links.Timeline'
            },
            'svg.draggable' : ['svg'],
            'svg.foreignobject' : ['svg'],
            'jquery-cookie' : {
                'deps' : ['jquery']
            },
            'jquery-ui' : {
                'deps' : ['jquery']
            },
            'bootstrap' : {
                'deps' : ['jquery']
            },
            'spin' : {
                'exports' : 'Spinner'
            }
        },
        urlArgs: "bust=" + (new Date()).getTime()
    };
}());

<|endoftext|>


<commit_before>
function setUpTangle () {

    var element = document.getElementById("scenario");

    var tangle = new Tangle(element, {
        initialize: function () {
            this.acres = 3.5;
            this.spaces_per_acre = 100; // units: car parking spaces

            this.parking_demand = 25; // max number of spaces needed. Based on observation.
            // editable (see update function):
            this.parking_coverage = 25; // % of site covered with parking
        },
        update: function () {
            this.parking_spaces = Math.floor((this.parking_coverage / 100) * this.acres * this.spaces_per_acre);
            this.empty_spaces = this.parking_spaces - this.parking_demand;
            this.angry_mjs = Math.floor(this.parking_spaces + Math.exp(1/this.parking_spaces));

            if (this.empty_spaces < 0) {
                console.log("But there may be as many as " + Math.abs(this.empty_spaces) + " angry neighbors.");
                this.empty_spaces = 0;
            }
        }
    });
}
<commit_msg>updates % of each image shown based on selected parking_coverage<commit_after>
function setUpTangle () {

    var element = document.getElementById("scenario");

    var tangle = new Tangle(element, {
        initialize: function () {
            this.acres = 3.5;
            this.spaces_per_acre = 100; // units: car parking spaces

            this.parking_demand = 25; // max number of spaces needed. Based on observation.
            // editable (see update function):
            this.parking_coverage = 25; // % of site covered with parking
        },
        update: function () {
            this.parking_spaces = Math.floor((this.parking_coverage / 100) * this.acres * this.spaces_per_acre);
            this.empty_spaces = this.parking_spaces - this.parking_demand;
            this.angry_mjs = Math.floor(this.parking_spaces + Math.exp(1/this.parking_spaces));

            if (this.empty_spaces < 0) {
                console.log("But there may be as many as " + Math.abs(this.empty_spaces) + " angry neighbors.");
                this.empty_spaces = 0;
            }

            /* Update the percentage of each image shown based on the parking_coverage % chosen by user. */
            /*
                | ----------------------------- 100 % ------------------------------- |
                | ------- parking_coverage% ---   |   ---------  Park Img  ---------- |
                | ------------------------------------------------------------------- |
            */
            var width = $("#img-slider .right img").width();
            var left = (this.parking_coverage/100 * width);
            $("#img-slider .right").css("clip", "rect(0, 1000px, 1000px, " + left + "px)"); /* top, right, bottom, left */

        }
    });
}
<|endoftext|>


<commit_before>var word = [
    'buenísimo.',
    'fantástico.',
    'increíble.',
    'asombroso.',
    'estupendo.',
    'genial.'];

var current = 1;
var timer = null;

function nextWord() {
  if (current < word.length) {
    ret = word[current];
    current = current + 1;
    return ret;
  }

  current = 1;
  return word[0];
}

function changeWord () {
  $('#adj').text(nextWord());
  $('#adj').removeClass().addClass('animated flipInX').on('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){$(this).removeClass();});

}

$(document).on("ready",
  function () {
    timer = setInterval(changeWord, 3000);
  });
<commit_msg>Adding adjectives<commit_after>var word = [
    'buenísimo.',
    'fantástico.',
    'increíble.',
    'sensacional.',
    'asombroso.',
    'estupendo.',
    'impresionante.',
    'sorprendente.',
    'genial.'];

var current = 1;
var timer = null;

function nextWord() {
  if (current < word.length) {
    ret = word[current];
    current = current + 1;
    return ret;
  }

  current = 1;
  return word[0];
}

function changeWord () {
  $('#adj').text(nextWord());
  $('#adj').removeClass().addClass('animated flipInX').on('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){$(this).removeClass();});

}

$(document).on("ready",
  function () {
    timer = setInterval(changeWord, 3000);
  });
<|endoftext|>


<commit_before>function showChild(text, Y, id, leftSide) {
	var X;
    if (leftSide == true) {
    	X = 2 + Math.floor(Math.random() * 37);
	} else {
		X = 55 + Math.floor(Math.random() * 25);
	}
	$('#childNodes').append('
' + text + '
');
	var item = $('#' + id);

	var speed = getRandomSpeed();
	setTransSpeed(item, speed + 'ms');
	setTimeout(function() {
		item.removeClass('invisible');
	}, 0)
	setTimeout(function() {
		setTransNormal(item);
	}, speed);
	var leftX = item.position().left;
	console.log(leftX);
	function animateLink(link, right) {
		if (right == true) {
			link.animate({"left": "+=2%"}, 2000 + Math.floor(Math.random() * 2000), function() { animateLink(link, false); });
		} else {
			link.animate({"left": "-=2%"}, 2000 + Math.floor(Math.random() * 2000), function() { animateLink(link, true); });
		}
	}
	if (Math.random() > 0.5) {
		animateLink(item, true);
	} else {
		animateLink(item, false);
	}
}

var currentObject;

function drawChildren() {
	var item = currentObject;
	var onLeft = false;
	for (childKey in item.children) {
		childText = contents[childKey].text;
		childLine = item.children[childKey];
		if (onLeft == true)
			onLeft = false;
		else
			onLeft = true;
		showChild(childText, childLine, childKey, onLeft);
	}
}

function getRandomSpeed() {
	return (50 + Math.floor(Math.random() * 950));
}

function clickedOn(child) {
	console.log(child);
	var item = contents[child];
	console.log(JSON.stringify(item));
	currentObject = item;
	eraseChildren();
	eraseParent();
}

function eraseParent() {
	$('#parentNode').css('opacity', 0);
}

function eraseChildren() {
	var maxSpeed = 0;
	$('.linkText').each(function() {
		var speed = getRandomSpeed();
		maxSpeed = Math.max(maxSpeed, speed);
		setTransSpeed($(this), speed + 'ms');
		$(this).css('opacity', 0);
	});
	console.log(maxSpeed);
	setTimeout(removeChildren, maxSpeed + 1);
}

function drawParent() {
	parentNode = $('#parentNode');
	parentNode.html(currentObject.text);
	parentNode.css('opacity', 1);
}
function removeChildren() {
	$('.linkText').remove();
	drawParent();
	drawChildren();
}

function setTransSpeed(item, speed) {
	item.css('transition', 'opacity ' + speed);
	item.css('-moz-transition', 'opacity ' + speed);
	item.css('-webkit-transition', 'opacity ' + speed);
	item.css('-o-transition', 'opacity ' + speed);
}

function setTransNormal(item) {
	item.css('transition', 'text-shadow 500ms, opacity 500ms');
	item.css('-moz-transition', 'text-shadow 500ms, opacity 500ms');
	item.css('-webkit-transition', 'text-shadow 500ms, opacity 500ms');
	item.css('-o-transition', 'text-shadow 500ms, opacity 500ms');
}
<commit_msg>Changed the position of LinkText to absolute, not %<commit_after>function showChild(text, Y, id, leftSide) {
	var X, width;
	width = $('#parentNode').width();
    if (leftSide == true) {
    	X = Math.floor(50 + Math.random() * (width / 2 - 260));
	} else {
		X = Math.floor(width / 2 + 30 + Math.random() * (width / 2 - 420));
	}
	$('#childNodes').append('
' + text + '
');
	var item = $('#' + id);

	var speed = getRandomSpeed();
	setTransSpeed(item, speed + 'ms');
	setTimeout(function() {
		item.removeClass('invisible');
	}, 0)
	setTimeout(function() {
		setTransNormal(item);
	}, speed);
	var leftX = item.position().left;
	console.log(leftX);
	function animateLink(link, right) {
		if (right == true) {
			link.animate({"left": "+=25px"}, 2000 + Math.floor(Math.random() * 2000), function() { animateLink(link, false); });
		} else {
			link.animate({"left": "-=25px"}, 2000 + Math.floor(Math.random() * 2000), function() { animateLink(link, true); });
		}
	}
	if (Math.random() > 0.5) {
		animateLink(item, true);
	} else {
		animateLink(item, false);
	}
}

var currentObject;

function drawChildren() {
	var item = currentObject;
	var onLeft = false;
	for (childKey in item.children) {
		childText = contents[childKey].text;
		childLine = item.children[childKey];
		if (onLeft == true)
			onLeft = false;
		else
			onLeft = true;
		showChild(childText, childLine, childKey, onLeft);
	}
}

function getRandomSpeed() {
	return (50 + Math.floor(Math.random() * 950));
}

function clickedOn(child) {
	console.log(child);
	var item = contents[child];
	console.log(JSON.stringify(item));
	currentObject = item;
	eraseChildren();
	eraseParent();
}

function eraseParent() {
	$('#parentNode').css('opacity', 0);
}

function eraseChildren() {
	var maxSpeed = 0;
	$('.linkText').each(function() {
		var speed = getRandomSpeed();
		maxSpeed = Math.max(maxSpeed, speed);
		setTransSpeed($(this), speed + 'ms');
		$(this).css('opacity', 0);
	});
	console.log(maxSpeed);
	setTimeout(removeChildren, maxSpeed + 1);
}

function drawParent() {
	parentNode = $('#parentNode');
	parentNode.html(currentObject.text);
	parentNode.css('opacity', 1);
}
function removeChildren() {
	$('.linkText').remove();
	drawParent();
	drawChildren();
}

function setTransSpeed(item, speed) {
	item.css('transition', 'opacity ' + speed);
	item.css('-moz-transition', 'opacity ' + speed);
	item.css('-webkit-transition', 'opacity ' + speed);
	item.css('-o-transition', 'opacity ' + speed);
}

function setTransNormal(item) {
	item.css('transition', 'text-shadow 500ms, opacity 500ms');
	item.css('-moz-transition', 'text-shadow 500ms, opacity 500ms');
	item.css('-webkit-transition', 'text-shadow 500ms, opacity 500ms');
	item.css('-o-transition', 'text-shadow 500ms, opacity 500ms');
}
<|endoftext|>


<commit_before>/**
 * AngularJS Tutorial 1
 * @author Nick Kaye <nick.c.kaye@gmail.com>
 */

/**
 * Main AngularJS Web Application
 tutorialWebApp
 */
 var servicelocation = "";
var app = angular.module('clientApp', [
'ngRoute', 'angular-timezone-selector'
]).directive('portalFrame', function() {
    return{
      restrict: "E",
         replace: true,
       transclude: true,
    compile: function (scope, element, attrs) {

    }
  }
})
.directive("bootstrapNavbar", function($location) {
   return {
     restrict: "E",
     replace: true,
     transclude: true,
     templateUrl: "components/bootstrapNavbar.html",
     compile: function(element, attrs) {  // (1)
       var li, liElements, links, index, length;

       servicelocation = "https://" + $location.$$host + "/api/"; //Update the service location to that of the host.

       liElements = $(element).find("#js-navbar-collapse li");   // (2)
       for (index = 0, length = liElements.length; index < length; index++) {
         li = liElements[index];
         links = $(li).find("a");  // (3)
         if (links[0].textContent === attrs.currentTab) $(li).addClass("active"); // (4)
       }
     }
   }})
;

/**
 * Configure the Routes
 */
app.config(['$routeProvider', function ($routeProvider) {
  $routeProvider
    // Home
    .when("/", {templateUrl: "views/main.html", controller: "MainCtrl"})
    // Pages
    .when('/ConfigFiles', {
      templateUrl: 'views/configfiles.html', controller: 'ConfigfilesCtrl'
    })
    .when('/UserManagement', {
      templateUrl: 'views/usermanagement.html', controller: 'UsermanagementCtrl',
      controllerAs: 'UserManagement'
    })
    .when('/Dashboard', {
      templateUrl: 'views/dashboard.html', controller: 'DashboardCtrl',
      controllerAs: 'Dashboard'
    })
    .when('/HQ', {
      templateUrl: 'views/hq.html', controller: 'HqCtrl',
      controllerAs: 'HQ'
    })
    .when('/systemservices', {
      templateUrl: 'views/systemservices.html', controller: 'SystemservicesCtrl',
      controllerAs: 'systemservices'
    })

    // Blog
  //  .when("/blog", {templateUrl: "partials/blog.html", controller: "BlogCtrl"})
  //  .when("/blog/post", {templateUrl: "partials/blog_item.html", controller: "BlogCtrl"})
    // else 404
    .otherwise("/404", {
      templateUrl: "views/about.html", controller: "AboutCtrl",
      controllerAs:'about'});
//    .otherwise("/", {templateUrl: "partials/404.html", controller: "AboutCtrl"});
}]);

/**
 * Controls all other Pages
 */
app.controller('PageCtrl', function (/* $scope, $location, $http */) {
  console.log("Page Controller reporting for duty.");

  // Activates the Carousel
  $('.carousel').carousel({
    interval: 5000
  });

  // Activates Tooltips for Social Links
  $('.tooltip-social').tooltip({
    selector: "a[data-toggle=tooltip]"
  })
});
<commit_msg>Removed main route<commit_after>/**
 * AngularJS Tutorial 1
 * @author Nick Kaye <nick.c.kaye@gmail.com>
 */

/**
 * Main AngularJS Web Application
 tutorialWebApp
 */
 var servicelocation = "";
var app = angular.module('clientApp', [
'ngRoute', 'angular-timezone-selector'
]).directive('portalFrame', function() {
    return{
      restrict: "E",
         replace: true,
       transclude: true,
    compile: function (scope, element, attrs) {

    }
  }
})
.directive("bootstrapNavbar", function($location) {
   return {
     restrict: "E",
     replace: true,
     transclude: true,
     templateUrl: "components/bootstrapNavbar.html",
     compile: function(element, attrs) {  // (1)
       var li, liElements, links, index, length;

       servicelocation = "https://" + $location.$$host + "/api/"; //Update the service location to that of the host.

       liElements = $(element).find("#js-navbar-collapse li");   // (2)
       for (index = 0, length = liElements.length; index < length; index++) {
         li = liElements[index];
         links = $(li).find("a");  // (3)
         if (links[0].textContent === attrs.currentTab) $(li).addClass("active"); // (4)
       }
     }
   }})
;

/**
 * Configure the Routes
 */
app.config(['$routeProvider', function ($routeProvider) {
  $routeProvider
    // Home
  //  .when("/", {templateUrl: "views/main.html", controller: "MainCtrl"})
    // Pages
    .when('/ConfigFiles', {
      templateUrl: 'views/configfiles.html', controller: 'ConfigfilesCtrl'
    })
    .when('/UserManagement', {
      templateUrl: 'views/usermanagement.html', controller: 'UsermanagementCtrl',
      controllerAs: 'UserManagement'
    })
    .when('/Dashboard', {
      templateUrl: 'views/dashboard.html', controller: 'DashboardCtrl',
      controllerAs: 'Dashboard'
    })
    .when('/HQ', {
      templateUrl: 'views/hq.html', controller: 'HqCtrl',
      controllerAs: 'HQ'
    })
    .when('/systemservices', {
      templateUrl: 'views/systemservices.html', controller: 'SystemservicesCtrl',
      controllerAs: 'systemservices'
    })

    // Blog
  //  .when("/blog", {templateUrl: "partials/blog.html", controller: "BlogCtrl"})
  //  .when("/blog/post", {templateUrl: "partials/blog_item.html", controller: "BlogCtrl"})
    // else 404
    .otherwise("/404", {
      templateUrl: "views/about.html", controller: "AboutCtrl",
      controllerAs:'about'});
//    .otherwise("/", {templateUrl: "partials/404.html", controller: "AboutCtrl"});
}]);

/**
 * Controls all other Pages
 */
app.controller('PageCtrl', function (/* $scope, $location, $http */) {
  console.log("Page Controller reporting for duty.");

  // Activates the Carousel
  $('.carousel').carousel({
    interval: 5000
  });

  // Activates Tooltips for Social Links
  $('.tooltip-social').tooltip({
    selector: "a[data-toggle=tooltip]"
  })
});
<|endoftext|>


<commit_before>/*eslint-env browser */
/*global require: false, console: false */

'use strict';

require('base');
var React = require('react');
var Spreadsheet = require('./spreadsheet');
var AppControls = require('./AppControls');
//var Input = require('react-bootstrap/lib/Input');
var Grid = require('react-bootstrap/lib/Grid');
var Row = require('react-bootstrap/lib/Row');
var Col = require('react-bootstrap/lib/Col');
var Rx = require('./rx.ext');
var KmPlot = require('./kmPlot');
//var Button = require('react-bootstrap/lib/Button');
require('rx.coincidence');
require('rx/dist/rx.aggregates');
require('rx/dist/rx.time');
require('rx-dom');
var _ = require('./underscore_ext');
//var meta = require('./meta');
require('./plotDenseMatrix'); // XXX better place or name for this?
var controllersControls = require('controllers/controls'); // XXX use npm package to simplify this import?
var controllersServer = require('controllers/server'); // XXX use npm package to simplify this import?
require('bootstrap/dist/css/bootstrap.css');
//var Perf = require('react/addons').addons.Perf;

var d = window.document;
var main = d.getElementById('main');
var defaultServers = ['https://genome-cancer.ucsc.edu:443/proj/public/xena',
		'https://local.xena.ucsc.edu:7223'];

// Create a channel for messages from the server. We
// want to avoid out-of-order responses for certain messages.
// To do that, we have to allocate somewhere. We can manage it
// by doing using a unique tag for the request, and using groupBy.
//
// Note that we can still bounce on column data requests, because they are not
// handled with switchLatest. We can't put them on their own channel, because
// that will leak memory: groupBy is leaky in keys. Maybe this leak is too small
// to worry about? Maybe we need a custom operator that won't leak? Maybe
// a takeUntil() should be applied to the groups?
var serverBus = new Rx.Subject();

var second = ([, b]) => b;

// Subject of [slot, obs]. We group by slot and apply switchLatest. If slot is '$none' we just
// merge.
var serverCh = serverBus.groupBy(([slot]) => slot)
	.map(g => g.key === '$none' ? g.map(second).mergeAll() : g.map(second).switchLatest()).mergeAll();

var initialState = {
	servers: {'default': defaultServers, user: defaultServers},
	zoom: {height: 300},
	columns: {},
	columnOrder: [],
	comms: {
		server: serverBus
	}
};

if (sessionStorage && sessionStorage.xena && location.search.indexOf('?nostate') !== 0) {
	initialState = _.extend(initialState, JSON.parse(sessionStorage.xena));
}

var controlsBus = new Rx.Subject();
var controlsCh = controlsBus;

function formatState(state) {
	return JSON.stringify(_.omit(state, ['comms']), null, 4);
}

var Application = React.createClass({
	displayName: 'Application',
	getInitialState() {
		return {
			debug: false,
			debugText: formatState(this.props.appState) // initial state of text area.
		};
	},
	//	XXX debug widget is currently too slow due to large appState.
	// Enable with <Grid onClick={this.onClick}>.
//	componentWillReceiveProps ({appState}) {
//		this.setState({debugText: formatState(appState)});
//	},
//	handleChange: function (ev) {
//		this.setState({debugText: ev.target.value});
//	},
//	onClick: function (ev) {
//		return;
//		if (ev[meta.key]) {
//			this.setState({debug: !this.state.debug});
//		}
//	},
	onKeyDown: function (ev) {
		if (ev.key === 'Enter' && ev.ctrlKey) {
			try {
				this.props.callback(['set-debug-state', JSON.parse(this.state.debugText)]);
			} catch (e) {
				if (console) {
					console.log(e);
				}
			}
			ev.preventDefault();
		}
	},
//	onPerf: function () {
//		this.perf = !this.perf;
//		if (this.perf) {
//			console.log("Starting perf");
//			Perf.start();
//		} else {
//			console.log("Stopping perf");
//			Perf.stop();
//			Perf.printInclusive();
//			Perf.printExclusive();
//			Perf.printWasted();
//		}
//	},
	render: function() {
		let {appState: {km, ...otherState}, ...otherProps} = this.props;
		return (
			<Grid>
			{/*
				<Row>
					<Button onClick={this.onPerf}>Perf</Button>
				</Row>
			*/}
				<Row>
					<Col md={12}>
						<AppControls {...otherProps} appState={otherState} />
					</Col>
				</Row>
				<Spreadsheet {...otherProps} appState={otherState} />
				{_.getIn(km, ['id']) ? <KmPlot
						callback={this.props.callback}
						appState={km}
						features={this.props.appState.features} /> : ''}
			{/*
				<Row>
					<Col md={12}>
						<Input
							type='textarea'
							id='debug'
							rows='20'
							cols='130'
							style={{display: this.state.debug ? 'block' : 'none'}}
							onChange={this.handleChange}
							onKeyDown={this.onKeyDown}
							value={this.state.debugText} />
					</Col>
				</Row>
			*/}

			</Grid>
		);
	}
});

// XXX rename controls ui, so we have ui + server.

function controlRunner(controller) {
	return function (state, ev) {
		try {
			var s = controller.event(state, ev);
			controller.postEvent(state, s, ev);
			return s;
		} catch (e) {
			console.log('Error', e); // comment this out to have hard errors.
			return state;
		}
	};
}

var serverReducer = controlRunner(controllersServer);
var controlsReducer = controlRunner(controllersControls);

// From page load, push indexes for state. Store in cache slots.
// Our state is too big to push directly. This mechanism is a bit
// confusing across page loads.
//
//  0 1 2 3 4 5 6 7
//        ^
//  back: move indx to 2.
//  forward: move indx to 4
//  new state: append state & invalidate  5 - 7? The browser will
//     invalidate them.

var [pushState, setState] = (function () {
	var i = 0, cache = [];
	return [function (s) {
		cache[i] = s;
		history.pushState(i, '');
		i = (i + 1) % 100;
	},
	Rx.DOM.fromEvent(window, 'popstate').map(s => {
		i = s.state;
		return cache[i];
	})];
})();

var stateObs = Rx.Observable.merge(
					serverCh.map(ev => [serverReducer, ev]),
					controlsCh.map(ev => [controlsReducer, ev])
			   ).scan(initialState, (state, [reduceFn, ev]) => reduceFn(state, ev))
			   .do(pushState)
			   .merge(setState)
			   .share();

var updater = ev => controlsBus.onNext(ev);
//stateObs.subscribe(state => {
//	React.render(<Application callback={updater} appState={state} />, main);
//});

stateObs.throttleWithTimeout(0, Rx.Scheduler.requestAnimationFrame)
	.subscribe(state => React.render(<Application callback={updater} appState={state} />, main));

// Save state in sessionStorage on page unload.
stateObs.sample(Rx.DOM.fromEvent(window, 'beforeunload'))
	.subscribe(state => sessionStorage.xena = JSON.stringify(_.omit(state, 'comms')));

//stateObs.subscribe(s => console.log('state', s));

// Kick things off.
controlsBus.onNext(['init']);
<commit_msg>comments.<commit_after>/*eslint-env browser */
/*global require: false, console: false */

'use strict';

require('base');
var React = require('react');
var Spreadsheet = require('./spreadsheet');
var AppControls = require('./AppControls');
//var Input = require('react-bootstrap/lib/Input');
var Grid = require('react-bootstrap/lib/Grid');
var Row = require('react-bootstrap/lib/Row');
var Col = require('react-bootstrap/lib/Col');
var Rx = require('./rx.ext');
var KmPlot = require('./kmPlot');
//var Button = require('react-bootstrap/lib/Button');
require('rx.coincidence');
require('rx/dist/rx.aggregates');
require('rx/dist/rx.time');
require('rx-dom');
var _ = require('./underscore_ext');
//var meta = require('./meta');
require('./plotDenseMatrix'); // XXX better place or name for this?
var controllersControls = require('controllers/controls'); // XXX use npm package to simplify this import?
var controllersServer = require('controllers/server'); // XXX use npm package to simplify this import?
require('bootstrap/dist/css/bootstrap.css');
//var Perf = require('react/addons').addons.Perf;

var d = window.document;
var main = d.getElementById('main');
var defaultServers = ['https://genome-cancer.ucsc.edu:443/proj/public/xena',
		'https://local.xena.ucsc.edu:7223'];

// Create a channel for messages from the server. We
// want to avoid out-of-order responses for certain messages.
// To do that, we have to allocate somewhere. We can manage it
// by doing using a unique tag for the request, and using groupBy.
//
// Note that we can still bounce on column data requests, because they are not
// handled with switchLatest. We can't put them on their own channel, because
// that will leak memory: groupBy is leaky in keys. Maybe this leak is too small
// to worry about? Maybe we need a custom operator that won't leak? Maybe
// a takeUntil() should be applied to the groups?
var serverBus = new Rx.Subject();

var second = ([, b]) => b;

// Subject of [slot, obs]. We group by slot and apply switchLatest. If slot is '$none' we just
// merge.
var serverCh = serverBus.groupBy(([slot]) => slot)
	.map(g => g.key === '$none' ? g.map(second).mergeAll() : g.map(second).switchLatest()).mergeAll();

var initialState = {
	servers: {'default': defaultServers, user: defaultServers},
	zoom: {height: 300},
	columns: {},
	columnOrder: [],
	comms: {
		server: serverBus
	}
};

if (sessionStorage && sessionStorage.xena && location.search.indexOf('?nostate') !== 0) {
	initialState = _.extend(initialState, JSON.parse(sessionStorage.xena));
}

var controlsBus = new Rx.Subject();
var controlsCh = controlsBus;

function formatState(state) {
	return JSON.stringify(_.omit(state, ['comms']), null, 4);
}

var Application = React.createClass({
	displayName: 'Application',
	getInitialState() {
		return {
			debug: false,
			debugText: formatState(this.props.appState) // initial state of text area.
		};
	},
	//	XXX debug widget is currently too slow due to large appState.
	// Enable with <Grid onClick={this.onClick}>.
//	componentWillReceiveProps ({appState}) {
//		this.setState({debugText: formatState(appState)});
//	},
//	handleChange: function (ev) {
//		this.setState({debugText: ev.target.value});
//	},
//	onClick: function (ev) {
//		return;
//		if (ev[meta.key]) {
//			this.setState({debug: !this.state.debug});
//		}
//	},
	onKeyDown: function (ev) {
		if (ev.key === 'Enter' && ev.ctrlKey) {
			try {
				this.props.callback(['set-debug-state', JSON.parse(this.state.debugText)]);
			} catch (e) {
				if (console) {
					console.log(e);
				}
			}
			ev.preventDefault();
		}
	},
//	onPerf: function () {
//		this.perf = !this.perf;
//		if (this.perf) {
//			console.log("Starting perf");
//			Perf.start();
//		} else {
//			console.log("Stopping perf");
//			Perf.stop();
//			Perf.printInclusive();
//			Perf.printExclusive();
//			Perf.printWasted();
//		}
//	},
	render: function() {
		let {appState: {km, ...otherState}, ...otherProps} = this.props;
		return (
			<Grid>
			{/*
				<Row>
					<Button onClick={this.onPerf}>Perf</Button>
				</Row>
			*/}
				<Row>
					<Col md={12}>
						<AppControls {...otherProps} appState={otherState} />
					</Col>
				</Row>
				<Spreadsheet {...otherProps} appState={otherState} />
				{_.getIn(km, ['id']) ? <KmPlot
						callback={this.props.callback}
						appState={km}
						features={this.props.appState.features} /> : ''}
			{/*
				<Row>
					<Col md={12}>
						<Input
							type='textarea'
							id='debug'
							rows='20'
							cols='130'
							style={{display: this.state.debug ? 'block' : 'none'}}
							onChange={this.handleChange}
							onKeyDown={this.onKeyDown}
							value={this.state.debugText} />
					</Col>
				</Row>
			*/}

			</Grid>
		);
	}
});

// XXX rename controls ui, so we have ui + server.

function controlRunner(controller) {
	return function (state, ev) {
		try {
			var s = controller.event(state, ev);
			controller.postEvent(state, s, ev);
			return s;
		} catch (e) {
			console.log('Error', e); // comment this out to have hard errors.
			return state;
		}
	};
}

var serverReducer = controlRunner(controllersServer);
var controlsReducer = controlRunner(controllersControls);

// From page load, push indexes for state. Store in cache slots.
// Our state is too big to push directly. This mechanism is a bit
// confusing across page loads.
//
//  0 1 2 3 4 5 6 7
//        ^
//  back: move indx to 2.
//  forward: move indx to 4
//  new state: append state & invalidate  5 - 7? The browser will
//     invalidate them.

var [pushState, setState] = (function () {
	var i = 0, cache = [];
	return [function (s) {
		cache[i] = s;
		history.pushState(i, '');
		i = (i + 1) % 100;
	},
	Rx.DOM.fromEvent(window, 'popstate').map(s => {
		i = s.state;
		return cache[i];
	})];
})();

var stateObs = Rx.Observable.merge(
					serverCh.map(ev => [serverReducer, ev]),
					controlsCh.map(ev => [controlsReducer, ev])
			   ).scan(initialState, (state, [reduceFn, ev]) => reduceFn(state, ev))
			   .do(pushState)
			   .merge(setState)
			   .share();

var updater = ev => controlsBus.onNext(ev);
//stateObs.subscribe(state => {
//	React.render(<Application callback={updater} appState={state} />, main);
//});

// XXX double check that this expression is doing what we want: don't draw faster
// than rAF.
stateObs.throttleWithTimeout(0, Rx.Scheduler.requestAnimationFrame)
	.subscribe(state => React.render(<Application callback={updater} appState={state} />, main));

// Save state in sessionStorage on page unload.
stateObs.sample(Rx.DOM.fromEvent(window, 'beforeunload'))
	.subscribe(state => sessionStorage.xena = JSON.stringify(_.omit(state, 'comms')));

// Kick things off.
controlsBus.onNext(['init']);
<|endoftext|>


<commit_before>// Currying

// 1

// let dragon = (name, size, element) =>
//     name + ' is a ' +
//     size + ' dragon that breathes ' +
//     element + '!'

// console.log(dragon('fluffykins', 'tiny', 'lightning'))

// 2

// let dragon =
//     name =>
//         size =>
//             element =>
//                 name + ' is a ' +
//                 size + ' dragon that breathes ' +
//                 element + '!'

// console.log(dragon('fluffykins')('tiny')('lightning'))<commit_msg>[FINAL] Currying Source<commit_after>// Currying

// 1

// let dragon = (name, size, element) =>
//     name + ' is a ' +
//     size + ' dragon that breathes ' +
//     element + '!'

// console.log(dragon('fluffykins', 'tiny', 'lightning'))

// 2

// let dragon =
//     name =>
//         size =>
//             element =>
//                 name + ' is a ' +
//                 size + ' dragon that breathes ' +
//                 element + '!'

// console.log(dragon('fluffykins')('tiny')('lightning'))

// 3

// let dragon =
//     name =>
//         size =>
//             element =>
//                 name + ' is a ' +
//                 size + ' dragon that breathes ' +
//                 element + '!'

// let fluffykinsDragon = dragon('fluffykins')
// let tinyDragon = fluffykinsDragon('tiny')

// console.log(tinyDragon('lightning'))

// 4

// import _ from 'lodash'

// let dragon = (name, size, element) =>
//     name + ' is a ' +
//     size + ' dragon that breathes ' +
//     element + '!'

// dragon = _.curry(dragon)

// let fluffykinsDragon = dragon('fluffykins')
// let tinyDragon = fluffykinsDragon('tiny')

// console.log(tinyDragon('lightning'))

// 5

// let dragons = [
//     { name: 'fluffykins', element: 'lightning' },
//     { name: 'noomi', element: 'lightning' },
//     { name: 'karo', element: 'fire' },
//     { name: 'doomer', element: 'timewarp' }
// ]

// let hasElement =
//     (element, obj) => obj.element === element

// let lightningDragons =
//     dragons.filter(x => hasElement('lightning', x))

// console.log(lightningDragons)

// 5.1

import _ from 'lodash'

let dragons = [
    { name: 'fluffykins', element: 'lightning' },
    { name: 'noomi', element: 'lightning' },
    { name: 'karo', element: 'fire' },
    { name: 'doomer', element: 'timewarp' }
]

let hasElement =
    _.curry((element, obj) => obj.element === element)

let lightningDragons =
    dragons.filter(hasElement('lightning'))

console.log(lightningDragons)<|endoftext|>


<commit_before>/**
 * Runs when page is loaded
 */
$(function() {
    $("#maxSamples").slider({
        scale: 'logarithmic'
    });
    window.sliderValue = parseInt($("#maxSamples").attr("data-slider-value"), 10);
    $("#maxSamples").on("slide", function(slideEvt) {
        window.sliderValue = slideEvt.value;
    });

    // Initialize compilerflasher
    compilerflasher = new compilerflasher(function() {});
    var parser = new GraphiteDataParser();
    var chartPlotter = new GraphiteGraphPlotter("chartContainer");
    /**
     * Runs whenever new data is detected on serial monitor
     */
    var firstLine = /^connecting at .+$/;
    $(document).on('serial_monitor_new_line', function(event, data) {
        if (firstLine.test(data)) return;
        parser.addRawData(data);
        if ((chartPlotter.dataNumber != parser.getdataNumber()) || (chartPlotter.withXCord != parser.isWithXCord())) {
            chartPlotter.initGraph(parser.getdataNumber(),parser.isWithXCord());
        }
        chartPlotter.updateChart(parser.showNewData());
    });

    // When a new arduino is connected, clear previous data from chart

    $(document).on('serial_monitor_connect', function(event, data) {
        clearData();
    });

    // When button to clear data is clicked, clear previous data from chart
    $('#clear-data').on('click', function() {
        clearData();
    });

    /**
     * Clears all data from the sensors, refreshing the chart
     */
    function clearData() {
        /*
        sensorArray.forEach(function(val, index) {
            val.length = 0;
        });
        window.myLineChart.render();*/
        parser = new GraphiteGraphPlotter();
    }
});<commit_msg>remove unnecessary lines from main.js<commit_after>/**
 * Runs when page is loaded
 */
$(function() {
    $("#maxSamples").slider({
        scale: 'logarithmic'
    });
    window.sliderValue = parseInt($("#maxSamples").attr("data-slider-value"), 10);
    $("#maxSamples").on("slide", function(slideEvt) {
        window.sliderValue = slideEvt.value;
    });

    // Initialize compilerflasher
    compilerflasher = new compilerflasher(function() {});
    var parser = new GraphiteDataParser();
    var chartPlotter = new GraphiteGraphPlotter("chartContainer");
    /**
     * Runs whenever new data is detected on serial monitor
     */
    var firstLine = /^connecting at .+$/;
    $(document).on('serial_monitor_new_line', function(event, data) {
        if (firstLine.test(data)) return;
        parser.addRawData(data);
        if ((chartPlotter.dataNumber != parser.getdataNumber()) || (chartPlotter.withXCord != parser.isWithXCord())) {
            chartPlotter.initGraph(parser.getdataNumber(),parser.isWithXCord());
        }
        chartPlotter.updateChart(parser.showNewData());
    });

    // When a new arduino is connected, clear previous data from chart

    $(document).on('serial_monitor_connect', function(event, data) {
        clearData();
    });

    // When button to clear data is clicked, clear previous data from chart
    $('#clear-data').on('click', function() {
        clearData();
    });

    /**
     * Clears all data from the sensors, refreshing the chart
     */
    function clearData() {
        chartPlotter = new GraphiteGraphPlotter("chartContainer");
    }
});<|endoftext|>


<commit_before>/*
1. Assume a sample large (50K items) JSON data set (e.g USA users for a site with location information)
2. Render a Google map, with pins shown for each state (e.g X users from California)
3. On zoom in, show the pins for each city (e.g X users from Palo Alto)
4. On zoom in further, show the pins for each zip code.
5. On zoom out, show the appropriate pins per the zoom level
 */

/*! @license
 *  Project: Buttons
 *  Description: Google Map Interface which extends to multi market
 *  Author: Sanyam Agrawal
 *  Date : 26/03/2015 (DD/MM/YYYY)
 *  License: Apache License v2.0
 */

// the semi-colon before function invocation is a safety net against concatenated
// scripts and/or other plugins which may not be closed properly.
;
(function($, window, document, undefined) {

    var MarkerUtil = {

            markers: [],
            bounds: new google.maps.LatLngBounds(),
            geocoder: new google.maps.Geocoder(),
            infowindow: new google.maps.InfoWindow(),

            initMarkers: function(type, data) {
                this.processMarker(data, type);
            },

            processMarker: function(interator, type) {
                var keys = Object.keys(interator);
                $(keys).each(function(index, key) {
                    /*jshint unused:true*/
                    var LatLng = interator[key].LatLng;
                    if (LatLng) {
                        this.addMarker(type, key, LatLng);
                    } else {
                        this.getLongLatInfo(key, type);
                    }
                }.bind(this));
            },

            getLongLatInfo: function(query, type) {
                var address = query;

                this.geocoder.geocode({
                    "address": address
                }, this.putMarker.bind(this, type, query));
            },

            putMarker: function(type, query, results, status) {

                var position;

                if (status === google.maps.GeocoderStatus.OK) {

                    position = results[0].geometry.location;
                    StoreUtil.saveLongLatInfo(type, query, position);
                    this.addMarker(type, query, position);

                } else {
                    alert("Geocode was not successful for the following reason: " + status);
                }
            },

            addMarker: function(type, query, position) {
                var marker;

                marker = new google.maps.Marker({
                    map: map,
                    position: position
                });

                this.markers.push(marker);
                google.maps.event.addListener(marker, "click", this.markerClickCallback.bind(this, type, query, marker));
                //this.addBounds(marker);
            },

            markerClickCallback: function(type, query, marker) {
                var count = StoreUtil.getObjectBasedOnType(type)[query].count + 1,
                    message = ["
", [count, "Users in this location."].join(" "), "
"].join("");
                this.infowindow.setContent(message);
                this.infowindow.open(map, marker);
            },

            // Removes the markers from the map, but keeps them in the array.
            clearMarkers: function() {
                this.setAllMap(null);
                this.markers = [];
            },

            // Sets the map on all markers in the array.
            setAllMap: function(map) {
                for (var i = 0; i < this.markers.length; i++) {
                    this.markers[i].setMap(map);
                }
            },

            addBounds: function(marker) {
                this.bounds.extend(marker.position);
            },

            fitBound: function() {
                //map.fitBounds(this.bounds);
            }
        },

        StoreUtil = {
            mappedJson: {},

            getJSON: function() {
                var response = [{
                    userId: 1,
                    locationDetails: {
                        state: {
                            value: "Karnataka",
                            longLat: [0.9876, 0.9988]
                        },
                        city: {
                            value: "Bangalore",
                            longLat: []
                        },
                        zipCode: {
                            value: 560103,
                            longLat: []
                        }
                    }

                }, {
                    userId: 1,
                    locationDetails: {
                        state: {
                            value: "Karnataka",
                            longLat: [0.9876, 0.9988]
                        },
                        city: {
                            value: "Bangalore",
                            longLat: []
                        },
                        zipCode: {
                            value: 560101,
                            longLat: []
                        }
                    }

                }, {
                    userId: 1,
                    locationDetails: {
                        state: {
                            value: "Karnataka",
                            longLat: [0.9876, 0.9988]
                        },
                        city: {
                            value: "Hubli",
                            longLat: []
                        },
                        zipCode: {
                            value: 560003,
                            longLat: []
                        }
                    }

                }, {
                    userId: 1,
                    locationDetails: {
                        state: {
                            value: "Delhi",
                            longLat: [0.9876, 0.9988]
                        },
                        city: {
                            value: "Delhi",
                            longLat: []
                        },
                        zipCode: {
                            value: 110556,
                            longLat: []
                        }
                    }

                }];
                return response;
            },

            processJSON: function() {
                var data = this.getJSON(),
                    stateInfo = {},
                    cityInfo = {},
                    zipInfo = {};

                $(data).each(function(index, user) {

                    /*jshint unused:true*/

                    var locationInfo = user.locationDetails,
                        state = locationInfo.state.value,
                        city = locationInfo.city.value,
                        zip = locationInfo.zipCode.value;

                    this.put(stateInfo, state);
                    this.put(cityInfo, [state, city].join(DELIMITOR));
                    this.put(zipInfo, [state, city, zip].join(DELIMITOR));
                    // cityInfo = put(stateInfo, state);
                    // zipInfo = put(cityInfo, city);
                    // put(zipInfo, zip);
                }.bind(this));

                this.mappedJson = {
                    state: stateInfo,
                    city: cityInfo,
                    zip: zipInfo
                };
            },

            put: function(array, value) {
                if (!array[value]) {
                    array[value] = {};
                    array[value].count = 0;
                } else {
                    array[value].count = array[value].count + 1;
                }
                return array[value];
            },

            getObjectBasedOnType: function(type) {
                return this.mappedJson[type];
            },

            getObjectBasedOnZoomLevel: function(level) {
                return this.getObjectBasedOnType(ZOOM_LEVEL_MAP[level]);
            },

            saveLongLatInfo: function(type, key, value) {
                var obj = this.getObjectBasedOnType(type);
                obj[key].LatLng = value;
            }
        },
        map,

        DELIMITOR = ",",
        ZOOM_LEVEL_MAP = {
            "5": "state",
            "6": "city",
            "7": "zip"
        },
        DEFAULT_ZOOM_LEVEL = 5;

    function initialize() {
        StoreUtil.processJSON();
        var mapOptions = {
            zoom: DEFAULT_ZOOM_LEVEL,
            center: new google.maps.LatLng(20.593684, 78.962880)
        };
        map = new google.maps.Map(document.getElementById("map-canvas"),
            mapOptions);

        initListerners();
        MarkerUtil.initMarkers(ZOOM_LEVEL_MAP[DEFAULT_ZOOM_LEVEL], StoreUtil.getObjectBasedOnZoomLevel(DEFAULT_ZOOM_LEVEL));
    }

    function initListerners() {
        google.maps.event.addListener(map, "zoom_changed", zoomChangedCallback);
    }

    function zoomChangedCallback() {
        var zoomLevel = map.getZoom(),
            typeOfZoom = ZOOM_LEVEL_MAP[zoomLevel];

        MarkerUtil.clearMarkers();
        if (!typeOfZoom) {
            return;
        }

        MarkerUtil.initMarkers(typeOfZoom, StoreUtil.getObjectBasedOnType(typeOfZoom));
    }

    google.maps.event.addDomListener(window, "load", initialize);

})(jQuery, window, document);
<commit_msg>More Cosmetic Changes<commit_after>/*
1. Assume a sample large (50K items) JSON data set (e.g USA users for a site with location information)
2. Render a Google map, with pins shown for each state (e.g X users from California)
3. On zoom in, show the pins for each city (e.g X users from Palo Alto)
4. On zoom in further, show the pins for each zip code.
5. On zoom out, show the appropriate pins per the zoom level
 */

/*! @license
 *  Project: Buttons
 *  Description: Google Map Interface which extends to multi market
 *  Author: Sanyam Agrawal
 *  Date : 26/03/2015 (DD/MM/YYYY)
 *  License: Apache License v2.0
 */

// the semi-colon before function invocation is a safety net against concatenated
// scripts and/or other plugins which may not be closed properly.
;
(function($, window, document, undefined) {

    var map,

        MapUtil = {
            ZOOM_LEVEL_MAP: {
                "5": "state",
                "6": "city",
                "7": "zip"
            },
            DEFAULT_ZOOM_LEVEL: 5,
            initialize: function() {
                StoreUtil.processJSON();
                var mapOptions = {
                    zoom: this.DEFAULT_ZOOM_LEVEL,
                    center: new google.maps.LatLng(20.593684, 78.962880)
                };
                map = new google.maps.Map(document.getElementById("map-canvas"),
                    mapOptions);

                this.initListerners();
                MarkerUtil.initMarkers(this.ZOOM_LEVEL_MAP[this.DEFAULT_ZOOM_LEVEL], StoreUtil.getObjectBasedOnZoomLevel(this.DEFAULT_ZOOM_LEVEL));
            },

            initListerners: function() {
                google.maps.event.addListener(map, "zoom_changed", this.zoomChangedCallback);
            },

            zoomChangedCallback: function() {
                var zoomLevel = map.getZoom(),
                    typeOfZoom = this.ZOOM_LEVEL_MAP[zoomLevel];

                MarkerUtil.clearMarkers();
                if (!typeOfZoom) {
                    return;
                }

                MarkerUtil.initMarkers(typeOfZoom, StoreUtil.getObjectBasedOnType(typeOfZoom));
            }
        },
        MarkerUtil = {

            markers: [],
            bounds: new google.maps.LatLngBounds(),
            geocoder: new google.maps.Geocoder(),
            infowindow: new google.maps.InfoWindow(),

            initMarkers: function(type, data) {
                this.processMarker(data, type);
            },

            processMarker: function(interator, type) {
                var keys = Object.keys(interator);

                $(keys).each(function(index, key) {
                    /*jshint unused:true*/
                    var LatLng = interator[key].LatLng;

                    if (LatLng) {
                        this.addMarker(type, key, LatLng);
                    } else {
                        this.getLongLatInfo(key, type);
                    }
                }.bind(this));
            },

            getLongLatInfo: function(query, type) {
                var address = query;

                this.geocoder.geocode({
                    "address": address
                }, this.putMarker.bind(this, type, query));
            },

            putMarker: function(type, query, results, status) {

                var position;

                if (status === google.maps.GeocoderStatus.OK) {

                    position = results[0].geometry.location;
                    StoreUtil.saveLongLatInfo(type, query, position);
                    this.addMarker(type, query, position);

                } else {
                    alert("Geocode was not successful for the following reason: " + status);
                }
            },

            addMarker: function(type, query, position) {
                var marker;

                marker = new google.maps.Marker({
                    map: map,
                    position: position
                });

                this.markers.push(marker);
                google.maps.event.addListener(marker, "click", this.markerClickCallback.bind(this, type, query, marker));
                //this.addBounds(marker);
            },

            markerClickCallback: function(type, query, marker) {
                var count = StoreUtil.getObjectBasedOnType(type)[query].count + 1,
                    message = ["
", [count, "Users in this location."].join(" "), "
"].join("");

                this.infowindow.setContent(message);
                this.infowindow.open(map, marker);
            },

            // Removes the markers from the map, but keeps them in the array.
            clearMarkers: function() {
                this.setAllMap(null);
                this.markers = [];
            },

            // Sets the map on all markers in the array.
            setAllMap: function(map) {
                var i = 0;
                for (i; i < this.markers.length; i++) {
                    this.markers[i].setMap(map);
                }
            },

            addBounds: function(marker) {
                this.bounds.extend(marker.position);
            },

            fitBound: function() {
                //map.fitBounds(this.bounds);
            }
        },

        StoreUtil = {
            mappedJson: {},
            DELIMITOR: ",",
            getJSON: function() {
                var response = [{
                    userId: 1,
                    locationDetails: {
                        state: {
                            value: "Karnataka",
                            longLat: [0.9876, 0.9988]
                        },
                        city: {
                            value: "Bangalore",
                            longLat: []
                        },
                        zipCode: {
                            value: 560103,
                            longLat: []
                        }
                    }

                }, {
                    userId: 1,
                    locationDetails: {
                        state: {
                            value: "Karnataka",
                            longLat: [0.9876, 0.9988]
                        },
                        city: {
                            value: "Bangalore",
                            longLat: []
                        },
                        zipCode: {
                            value: 560101,
                            longLat: []
                        }
                    }

                }, {
                    userId: 1,
                    locationDetails: {
                        state: {
                            value: "Karnataka",
                            longLat: [0.9876, 0.9988]
                        },
                        city: {
                            value: "Hubli",
                            longLat: []
                        },
                        zipCode: {
                            value: 560003,
                            longLat: []
                        }
                    }

                }, {
                    userId: 1,
                    locationDetails: {
                        state: {
                            value: "Delhi",
                            longLat: [0.9876, 0.9988]
                        },
                        city: {
                            value: "Delhi",
                            longLat: []
                        },
                        zipCode: {
                            value: 110556,
                            longLat: []
                        }
                    }

                }];
                return response;
            },

            processJSON: function() {
                var data = this.getJSON(),
                    stateInfo = {},
                    cityInfo = {},
                    zipInfo = {};

                $(data).each(function(index, user) {

                    /*jshint unused:true*/

                    var locationInfo = user.locationDetails,
                        state = locationInfo.state.value,
                        city = locationInfo.city.value,
                        zip = locationInfo.zipCode.value;

                    this.put(stateInfo, state);
                    this.put(cityInfo, [state, city].join(this.DELIMITOR));
                    this.put(zipInfo, [state, city, zip].join(this.DELIMITOR));
                    // cityInfo = put(stateInfo, state);
                    // zipInfo = put(cityInfo, city);
                    // put(zipInfo, zip);
                }.bind(this));

                this.mappedJson = {
                    state: stateInfo,
                    city: cityInfo,
                    zip: zipInfo
                };
            },

            put: function(array, value) {

                if (!array[value]) {
                    array[value] = {};
                    array[value].count = 0;
                } else {
                    array[value].count = array[value].count + 1;
                }

                return array[value];
            },

            getObjectBasedOnType: function(type) {
                return this.mappedJson[type];
            },

            getObjectBasedOnZoomLevel: function(level) {
                return this.getObjectBasedOnType(MapUtil.ZOOM_LEVEL_MAP[level]);
            },

            saveLongLatInfo: function(type, key, value) {
                var obj = this.getObjectBasedOnType(type);

                obj[key].LatLng = value;
            }
        };

    google.maps.event.addDomListener(window, "load", MapUtil.initialize.bind(MapUtil));

})(jQuery, window, document);
<|endoftext|>


<commit_before>//HV control panel
(function(){

    xtag.register('widget-rateBar', {
        extends: 'div',
        lifecycle: {
            created: function() {
                var barTitle = document.createElement('h2')

                ////////////////////
                //build the DOM
                ////////////////////
                barTitle.setAttribute('id', this.id + 'Title');
                barTitle.innerHTML = 'Click on a rate or threshold channel to get started.';
                this.appendChild(barTitle);
                this.UIdeployed = false;

                this.addEventListener('postADC', function(evt){
                    this.updateRates(evt.detail);
                }, false);

            },
            inserted: function() {},
            removed: function() {},
            attributeChanged: function() {}
        },
        events: {

        },
        accessors: {
            'MIDAS':{
                attribute: {} //this just needs to be declared
            }
        },
        methods: {
            'updateRates' : function(customEventData){
                document.getElementById(this.id + 'Title').innerHTML = customEventData.channel
                if(!this.UIdeployed)
                    this.setUpUI();
            },

            'setUpUI' : function(){
                var control = document.createElement('div'),
                    mainSections = ['ADCstatusPane', 'ADC', 'trig', 'pulseHeight', 'time', 'waveform', 'simulation', 'misc'],
                    mainSectionDivs = [],
                    mainSectionTitles = ['MSCB Node Info', 'ADC Control', 'Triggering', 'Pulse Height Evaluation', 'Time Evaluation', 'Waveform Readout', 'Simulation Pulse', 'Miscellaneous'],
                    mainSectionH3 = [],
                    mainLists = [],
                    i;

                //wrapper for ADC UI
                control.setAttribute('id', 'control');
                this.appendChild(control);

                //main sections
                for(i=0; i<mainSections.length; i++){
                    mainSectionDivs[i] = document.createElement('div');
                    mainSectionDivs[i].setAttribute('id', mainSections[i]);
                    mainSectionDivs[i].setAttribute('class', 'collapse');

                    mainSectionH3[i] = document.createElement('h3');
                    mainSectionH3[i].setAttribute('class', 'sectionHead');
                    mainSectionH3[i].onclick = toggleSelection.bind(this, mainSections[i]);
                    mainSectionH3[i].innerHTML = String.fromCharCode(0x25B6) + ' ' +mainSectionTitles[i];
                    mainSectionDivs[i].appendChild(mainSectionH3[i]);

                    mainLists[i] = document.createElement('ul');
                    mainSectionDivs[i].appendChild(mainLists[i]);

                    control.appendChild(mainSectionDivs[i]);
                }

            }
        }
    });

})();

function toggleSection(id){
    var section = document.getElementById(id)

    if(section.className == 'collapse'){
        section.className = 'expand'
        this.innerHTML = String.fromCharCode(0x25BC) + this.innerHTML.slice(this.innerHTML.indexOf(' '));
    }
    else{
        section.className = 'collapse'
        this.innerHTML = String.fromCharCode(0x25B6) + this.innerHTML.slice(this.innerHTML.indexOf(' '));
    }
}<commit_msg>setting up ADC control UI<commit_after>//HV control panel
(function(){

    xtag.register('widget-rateBar', {
        extends: 'div',
        lifecycle: {
            created: function() {
                var barTitle = document.createElement('h2')

                ////////////////////
                //build the DOM
                ////////////////////
                barTitle.setAttribute('id', this.id + 'Title');
                barTitle.innerHTML = 'Click on a rate or threshold channel to get started.';
                this.appendChild(barTitle);
                this.UIdeployed = false;

                this.addEventListener('postADC', function(evt){
                    this.updateRates(evt.detail);
                }, false);

            },
            inserted: function() {},
            removed: function() {},
            attributeChanged: function() {}
        },
        events: {

        },
        accessors: {
            'MIDAS':{
                attribute: {} //this just needs to be declared
            }
        },
        methods: {
            'updateRates' : function(customEventData){
                document.getElementById(this.id + 'Title').innerHTML = customEventData.channel
                if(!this.UIdeployed)
                    this.setUpUI();
            },

            'setUpUI' : function(){
                var control = document.createElement('div'),
                    mainSections = ['ADCstatusPane', 'ADC', 'trig', 'pulseHeight', 'time', 'waveform', 'simulation', 'misc'],
                    mainSectionDivs = [],
                    mainSectionTitles = ['MSCB Node Info', 'ADC Control', 'Triggering', 'Pulse Height Evaluation', 'Time Evaluation', 'Waveform Readout', 'Simulation Pulse', 'Miscellaneous'],
                    mainSectionH3 = [],
                    mainLists = [],
                    i;

                //wrapper for ADC UI
                control.setAttribute('id', 'control');
                this.appendChild(control);

                //main sections
                for(i=0; i<mainSections.length; i++){
                    mainSectionDivs[i] = document.createElement('div');
                    mainSectionDivs[i].setAttribute('id', mainSections[i]);
                    mainSectionDivs[i].setAttribute('class', 'collapse');

                    mainSectionH3[i] = document.createElement('h3');
                    mainSectionH3[i].setAttribute('class', 'sectionHead');
                    mainSectionH3[i].onclick = toggleSection.bind(this, mainSections[i]);
                    mainSectionH3[i].innerHTML = String.fromCharCode(0x25B6) + ' ' +mainSectionTitles[i];
                    mainSectionDivs[i].appendChild(mainSectionH3[i]);

                    mainLists[i] = document.createElement('ul');
                    mainSectionDivs[i].appendChild(mainLists[i]);

                    control.appendChild(mainSectionDivs[i]);
                }

            }
        }
    });

})();

function toggleSection(id){
    var section = document.getElementById(id)

    if(section.className == 'collapse'){
        section.className = 'expand'
        this.innerHTML = String.fromCharCode(0x25BC) + this.innerHTML.slice(this.innerHTML.indexOf(' '));
    }
    else{
        section.className = 'collapse'
        this.innerHTML = String.fromCharCode(0x25B6) + this.innerHTML.slice(this.innerHTML.indexOf(' '));
    }
}<|endoftext|>