<commit_before>
"use strict";

var todosList;
var oldList;
var sleepycounter = 0;
var justChanged;
var fading;
var backgroundImage, backgroundOpacity;

$(document).ready(function () {

	if ($('#inputDeadline').length) {
		$.datetimepicker.setLocale('en');
		$('#inputDeadline').datetimepicker();
	}

	if ($("#tasksTable").length) {
		getTasks();
		sortTable();
	}

	if ($("#prefs").length) {
		getPrefs();
	}

	$('#btnSubmit').click(function () {
		justChanged = $('#inputCourseCode').val() + " " + $('#inputTask').val();
		addTask($('#inputCourseCode').val(), $('#inputTask').val(), $('#inputDeadline').val(), $('#inputWeight').val() / 100);
	});

	$('#prefslink').click(function () {
		$('#prefs').show();
		$('#bigbkgdiv').show();
		$('#inputBkgURL').val(backgroundImage);
		$('#inputOpacity').val(backgroundOpacity);
	});

	$('#btnPrefSubmit').click(function () {
		$('#prefs').hide();
		$('#bigbkgdiv').hide();
		$.ajax({
			url: 'setPrefs',
			type: 'POST',
			data: {
				BkgURL: $('#inputBkgURL').val(),
				inputOpacity: $('#inputOpacity').val()
			},
			success: function (result) {
				if (result) {
					getPrefs();
				}
			},
			timeout: function () {
				console.log("setPrefs: timeout");
			},
			error: function (error) {
				console.log("setPrefs: error", error);
			}
		});
	});

	$('#completedHead').click(function () {
		$('#completedTable').toggle();
		$('#complRight').toggle();
		$('#complDown').toggle();
	});

	// Updates
	var updateLoop = setInterval(function () {
		if (todosList) {
			oldList = todosList;
			if (todosList === oldList && sleepycounter < 6) {
				// Every five minutes, update the table order and the priorities
				console.log("Just updating the numbers");
				updateTables(todosList);
				sleepycounter++;
			} else {
				// Every half hour, poll the server
				console.log("Updating the list");
				sleepycounter = 0;
				getTasks();
				getPrefs();
			}
		}
	}, 300000);
});

function jsDateToExcelDate(inDate) {
	var returnDateTime = 25569.0 + ((inDate.getTime() - (inDate.getTimezoneOffset() * 60 * 1000)) / (1000 * 60 * 60 * 24));
	return returnDateTime.toString().substr(0, 20);
}

function getTasks() {
	$.ajax({
		url: 'getTasks',
		type: 'POST',
		data: {
			gettasks: "get tasks"
		},
		success: function (result) {
			if (result) {
				todosList = result;
				updateTables(todosList);
			}
		},
		timeout: function () {
			console.log("Timeout");
			updateTables(todosList);
		},
		error: function (error) {
			console.log("Error", error);
			updateTables(todosList);
		}
	});
}

function getPrefs() {
	$.ajax({
		url: 'getPrefs',
		type: 'POST',
		data: {
			gettasks: "get prefs"
		},
		success: function (result) {
			if (result) {
				backgroundImage = result[0].backgroundURL;
				backgroundOpacity = result[0].backgroundOpacity;
				$('body').css('background', 'url(' + backgroundImage + ') no-repeat left top');
				$('body').css('background-attachment', 'fixed');
				$('body').css('background-size', 'cover');
				$('#content').css('background-color', 'rgba(255, 255, 255, ' + backgroundOpacity + ')');
				console.log(result);
			}
		},
		timeout: function () {
			console.log("getPrefs: timeout");
		},
		error: function (error) {
			console.log("getPrefs: error", error);
		}
	});
}

function updateTables(result) {
	var len = result.length;
	var currentText, completedText, priority, style, weight, dueDate, isCompleted, completedButton, priorityColumn, string;
	var rightNow = new Date();
	var rightNowPlusSeven = rightNow.addDays(7);
	var rightNowPlusFourteen = rightNow.addDays(14);
	if (len > 0) {
		for (var i = 0; i < len; i++) {
			if (result[i].coursecode && result[i].task && result[i].deadline && result[i].weight) {
				result[i].deadline = new Date(result[i].deadline);
				dueDate = new Date(result[i].deadline);
				weight = parseFloat(result[i].weight * 100).toFixed(1);
				priority = (result[i].weight / (jsDateToExcelDate(result[i].deadline) - jsDateToExcelDate(rightNow))) * 100;
				priority = parseFloat(priority).toFixed(2);
				if (priority < 0 || result[i].completed) {
					isCompleted = true;
				} else {
					isCompleted = false;
				}
				if (isCompleted === false) {
					completedButton = '';
					priorityColumn = '' + priority + '	'
					if (dueDate && dueDate < rightNowPlusSeven) {
						style = ' style="background-color: rgba(255,0,0,0.4);"';
					} else if (dueDate && dueDate < rightNowPlusFourteen) {
						style = ' style="background-color: rgba(255,255,0,0.4);"';
					} else {
						style = "";
					}
				} else { // If the task is completed
					completedButton = '';
					priorityColumn = '';
					style = "";
				}
				string = '
' + completedButton + '	' + result[i].coursecode + '	' + result[i].task + '	' + moment(dueDate).format("ddd") + '	' + moment(dueDate).format("D") + '	' + moment(dueDate).format("MMM") + ',	' + moment(dueDate).format("h:mm A") + '	' + weight + '%	' + priorityColumn + '
';

				if (isCompleted === false) {
					currentText += string;
				} else {
					completedText += string;
				}
			}
		}
		if (currentText !== "") {
			$("#tasksTable").find("tr:gt(0)").remove();
			$("#tasksTable").append(currentText);
			sortTable();
		}
		if (completedText !== "") {
			$("#completedTable").find("tr:gt(0)").remove();
			$("#completedTable").append(completedText);
		}
	}
}

function sortTable() {
	var tbl = document.getElementById("tasksTable").tBodies[0];
	var store = [],
		len;
	for (var i = 0, len = tbl.rows.length; i < len; i++) {
		var row = tbl.rows[i];
		var sortnr = parseFloat(row.cells[8].textContent || row.cells[8].innerText);
		if (!isNaN(sortnr)) store.push([sortnr, row]);
	}
	store.sort(function (y, x) {
		return x[0] - y[0];
	});
	for (var j = 0, len = store.length; j < len; j++) {
		tbl.appendChild(store[j][1]);
	}
	store = null;
	//var tableWidth = $("#tasksTable").width;
	//$("#content").width(tableWidth);
}

function addTask(coursecode, task, deadline, weight) {
	$.ajax({
		url: 'addTask',
		type: 'POST',
		data: {
			'coursecode': coursecode,
			'task': task,
			'deadline': deadline,
			'weight': weight
		},
		success: function (result) {
			getTasks();
			showToast("Task " + justChanged + " added.");
		},
		timeout: function () {
			showToast("Task could not be added. Server did not respond.");
		},
		error: function (error) {
			console.log(error);
			showToast("Task could not be added. Server gave an error.");
		}
	});
}

function deleteItem(id) {
	var t = $("#" + id);
	var undo = ' Undo';
	justChanged = t.next().text() + " " + t.next().next().text();
	$.ajax({
		url: 'deleteTask',
		type: 'POST',
		data: {
			'delID': id
		},
		success: function (result) {
			if (result) {
				getTasks();
				showToast("Task " + justChanged + " deleted.", undo);
			}
		},
		timeout: function () {
			showToast("Task could not be deleted. Server did not respond.");
		},
		error: function (error) {
			console.log(error);
			showToast("Task could not be deleted. Server gave an error.");
		}
	});
}

function completeItem(id) {
	$.ajax({
		url: 'completeTask',
		type: 'POST',
		data: {
			'complID': id
		},
		success: function (result) {
			if (result) {
				getTasks();
			}
		},
		timeout: function () {
			showToast("Task could not be marked as complete. Server did not respond.");
		},
		error: function (error) {
			console.log(error);
			showToast("Task could not be marked as complete. Server gave an error.");
		}
	});
}

Date.prototype.addDays = function (days) {
	var dat = new Date(this.valueOf());
	dat.setDate(dat.getDate() + days);
	return dat;
};

var fadeToast = function () {
	$("#toast").empty();
	$("#toast").hide();
};

function showToast(text, action) {
	clearTimeout(fading);
	$("#toast").text(text);
	if (action) {
		var oldHTML = $("#toast").html();
		$("#toast").html(oldHTML + action);
	}
	$("#toast").show();
	$("#toast").css('background-color', 'pink');
	fading = setTimeout(fadeToast, 8000);
}
<commit_msg>Define console for compatibility with old IE<commit_after>
"use strict";

var todosList;
var oldList;
var sleepycounter = 0;
var justChanged;
var fading;
var backgroundImage, backgroundOpacity;

if (typeof console === "undefined") {
	console = {
		log: function(i) {},
		debug: function(i) {}
	};
}

$(document).ready(function () {

	if ($('#inputDeadline').length) {
		$.datetimepicker.setLocale('en');
		$('#inputDeadline').datetimepicker();
	}

	if ($("#tasksTable").length) {
		getTasks();
		sortTable();
	}

	if ($("#prefs").length) {
		getPrefs();
	}

	$('#btnSubmit').click(function () {
		justChanged = $('#inputCourseCode').val() + " " + $('#inputTask').val();
		addTask($('#inputCourseCode').val(), $('#inputTask').val(), $('#inputDeadline').val(), $('#inputWeight').val() / 100);
	});

	$('#prefslink').click(function () {
		$('#prefs').show();
		$('#bigbkgdiv').show();
		$('#inputBkgURL').val(backgroundImage);
		$('#inputOpacity').val(backgroundOpacity);
	});

	$('#btnPrefSubmit').click(function () {
		$('#prefs').hide();
		$('#bigbkgdiv').hide();
		$.ajax({
			url: 'setPrefs',
			type: 'POST',
			data: {
				BkgURL: $('#inputBkgURL').val(),
				inputOpacity: $('#inputOpacity').val()
			},
			success: function (result) {
				if (result) {
					getPrefs();
				}
			},
			timeout: function () {
				console.log("setPrefs: timeout");
			},
			error: function (error) {
				console.log("setPrefs: error", error);
			}
		});
	});

	$('#completedHead').click(function () {
		$('#completedTable').toggle();
		$('#complRight').toggle();
		$('#complDown').toggle();
	});

	// Updates
	var updateLoop = setInterval(function () {
		if (todosList) {
			oldList = todosList;
			if (todosList === oldList && sleepycounter < 6) {
				// Every five minutes, update the table order and the priorities
				console.log("Just updating the numbers");
				updateTables(todosList);
				sleepycounter++;
			} else {
				// Every half hour, poll the server
				console.log("Updating the list");
				sleepycounter = 0;
				getTasks();
				getPrefs();
			}
		}
	}, 300000);
});

function jsDateToExcelDate(inDate) {
	var returnDateTime = 25569.0 + ((inDate.getTime() - (inDate.getTimezoneOffset() * 60 * 1000)) / (1000 * 60 * 60 * 24));
	return returnDateTime.toString().substr(0, 20);
}

function getTasks() {
	$.ajax({
		url: 'getTasks',
		type: 'POST',
		data: {
			gettasks: "get tasks"
		},
		success: function (result) {
			if (result) {
				todosList = result;
				updateTables(todosList);
			}
		},
		timeout: function () {
			console.log("Timeout");
			updateTables(todosList);
		},
		error: function (error) {
			console.log("Error", error);
			updateTables(todosList);
		}
	});
}

function getPrefs() {
	$.ajax({
		url: 'getPrefs',
		type: 'POST',
		data: {
			gettasks: "get prefs"
		},
		success: function (result) {
			if (result) {
				backgroundImage = result[0].backgroundURL;
				backgroundOpacity = result[0].backgroundOpacity;
				$('body').css('background', 'url(' + backgroundImage + ') no-repeat left top');
				$('body').css('background-attachment', 'fixed');
				$('body').css('background-size', 'cover');
				$('#content').css('background-color', 'rgba(255, 255, 255, ' + backgroundOpacity + ')');
				console.log(result);
			}
		},
		timeout: function () {
			console.log("getPrefs: timeout");
		},
		error: function (error) {
			console.log("getPrefs: error", error);
		}
	});
}

function updateTables(result) {
	var len = result.length;
	var currentText, completedText, priority, style, weight, dueDate, isCompleted, completedButton, priorityColumn, string;
	var rightNow = new Date();
	var rightNowPlusSeven = rightNow.addDays(7);
	var rightNowPlusFourteen = rightNow.addDays(14);
	if (len > 0) {
		for (var i = 0; i < len; i++) {
			if (result[i].coursecode && result[i].task && result[i].deadline && result[i].weight) {
				result[i].deadline = new Date(result[i].deadline);
				dueDate = new Date(result[i].deadline);
				weight = parseFloat(result[i].weight * 100).toFixed(1);
				priority = (result[i].weight / (jsDateToExcelDate(result[i].deadline) - jsDateToExcelDate(rightNow))) * 100;
				priority = parseFloat(priority).toFixed(2);
				if (priority < 0 || result[i].completed) {
					isCompleted = true;
				} else {
					isCompleted = false;
				}
				if (isCompleted === false) {
					completedButton = '';
					priorityColumn = '' + priority + '	'
					if (dueDate && dueDate < rightNowPlusSeven) {
						style = ' style="background-color: rgba(255,0,0,0.4);"';
					} else if (dueDate && dueDate < rightNowPlusFourteen) {
						style = ' style="background-color: rgba(255,255,0,0.4);"';
					} else {
						style = "";
					}
				} else { // If the task is completed
					completedButton = '';
					priorityColumn = '';
					style = "";
				}
				string = '
' + completedButton + '	' + result[i].coursecode + '	' + result[i].task + '	' + moment(dueDate).format("ddd") + '	' + moment(dueDate).format("D") + '	' + moment(dueDate).format("MMM") + ',	' + moment(dueDate).format("h:mm A") + '	' + weight + '%	' + priorityColumn + '
';

				if (isCompleted === false) {
					currentText += string;
				} else {
					completedText += string;
				}
			}
		}
		if (currentText !== "") {
			$("#tasksTable").find("tr:gt(0)").remove();
			$("#tasksTable").append(currentText);
			sortTable();
		}
		if (completedText !== "") {
			$("#completedTable").find("tr:gt(0)").remove();
			$("#completedTable").append(completedText);
		}
	}
}

function sortTable() {
	var tbl = document.getElementById("tasksTable").tBodies[0];
	var store = [],
		len;
	for (var i = 0, len = tbl.rows.length; i < len; i++) {
		var row = tbl.rows[i];
		var sortnr = parseFloat(row.cells[8].textContent || row.cells[8].innerText);
		if (!isNaN(sortnr)) store.push([sortnr, row]);
	}
	store.sort(function (y, x) {
		return x[0] - y[0];
	});
	for (var j = 0, len = store.length; j < len; j++) {
		tbl.appendChild(store[j][1]);
	}
	store = null;
	//var tableWidth = $("#tasksTable").width;
	//$("#content").width(tableWidth);
}

function addTask(coursecode, task, deadline, weight) {
	$.ajax({
		url: 'addTask',
		type: 'POST',
		data: {
			'coursecode': coursecode,
			'task': task,
			'deadline': deadline,
			'weight': weight
		},
		success: function (result) {
			getTasks();
			showToast("Task " + justChanged + " added.");
		},
		timeout: function () {
			showToast("Task could not be added. Server did not respond.");
		},
		error: function (error) {
			console.log(error);
			showToast("Task could not be added. Server gave an error.");
		}
	});
}

function deleteItem(id) {
	var t = $("#" + id);
	var undo = ' Undo';
	justChanged = t.next().text() + " " + t.next().next().text();
	$.ajax({
		url: 'deleteTask',
		type: 'POST',
		data: {
			'delID': id
		},
		success: function (result) {
			if (result) {
				getTasks();
				showToast("Task " + justChanged + " deleted.", undo);
			}
		},
		timeout: function () {
			showToast("Task could not be deleted. Server did not respond.");
		},
		error: function (error) {
			console.log(error);
			showToast("Task could not be deleted. Server gave an error.");
		}
	});
}

function completeItem(id) {
	$.ajax({
		url: 'completeTask',
		type: 'POST',
		data: {
			'complID': id
		},
		success: function (result) {
			if (result) {
				getTasks();
			}
		},
		timeout: function () {
			showToast("Task could not be marked as complete. Server did not respond.");
		},
		error: function (error) {
			console.log(error);
			showToast("Task could not be marked as complete. Server gave an error.");
		}
	});
}

Date.prototype.addDays = function (days) {
	var dat = new Date(this.valueOf());
	dat.setDate(dat.getDate() + days);
	return dat;
};

var fadeToast = function () {
	$("#toast").empty();
	$("#toast").hide();
};

function showToast(text, action) {
	clearTimeout(fading);
	$("#toast").text(text);
	if (action) {
		var oldHTML = $("#toast").html();
		$("#toast").html(oldHTML + action);
	}
	$("#toast").show();
	$("#toast").css('background-color', 'pink');
	fading = setTimeout(fadeToast, 8000);
}

<|endoftext|>


<commit_before><commit_msg>Fixed AppDirectives bug<commit_after>angular.module('appDirectives', []).config([function () {

}]);<|endoftext|>


<commit_before>function InputManager() {
	this.KEY_CODES = {
		32: 'space',
		37: 'left',
		38: 'up',
		39: 'right',
		40: 'down',
	}

	this.KEY_STATUS = {};
	this.resetKeys();

	this.oldonkeydown = null;
	this.oldonkeyup = null;
}
InputManager.prototype.resetKeys = function() {
	for(code in this.KEY_CODES) {
		this.KEY_STATUS[this.KEY_CODES[code]] = false;
	}
}
InputManager.prototype.onkeydown = function(e) {
	var self = this;
	return function(e) {
		var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
		if(self.KEY_CODES[keyCode]) {
			e.preventDefault();
			self.KEY_STATUS[self.KEY_CODES[keyCode]] = true;
		}
	}
}
InputManager.prototype.onkeyup = function(e) {
	var self = this;
	return function(e) {
		var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
		if(self.KEY_CODES[keyCode]) {
			e.preventDefault();
			self.KEY_STATUS[self.KEY_CODES[keyCode]] = false;
		}
	}
}
InputManager.prototype.attach = function() {
	this.oldonkeydown = document.onkeydown;
	this.oldonkeyup = document.onkeyup;

	document.onkeydown = this.onkeydown();
	document.onkeyup = this.onkeyup();
}

InputManager.prototype.detach = function() {
	document.onkeydown = this.oldonkeydown;
	document.onkeyup = this.oldonkeyup;

	this.oldonkeyup = null;
	this.oldonkeydown = null;
}

InputManager.prototype.getKey = function() {
	for(code in this.KEY_CODES) {
		if(this.KEY_STATUS[this.KEY_CODES[code]]) {
			this.KEY_STATUS[this.KEY_CODES[code]] = false;
			return this.KEY_CODES[code];
		}
	}
}

<commit_msg>Ignore key-repeats<commit_after>function InputManager() {
	this.KEY_CODES = {
		32: 'space',
		37: 'left',
		38: 'up',
		39: 'right',
		40: 'down',
	}

	this.KEY_STATUS = {};
	this.resetKeys();

	this.oldonkeydown = null;
	this.oldonkeyup = null;
	this.ignoreRepeats = false;
}
InputManager.prototype.resetKeys = function() {
	for(code in this.KEY_CODES) {
		this.KEY_STATUS[this.KEY_CODES[code]] = false;
	}
}
InputManager.prototype.onkeydown = function(e) {
	var self = this;
	return function(e) {
		if(self.ignoreRepeats)
			return;
		self.ignoreRepeats=true;
		var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
		if(self.KEY_CODES[keyCode]) {
			e.preventDefault();
			self.KEY_STATUS[self.KEY_CODES[keyCode]] = true;
		}
	}
}
InputManager.prototype.onkeyup = function(e) {
	var self = this;
	return function(e) {
		self.ignoreRepeats=false;
		var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
		if(self.KEY_CODES[keyCode]) {
			e.preventDefault();
			self.KEY_STATUS[self.KEY_CODES[keyCode]] = false;
		}
	}
}
InputManager.prototype.attach = function() {
	this.oldonkeydown = document.onkeydown;
	this.oldonkeyup = document.onkeyup;

	document.onkeydown = this.onkeydown();
	document.onkeyup = this.onkeyup();
}

InputManager.prototype.detach = function() {
	document.onkeydown = this.oldonkeydown;
	document.onkeyup = this.oldonkeyup;

	this.oldonkeyup = null;
	this.oldonkeydown = null;
}

InputManager.prototype.getKey = function() {
	for(code in this.KEY_CODES) {
		if(this.KEY_STATUS[this.KEY_CODES[code]]) {
			this.KEY_STATUS[this.KEY_CODES[code]] = false;
			return this.KEY_CODES[code];
		}
	}
}

<|endoftext|>


<commit_before>function showhideCategories(hdr,on) {
  var table = hdr.parentNode.parentNode.parentNode,
      newDisplay = on ? '' : 'none',
      nameList = new Array(), name;
  for (var i = 1; i < table.rows.length; i++) {
    if (on || table.rows[i].cells.length == 1)
      table.rows[i].style.display = newDisplay;
     else {
      // Hide duplicate rows for a plugin when not viewing by-category
      name = table.rows[i].cells[1].getAttribute('data');
      if (nameList[name] == 1) table.rows[i].style.display = 'none';
      nameList[name] = 1;
    }
  }
}
function showhideCategory(col) {
  var row = col.parentNode.nextSibling;
  var newDisplay = row && row.style.display == 'none' ? '' : 'none';
  for (; row && row.cells.length > 1; row = row.nextSibling)
    row.style.display = newDisplay;
}

Behaviour.register({
  "#filter-box": function(e) {
      function applyFilter() {
          var filter = e.value.toLowerCase();
          ["TR.plugin","TR.plugin-category"].each(function(clz) {
            var items = document.getElementsBySelector(clz);
            for (var i=0; i<items.length; i++) {
                var visible = (filter=="" || items[i].innerHTML.toLowerCase().indexOf(filter)>=0);
                items[i].style.display = (visible ? "" : "none");
            }
          });
      }

      e.onkeyup = applyFilter;
  }
});
<commit_msg>Update the position when the filter applies.<commit_after>function showhideCategories(hdr,on) {
  var table = hdr.parentNode.parentNode.parentNode,
      newDisplay = on ? '' : 'none',
      nameList = new Array(), name;
  for (var i = 1; i < table.rows.length; i++) {
    if (on || table.rows[i].cells.length == 1)
      table.rows[i].style.display = newDisplay;
     else {
      // Hide duplicate rows for a plugin when not viewing by-category
      name = table.rows[i].cells[1].getAttribute('data');
      if (nameList[name] == 1) table.rows[i].style.display = 'none';
      nameList[name] = 1;
    }
  }
}
function showhideCategory(col) {
  var row = col.parentNode.nextSibling;
  var newDisplay = row && row.style.display == 'none' ? '' : 'none';
  for (; row && row.cells.length > 1; row = row.nextSibling)
    row.style.display = newDisplay;
}

Behaviour.register({
  "#filter-box": function(e) {
      function applyFilter() {
          var filter = e.value.toLowerCase();
          ["TR.plugin","TR.plugin-category"].each(function(clz) {
            var items = document.getElementsBySelector(clz);
            for (var i=0; i<items.length; i++) {
                var visible = (filter=="" || items[i].innerHTML.toLowerCase().indexOf(filter)>=0);
                items[i].style.display = (visible ? "" : "none");
            }
          });

          layoutUpdateCallback.call();
      }

      e.onkeyup = applyFilter;
  }
});
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2013 - 2018, Logical Clocks AB and RISE SICS AB. All rights reserved
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this
 * software and associated documentation files (the "Software"), to deal in the Software
 * without restriction, including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software, and to permit
 * persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or
 * substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  OR IMPLIED, INCLUDING
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR  OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

/**
 * Controller for the kafka page.
 */

'use strict';

angular.module('hopsWorksApp')
        .controller('KafkaCtrl', ['$routeParams', 'growl',
        'KafkaService', '$location', 'ModalService', '$interval',
        '$mdSidenav', 'TourService', 'ProjectService',
          function ($routeParams, growl, KafkaService, $location,
          ModalService, $interval, $mdSidenav, TourService, ProjectService) {

            var self = this;
            self.projectId = $routeParams.projectID;
            self.topics = [];
            self.sharedTopics = [];
            self.topicDetails = {};
            self.maxNumTopics = 10;
            self.numTopicsUsed = 0;

            self.currentTopic = "";
            self.topicName = "";
            self.numReplicas = "";
            self.numPartitions = "";
            self.projectName = "";
            self.projectIsGuide = false;
            self.userEmail = "";
            self.permission_type = "Allow";
            self.operation_type = "Read";
            self.host = "*";
            self.role = "*";
           // self.activeId = -1;
            self.selectedProjectName="";

            self.users =[];
            self.project;

            self.showTopics = 1;
            self.showSchemas = -1;
            self.schemas = [];
            self.schemaVersions = [];
           self.tourService = TourService;

            self.selectAcl = function (acl, topicName) {
              if (self.activeId === acl.id) {
                return;
              }
              self.projectName = acl.projectName;
              self.userEmail = acl.userEmail;
              self.permission_type = acl.permission_type;
              self.operation_type = acl.operation_type;
              self.host = acl.host;
              self.role = acl.role;
              self.activeId = acl.id;

              KafkaService.aclUsers(self.projectId, topicName).then(
                    function (success) {
                        self.users = success.data;
                }, function (error) {
                    growl.error(error.data.errorMsg, {title: 'Could not load ACL users', ttl: 5000, referenceId: 10});
                   });

            };

            self.updateAcl = function (topicName, aclId){
              var acl ={};
              acl.projectName = self.project.projectName;
              acl.role = self.role;
              acl.userEmail = self.userEmail;
              acl.permissionType = self.permission_type;
              acl.operationType = self.operation_type;
              acl.host = self.host;
                KafkaService.updateTopicAcl(self.projectId, topicName, aclId, acl).then(
                        function(success){
                            self.getAclsForTopic(topicName);
                        }, function(error){
                            growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000});

                        });
            };

            self.getAllTopics = function () {
              KafkaService.getTopics(self.projectId).then(
                      function (success) {
                        self.topics = success.data;
                        self.numTopicsUsed = self.topics.length;
                      }, function (error) {
                growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000});
              });
            };

            self.getAllSharedTopics = function () {
              KafkaService.getSharedTopics(self.projectId).then(
                      function (success) {
                        self.sharedTopics = success.data;
                      }, function (error) {
                growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000});
              });
            };

            self.getTopicDetails = function (topicName) {
                KafkaService.getTopicDetails(self.projectId, topicName).then(
                        function (success) {
                            for(var i =0;i<self.topics.length;i++){
                              if(self.topics[i].name === topicName){
                                  self.topics[i].partitionDetails= success.data;
                                  return;
                              }
                          }
                        }, function (error) {
                    growl.warning(error.data.errorMsg, {title: 'Warning', ttl: 5000, referenceId: 10});
               });
            };

            /**
             * Navigate to the new job page.
             * @returns {undefined}
             */
            self.createSchema = function () {
              ModalService.createSchema('lg', self.projectId,
                self.projectIsGuide).then(
                      function (success) {
                          growl.success(success.data.successMessage, {title: 'New schema added successfully.', ttl: 2000});
                          self.listSchemas();
                          if (self.projectIsGuide) {
                            self.tourService.currentStep_TourThree = 2;
                          }
                      }, function (error) {
                //The user changed their mind.
              });
            };

            self.listSchemas = function () {

                KafkaService.getSchemasForTopics(self.projectId).then(
                 function (success) {
                 self.schemas = success.data;
                 var size = self.schemas.length;
                for(var i =0; i<size;i++){
                    self.schemaVersions[i] = Math.max.apply(null, self.schemas[i].versions);
                }
                 }, function (error) {
                 growl.error(error.data.errorMsg, {title: 'Could not get schemas for topic', ttl: 5000, referenceId: 10});
                 });

            };

            self.deleteSchema = function(schemaName, index){

                if(!self.schemaVersions[index]>0){
                  growl.info("Delete aborted", {title: 'Schema version not selected', ttl: 2000});
                    return;
                }
                 ModalService.confirm("sm", "Delete Schema (" + schemaName + ")",
                      "Do you really want to delete this Scehma? This action cannot be undone.")
                      .then(function (success) {
                          KafkaService.deleteSchema(self.projectId, schemaName, self.schemaVersions[index]).then(
                 function (success) {
                     self.listSchemas();
                 }, function (error) {
                 growl.error(error.data.errorMsg, {title: 'Schema is not removed', ttl: 5000, referenceId: 10});
                 });
                }, function (error) {
                    growl.info("Delete aborted", {title: 'Info', ttl: 2000});
                    });
            };

            self.viewSchemaContent = function(schemaName, index){

                if(!self.schemaVersions[index]>0){
                     growl.info("Please select schema version", {title: 'Schema version not selected', ttl: 2000});
                return;
                }

               ModalService.viewSchemaContent('lg', self.projectId, schemaName, self.schemaVersions[index]).then(
                      function (success) {

                      }, function (error) {
                //The user changed their mind.
              });
            };

            self.updateSchemaContent = function(schema){

                //increment the version number
                self.version = Math.max.apply(null,schema.versions);

                 ModalService.updateSchemaContent('lg', self.projectId, schema.name, self.version).then(
                      function (success) {
                         self.listSchemas();
                      }, function (error) {
                //The user changed their mind.
              });
            };

            self.lala = function () {
              console.log("Step: " + self.tourService.currentStep_TourThree);
            };
            /**
             * Navigate to the new job page.
             * @returns {undefined}
             */
            self.createTopic = function () {
              ModalService.createTopic('lg', self.projectId, self.projectIsGuide)
              .then(
                      function (success) {
                          growl.success(success.data.successMessage, {title: 'New topic created successfully.', ttl: 2000});
                          self.getAllTopics();
                          if (self.projectIsGuide) {
                            self.tourService.currentStep_TourThree = 4;
                          }
                      }, function (error) {
                      growl.error(error.data.errorMsg, {title: 'Failure to create topic', ttl: 5000, referenceId: 10});
              });
              self.getAllTopics();

            };

            self.removeTopic = function (topicName) {
              ModalService.confirm("sm", "Delete Topic (" + topicName + ")",
                      "Do you really want to delete this topic? This action cannot be undone.")
                      .then(function (success) {
                        KafkaService.removeTopic(self.projectId, topicName).then(
                                function (success) {
                                  self.getAllTopics();
                                }, function (error) {
                          growl.error(error.data.errorMsg, {title: 'Failed to remove topic', ttl: 5000});
                        });
                      }, function (cancelled) {
                        growl.info("Delete aborted", {title: 'Info', ttl: 2000});
                      });
            };

            self.getAclsForTopic = function (topicName) {
              KafkaService.getAclsForTopic(self.projectId, topicName).then(
                      function (success) {
                          for(var i =0;i<self.topics.length;i++){
                              if(self.topics[i].name === topicName){
                                  self.topics[i].acls = success.data;
                                  return;
                              }
                          }
                        self.activeId = "";
                      }, function (error) {
                growl.error(error.data.errorMsg, {title: 'Failed to get ACLs for the topic', ttl: 5000});
              });
            };

            self.addAcl = function (topicName) {

                ModalService.createTopicAcl('lg', self.projectId, topicName).then(
                      function (success) {
                          growl.success(success.data.successMessage, {title: 'New acl added for the topic: '+topicName, ttl: 5000});
                          self.getAclsForTopic(topicName);
                      }, function (error) {
                //The user changed their mind.
              });
            };

            self.removeAcl = function (topicName, aclId) {
              KafkaService.removeTopicAcl(self.projectId, topicName, aclId).then(
                      function (success) {
                        self.getAclsForTopic(topicName);
                      }, function (error) {
                growl.error(error.data.errorMsg, {title: 'Failed to remove topic', ttl: 5000});
              });

            };

            self.shareTopic = function(topicName) {
              ModalService.selectProject('lg', true, self.projectId,
                      "Select a Project to share the topic with.").then(
                      function (success) {
                        var destProj = success.projectId;
                        KafkaService.shareTopic(self.projectId, topicName, destProj).then(
                                function (success) {
                                  self.topicIsSharedTo(topicName);
                                  growl.success(success.data.successMessage, {title: 'Topic shared successfully with project: ' + destProj.name, ttl: 5000});
                                }, function (error) {
                          growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000});
                        });

                      }, function (error) {
                //The user changed their mind.
              });
            };

            //operation done from topic
            self.unshareTopic = function(topicName, project) {

                        KafkaService.unshareTopic(self.projectId, topicName, project.id).then(
                                function (success) {
                                  self.topicIsSharedTo(topicName);
                                  growl.success(success.data.successMessage, {title: 'Topic share removed (unshared) from project: ' + project.name, ttl: 2000});
                                }, function (error) {
                          growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000});
                        });
            };

            //operation done from project
            self.unshareTopicFromProject =function (topicName){
                KafkaService.unshareTopicFromProject(self.projectId, topicName).then(
                        function (success) {
                                  self.getAllSharedTopics();
                                  growl.success(success.data.successMessage, {title: 'Topic share removed (unshared) from project:.', ttl: 2000});
                                }, function (error) {
                          growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000});
                        });
            };

            self.topicIsSharedTo = function (topicName) {
                KafkaService.topicIsSharedTo(this.projectId, topicName).then(
                        function (success) {
                           for(var i =0;i<self.topics.length;i++){
                              if(self.topics[i].name === topicName){
                                  self.topics[i].shares=success.data;
                                  return;
                              }
                          }
                        }, function (error) {
                    growl.error(error.data.errorMsg, {title: 'Failed to get topic sharing information', ttl: 5000});
                });
            };

            self.init = function(){
              ProjectService.get({}, {'id': self.projectId}).$promise.then(
                function (success) {
                  var projectNameTour = success.projectName;
                  if (angular.equals(projectNameTour.substr(0, 5), 'demo_')) {
                    self.tourService.currentStep_TourThree = 0;
                    self.projectIsGuide = true;
                  }
                }, function (error) {
                  $location.path('/');
                }
              );

              self.getAllTopics();
              self.getAllSharedTopics();
             };

            self.init();

            self.showTopic = function(){
              if (self.projectIsGuide) {
                self.tourService.currentStep_TourThree = 3;
              }
              self.showSchemas = -1;
              self.showTopics = 1;
            };

            self.showSchema = function(){
              if (self.projectIsGuide) {
                self.tourService.currentStep_TourThree = 1;
              }
              self.showSchemas = 1;
              self.showTopics = -1;
              self.listSchemas();
            };

          }]);

<commit_msg>HOPSWORKS-522 fix (#939)<commit_after>/*
 * Copyright (C) 2013 - 2018, Logical Clocks AB and RISE SICS AB. All rights reserved
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this
 * software and associated documentation files (the "Software"), to deal in the Software
 * without restriction, including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software, and to permit
 * persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or
 * substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  OR IMPLIED, INCLUDING
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR  OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

/**
 * Controller for the kafka page.
 */

'use strict';

angular.module('hopsWorksApp')
        .controller('KafkaCtrl', ['$routeParams', 'growl',
        'KafkaService', '$location', 'ModalService', '$interval',
        '$mdSidenav', 'TourService', 'ProjectService',
          function ($routeParams, growl, KafkaService, $location,
          ModalService, $interval, $mdSidenav, TourService, ProjectService) {

            var self = this;
            self.projectId = $routeParams.projectID;
            self.topics = [];
            self.sharedTopics = [];
            self.topicDetails = {};
            self.maxNumTopics = 100;
            self.numTopicsUsed = 0;

            self.currentTopic = "";
            self.topicName = "";
            self.numReplicas = "";
            self.numPartitions = "";
            self.projectName = "";
            self.projectIsGuide = false;
            self.userEmail = "";
            self.permission_type = "Allow";
            self.operation_type = "Read";
            self.host = "*";
            self.role = "*";
           // self.activeId = -1;
            self.selectedProjectName="";

            self.users =[];
            self.project;

            self.showTopics = 1;
            self.showSchemas = -1;
            self.schemas = [];
            self.schemaVersions = [];
           self.tourService = TourService;

            self.selectAcl = function (acl, topicName) {
              if (self.activeId === acl.id) {
                return;
              }
              self.projectName = acl.projectName;
              self.userEmail = acl.userEmail;
              self.permission_type = acl.permission_type;
              self.operation_type = acl.operation_type;
              self.host = acl.host;
              self.role = acl.role;
              self.activeId = acl.id;

              KafkaService.aclUsers(self.projectId, topicName).then(
                    function (success) {
                        self.users = success.data;
                }, function (error) {
                    growl.error(error.data.errorMsg, {title: 'Could not load ACL users', ttl: 5000, referenceId: 10});
                   });

            };

            self.updateAcl = function (topicName, aclId){
              var acl ={};
              acl.projectName = self.project.projectName;
              acl.role = self.role;
              acl.userEmail = self.userEmail;
              acl.permissionType = self.permission_type;
              acl.operationType = self.operation_type;
              acl.host = self.host;
                KafkaService.updateTopicAcl(self.projectId, topicName, aclId, acl).then(
                        function(success){
                            self.getAclsForTopic(topicName);
                        }, function(error){
                            growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000});

                        });
            };

            self.getAllTopics = function () {
              KafkaService.getTopics(self.projectId).then(
                      function (success) {
                        self.topics = success.data;
                        self.numTopicsUsed = self.topics.length;
                      }, function (error) {
                growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000});
              });
            };

            self.getAllSharedTopics = function () {
              KafkaService.getSharedTopics(self.projectId).then(
                      function (success) {
                        self.sharedTopics = success.data;
                      }, function (error) {
                growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000});
              });
            };

            self.getTopicDetails = function (topicName) {
                KafkaService.getTopicDetails(self.projectId, topicName).then(
                        function (success) {
                            for(var i =0;i<self.topics.length;i++){
                              if(self.topics[i].name === topicName){
                                  self.topics[i].partitionDetails= success.data;
                                  return;
                              }
                          }
                        }, function (error) {
                    growl.warning(error.data.errorMsg, {title: 'Warning', ttl: 5000, referenceId: 10});
               });
            };

            /**
             * Navigate to the new job page.
             * @returns {undefined}
             */
            self.createSchema = function () {
              ModalService.createSchema('lg', self.projectId,
                self.projectIsGuide).then(
                      function (success) {
                          growl.success(success.data.successMessage, {title: 'New schema added successfully.', ttl: 2000});
                          self.listSchemas();
                          if (self.projectIsGuide) {
                            self.tourService.currentStep_TourThree = 2;
                          }
                      }, function (error) {
                //The user changed their mind.
              });
            };

            self.listSchemas = function () {

                KafkaService.getSchemasForTopics(self.projectId).then(
                 function (success) {
                 self.schemas = success.data;
                 var size = self.schemas.length;
                for(var i =0; i<size;i++){
                    self.schemaVersions[i] = Math.max.apply(null, self.schemas[i].versions);
                }
                 }, function (error) {
                 growl.error(error.data.errorMsg, {title: 'Could not get schemas for topic', ttl: 5000, referenceId: 10});
                 });

            };

            self.deleteSchema = function(schemaName, index){

                if(!self.schemaVersions[index]>0){
                  growl.info("Delete aborted", {title: 'Schema version not selected', ttl: 2000});
                    return;
                }
                 ModalService.confirm("sm", "Delete Schema (" + schemaName + ")",
                      "Do you really want to delete this Scehma? This action cannot be undone.")
                      .then(function (success) {
                          KafkaService.deleteSchema(self.projectId, schemaName, self.schemaVersions[index]).then(
                 function (success) {
                     self.listSchemas();
                 }, function (error) {
                 growl.error(error.data.errorMsg, {title: 'Schema is not removed', ttl: 5000, referenceId: 10});
                 });
                }, function (error) {
                    growl.info("Delete aborted", {title: 'Info', ttl: 2000});
                    });
            };

            self.viewSchemaContent = function(schemaName, index){

                if(!self.schemaVersions[index]>0){
                     growl.info("Please select schema version", {title: 'Schema version not selected', ttl: 2000});
                return;
                }

               ModalService.viewSchemaContent('lg', self.projectId, schemaName, self.schemaVersions[index]).then(
                      function (success) {

                      }, function (error) {
                //The user changed their mind.
              });
            };

            self.updateSchemaContent = function(schema){

                //increment the version number
                self.version = Math.max.apply(null,schema.versions);

                 ModalService.updateSchemaContent('lg', self.projectId, schema.name, self.version).then(
                      function (success) {
                         self.listSchemas();
                      }, function (error) {
                //The user changed their mind.
              });
            };

            self.lala = function () {
              console.log("Step: " + self.tourService.currentStep_TourThree);
            };
            /**
             * Navigate to the new job page.
             * @returns {undefined}
             */
            self.createTopic = function () {
              ModalService.createTopic('lg', self.projectId, self.projectIsGuide)
              .then(
                      function (success) {
                          growl.success(success.data.successMessage, {title: 'New topic created successfully.', ttl: 2000});
                          self.getAllTopics();
                          if (self.projectIsGuide) {
                            self.tourService.currentStep_TourThree = 4;
                          }
                      }, function (error) {
                      growl.error(error.data.errorMsg, {title: 'Failure to create topic', ttl: 5000, referenceId: 10});
              });
              self.getAllTopics();

            };

            self.removeTopic = function (topicName) {
              ModalService.confirm("sm", "Delete Topic (" + topicName + ")",
                      "Do you really want to delete this topic? This action cannot be undone.")
                      .then(function (success) {
                        KafkaService.removeTopic(self.projectId, topicName).then(
                                function (success) {
                                  self.getAllTopics();
                                }, function (error) {
                          growl.error(error.data.errorMsg, {title: 'Failed to remove topic', ttl: 5000});
                        });
                      }, function (cancelled) {
                        growl.info("Delete aborted", {title: 'Info', ttl: 2000});
                      });
            };

            self.getAclsForTopic = function (topicName) {
              KafkaService.getAclsForTopic(self.projectId, topicName).then(
                      function (success) {
                          for(var i =0;i<self.topics.length;i++){
                              if(self.topics[i].name === topicName){
                                  self.topics[i].acls = success.data;
                                  return;
                              }
                          }
                        self.activeId = "";
                      }, function (error) {
                growl.error(error.data.errorMsg, {title: 'Failed to get ACLs for the topic', ttl: 5000});
              });
            };

            self.addAcl = function (topicName) {

                ModalService.createTopicAcl('lg', self.projectId, topicName).then(
                      function (success) {
                          growl.success(success.data.successMessage, {title: 'New acl added for the topic: '+topicName, ttl: 5000});
                          self.getAclsForTopic(topicName);
                      }, function (error) {
                //The user changed their mind.
              });
            };

            self.removeAcl = function (topicName, aclId) {
              KafkaService.removeTopicAcl(self.projectId, topicName, aclId).then(
                      function (success) {
                        self.getAclsForTopic(topicName);
                      }, function (error) {
                growl.error(error.data.errorMsg, {title: 'Failed to remove topic', ttl: 5000});
              });

            };

            self.shareTopic = function(topicName) {
              ModalService.selectProject('lg', true, self.projectId,
                      "Select a Project to share the topic with.").then(
                      function (success) {
                        var destProj = success.projectId;
                        KafkaService.shareTopic(self.projectId, topicName, destProj).then(
                                function (success) {
                                  self.topicIsSharedTo(topicName);
                                  growl.success(success.data.successMessage, {title: 'Topic shared successfully with project: ' + destProj.name, ttl: 5000});
                                }, function (error) {
                          growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000});
                        });

                      }, function (error) {
                //The user changed their mind.
              });
            };

            //operation done from topic
            self.unshareTopic = function(topicName, project) {

                        KafkaService.unshareTopic(self.projectId, topicName, project.id).then(
                                function (success) {
                                  self.topicIsSharedTo(topicName);
                                  growl.success(success.data.successMessage, {title: 'Topic share removed (unshared) from project: ' + project.name, ttl: 2000});
                                }, function (error) {
                          growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000});
                        });
            };

            //operation done from project
            self.unshareTopicFromProject =function (topicName){
                KafkaService.unshareTopicFromProject(self.projectId, topicName).then(
                        function (success) {
                                  self.getAllSharedTopics();
                                  growl.success(success.data.successMessage, {title: 'Topic share removed (unshared) from project:.', ttl: 2000});
                                }, function (error) {
                          growl.error(error.data.errorMsg, {title: 'Error', ttl: 5000});
                        });
            };

            self.topicIsSharedTo = function (topicName) {
                KafkaService.topicIsSharedTo(this.projectId, topicName).then(
                        function (success) {
                           for(var i =0;i<self.topics.length;i++){
                              if(self.topics[i].name === topicName){
                                  self.topics[i].shares=success.data;
                                  return;
                              }
                          }
                        }, function (error) {
                    growl.error(error.data.errorMsg, {title: 'Failed to get topic sharing information', ttl: 5000});
                });
            };

            self.init = function(){
              ProjectService.get({}, {'id': self.projectId}).$promise.then(
                function (success) {
                  var projectNameTour = success.projectName;
                  if (angular.equals(projectNameTour.substr(0, 5), 'demo_')) {
                    self.tourService.currentStep_TourThree = 0;
                    self.projectIsGuide = true;
                  }
                }, function (error) {
                  $location.path('/');
                }
              );

              self.getAllTopics();
              self.getAllSharedTopics();
             };

            self.init();

            self.showTopic = function(){
              if (self.projectIsGuide) {
                self.tourService.currentStep_TourThree = 3;
              }
              self.showSchemas = -1;
              self.showTopics = 1;
            };

            self.showSchema = function(){
              if (self.projectIsGuide) {
                self.tourService.currentStep_TourThree = 1;
              }
              self.showSchemas = 1;
              self.showTopics = -1;
              self.listSchemas();
            };

          }]);

<|endoftext|>


<commit_before>/**
 * This file holds views to represent the voting procedure and to allow
 * the users to vote.
 */
(function () {

  var Dom = require('dom');
  var Plugin = require('plugin');
  var Modal = require('modal');
  var Ui = require('ui');
  var Db = require('db');
  var Server = require('server');
  var Obs = require('obs');

  /**
   * A pop-up like menu to choose a user to vote on.
   * @param users the users to vote for
   * @param an observer holding what currently is selected
   * @param callback for who is voted on
   */
  function voteModal(users, selected, onVote) {
    Modal.show('Vote for', function () {
      Dom.style({width: '80%'});

      // the panel with the content
      Dom.div(function () {
        Dom.style({
          maxHeight: '40%',
          overflow: 'auto',
          _overflowScrolling: 'touch',
          backgroundColor: '#eee',
          margin: '-12px'
        });

        // showing the users
        Obs.observe(function () {
          var selectedGet = selected.get();

          users.forEach(function (user) {
            Ui.item(function () {
              Ui.avatar(Plugin.userAvatar(user));
              Dom.text(Plugin.userName(user));

              // making the selected vote appear different
              if (user === selectedGet) {
                Dom.style({fontWeight: 'bold'});

                Dom.div(function () {
                  Dom.style({
                    flex: 1,
                    padding: '0 10px',
                    textAlign: 'right',
                    fontSize: '150%',
                    color: Plugin.colors().highlight
                  });
                  Dom.text('✓');
                });
              }

              // handling tap event
              Dom.onTap(function () {
                onVote(user);
                Modal.remove();
              });
            });
          });
        });

      });
    });
  }

  /**
   * Gets the users that are still alive.
   */
  function livingUsers() {
    // an object containing the users, with their id as key
    var users = Db.shared.ref('users').get();

    // the users that are alive
    var alive = Object.keys(users).filter(function (user) {
      return users[user].isAlive;
    });

    // cast back to int (the Object.keys always returns strings)
    return alive.map(function (user) {
      return parseInt(user, 10);
    });
  }

  /**
   * Button that allows you to vote.
   */
  function voteButton(votingId) {

    // observer for who is voted on
    var selected = Db.shared.ref('votings').get(votingId, Plugin.userId());
    var selectedObs = Obs.create(selected);

    // callback used for voteModal
    function vote(user) {
      selectedObs.set(user);
      Server.call('vote', votingId, user);
    }
    // the user we can vote on
    var users = livingUsers();

    // the button
    Ui.button('Vote', voteModal.bind(this, users, selectedObs, vote));
  }

}());
<commit_msg>Add a function to display a disabled vote button<commit_after>/**
 * This file holds views to represent the voting procedure and to allow
 * the users to vote.
 */
(function () {

  var Dom = require('dom');
  var Plugin = require('plugin');
  var Modal = require('modal');
  var Ui = require('ui');
  var Db = require('db');
  var Server = require('server');
  var Obs = require('obs');

  /**
   * A pop-up like menu to choose a user to vote on.
   * @param users the users to vote for
   * @param an observer holding what currently is selected
   * @param callback for who is voted on
   */
  function voteModal(users, selected, onVote) {
    Modal.show('Vote for', function () {
      Dom.style({width: '80%'});

      // the panel with the content
      Dom.div(function () {
        Dom.style({
          maxHeight: '40%',
          overflow: 'auto',
          _overflowScrolling: 'touch',
          backgroundColor: '#eee',
          margin: '-12px'
        });

        // showing the users
        Obs.observe(function () {
          var selectedGet = selected.get();

          users.forEach(function (user) {
            Ui.item(function () {
              Ui.avatar(Plugin.userAvatar(user));
              Dom.text(Plugin.userName(user));

              // making the selected vote appear different
              if (user === selectedGet) {
                Dom.style({fontWeight: 'bold'});

                Dom.div(function () {
                  Dom.style({
                    flex: 1,
                    padding: '0 10px',
                    textAlign: 'right',
                    fontSize: '150%',
                    color: Plugin.colors().highlight
                  });
                  Dom.text('✓');
                });
              }

              // handling tap event
              Dom.onTap(function () {
                onVote(user);
                Modal.remove();
              });
            });
          });
        });

      });
    });
  }

  /**
   * Gets the users that are still alive.
   */
  function livingUsers() {
    // an object containing the users, with their id as key
    var users = Db.shared.ref('users').get();

    // the users that are alive
    var alive = Object.keys(users).filter(function (user) {
      return users[user].isAlive;
    });

    // cast back to int (the Object.keys always returns strings)
    return alive.map(function (user) {
      return parseInt(user, 10);
    });
  }

  /**
   * Button that allows you to vote.
   */
  function voteButton(votingId) {

    // observer for who is voted on
    var selected = Db.shared.ref('votings').get(votingId, Plugin.userId());
    var selectedObs = Obs.create(selected);

    // callback used for voteModal
    function vote(user) {
      selectedObs.set(user);
      Server.call('vote', votingId, user);
    }
    // the user we can vote on
    var users = livingUsers();

    // the button
    Ui.button('Vote', voteModal.bind(this, users, selectedObs, vote));
  }

  /**
   * A button that looks like a vote button, but which is disabled.
   */
  function disabledVoteButton() {
    Dom.div(function () {
      Dom.style({'background-color': '#A88698'});
      Dom.cls('button');
      Dom.text('Vote');
    });
  }

}());
<|endoftext|>


<commit_before>var viewData = {};

$('#searchBox').on('submit', function(e) {
  e.preventDefault();
  var searchTerms = this.search.value;
  getData.runSearch(searchTerms);
});

var template = $('#search-results').html();
var render = Handlebars.compile(template);

viewData.printResults = function(data) {
  data.matches.forEach(function(ele) {
    console.log(ele);
    $('#print-results').append(render(ele));
  });
};
<commit_msg>Old results now delete when new search is performed<commit_after>var viewData = {};

$('#searchBox').on('submit', function(e) {
  e.preventDefault();
  $('#print-results').children().remove();
  var searchTerms = this.search.value;
  getData.runSearch(searchTerms);
});

var render = Handlebars.compile($('#search-results').html());

viewData.printResults = function(data) {
  data.matches.forEach(function(ele) {
    console.log(ele);
    $('#print-results').append(render(ele));
  });
};
<|endoftext|>


<commit_before>/*
 * Postmonger.js   version 0.0.12
 * https://github.com/kevinparkerson/postmonger
 *
 * Copyright (c) 2012-2013 Kevin Parkerson
 * Available via the MIT or new BSD license.
 * Further details and documentation:
 * http://kevinparkerson.github.com/postmonger/
 *
 *///

(function(root, factory){
    if(typeof define === 'function' && define.amd) {
        define('postmonger', [], function(){ return factory(root); });
    }else {
        root.Postmonger = factory(root);
    }
}(this, function(root){
    root = root || window;

    var exports = exports || undefined;
    var Postmonger;
    var previous = root.Postmonger;
    var _window = (root.addEventListener || root.attachEvent) ? root : window;
    var Connection, Events, Session;

    //Set up Postmonger namespace, provide noConflict support, and
    //version
    if (typeof(exports) !== 'undefined') {
        Postmonger = exports;
    } else {
        Postmonger = {};
    }
    Postmonger.noConflict = function(){
        root.Postmonger = previous;
        return this;
    };
    Postmonger.version = '0.0.12';

    //Create a new Postmonger Connection
    Connection = Postmonger.Connection = function(options){
        options = (typeof(options)==='object') ? options : {};

        var connect = options.connect || _window.parent;
        var from = options.from || '*';
        var to = options.to || '*';
        var self = this;

        //If string, grab based on id
        if(typeof(connect)==='string'){
            connect = document.getElementById(connect);
        }

        //If no connection, check for jquery object
        if(connect && !connect.postMessage && connect.jquery){
            connect = connect.get(0);
        }

        //If still no connection, check for iframe
        if(connect && !connect.postMessage && (connect.contentWindow || connect.contentDocument)){
            connect = connect.contentWindow || connect.contentDocument;
        }

        //Throw warning if connection could not be made
        if(!(connect && connect.postMessage)){
            if(_window.console && _window.console.warn){
                _window.console.warn(' Warning: Postmonger could not establish connection with ', options.connect);
            }
            return false;
        }

        self.connect = connect;
        self.to = to;
        self.from = from;

        return self;
    };

    //Postmonger.Events - Hacked together from Backbone.Events and two
    //Underscore functions.
    Events = Postmonger.Events = function(){
        var eventSplitter = /\s+/;
        var self = this;

        self._callbacks = {};

        self._has = function(obj, key){
            return Object.prototype.hasOwnProperty.call(obj, key);
        };

        self._keys = function(obj){
            if(Object.keys){
                return Object.keys(obj);
            }

            if (typeof(obj)!=='object'){
                throw new TypeError('Invalid object');
            }

            var keys = [];

            for(var key in obj){
                if (self._has(obj, key)) {
                    keys[keys.length] = key;
                }
            }

            return keys;
        };

        self.on = function(events, callback, context){
            var calls, event, node, tail, list;

            if(!callback){
                return self;
            }

            events = events.split(eventSplitter);

            self._callbacks = self._callbacks || {};
            calls = self._callbacks;

            while (event = events.shift()) {
                list = calls[event];

                node = (list) ? list.tail : {};
                tail = {};

                node.next = tail;
                node.context = context;
                node.callback = callback;

                calls[event] = {
                    tail: tail,
                    next: (list) ? list.next : node
                };
            }

            return self;
        };

        self.off = function(events, callback, context){
            var calls = self._callbacks;
            var event, node, tail, cb, ctx;

            if(!calls){
                return;
            }

            if(!(events || callback || context)){
                delete self._callbacks;
                return self;
            }

            events = (events) ? events.split(eventSplitter) : self._keys(calls);

            while (event = events.shift()) {
                node = calls[event];
                delete calls[event];
                if (!node || !(callback || context)) {
                    continue;
                }

                tail = node.tail;
                while ((node = node.next) !== tail) {
                    cb = node.callback;
                    ctx = node.context;
                    if (((callback && cb) !== callback) || ((context && ctx) !== context)) {
                        self.on(event, cb, ctx);
                    }
                }
            }

            return self;
        };

        self.trigger = function(events){
            console.log("Postmonger trigger: " + events);
            var event, node, calls, tail, args, all, rest;

            if (!(calls = self._callbacks)) {
                return self;
            }

            all = calls.all;
            events = events.split(eventSplitter);
            rest = Array.prototype.slice.call(arguments, 1);

            while (event = events.shift()) {
                if (node = calls[event]) {
                    tail = node.tail;
                    while ((node = node.next) !== tail) {
                        node.callback.apply(node.context || self, rest);
                    }
                }
                if (node = all) {
                    tail = node.tail;
                    args = [event].concat(rest);
                    while ((node = node.next) !== tail) {
                        node.callback.apply(node.context || self, args);
                    }
                }
            }

            return self;
        };

        return self;
    };

    //Create a new Postmonger Session
    Session = Postmonger.Session = function(){
        var args = (arguments.length>0) ? Array.prototype.slice.call(arguments, 0) : [{}];
        var connections = [];
        var incoming = new Events();
        var outgoing = new Events();
        var self = this;
        var connection, i, j, l, ln, postMessageListener;

        //Session API hooks
        self.on = incoming.on;
        self.off = incoming.off;
        self.trigger = outgoing.trigger;
        self.end = function(){
            incoming.off();
            outgoing.off();
            if(_window.removeEventListener){
                _window.removeEventListener('message', postMessageListener, false);
            }else if(_window.detachEvent){
                _window.detachEvent('onmessage', postMessageListener);
            }
            return self;
        };

        //Establishing connections
        for(i=0, l=args.length; i<l; i++){
            connection = new Connection(args[i]);
            if(connection){
                for(j=0, ln=connections.length; j<ln; j++){
                    if(
                        connections[j].connect===connection.connect &&
                        connections[j].from===connection.from &&
                        connections[j].to===connection.to
                    ){
                        connection = null;
                        break;
                    }
                }
                if(connection){
                    connections.push(connection);
                }
            }
        }

        //Listener for incoming messages
        postMessageListener = function(event){
            console.log("Inbound event: " + event);
            var conn = null;
            var message = [];
            var data;
            var k, len;

            //Attempt to find the connection we're dealing with
            for(k=0, len=connections.length; k<len; k++){
                if(connections[k].connect===event.source){
                    conn = connections[k];
                    break;
                }
            }

            //Check if we've found the connection
            if(!conn){
                return false;
            }

            console.log("Postmonger: " + conn.from);
            console.log("Postmonger: " + event.origin);

            //Check if the message is from the expected origin
            if(conn.from!=='*' && conn.from!==event.origin){
                return false;
            }

            //Check the data that's been passed
            try{
                data = JSON.parse(event.data);
                console.log("Postmonger: parse data: " + JSON.stringify(data));
                if(!data.e){
                    console.log("Returning false...");
                    return false;
                }
            }catch(e){
                console.log("Exception!" + e);
                return false;
            }

            //Format the passed in data
            message.push(data.e);
            delete data.e;
            for(k in data){
                message.push(data[k]);
            }

            console.log('Postmonger: sending message: ' + message);

            //Send the message
            incoming['trigger'].apply(root, message);
        };

        //Add the listener
        if(_window.addEventListener){
            _window.addEventListener('message', postMessageListener, false);
        }else if(_window.attachEvent){
            _window.attachEvent('onmessage', postMessageListener);
        }else{
            if(_window.console && _window.console.warn){
                _window.console.warn('WARNING: Postmonger could not listen for messages on window %o', _window);
            }
            return false;
        }

        //Sending outgoing messages
        outgoing.on('all', function(){
            var args = Array.prototype.slice.call(arguments, 0);
            var message = {};
            var k, len;

            message.e = args[0];

            for(k=1, len=args.length; k<len; k++){
                message['a' + k] = args[k];
            }

            for(k=0, len=connections.length; k<len; k++){
                connections[k].connect.postMessage(JSON.stringify(message), connections[k].to);
            }
        });

        return self;
    };

    return Postmonger;
}));
<commit_msg>playing around<commit_after>/*
 * Postmonger.js   version 0.0.12
 * https://github.com/kevinparkerson/postmonger
 *
 * Copyright (c) 2012-2013 Kevin Parkerson
 * Available via the MIT or new BSD license.
 * Further details and documentation:
 * http://kevinparkerson.github.com/postmonger/
 *
 *///

(function(root, factory){
    if(typeof define === 'function' && define.amd) {
        define('postmonger', [], function(){ return factory(root); });
    }else {
        root.Postmonger = factory(root);
    }
}(this, function(root){
    root = root || window;

    var exports = exports || undefined;
    var Postmonger;
    var previous = root.Postmonger;
    var _window = (root.addEventListener || root.attachEvent) ? root : window;
    var Connection, Events, Session;

    //Set up Postmonger namespace, provide noConflict support, and
    //version
    if (typeof(exports) !== 'undefined') {
        Postmonger = exports;
    } else {
        Postmonger = {};
    }
    Postmonger.noConflict = function(){
        root.Postmonger = previous;
        return this;
    };
    Postmonger.version = '0.0.12';

    //Create a new Postmonger Connection
    Connection = Postmonger.Connection = function(options){
        options = (typeof(options)==='object') ? options : {};

        var connect = options.connect || _window.parent;
        var from = options.from || '*';
        var to = options.to || '*';
        var self = this;

        //If string, grab based on id
        if(typeof(connect)==='string'){
            connect = document.getElementById(connect);
        }

        //If no connection, check for jquery object
        if(connect && !connect.postMessage && connect.jquery){
            connect = connect.get(0);
        }

        //If still no connection, check for iframe
        if(connect && !connect.postMessage && (connect.contentWindow || connect.contentDocument)){
            connect = connect.contentWindow || connect.contentDocument;
        }

        //Throw warning if connection could not be made
        if(!(connect && connect.postMessage)){
            if(_window.console && _window.console.warn){
                _window.console.warn(' Warning: Postmonger could not establish connection with ', options.connect);
            }
            return false;
        }

        self.connect = connect;
        self.to = to;
        self.from = from;

        return self;
    };

    //Postmonger.Events - Hacked together from Backbone.Events and two
    //Underscore functions.
    Events = Postmonger.Events = function(){
        var eventSplitter = /\s+/;
        var self = this;

        self._callbacks = {};

        self._has = function(obj, key){
            return Object.prototype.hasOwnProperty.call(obj, key);
        };

        self._keys = function(obj){
            if(Object.keys){
                return Object.keys(obj);
            }

            if (typeof(obj)!=='object'){
                throw new TypeError('Invalid object');
            }

            var keys = [];

            for(var key in obj){
                if (self._has(obj, key)) {
                    keys[keys.length] = key;
                }
            }

            return keys;
        };

        self.on = function(events, callback, context){
            var calls, event, node, tail, list;

            if(!callback){
                return self;
            }

            events = events.split(eventSplitter);

            self._callbacks = self._callbacks || {};
            calls = self._callbacks;

            while (event = events.shift()) {
                list = calls[event];

                node = (list) ? list.tail : {};
                tail = {};

                node.next = tail;
                node.context = context;
                node.callback = callback;

                calls[event] = {
                    tail: tail,
                    next: (list) ? list.next : node
                };
            }

            return self;
        };

        self.off = function(events, callback, context){
            var calls = self._callbacks;
            var event, node, tail, cb, ctx;

            if(!calls){
                return;
            }

            if(!(events || callback || context)){
                delete self._callbacks;
                return self;
            }

            events = (events) ? events.split(eventSplitter) : self._keys(calls);

            while (event = events.shift()) {
                node = calls[event];
                delete calls[event];
                if (!node || !(callback || context)) {
                    continue;
                }

                tail = node.tail;
                while ((node = node.next) !== tail) {
                    cb = node.callback;
                    ctx = node.context;
                    if (((callback && cb) !== callback) || ((context && ctx) !== context)) {
                        self.on(event, cb, ctx);
                    }
                }
            }

            return self;
        };

        self.trigger = function(events){
            console.log("Postmonger trigger: " + events);
            var event, node, calls, tail, args, all, rest;

            if (!(calls = self._callbacks)) {
                console.log("Postmonger returning self...");
                console.log("calls: " + JSON.stringify(self._callbacks));
                return self;
            }

            all = calls.all;
            events = events.split(eventSplitter);
            rest = Array.prototype.slice.call(arguments, 1);

            while (event = events.shift()) {
                if (node = calls[event]) {
                    tail = node.tail;
                    while ((node = node.next) !== tail) {
                        node.callback.apply(node.context || self, rest);
                    }
                }
                if (node = all) {
                    tail = node.tail;
                    args = [event].concat(rest);
                    while ((node = node.next) !== tail) {
                        node.callback.apply(node.context || self, args);
                    }
                }
            }
            console.log("Postmonger 1: " + self);
            return self;
        };
        console.log("Postmonger 2: " + self);
        return self;
    };

    //Create a new Postmonger Session
    Session = Postmonger.Session = function(){
        var args = (arguments.length>0) ? Array.prototype.slice.call(arguments, 0) : [{}];
        var connections = [];
        var incoming = new Events();
        var outgoing = new Events();
        var self = this;
        var connection, i, j, l, ln, postMessageListener;

        //Session API hooks
        self.on = incoming.on;
        self.off = incoming.off;
        self.trigger = outgoing.trigger;
        self.end = function(){
            incoming.off();
            outgoing.off();
            if(_window.removeEventListener){
                _window.removeEventListener('message', postMessageListener, false);
            }else if(_window.detachEvent){
                _window.detachEvent('onmessage', postMessageListener);
            }
            return self;
        };

        //Establishing connections
        for(i=0, l=args.length; i<l; i++){
            connection = new Connection(args[i]);
            if(connection){
                for(j=0, ln=connections.length; j<ln; j++){
                    if(
                        connections[j].connect===connection.connect &&
                        connections[j].from===connection.from &&
                        connections[j].to===connection.to
                    ){
                        connection = null;
                        break;
                    }
                }
                if(connection){
                    connections.push(connection);
                }
            }
        }

        //Listener for incoming messages
        postMessageListener = function(event){
            console.log("Inbound event: " + event);
            var conn = null;
            var message = [];
            var data;
            var k, len;

            //Attempt to find the connection we're dealing with
            for(k=0, len=connections.length; k<len; k++){
                if(connections[k].connect===event.source){
                    conn = connections[k];
                    break;
                }
            }

            //Check if we've found the connection
            if(!conn){
                return false;
            }

            console.log("Postmonger: " + conn.from);
            console.log("Postmonger: " + event.origin);

            //Check if the message is from the expected origin
            if(conn.from!=='*' && conn.from!==event.origin){
                return false;
            }

            //Check the data that's been passed
            try{
                data = JSON.parse(event.data);
                console.log("Postmonger: parse data: " + JSON.stringify(data));
                if(!data.e){
                    console.log("Returning false...");
                    return false;
                }
            }catch(e){
                console.log("Exception!" + e);
                return false;
            }

            //Format the passed in data
            message.push(data.e);
            delete data.e;
            for(k in data){
                message.push(data[k]);
            }

            console.log('Postmonger: sending message: ' + message);

            //Send the message
            incoming['trigger'].apply(root, message);
        };

        //Add the listener
        if(_window.addEventListener){
            _window.addEventListener('message', postMessageListener, false);
        }else if(_window.attachEvent){
            _window.attachEvent('onmessage', postMessageListener);
        }else{
            if(_window.console && _window.console.warn){
                _window.console.warn('WARNING: Postmonger could not listen for messages on window %o', _window);
            }
            return false;
        }

        //Sending outgoing messages
        outgoing.on('all', function(){
            var args = Array.prototype.slice.call(arguments, 0);
            var message = {};
            var k, len;

            message.e = args[0];

            for(k=1, len=args.length; k<len; k++){
                message['a' + k] = args[k];
            }

            for(k=0, len=connections.length; k<len; k++){
                connections[k].connect.postMessage(JSON.stringify(message), connections[k].to);
            }
        });

        return self;
    };

    return Postmonger;
}));
<|endoftext|>