<commit_before>/* HEADER */

var headerState = $.cookie('header');
if ($.cookie('header') == 'header-small') {
	$('html').toggleClass('header-small');
	$('.header-button').removeClass('icon-chevron-up').addClass('icon-chevron-down');
}
$('.header-button').click(function() {
	if ($.cookie('header') == 'header-small') {
		$.cookie('header', '');
		$('html').toggleClass('header-small', '');
		$('.header-button').removeClass('icon-chevron-down').addClass('icon-chevron-up');
	} else {
		$.cookie('header', 'header-small');
		$('html').toggleClass('header-small');
		$('.header-button').removeClass('icon-chevron-up').addClass('icon-chevron-down');
	}
});

/* HEADER (end) */

/* SET FOOTER DIV HEIGHT */

$('footer .wrap div:first-child').height(215);
$('footer .wrap div:nth-child(2)').height(126);
$('footer .wrap div:nth-child(3)').height(106);

/* SET FOOTER DIV HEIGHT (end) */

/* MISC */

$('.selectHandschriften').change(function() {
	$('#scriptsSelection option:selected').val();
});

/* MISC (end) */

EditionProperties.applySettings({
									configurationUrl: 'Resources/Public/JavaScript/Archaeo18Config.js',
									maxTags: 20
								});

var showDiv = function(div, link) {
	$('#start_page').css('display', 'none');
	$('#edition_page').css('display', 'none');
	$('#indices_page').css('display', 'none');
	$('#manuscripts_page').css('display', 'none');
	$('#help_page').css('display', 'none');
	$('#terms_page').css('display', 'none');
	$('#databases_page').css('display', 'none');
	$('#acknowledgment_page').css('display', 'none');
	$('#people_page').css('display', 'none');
	$('#imprint_page').css('display', 'none');
	$('#linkstart').removeClass('selected');
	$('#linkedition').removeClass('selected');
	$('#linkindices').removeClass('selected');
	$('#linkhandschriften').removeClass('selected');
	if (typeof link != 'undefined') {
		$(link).addClass('selected');
	}
	$(div).css('display', 'block');
}

var loadHelp = function(div) {

	var mainContentContainer = $(div + ' .maincontent .helptopics');
	var subNavigationContainer = div + ' .subnav';

	$('.helptopic').hide();
	$(subNavigationContainer + ' a').removeClass('selected');

	// listener for clicks on item
	$(subNavigationContainer + ' li').click(function() {
		var scriptId = $('a', this).attr('id')
		if (scriptId != '') {
			$(subNavigationContainer + ' a').each(function() {
				$(this).removeClass("selected");
			});

			$('a', this).addClass('selected');
			$('.helptopic').hide();

			var idToMarkdown = function(id) {
				var pathParts = id.split('-');
				var firstPartOfPath = pathParts[0];
				pathParts.splice(0, 1);

				var fileName = firstPartOfPath + '/' + pathParts.join('-');
				return fileName;
			}

			var pageUrl = 'content/' + idToMarkdown(scriptId) + '.md';

			$.ajax({
					   url: pageUrl
				   }).done(function(html) {
							   mainContentContainer.html(markdown.toHTML(html), 'md_tree');
						   });
			return false;
		}
	});

	$(subNavigationContainer + ' li:first').click();

};

var loadContent = function(page) {
console.log(page);
	var pageUrl = 'content/' + page + '/index.md';

	var content = this;

	content.container = function() {
		return '#' + page + '_page';
	}

	$.ajax({
		url: pageUrl
		})
			.done(function(html) {
					  var container = $(content.container() + ' .wrap');
					  container.html(markdown.toHTML(html));
				  });
}

var loadIndices = function() {
	if (!Indices.initialized) {
		Indices.initialize();
	}
	Indices.checkDisplay();
}

var loadScripts = function() {
	if (!Scripts.initialized) {
		Scripts.initialize();
	}
}

var loadEdition = function() {
	if (!EditionGui.initialized) {
		EditionGui.initialize();
	}
	EditionGui.gridLayout();
}

var loadPage = function() {
	if (window.location.href.indexOf('?params') != -1) {
		showDiv('#edition_page', '#linkedition');
		loadEdition();
	} else
		if (window.location.href.indexOf('?page=') != -1) {
			var data = window.location.href.split('?page=')[1];

			// get path to be loaded from the "CMS"
			var pagePath = data.split('_page')[0].replace('#', '');

			var page = data, link;
			if (data.indexOf('&link=') != -1) {
				var data2 = data.split('&link=');
				page = data2[0];
				link = data2[1];
			}
			showDiv(page, link);
			loadContent(pagePath);

			if (page.indexOf('edition') != -1) {
				loadEdition();
			}
			else
				if (page.indexOf('indices') != -1) {
					loadIndices();
				}
				else
					if (page.indexOf('manuscripts') != -1) {
						loadScripts();
					} else
						if (page.indexOf('start') !== -1) {
							showDiv('#start_page', '#linkstart');
							loadContent('start');
						} else
							if (page.indexOf('help') !== -1) {
								loadHelp('#help_page');
							}
		} else {
			showDiv('#start_page', '#linkstart');
			loadContent('start');
		}
}
loadPage();

var addGeoTemCo = function() {
	if (typeof(GeoTemConfig) === 'undefined') {
		var css, js;
		css = '<link rel="stylesheet" href="ropen/Resources/Public/JavaScript/Libraries/GeoTemCo/css/geotemco.css" type="text/css" />';
		js = '<script src="ropen/Resources/Public/JavaScript/Libraries/GeoTemCo/geotemco-min.js"></script>';
		$('head').append(css + js);
	}
}

$('#linkstart').click(function() {
	showDiv('#start_page', '#linkstart');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#start_page&link=#linkstart";
	document.title = 'Archaeo 18: Start';
});

$('#linkedition').click(function() {
	showDiv('#edition_page', '#linkedition');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#edition_page&link=#linkedition";
	addGeoTemCo();
	document.title = 'Archaeo 18: Edition';
	loadEdition();
});

$('#linkindices').click(function() {
	showDiv('#indices_page', '#linkindices');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#indices_page&link=#linkindices";
	addGeoTemCo();
	document.title = 'Archaeo 18: Indices';
	loadIndices();
});

$('#linkhandschriften').click(function() {
	showDiv('#manuscripts_page', '#linkhandschriften');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#manuscripts_page&link=#linkhandschriften";
	document.title = 'Archaeo 18: Handschriften';
	loadScripts();
});

$('#linkstart2').click(function() {
	showDiv('#start_page', '#linkstart');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#start_page&link=#linkstart";
	document.title = 'Archaeo 18: Start';
});

$('#linkedition2').click(function() {
	showDiv('#edition_page', '#linkedition');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#edition_page&link=#linkedition";
	document.title = 'Archaeo 18: Edition';
	loadEdition();
});

$('#linkedition3').click(function() {
	showDiv('#edition_page', '#linkedition');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#edition_page&link=#linkedition";
	document.title = 'Archaeo 18: Edition';
	loadEdition();
});

$('#linkindices2').click(function() {
	showDiv('#indices_page', '#linkindices');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#indices_page&link=#linkindices";
	document.title = 'Archaeo 18: Indices';
	loadIndices();
});

$('#linkhandschriften2').click(function() {
	showDiv('#manuscripts_page', '#linkhandschriften');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#manuscripts_page&link=#linkhandschriften";
	document.title = 'Archaeo 18: Handschriften';
	loadScripts();
});

$('#linkhelp').click(function() {
	var divToShow = '#help_page';
	showDiv(divToShow, '#linkhelp');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#help_page";
	document.title = 'Archaeo 18: Hilfe';
	loadHelp(divToShow);
});

$('#linkterms').click(function() {
	showDiv('#terms_page', '#linkhelp');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#terms_page";
	document.title = 'Archaeo 18: Editionsrichtlinien';
});

$('#linkimprint').click(function() {
	showDiv('#imprint_page', '#linkimprint');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#imprint_page";
	document.title = 'Archaeo 18: Impressum';
});

$('#linkdatabases').click(function(e) {
	showDiv('#databases_page', '#linkdatabases', e);
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#databases_page";
	document.title = 'Archaeo 18: Datenbanken und Repositorien';
});

$('#linkacknowledgment').click(function(e) {
	showDiv('#acknowledgment_page', '#linkacknowledgment', e);
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#acknowledgment_page";
	document.title = 'Archaeo 18: Danksagung';
});

$('#linkpeople').click(function(e) {
	showDiv('#people_page', '#linkpeople', e);
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#people_page";
	document.title = 'Archaeo 18: Projekmitarbeiter';
});

window.onhashchange = function() {
	if (location.hash.indexOf('?') != -1) {
		loadPage();
	}
};

var footerWidth = $('#logoPanel').width();
$(window).resize(function() {
	var w = Math.max($(window).width(), $('#editionContainer').width());
	if (footerWidth > w) {
		$('footer').css('width', footerWidth + 'px');
	}
	else {
		$('footer').css('width', w + 'px');
	}
});<commit_msg>Fixed loading error for edition and indices<commit_after>/* HEADER */

var headerState = $.cookie('header');
if ($.cookie('header') == 'header-small') {
	$('html').toggleClass('header-small');
	$('.header-button').removeClass('icon-chevron-up').addClass('icon-chevron-down');
}
$('.header-button').click(function() {
	if ($.cookie('header') == 'header-small') {
		$.cookie('header', '');
		$('html').toggleClass('header-small', '');
		$('.header-button').removeClass('icon-chevron-down').addClass('icon-chevron-up');
	} else {
		$.cookie('header', 'header-small');
		$('html').toggleClass('header-small');
		$('.header-button').removeClass('icon-chevron-up').addClass('icon-chevron-down');
	}
});

/* HEADER (end) */

/* SET FOOTER DIV HEIGHT */

$('footer .wrap div:first-child').height(215);
$('footer .wrap div:nth-child(2)').height(126);
$('footer .wrap div:nth-child(3)').height(106);

/* SET FOOTER DIV HEIGHT (end) */

/* MISC */

$('.selectHandschriften').change(function() {
	$('#scriptsSelection option:selected').val();
});

/* MISC (end) */

EditionProperties.applySettings({
									configurationUrl: 'Resources/Public/JavaScript/Archaeo18Config.js',
									maxTags: 20
								});

var showDiv = function(div, link) {
	$('#start_page').css('display', 'none');
	$('#edition_page').css('display', 'none');
	$('#indices_page').css('display', 'none');
	$('#manuscripts_page').css('display', 'none');
	$('#help_page').css('display', 'none');
	$('#terms_page').css('display', 'none');
	$('#databases_page').css('display', 'none');
	$('#acknowledgment_page').css('display', 'none');
	$('#people_page').css('display', 'none');
	$('#imprint_page').css('display', 'none');
	$('#linkstart').removeClass('selected');
	$('#linkedition').removeClass('selected');
	$('#linkindices').removeClass('selected');
	$('#linkhandschriften').removeClass('selected');
	if (typeof link != 'undefined') {
		$(link).addClass('selected');
	}
	$(div).css('display', 'block');
}

var loadHelp = function(div) {

	var mainContentContainer = $(div + ' .maincontent .helptopics');
	var subNavigationContainer = div + ' .subnav';

	$('.helptopic').hide();
	$(subNavigationContainer + ' a').removeClass('selected');

	// listener for clicks on item
	$(subNavigationContainer + ' li').click(function() {
		var scriptId = $('a', this).attr('id')
		if (scriptId != '') {
			$(subNavigationContainer + ' a').each(function() {
				$(this).removeClass("selected");
			});

			$('a', this).addClass('selected');
			$('.helptopic').hide();

			var idToMarkdown = function(id) {
				var pathParts = id.split('-');
				var firstPartOfPath = pathParts[0];
				pathParts.splice(0, 1);

				var fileName = firstPartOfPath + '/' + pathParts.join('-');
				return fileName;
			}

			var pageUrl = 'content/' + idToMarkdown(scriptId) + '.md';

			$.ajax({
					   url: pageUrl
				   }).done(function(html) {
							   mainContentContainer.html(markdown.toHTML(html), 'md_tree');
						   });
			return false;
		}
	});

	$(subNavigationContainer + ' li:first').click();

};

var loadContent = function(page) {
	var pageUrl = 'content/' + page + '/index.md';

	var content = this;

	content.container = function() {
		return '#' + page + '_page';
	}

	$.ajax({
		url: pageUrl
		})
			.done(function(html) {
					  var container = $(content.container() + ' .wrap');
					  container.html(markdown.toHTML(html));
				  });
}

var loadIndices = function() {
	if (!Indices.initialized) {
		Indices.initialize();
	}
	Indices.checkDisplay();
}

var loadScripts = function() {
	if (!Scripts.initialized) {
		Scripts.initialize();
	}
}

var loadEdition = function() {
	if (!EditionGui.initialized) {
		EditionGui.initialize();
	}
	EditionGui.gridLayout();
}

var addGeoTemCo = function() {
	if (typeof(GeoTemConfig) === 'undefined') {
		var css, js;
		css = '<link rel="stylesheet" href="ropen/Resources/Public/JavaScript/Libraries/GeoTemCo/css/geotemco.css" type="text/css" />';
		js = '<script src="ropen/Resources/Public/JavaScript/Libraries/GeoTemCo/geotemco-min.js"></script>';
		$('head').append(css + js);
	}
}

var loadPage = function() {
	if (window.location.href.indexOf('?params') != -1) {
		showDiv('#edition_page', '#linkedition');
		loadEdition();
	} else
		if (window.location.href.indexOf('?page=') != -1) {
			var data = window.location.href.split('?page=')[1];

			// get path to be loaded from the "CMS"
			var pagePath = data.split('_page')[0].replace('#', '');

			var page = data, link;
			if (data.indexOf('&link=') != -1) {
				var data2 = data.split('&link=');
				page = data2[0];
				link = data2[1];
			}
			showDiv(page, link);
			if (pagePath !== 'edition' && pagePath !== 'indices' && pagePath !== 'manuscripts') {
				loadContent(pagePath);
			}

			if (page.indexOf('edition') != -1) {
				addGeoTemCo();
				loadEdition();
			}
			else
				if (page.indexOf('indices') != -1) {
					addGeoTemCo();
					loadIndices();
				}
				else
					if (page.indexOf('manuscripts') != -1) {
						loadScripts();
					} else
						if (page.indexOf('start') !== -1) {
							showDiv('#start_page', '#linkstart');
							loadContent('start');
						} else
							if (page.indexOf('help') !== -1) {
								loadHelp('#help_page');
							}
		} else {
			showDiv('#start_page', '#linkstart');
			loadContent('start');
		}
}
loadPage();

$('#linkstart').click(function() {
	showDiv('#start_page', '#linkstart');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#start_page&link=#linkstart";
	document.title = 'Archaeo 18: Start';
});

$('#linkedition').click(function() {
	showDiv('#edition_page', '#linkedition');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#edition_page&link=#linkedition";
	addGeoTemCo();
	document.title = 'Archaeo 18: Edition';
	loadEdition();
});

$('#linkindices').click(function() {
	showDiv('#indices_page', '#linkindices');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#indices_page&link=#linkindices";
	addGeoTemCo();
	document.title = 'Archaeo 18: Indices';
	loadIndices();
});

$('#linkhandschriften').click(function() {
	showDiv('#manuscripts_page', '#linkhandschriften');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#manuscripts_page&link=#linkhandschriften";
	document.title = 'Archaeo 18: Handschriften';
	loadScripts();
});

$('#linkstart2').click(function() {
	showDiv('#start_page', '#linkstart');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#start_page&link=#linkstart";
	document.title = 'Archaeo 18: Start';
});

$('#linkedition2').click(function() {
	showDiv('#edition_page', '#linkedition');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#edition_page&link=#linkedition";
	document.title = 'Archaeo 18: Edition';
	loadEdition();
});

$('#linkedition3').click(function() {
	showDiv('#edition_page', '#linkedition');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#edition_page&link=#linkedition";
	document.title = 'Archaeo 18: Edition';
	loadEdition();
});

$('#linkindices2').click(function() {
	showDiv('#indices_page', '#linkindices');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#indices_page&link=#linkindices";
	document.title = 'Archaeo 18: Indices';
	loadIndices();
});

$('#linkhandschriften2').click(function() {
	showDiv('#manuscripts_page', '#linkhandschriften');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#manuscripts_page&link=#linkhandschriften";
	document.title = 'Archaeo 18: Handschriften';
	loadScripts();
});

$('#linkhelp').click(function() {
	var divToShow = '#help_page';
	showDiv(divToShow, '#linkhelp');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#help_page";
	document.title = 'Archaeo 18: Hilfe';
	loadHelp(divToShow);
});

$('#linkterms').click(function() {
	showDiv('#terms_page', '#linkhelp');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#terms_page";
	document.title = 'Archaeo 18: Editionsrichtlinien';
});

$('#linkimprint').click(function() {
	showDiv('#imprint_page', '#linkimprint');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#imprint_page";
	document.title = 'Archaeo 18: Impressum';
});

$('#linkdatabases').click(function(e) {
	showDiv('#databases_page', '#linkdatabases', e);
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#databases_page";
	document.title = 'Archaeo 18: Datenbanken und Repositorien';
});

$('#linkacknowledgment').click(function(e) {
	showDiv('#acknowledgment_page', '#linkacknowledgment', e);
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#acknowledgment_page";
	document.title = 'Archaeo 18: Danksagung';
});

$('#linkpeople').click(function(e) {
	showDiv('#people_page', '#linkpeople', e);
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#people_page";
	document.title = 'Archaeo 18: Projekmitarbeiter';
});

window.onhashchange = function() {
	if (location.hash.indexOf('?') != -1) {
		loadPage();
	}
};

var footerWidth = $('#logoPanel').width();
$(window).resize(function() {
	var w = Math.max($(window).width(), $('#editionContainer').width());
	if (footerWidth > w) {
		$('footer').css('width', footerWidth + 'px');
	}
	else {
		$('footer').css('width', w + 'px');
	}
});<|endoftext|>


<commit_before>(function(d, w, u) {
	var run = function() {
		/**
		 * The constructor for the CustomInfoWindow class
		 * @param  {string|DomNode}   elem      The element to use as an InfoWindow
		 * @param  {object}           options   The object with all the options to use
		 * @return {CustomInfoWindow}           The Custom InfoWindow
		 */
		var c = w.CustomInfoWindow = function(elem, options) {
			var defaultOptions = {
				location: new google.maps.LatLng(52.374004, 4.890359), //The location to place the CustomInfoWindow
				offset: {
					x: 0, //Horizontal offset for the CustomInfoWindow
					y: 0  //Vertical offset for the CustomInfoWindow
				},
				padding: 40, //Minimal distance between the border of the map and the border of the CustomInfoWindow
				elementEdge: {
					x: 'left', //Vertical edge of the CustomInfoWindow to align with the location
					y: 'top'   //Horizontal edge of the CustomInfoWindow to align with the location
				}
			}
			this.shown = false; //Keep track whether the CustomInfoWindow is being shown (so we can call the draw-method if needed)
			this.firstDraw = true; //Keep track if drawing the CustomInfoWindow for the first time, since we need to do extra calculations on the first draw
			this.setElement(elem);
			this.options = options || {};
			for (var o in defaultOptions) {
				if (!this.options.hasOwnProperty(o)) this.options[o] = defaultOptions[o];
			}
			//Normalize some of the options
			if (this.options.elementEdge.x != 'left' && this.options.elementEdge.x != 'right') this.options.elementEdge.x = 'left';
			if (this.options.elementEdge.y != 'top' && this.options.elementEdge.y != 'bottom') this.options.elementEdge.y = 'top';
			//Set the location and the map if provided
			if (this.options.location && this.options.location.constructor == google.maps.LatLng) this.setLocation(this.options.location);
			if (this.options.map && this.options.map.constructor == google.maps.Map) this.setMap(this.options.map);
		};
		c.prototype = new google.maps.OverlayView(); //extend google.maps.OverlayView
		/**
		 * Called when the CustomInfoWindow is added to the map
		 * @return {void}
		 */
		c.prototype.onAdd = function() {
			var d = this.getMap().getDiv();
			d.parentNode.insertBefore(this.elem, d); //Move the element to the parent of the map so we can position it rightly
			var that = this;
			//add eventlisteners so we can keep the CustomInfoWindow in the correct location
			this.devh = google.maps.event.addListener(this.getMap(), 'drag', function() {that.draw()});
			this.ievh = google.maps.event.addListener(this.getMap(), 'idle', function() {that.draw()});
			this.elem.style.display = 'block';
			this.shown = true; //CustomInfoWindow is shown now
			this.firstDraw = true; //We'll be drawing for the first time soon

			//If using a different edge then top/left, adjust the offsets accordingly
			//This is done here because now the element is shown, so we can safely measure it
			if (this.options.elementEdge.x == 'right') this.options.offset.x -= this.elem.clientWidth;
			if (this.options.elementEdge.y == 'bottom') this.options.offset.y -= this.elem.clientHeight;
		};
		c.prototype.draw = function() {
			var p = this.getProjection().fromLatLngToContainerPixel(this.location); //Determine the left/top in px for the chosen location
			var x = p.x + this.options.offset.x, y = p.y + this.options.offset.y; //determine the top and left, taking offset into account
			//now position the element
			this.elem.style.left = x+"px";
			this.elem.style.top = y+"px";

			//if this is the first drawing (right after adding), make sure we show the CustomInfoWindow within the given padding around the map-border
			if (this.firstDraw) {
				if (x < 0) {
					if (y < 0) this.getMap().panBy(x - this.options.padding, y -this.options.padding);
					else this.getMap().panBy(x - this.options.padding, 0);
				} else if (y < 0) {
					this.getMap().panBy(0, y - this.options.padding);
				}
				//also determine this for the bottom and right edges of the map
				var d = this.getMap().getDiv();
				var mx = d.clientWidth - (x + this.elem.clientWidth), my = d.clientHeight - (y + this.elem.clientHeight);
				if (mx < 0) {
					if (my < 0)  this.getMap().panBy(-mx + this.options.padding, -my + this.options.padding);
					else this.getMap().panBy(-mx + this.options.padding, 0);
				} else if (my < 0) {
					this.getMap().panBy(0, -my + this.options.padding);
				}
			}
			this.firstDraw = false;
		};
		/**
		 * Called when removing the CustomInfoWindow from the map (by calling setMap(null))
		 * @return {void}
		 */
		c.prototype.onRemove = function() {
			this.elem.style.display = 'none'; //hide the element
			this.shown = false;
			//remove the eventlisteners for performance
			google.maps.event.removeListener(this.devh);
			google.maps.event.removeListener(this.ievh);
		};
		/**
		 * Sets the element to use as a CustomInfoWindow
		 * @param  {string|DomNode} elem The element to use
		 * @return {void}
		 */
		c.prototype.setElement = function(elem) {
			//normalize the element
			if (typeof elem == 'string') elem = d.getElementById(elem);
			this.elem = elem;
			//make sure the element is hidden
			this.elem.style.display = 'none';
			this.elem.style.position = 'absolute';
		};
		/**
		 * Set the location to show the CustomInfoWindow
		 * @param  {google.maps.LatLng} location The location
		 * @return {void}
		 */
		c.prototype.setLocation = function(location) {
			if (location.constructor != google.maps.LatLng) {
				alert('Please provide a google.maps.LatLng to set the location.');
			}
			this.location = location;
			if (this.shown) this.draw(); //update the map if the CustomInfoWindow is currently shown
		};
	};
	var loader = function() {
		if (w.google && w.google.maps && w.google.maps.OverlayView) {
			run(); //don't load the class-definition till google.maps.OverlayView is available, since we need that class for our prototype
		} else {
			w.setTimeout(loader, 50); //try again in 50ms to see if google.maps.OverlayView is available
		}
	};
	loader();
})(document, window);
<commit_msg>Update CustomInfoWindow.js<commit_after>/**
 * CustomInfoWindow Object
 * Class to create custom InfoWindows on Google Maps, which you can style as you like.
 *
 * @author R. Mansveld <ronald@ronaldmansveld.nl>
 *
 * @copyright Copyright (c) 2013 R. Mansveld

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.

 *
 * @param  {document} d The document
 * @param  {window} w The window
 * @param  {undefined} u Undefined
 *
 */
(function(d, w, u) {
	var run = function() {
		/**
		 * The constructor for the CustomInfoWindow class
		 * @param  {string|DomNode}   elem      The element to use as an InfoWindow
		 * @param  {object}           options   The object with all the options to use
		 * @return {CustomInfoWindow}           The Custom InfoWindow
		 */
		var c = w.CustomInfoWindow = function(elem, options) {
			var defaultOptions = {
				location: new google.maps.LatLng(52.374004, 4.890359), //The location to place the CustomInfoWindow
				offset: {
					x: 0, //Horizontal offset for the CustomInfoWindow
					y: 0  //Vertical offset for the CustomInfoWindow
				},
				padding: 40, //Minimal distance between the border of the map and the border of the CustomInfoWindow
				elementEdge: {
					x: 'left', //Vertical edge of the CustomInfoWindow to align with the location
					y: 'top'   //Horizontal edge of the CustomInfoWindow to align with the location
				}
			}
			this.shown = false; //Keep track whether the CustomInfoWindow is being shown (so we can call the draw-method if needed)
			this.firstDraw = true; //Keep track if drawing the CustomInfoWindow for the first time, since we need to do extra calculations on the first draw
			this.setElement(elem);
			this.options = options || {};
			for (var o in defaultOptions) {
				if (!this.options.hasOwnProperty(o)) this.options[o] = defaultOptions[o];
			}
			//Normalize some of the options
			if (this.options.elementEdge.x != 'left' && this.options.elementEdge.x != 'right') this.options.elementEdge.x = 'left';
			if (this.options.elementEdge.y != 'top' && this.options.elementEdge.y != 'bottom') this.options.elementEdge.y = 'top';
			//Set the location and the map if provided
			if (this.options.location && this.options.location.constructor == google.maps.LatLng) this.setLocation(this.options.location);
			if (this.options.map && this.options.map.constructor == google.maps.Map) this.setMap(this.options.map);
		};
		c.prototype = new google.maps.OverlayView(); //extend google.maps.OverlayView
		/**
		 * Called when the CustomInfoWindow is added to the map
		 * @return {void}
		 */
		c.prototype.onAdd = function() {
			var d = this.getMap().getDiv();
			d.parentNode.insertBefore(this.elem, d); //Move the element to the parent of the map so we can position it rightly
			var that = this;
			//add eventlisteners so we can keep the CustomInfoWindow in the correct location
			this.devh = google.maps.event.addListener(this.getMap(), 'drag', function() {that.draw()});
			this.ievh = google.maps.event.addListener(this.getMap(), 'idle', function() {that.draw()});
			this.elem.style.display = 'block';
			this.shown = true; //CustomInfoWindow is shown now
			this.firstDraw = true; //We'll be drawing for the first time soon

			//If using a different edge then top/left, adjust the offsets accordingly
			//This is done here because now the element is shown, so we can safely measure it
			if (this.options.elementEdge.x == 'right') this.options.offset.x -= this.elem.clientWidth;
			if (this.options.elementEdge.y == 'bottom') this.options.offset.y -= this.elem.clientHeight;
		};
		c.prototype.draw = function() {
			var p = this.getProjection().fromLatLngToContainerPixel(this.location); //Determine the left/top in px for the chosen location
			var x = p.x + this.options.offset.x, y = p.y + this.options.offset.y; //determine the top and left, taking offset into account
			//now position the element
			this.elem.style.left = x+"px";
			this.elem.style.top = y+"px";

			//if this is the first drawing (right after adding), make sure we show the CustomInfoWindow within the given padding around the map-border
			if (this.firstDraw) {
				if (x < 0) {
					if (y < 0) this.getMap().panBy(x - this.options.padding, y -this.options.padding);
					else this.getMap().panBy(x - this.options.padding, 0);
				} else if (y < 0) {
					this.getMap().panBy(0, y - this.options.padding);
				}
				//also determine this for the bottom and right edges of the map
				var d = this.getMap().getDiv();
				var mx = d.clientWidth - (x + this.elem.clientWidth), my = d.clientHeight - (y + this.elem.clientHeight);
				if (mx < 0) {
					if (my < 0)  this.getMap().panBy(-mx + this.options.padding, -my + this.options.padding);
					else this.getMap().panBy(-mx + this.options.padding, 0);
				} else if (my < 0) {
					this.getMap().panBy(0, -my + this.options.padding);
				}
			}
			this.firstDraw = false;
		};
		/**
		 * Called when removing the CustomInfoWindow from the map (by calling setMap(null))
		 * @return {void}
		 */
		c.prototype.onRemove = function() {
			this.elem.style.display = 'none'; //hide the element
			this.shown = false;
			//remove the eventlisteners for performance
			google.maps.event.removeListener(this.devh);
			google.maps.event.removeListener(this.ievh);
		};
		/**
		 * Sets the element to use as a CustomInfoWindow
		 * @param  {string|DomNode} elem The element to use
		 * @return {void}
		 */
		c.prototype.setElement = function(elem) {
			//normalize the element
			if (typeof elem == 'string') elem = d.getElementById(elem);
			this.elem = elem;
			//make sure the element is hidden
			this.elem.style.display = 'none';
			this.elem.style.position = 'absolute';
		};
		/**
		 * Set the location to show the CustomInfoWindow
		 * @param  {google.maps.LatLng} location The location
		 * @return {void}
		 */
		c.prototype.setLocation = function(location) {
			if (location.constructor != google.maps.LatLng) {
				alert('Please provide a google.maps.LatLng to set the location.');
			}
			this.location = location;
			if (this.shown) this.draw(); //update the map if the CustomInfoWindow is currently shown
		};

		/**
		 * All code is now available, check if a callback is available, and run it
		 */
		if (w.CustomInfoWindowCallback) {
			w.CustomInfoWindowCallback();
		}
	};
	var loader = function() {
		if (w.google && w.google.maps && w.google.maps.OverlayView) {
			run(); //don't load the class-definition till google.maps.OverlayView is available, since we need that class for our prototype
		} else {
			w.setTimeout(loader, 50); //try again in 50ms to see if google.maps.OverlayView is available
		}
	};
	loader();
})(document, window);
<|endoftext|>


<commit_before>StartTest(function (t) {
    t.diag("Sanity");

    t.ok(Ext, 'Ext is defined');
    t.ok(Ext.Window, 'Ext.Window is defined');

    t.ok(Traccar, 'Traccar is defined');
    t.ok(Traccar.Application, 'Traccar.Application is defined');

    t.ok(strings, 'strings are defined');
    t.ok(styles, 'styles are defined');

    t.done();
});
<commit_msg>Update siesta sanity UI test<commit_after>StartTest(function (t) {
    t.diag("Sanity");

    t.ok(Ext, 'Ext is defined');
    t.ok(Ext.Window, 'Ext.Window is defined');

    t.ok(Traccar, 'Traccar is defined');
    t.ok(Traccar.Application, 'Traccar.Application is defined');

    t.ok(Strings, 'Strings are defined');
    t.ok(Traccar.Styles, 'Traccar.Styles are defined');

    t.done();
});
<|endoftext|>


<commit_before>(function($) {
    'use strict';
    function checkKeys(event, keys) {
        var actualKeys = '';
        if(event.ctrlKey)
            actualKeys += 'ctrl+';

        if(event.shiftKey)
            actualKeys += 'shift+';

        if(event.metaKey)
            actualKeys += 'meta+';

	if(event.altKey)
	    actualKeys += 'alt';

        var which = event.which;

        if((which >= 48 && which <= 57) || (which >= 65 && which <= 90)) {
            actualKeys += String.fromCharCode(which);
        }

        return actualKeys.toLowerCase() === keys.toLowerCase();
    }

    $.fn.qeydown = function(keys, handler) {
        this.keydown(function(e) {
            if(checkKeys(e, keys))
                handler(e);
        });
        return this;
    };

    $.fn.qeyup = function(keys, handler) {
        this.keyup(function(e) {
            if(checkKeys(e, keys))
                handler(e);
        });
        return this;
    };

    $.fn.qeypress = function(keys, handler) {
        this.keypress(function(e) {
            if(checkKeys(e, keys))
                handler(e);
        });
        return this;
    };
})(jQuery);
<commit_msg>in ubuntu it seems which differs between lare and small letters<commit_after>(function($) {
    'use strict';
    function checkKeys(event, keys) {
        var actualKeys = '';
        if(event.ctrlKey)
            actualKeys += 'ctrl+';

        if(event.shiftKey)
            actualKeys += 'shift+';

        if(event.metaKey)
            actualKeys += 'meta+';

	if(event.altKey)
	    actualKeys += 'alt';

        var which = event.which;

        if((which >= 48 && which <= 57) || (which >= 65 && which <= 90) || (which >= 97 && which <= 122) ) {
            actualKeys += String.fromCharCode(which);
        }

        return actualKeys.toLowerCase() === keys.toLowerCase();
    }

    $.fn.qeydown = function(keys, handler) {
        this.keydown(function(e) {
            if(checkKeys(e, keys))
                handler(e);
        });
        return this;
    };

    $.fn.qeyup = function(keys, handler) {
        this.keyup(function(e) {
            if(checkKeys(e, keys))
                handler(e);
        });
        return this;
    };

    $.fn.qeypress = function(keys, handler) {
        this.keypress(function(e) {
            if(checkKeys(e, keys))
                handler(e);
        });
        return this;
    };
})(jQuery);
<|endoftext|>


<commit_before>/* Copyright 2015-2016,2018 Ivan Yelizariev <https://it-projects.info/team/yelizariev>
 * Copyright 2015-2016 Ilyas Rakhimkulov
 * Copyright 2016-2018 Dinar Gabbasov <https://it-projects.info/team/GabbasovDinar>
 * Copyright 2017,2019 Kolushov Alexandr <https://it-projects.info/team/KolushovAlexandr>
 * Copyright 2017 Attila Szöllősi
 * Copyright 2017 Thomas Paul
 * License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). */

odoo.define('pos_multi_session_restaurant', function(require){
    var screens = require('pos_restaurant_base.screens');
    var models = require('pos_restaurant_base.models');
    var multiprint = require('pos_restaurant.multiprint');
    var floors = require('pos_restaurant.floors');
    var core = require('web.core');
    var gui = require('point_of_sale.gui');
    var chrome = require('point_of_sale.chrome');
    var multi_session = require('pos_multi_session');
    var rpc = require('web.rpc');

    var _t = core._t;

    gui.Gui.prototype.screen_classes.filter(function(el) {
        return el.name === 'splitbill';
    })[0].widget.include({
        pay: function(order,neworder,splitlines){
            this._super(order,neworder,splitlines);
            neworder.save_to_db();
        }
    });

    screens.OrderWidget.include({
        update_summary: function(){
            var order = this.pos.get('selectedOrder');
            if (!order){
                return;
            }
            this._super();
        },
        remove_orderline: function(order_line){
            if (this.pos.get_order() && this.pos.get_order().get_orderlines().length === 0){
                this._super(order_line);
            } else {
                if (order_line.node && order_line.node.parentNode) {
                    order_line.node.parentNode.removeChild(order_line.node);
                }
            }
        }
    });

    var PosModelSuper = models.PosModel;
    models.PosModel = models.PosModel.extend({
        initialize: function(){
            var ms_model = {
                model: 'pos.multi_session',
                fields: ['name','floor_ids'],
                domain: null,
                loaded: function(self,floor_set){
                    self.multi_session_floors = floor_set;
            }};
            this.models.splice(
                1 + this.models.indexOf(_.find(this.models, function(model){
                    return model.model === 'pos.config';
                })), 0, ms_model);
            var floor_model = _.find(this.models, function(model){
                return model.model === 'restaurant.floor';
            });
            floor_model.domain = function(self){
                var temporary = [['id','in',self.config.floor_ids]];
                if (self.config.multi_session_id){
                    var ms_floors = _.find(self.multi_session_floors, function(session){
                        return session.id === self.config.multi_session_id[0];
                    });
                    temporary = [['id','in', ms_floors.floor_ids]];
                }
                return temporary;
            };
            var self = this;
            PosModelSuper.prototype.initialize.apply(this, arguments);
            this.ready.then(function () {
                if (!self.config.multi_session_id){
                    return;
                }
                self.multi_session.floor_ids = self.multi_session_floors.floor_ids;
                self.config.floor_ids = self.multi_session.floor_ids;
            });
        },
        add_new_order: function(){
            var self = this;
            PosModelSuper.prototype.add_new_order.apply(this, arguments);
            var current_order = this.get_order();
            if (this.multi_session && current_order){
                current_order.new_updates_to_send();
                current_order.save_to_db();
            }
        },
        ms_create_order: function(options) {
            var self = this;
            var data = options.json;
            var table = false;
            var floor_table = false;
            var order = false;

            if (data.table_id) {
                table = this.tables_by_id[data.table_id];
            }

            // Is there a table on the floor?
            if (table) {
                floor_table = table.floor.tables.find(function (t) {
                    return t.id === data.table_id;
                });
            }

            if (table && data.removed_table_id && this.tables_by_id[data.removed_table_id]) {
                var removed_table = this.tables_by_id[data.removed_table_id];
                this.gui.show_popup('error', {
                    'title': _t('Got unknown table ' + removed_table.name),
                    'body': _t('Order will be moved to ' + table.name + ' table')
                });

                // remove old table from floor screen
                var floor = this.floors.find(function(f){
                    return f.id === removed_table.floor_id[0];
                });
                var index = floor.tables.findIndex(function(t) {
                    return t.id === removed_table.id;
                });
                floor.tables.splice(index, 1);
                delete this.tables_by_id[data.removed_table_id];

                if (this.gui.screen_instances.floors && this.gui.get_current_screen() === "floors") {
                    this.gui.screen_instances.floors.renderElement();
                }
            }

            if (table && floor_table) {
                order = PosModelSuper.prototype.ms_create_order.call(this, options);
                order.table = self.tables_by_id[data.table_id];
                order.customer_count = data.customer_count;
                order.removed_table_id = false;
            } else {
                // load new table
                var domain = [['id', '=', data.table_id]];
                rpc.query({
                    model: 'restaurant.table',
                    method: 'search_read',
                    domain: domain,
                }).then(function (t) {
                    if (t.length) {
                        self.gui.show_popup('confirm',{
                             'title': _t('Got a new table'),
                             'body': _t('Do you want to reload this page to receive the latest updates?'),
                             confirm: function() {
                                 location.reload();
                             }
                        });
                    } else {
                        if (!self.floors.length) {
                            return;
                        }
                        // if the table is not exist move the order to a first empty table
                        var empty_tables = self.floors[0].tables.filter(function(exist_table) {
                           return self.get_table_orders(exist_table).length === 0;
                        });
                        var transfer_table = self.tables_by_id[self.floors[0].table_ids[0]];
                        if (empty_tables.length) {
                            transfer_table = empty_tables[0];
                        }

                        var removed_table_id = data.table_id;
                        options.json.table_id = transfer_table.id;
                        order = self.ms_create_order(options);
                        order.removed_table_id = removed_table_id;
                        order.trigger('new_updates_to_send');
                        if (self.gui.screen_instances.floors && self.gui.get_current_screen() === "floors") {
                            self.gui.screen_instances.floors.renderElement();
                        }
                    }
                });
            }
            return order;
        },
        updates_from_server: function(message){
            var data = message.data || {};
            var order = false;
            var old_order = this.get_order();

            if (data.uid){
                order = this.get('orders').find(function(ord) {
                    return ord.uid === data.uid;
                });
            }
            PosModelSuper.prototype.updates_from_server.apply(this, arguments);
            if ((order && old_order && old_order.uid !== order.uid) || (old_order === null)) {
                this.set('selectedOrder',old_order);
            }
            if (this.gui.screen_instances.floors && this.gui.get_current_screen() === "floors") {
                this.gui.screen_instances.floors.renderElement();
            }
        },
        ms_update_order: function(order, data){
            PosModelSuper.prototype.ms_update_order.apply(this, arguments);
            if (order) {
                order.init_locked = true;
                order.set_customer_count(data.customer_count, true);
                order.saved_resume = data.multiprint_resume;
                order.trigger('change');
                order.init_locked = false;
            }
        },
        ms_update_existing_order: function(order, data) {
            if (order.table && order.table.id !== data.table_id) {
                // the order has been transferred to another table
                this.order_to_transfer_to_different_table = order;
                this.set_table(this.tables_by_id[data.table_id]);
                this.order_to_transfer_to_different_table = null;
            }
            PosModelSuper.prototype.ms_update_existing_order.apply(this, arguments);
        },
        // changes the current table.
        set_table: function(table) {
            var order = this.order_to_transfer_to_different_table;
            if (table && order) {
                var old_table = order.table;
                order.table = table;
                order.new_updates_to_send();
                order.table = old_table;
            }
            PosModelSuper.prototype.set_table.apply(this, arguments);
        },

        check_table_inaccessibility: function(table) {
            // Allows to open if you are the one who created there an order or if you POS responsible person
            if (!this.config.table_blocking) {
                return false;
            }
            var cashier = this.get_cashier();
            var user_is_manager = _.contains(cashier.groups_id, this.config.group_pos_manager_id[0]);
            if (user_is_manager) {
                return false;
            }
            var table_orders = this.get_table_orders(table);
            var creators = _.chain(table_orders)
                .map(function(o){
                    return o.ms_info.created.user;
                })
                .unique().value();
            var creator_ids = _.pluck(creators, 'id');
            if (!creator_ids.length ||
                (creator_ids.length && _.contains(creator_ids, cashier.id))) {

                return false;
            }
            return creators;
        },
    });

    var OrderSuper = models.Order;
    models.Order = models.Order.extend({
        set_customer_count: function (count, skip_ms_update) {
            OrderSuper.prototype.set_customer_count.apply(this, arguments);
            if (!skip_ms_update) {
                this.new_updates_to_send();
            }
        },
        order_removing_to_send: function() {
            if (this.transfer) {
                return;
            }
            return OrderSuper.prototype.order_removing_to_send.call(this, arguments);
        },
        saveChanges: function(){
            OrderSuper.prototype.saveChanges.apply(this, arguments);
            this.trigger('new_updates_to_send');
        },
        export_as_JSON: function(){
            var data = OrderSuper.prototype.export_as_JSON.apply(this, arguments);
            data.removed_table_id = this.removed_table_id;
            return data;
        },
    });

    var OrderlineSuper = models.Orderline;
    models.Orderline = models.Orderline.extend({
        get_line_diff_hash: function(){
            var res = OrderlineSuper.prototype.get_line_diff_hash.apply(this, arguments);
            res = res.split('|');
            res[0] = this.uid;
            res = res.join('|');
            return res;
        },
        /*  There is no need to check the presence of super method.
            Because pos_multi_session_restaurant is loaded later than pos_multi_session.
        */
        apply_ms_data: function(data) {
            if(typeof data.mp_dirty !== 'undefined'){
                this.set_dirty(data.mp_dirty);
            }
            if(typeof data.mp_skip !== 'undefined'){
                this.set_skip(data.mp_skip);
            }
            if(typeof data.note !== 'undefined'){
                this.set_note(data.note);
            }
            OrderlineSuper.prototype.apply_ms_data.apply(this, arguments);
        },
    });

    floors.FloorScreenWidget.include({
        init: function(parent, options) {
            this._super(parent, options);
            this.saved_data = false;
        },
        show: function(){
            if (this.pos.debug) {
                console.log("renderElement of TableWidget");
            }
            this._super();
        },
        renderElement: function(){
            if (this.compare_data()) {
                return false;
            }
            if (this.pos.debug) {
                console.log("renderElement of FloorScreenWidget and TableWidget");
            }
            this._super();
            this.save_changes_data();
        },
        save_changes_data: function() {
            var self = this;
            var collection = this.get_current_data();
            this.saved_data = JSON.stringify(collection);
        },
        compare_data: function() {
            var collection = this.get_current_data();
            return this.saved_data === JSON.stringify(collection);
        },
        tool_trash_table: function() {
            var self = this;
            if (this.selected_table) {
                if (this.pos.get_table_orders(this.selected_table.table).length) {
                    this.gui.show_popup('error', {
                        'title': _t('You can not remove the table'),
                        'body': _t('Please, complete your orders before deleting the table.')
                    });
                } else if (this.floor.tables.length === 1) {
                    this.gui.show_popup('error', {
                        'title': _t('You can not remove the table'),
                        'body': _t('Forbidden to remove the last table on the floor.')
                    });
                } else {
                    this.gui.show_popup('confirm', {
                        'title': _t('Are you sure ?'),
                        'comment': _t('Removing a table cannot be undone'),
                        'body': _t('The table can be used in other POS'),
                        'confirm': function () {
                            self.selected_table.trash();
                            delete self.pos.tables_by_id[self.selected_table.table.id];
                        },
                    });
                }
            }
        },
        get_current_data: function(){
            var self = this;
            var tables = this.floor.tables;

            var collection = [];
            tables.forEach(function(table) {
                collection.push({
                    'floor': {
                        'background_color': table.floor.background_color,
                        'name': table.floor.name,
                        'sequence': table.floor.sequence,
                    },
                    'name': table.name,
                    'height': table.height,
                    'position_h': table.position_h,
                    'position_v': table.position_v,
                    'seats': table.seats,
                    'shape': table.shape,
                    'width': table.width,
                    'order_count': self.pos.get_table_orders(table).length,
                    'customer_count': self.pos.get_customer_count(table),
                    'fill': Math.min(1,Math.max(0,self.pos.get_customer_count(table) / table.seats)),
                    'notifications': self.get_notifications(table),
                });
            });
            return collection;
        },
        get_notifications: function(table){
            var orders = this.pos.get_table_orders(table);
            var notifications = {};
            for (var i = 0; i < orders.length; i++) {
                if (orders[i].hasChangesToPrint()) {
                    notifications.printing = true;
                    break;
                } else if (orders[i].hasSkippedChanges()) {
                    notifications.skipped = true;
                }
            }
            return notifications;
        },
    });

    floors.TableWidget.include({
        click_handler: function(){
            var self = this;
            var floorplan = this.getParent();
            if (floorplan.editing) {
                this._super();
            } else {
                var table = this.table;
                if (!table) {
                    return this._super();
                }
                var table_waiters = this.pos.check_table_inaccessibility(table);
                if (!table_waiters || !table_waiters.length) {
                    return this._super();
                }
                return this.pos.gui.show_popup('alert',{
                    'title': _t('Can not open the Table'),
                    'body': _t('The Table is served by another waiter ' + _.pluck(table_waiters, 'name')),
                });
            }
        },
    });

});
<commit_msg>:shield: type error: undefined is not a function<commit_after>/* Copyright 2015-2016,2018 Ivan Yelizariev <https://it-projects.info/team/yelizariev>
 * Copyright 2015-2016 Ilyas Rakhimkulov
 * Copyright 2016-2018 Dinar Gabbasov <https://it-projects.info/team/GabbasovDinar>
 * Copyright 2017,2019 Kolushov Alexandr <https://it-projects.info/team/KolushovAlexandr>
 * Copyright 2017 Attila Szöllősi
 * Copyright 2017 Thomas Paul
 * License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html). */

odoo.define('pos_multi_session_restaurant', function(require){
    var screens = require('pos_restaurant_base.screens');
    var models = require('pos_restaurant_base.models');
    var multiprint = require('pos_restaurant.multiprint');
    var floors = require('pos_restaurant.floors');
    var core = require('web.core');
    var gui = require('point_of_sale.gui');
    var chrome = require('point_of_sale.chrome');
    var multi_session = require('pos_multi_session');
    var rpc = require('web.rpc');

    var _t = core._t;

    gui.Gui.prototype.screen_classes.filter(function(el) {
        return el.name === 'splitbill';
    })[0].widget.include({
        pay: function(order,neworder,splitlines){
            this._super(order,neworder,splitlines);
            neworder.save_to_db();
        }
    });

    screens.OrderWidget.include({
        update_summary: function(){
            var order = this.pos.get('selectedOrder');
            if (!order){
                return;
            }
            this._super();
        },
        remove_orderline: function(order_line){
            if (this.pos.get_order() && this.pos.get_order().get_orderlines().length === 0){
                this._super(order_line);
            } else {
                if (order_line.node && order_line.node.parentNode) {
                    order_line.node.parentNode.removeChild(order_line.node);
                }
            }
        }
    });

    var PosModelSuper = models.PosModel;
    models.PosModel = models.PosModel.extend({
        initialize: function(){
            var ms_model = {
                model: 'pos.multi_session',
                fields: ['name','floor_ids'],
                domain: null,
                loaded: function(self,floor_set){
                    self.multi_session_floors = floor_set;
            }};
            this.models.splice(
                1 + this.models.indexOf(_.find(this.models, function(model){
                    return model.model === 'pos.config';
                })), 0, ms_model);
            var floor_model = _.find(this.models, function(model){
                return model.model === 'restaurant.floor';
            });
            floor_model.domain = function(self){
                var temporary = [['id','in',self.config.floor_ids]];
                if (self.config.multi_session_id){
                    var ms_floors = _.find(self.multi_session_floors, function(session){
                        return session.id === self.config.multi_session_id[0];
                    });
                    temporary = [['id','in', ms_floors.floor_ids]];
                }
                return temporary;
            };
            var self = this;
            PosModelSuper.prototype.initialize.apply(this, arguments);
            this.ready.then(function () {
                if (!self.config.multi_session_id){
                    return;
                }
                self.multi_session.floor_ids = self.multi_session_floors.floor_ids;
                self.config.floor_ids = self.multi_session.floor_ids;
            });
        },
        add_new_order: function(){
            var self = this;
            PosModelSuper.prototype.add_new_order.apply(this, arguments);
            var current_order = this.get_order();
            if (this.multi_session && current_order){
                current_order.new_updates_to_send();
                current_order.save_to_db();
            }
        },
        ms_create_order: function(options) {
            var self = this;
            var data = options.json;
            var table = false;
            var floor_table = false;
            var order = false;

            if (data.table_id) {
                table = this.tables_by_id[data.table_id];
            }

            // Is there a table on the floor?
            if (table) {
                floor_table = _.find(table.floor.tables, function (t) {
                    return t.id === data.table_id;
                });
            }

            if (table && data.removed_table_id && this.tables_by_id[data.removed_table_id]) {
                var removed_table = this.tables_by_id[data.removed_table_id];
                this.gui.show_popup('error', {
                    'title': _t('Got unknown table ' + removed_table.name),
                    'body': _t('Order will be moved to ' + table.name + ' table')
                });

                // remove old table from floor screen
                var floor = this.floors.find(function(f){
                    return f.id === removed_table.floor_id[0];
                });
                var index = floor.tables.findIndex(function(t) {
                    return t.id === removed_table.id;
                });
                floor.tables.splice(index, 1);
                delete this.tables_by_id[data.removed_table_id];

                if (this.gui.screen_instances.floors && this.gui.get_current_screen() === "floors") {
                    this.gui.screen_instances.floors.renderElement();
                }
            }

            if (table && floor_table) {
                order = PosModelSuper.prototype.ms_create_order.call(this, options);
                order.table = self.tables_by_id[data.table_id];
                order.customer_count = data.customer_count;
                order.removed_table_id = false;
            } else {
                // load new table
                var domain = [['id', '=', data.table_id]];
                rpc.query({
                    model: 'restaurant.table',
                    method: 'search_read',
                    domain: domain,
                }).then(function (t) {
                    if (t.length) {
                        self.gui.show_popup('confirm',{
                             'title': _t('Got a new table'),
                             'body': _t('Do you want to reload this page to receive the latest updates?'),
                             confirm: function() {
                                 location.reload();
                             }
                        });
                    } else {
                        if (!self.floors.length) {
                            return;
                        }
                        // if the table is not exist move the order to a first empty table
                        var empty_tables = self.floors[0].tables.filter(function(exist_table) {
                           return self.get_table_orders(exist_table).length === 0;
                        });
                        var transfer_table = self.tables_by_id[self.floors[0].table_ids[0]];
                        if (empty_tables.length) {
                            transfer_table = empty_tables[0];
                        }

                        var removed_table_id = data.table_id;
                        options.json.table_id = transfer_table.id;
                        order = self.ms_create_order(options);
                        order.removed_table_id = removed_table_id;
                        order.trigger('new_updates_to_send');
                        if (self.gui.screen_instances.floors && self.gui.get_current_screen() === "floors") {
                            self.gui.screen_instances.floors.renderElement();
                        }
                    }
                });
            }
            return order;
        },
        updates_from_server: function(message){
            var data = message.data || {};
            var order = false;
            var old_order = this.get_order();

            if (data.uid){
                order = this.get('orders').find(function(ord) {
                    return ord.uid === data.uid;
                });
            }
            PosModelSuper.prototype.updates_from_server.apply(this, arguments);
            if ((order && old_order && old_order.uid !== order.uid) || (old_order === null)) {
                this.set('selectedOrder',old_order);
            }
            if (this.gui.screen_instances.floors && this.gui.get_current_screen() === "floors") {
                this.gui.screen_instances.floors.renderElement();
            }
        },
        ms_update_order: function(order, data){
            PosModelSuper.prototype.ms_update_order.apply(this, arguments);
            if (order) {
                order.init_locked = true;
                order.set_customer_count(data.customer_count, true);
                order.saved_resume = data.multiprint_resume;
                order.trigger('change');
                order.init_locked = false;
            }
        },
        ms_update_existing_order: function(order, data) {
            if (order.table && order.table.id !== data.table_id) {
                // the order has been transferred to another table
                this.order_to_transfer_to_different_table = order;
                this.set_table(this.tables_by_id[data.table_id]);
                this.order_to_transfer_to_different_table = null;
            }
            PosModelSuper.prototype.ms_update_existing_order.apply(this, arguments);
        },
        // changes the current table.
        set_table: function(table) {
            var order = this.order_to_transfer_to_different_table;
            if (table && order) {
                var old_table = order.table;
                order.table = table;
                order.new_updates_to_send();
                order.table = old_table;
            }
            PosModelSuper.prototype.set_table.apply(this, arguments);
        },

        check_table_inaccessibility: function(table) {
            // Allows to open if you are the one who created there an order or if you POS responsible person
            if (!this.config.table_blocking) {
                return false;
            }
            var cashier = this.get_cashier();
            var user_is_manager = _.contains(cashier.groups_id, this.config.group_pos_manager_id[0]);
            if (user_is_manager) {
                return false;
            }
            var table_orders = this.get_table_orders(table);
            var creators = _.chain(table_orders)
                .map(function(o){
                    return o.ms_info.created.user;
                })
                .unique().value();
            var creator_ids = _.pluck(creators, 'id');
            if (!creator_ids.length ||
                (creator_ids.length && _.contains(creator_ids, cashier.id))) {

                return false;
            }
            return creators;
        },
    });

    var OrderSuper = models.Order;
    models.Order = models.Order.extend({
        set_customer_count: function (count, skip_ms_update) {
            OrderSuper.prototype.set_customer_count.apply(this, arguments);
            if (!skip_ms_update) {
                this.new_updates_to_send();
            }
        },
        order_removing_to_send: function() {
            if (this.transfer) {
                return;
            }
            return OrderSuper.prototype.order_removing_to_send.call(this, arguments);
        },
        saveChanges: function(){
            OrderSuper.prototype.saveChanges.apply(this, arguments);
            this.trigger('new_updates_to_send');
        },
        export_as_JSON: function(){
            var data = OrderSuper.prototype.export_as_JSON.apply(this, arguments);
            data.removed_table_id = this.removed_table_id;
            return data;
        },
    });

    var OrderlineSuper = models.Orderline;
    models.Orderline = models.Orderline.extend({
        get_line_diff_hash: function(){
            var res = OrderlineSuper.prototype.get_line_diff_hash.apply(this, arguments);
            res = res.split('|');
            res[0] = this.uid;
            res = res.join('|');
            return res;
        },
        /*  There is no need to check the presence of super method.
            Because pos_multi_session_restaurant is loaded later than pos_multi_session.
        */
        apply_ms_data: function(data) {
            if(typeof data.mp_dirty !== 'undefined'){
                this.set_dirty(data.mp_dirty);
            }
            if(typeof data.mp_skip !== 'undefined'){
                this.set_skip(data.mp_skip);
            }
            if(typeof data.note !== 'undefined'){
                this.set_note(data.note);
            }
            OrderlineSuper.prototype.apply_ms_data.apply(this, arguments);
        },
    });

    floors.FloorScreenWidget.include({
        init: function(parent, options) {
            this._super(parent, options);
            this.saved_data = false;
        },
        show: function(){
            if (this.pos.debug) {
                console.log("renderElement of TableWidget");
            }
            this._super();
        },
        renderElement: function(){
            if (this.compare_data()) {
                return false;
            }
            if (this.pos.debug) {
                console.log("renderElement of FloorScreenWidget and TableWidget");
            }
            this._super();
            this.save_changes_data();
        },
        save_changes_data: function() {
            var self = this;
            var collection = this.get_current_data();
            this.saved_data = JSON.stringify(collection);
        },
        compare_data: function() {
            var collection = this.get_current_data();
            return this.saved_data === JSON.stringify(collection);
        },
        tool_trash_table: function() {
            var self = this;
            if (this.selected_table) {
                if (this.pos.get_table_orders(this.selected_table.table).length) {
                    this.gui.show_popup('error', {
                        'title': _t('You can not remove the table'),
                        'body': _t('Please, complete your orders before deleting the table.')
                    });
                } else if (this.floor.tables.length === 1) {
                    this.gui.show_popup('error', {
                        'title': _t('You can not remove the table'),
                        'body': _t('Forbidden to remove the last table on the floor.')
                    });
                } else {
                    this.gui.show_popup('confirm', {
                        'title': _t('Are you sure ?'),
                        'comment': _t('Removing a table cannot be undone'),
                        'body': _t('The table can be used in other POS'),
                        'confirm': function () {
                            self.selected_table.trash();
                            delete self.pos.tables_by_id[self.selected_table.table.id];
                        },
                    });
                }
            }
        },
        get_current_data: function(){
            var self = this;
            var tables = this.floor.tables;

            var collection = [];
            tables.forEach(function(table) {
                collection.push({
                    'floor': {
                        'background_color': table.floor.background_color,
                        'name': table.floor.name,
                        'sequence': table.floor.sequence,
                    },
                    'name': table.name,
                    'height': table.height,
                    'position_h': table.position_h,
                    'position_v': table.position_v,
                    'seats': table.seats,
                    'shape': table.shape,
                    'width': table.width,
                    'order_count': self.pos.get_table_orders(table).length,
                    'customer_count': self.pos.get_customer_count(table),
                    'fill': Math.min(1,Math.max(0,self.pos.get_customer_count(table) / table.seats)),
                    'notifications': self.get_notifications(table),
                });
            });
            return collection;
        },
        get_notifications: function(table){
            var orders = this.pos.get_table_orders(table);
            var notifications = {};
            for (var i = 0; i < orders.length; i++) {
                if (orders[i].hasChangesToPrint()) {
                    notifications.printing = true;
                    break;
                } else if (orders[i].hasSkippedChanges()) {
                    notifications.skipped = true;
                }
            }
            return notifications;
        },
    });

    floors.TableWidget.include({
        click_handler: function(){
            var self = this;
            var floorplan = this.getParent();
            if (floorplan.editing) {
                this._super();
            } else {
                var table = this.table;
                if (!table) {
                    return this._super();
                }
                var table_waiters = this.pos.check_table_inaccessibility(table);
                if (!table_waiters || !table_waiters.length) {
                    return this._super();
                }
                return this.pos.gui.show_popup('alert',{
                    'title': _t('Can not open the Table'),
                    'body': _t('The Table is served by another waiter ' + _.pluck(table_waiters, 'name')),
                });
            }
        },
    });

});
<|endoftext|>


<commit_before>// ==UserScript==
// @name        GitHub News Filter
// @namespace   hckr
// @description Userscript to filter GitHub news feed using case-insensitive regular expression
// @include     https://github.com/
// @version     0.2
// @author      Jakub Młokosiewicz
// @source      https://github.com/hckr/github-news-filter
// @license     MIT
// ==/UserScript==

let news = document.querySelector('.news'),
    minimum = 10;

news.style.position = 'relative';
news.insertAdjacentHTML('afterbegin', `
    News filter
    <input id="pattern-input" class="form-control" style="width: 150px; position: absolute; right: 20px;" placeholder="News filter">
`);

let patternInput = document.getElementById('pattern-input'),
    underMinimum = 0,
    forcedMore = false,
    inputTimeout = null;

patternInput.addEventListener('input', function() {
    clearTimeout(inputTimeout);
    setTimeout(function() {
        let notHidden = filterNews(news.querySelectorAll('.alert'));
        if (notHidden < minimum) {
            underMinimum = minimum - notHidden;
            forcedMore = true;
            clickMoreIfExists();
        }
    }, 1000);
});

let observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        if (mutation.type === 'childList' && mutation.addedNodes) {
            if (!forcedMore) {
                underMinimum = minimum;
            }
            let notHidden = filterNews(
                [].filter.call(mutation.addedNodes,
                    node => node.className && node.className.match(/alert/)));
            underMinimum -= notHidden;
            if (notHidden == 0 || underMinimum > 0) {
                forcedMore = true;
                clickMoreIfExists();
            }
        }
    });
});
observer.observe(news, { childList: true });

function filterNews(newsItems) {
    let regexp = new RegExp(patternInput.value, 'i'),
        notHidden = 0;
    newsItems.forEach(el => {
        if (el.innerText.match(regexp)) {
            el.style.removeProperty('display');
            notHidden += 1;
        } else {
            el.style.display = 'none';
        }
    });

    return notHidden;
}

function clickMoreIfExists() {
    let moreButton = document.querySelector('.ajax-pagination-btn');
    if (moreButton) {
        moreButton.click();
    }
}
<commit_msg>Adapt to GitHub changes<commit_after>// ==UserScript==
// @name        GitHub News Filter
// @namespace   hckr
// @description Userscript to filter GitHub news feed using case-insensitive regular expression
// @include     https://github.com/
// @version     0.3
// @author      Jakub Młokosiewicz
// @source      https://github.com/hckr/github-news-filter
// @license     MIT
// ==/UserScript==

let news = document.querySelector('.news'),
    minimum = 10;

news.style.position = 'relative';
news.insertAdjacentHTML('afterbegin', `
    News filter
    <input id="pattern-input" class="form-control" style="width: 150px; position: absolute; right: 20px;" placeholder="News filter">
`);

let patternInput = document.getElementById('pattern-input'),
    underMinimum = 0,
    forcedMore = false,
    inputTimeout = null;

patternInput.addEventListener('input', function() {
    clearTimeout(inputTimeout);
    setTimeout(function() {
        let notHidden = filterNews([].filter.call(news.querySelectorAll('div'),
                                                  node => node.querySelector('.body')));
        if (notHidden < minimum) {
            underMinimum = minimum - notHidden;
            forcedMore = true;
            clickMoreIfExists();
        }
    }, 1000);
});

let observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        if (mutation.type === 'childList' && mutation.addedNodes) {
            if (!forcedMore) {
                underMinimum = minimum;
            }
            let notHidden = filterNews(
                [].filter.call(mutation.addedNodes,
                               node => node.querySelector && node.querySelector('.body')));
            underMinimum -= notHidden;
            if (notHidden == 0 || underMinimum > 0) {
                forcedMore = true;
                clickMoreIfExists();
            }
        }
    });
});
observer.observe(news, { childList: true });

function filterNews(newsItems) {
    let regexp = new RegExp(patternInput.value, 'i'),
        notHidden = 0;
    newsItems.forEach(el => {
        if (el.innerText.match(regexp)) {
            el.style.removeProperty('display');
            notHidden += 1;
        } else {
            el.style.display = 'none';
        }
    });

    return notHidden;
}

function clickMoreIfExists() {
    let moreButton = document.querySelector('.ajax-pagination-btn');
    if (moreButton) {
        moreButton.click();
    }
}
<|endoftext|>


<commit_before>define (['jquery', 'aggregate'], function ($, Aggregate) {

    var stats = [];

    function build (statsParam) {

        stats = statsParam;
    }

    function getAgeText () {

        var part1 = $('#result-age-1').val();
        var part2 = $('#result-age-2').val();
        var age = 0;
        var count = 0;

        // Average fan age
        for (var artist in stats) {
            if (stats.hasOwnProperty(artist)) {
                if (stats[artist] !== 0 && stats[artist].averageFanAge !== -1) {
                    age += parseInt(stats[artist].averageFanAge);
                    count++;
                }
            }
        }
        age = Math.round(age / count);

        return part1 + age + part2;
    }

    function getEpochText () {

        var part1 = $('#result-epoch-1').val();
        var part2 = $('#result-epoch-2').val();
        var part3 = $('#result-epoch-3').val();

        var oldestYear = (new Date()).getFullYear();
        var oldestArtist = "";
        var oldestAlbum = "";

        console.log(stats);

        // Look for the oldest album
        for (var artist in stats) {
            if (stats.hasOwnProperty(artist)) {
                if (stats[artist] !== 0 && stats[artist].firstAlbum.length > 0) {
                    // If very old
                    var releaseYear = (new Date(stats[artist].firstAlbum[0].date)).getFullYear();
                    if (releaseYear < oldestYear) {
                        oldestYear = releaseYear;
                        oldestArtist = artist;
                        oldestAlbum = stats[artist].firstAlbum[0].name;
                    }
                }
            }
        }

        return part1 + oldestYear + part2 + oldestArtist + part3 + oldestAlbum;
    }

    function getStyleText () {

        var part1 = $('#result-style').val();
        var styles = "Estilo, otro, otro";

        // Get all the tags
        var tags = [];
        for (var artist in stats) {
            if (stats.hasOwnProperty(artist)) {
                if (stats[artist] !== 0 && stats[artist].tags.length > 0) {
                    for (var tag in stats[artist].tags) {
                        tags.push(tag);
                    }
                }
            }
        }
        console.log('tags:');
        console.log(tags);
        Aggregate.sortByFrequency(tags);

        return part1 + styles;
    }

    function getSimilarText () {
        var part1 = $('#result-similar').val();
        var similar = "Uno, dos, tres";

        return part1 + similar;
    }

    return {
        build: build,
        getAgeText: getAgeText,
        getEpochText: getEpochText,
        getStyleText: getStyleText,
        getSimilarText: getSimilarText
    };
});<commit_msg>debug tag results 3<commit_after>define (['jquery', 'aggregate'], function ($, Aggregate) {

    var stats = [];

    function build (statsParam) {

        stats = statsParam;
    }

    function getAgeText () {

        var part1 = $('#result-age-1').val();
        var part2 = $('#result-age-2').val();
        var age = 0;
        var count = 0;

        // Average fan age
        for (var artist in stats) {
            if (stats.hasOwnProperty(artist)) {
                if (stats[artist] !== 0 && stats[artist].averageFanAge !== -1) {
                    age += parseInt(stats[artist].averageFanAge);
                    count++;
                }
            }
        }
        age = Math.round(age / count);

        return part1 + age + part2;
    }

    function getEpochText () {

        var part1 = $('#result-epoch-1').val();
        var part2 = $('#result-epoch-2').val();
        var part3 = $('#result-epoch-3').val();

        var oldestYear = (new Date()).getFullYear();
        var oldestArtist = "";
        var oldestAlbum = "";

        console.log(stats);

        // Look for the oldest album
        for (var artist in stats) {
            if (stats.hasOwnProperty(artist)) {
                if (stats[artist] !== 0 && stats[artist].firstAlbum.length > 0) {
                    // If very old
                    var releaseYear = (new Date(stats[artist].firstAlbum[0].date)).getFullYear();
                    if (releaseYear < oldestYear) {
                        oldestYear = releaseYear;
                        oldestArtist = artist;
                        oldestAlbum = stats[artist].firstAlbum[0].name;
                    }
                }
            }
        }

        return part1 + oldestYear + part2 + oldestArtist + part3 + oldestAlbum;
    }

    function getStyleText () {

        var part1 = $('#result-style').val();
        var styles = "Estilo, otro, otro";

        // Get all the tags
        var tags = [];
        for (var artist in stats) {
            if (stats.hasOwnProperty(artist)) {
                if (stats[artist] !== 0 && stats[artist].tags.length > 0) {
                    for (var tag in stats[artist].tags) {
                        tags.push(tag.name);
                    }
                }
            }
        }
        console.log('tags:');
        console.log(tags);
        var sortedTags = Aggregate.sortByFrequency(tags);
        console.log('sorted:');
        console.log(sortedTags);
        styles = sortedTags.splice(0,3).join(", ");
        return part1 + styles;
    }

    function getSimilarText () {
        var part1 = $('#result-similar').val();
        var similar = "Uno, dos, tres";

        return part1 + similar;
    }

    return {
        build: build,
        getAgeText: getAgeText,
        getEpochText: getEpochText,
        getStyleText: getStyleText,
        getSimilarText: getSimilarText
    };
});<|endoftext|>


<commit_before>var dataHistory = {}
var currentRequest = null

jQuery.ajaxPrefilter(function(options, originalOptions, xhr) {
    if(options.spinner) {
        var spinner = jQuery(options.spinner);
        if(spinner && spinner.length > 0) {
            var timeoutId = setTimeout(function() { spinner.show(); }, 250);
            xhr.always(function() {
                clearTimeout(timeoutId);
                spinner.hide();
            });
        }
    }
});

$(document).ready(function() {
    // Load up our list of servers in the dropdown.
    $.ajax("/_getServerGroups", {
        success: function(data, statusCode, xhr) {
            if(data.success && data.payload.groups) {
                $.each(data.payload.groups, function(key, group) {
                    // Add in the category name and divider if this isn't the default category.
                    if(group.categoryName != "") {
                        $("#serverList")
                        .append($("<option></option>").html(group.categoryName).val("empty"))
                        .append($("<option></option>").html("--------------").val("empty"))
                    }

                    // Add in the servers now.
                    $.each(group.servers, function(key, server) {
                        $("#serverList").append($("<option></option>").html(server.displayName).val(server.internalName))
                    })

                    // Add in a spacer at the end.
                    $("#serverList").append($("<option></option>").html("").val("empty"))
                })

                // Remove the last empty option to tidy up the dropdown.
                $("#serverList option:last-child").remove()
            }
        }
    })

    $("#serverList").on('change', function(e) {
        e.preventDefault()

        // Short circuit if this isn't an actual server selection.
        var selection = $("#serverList option:selected")
        if(selection.val() == "empty") {
            return
        }

        // Clear out any existing errors.
        $("#errors").empty()

        // If we have an existing loading call, abort it.
        if(currentRequest != null) {
            currentRequest.abort()
        }

        var retryButton = $("<button></button>").addClass("btn").html("Reload")
            .on('click', function(e) { $("#serverList").change() })

        // Try and get a current process list snapshot for the selected server.
        currentRequest = $.ajax("/_getCurrentSnapshot/" + selection.val(), {
            success: function(data, statusCode, xhr) {
                if(data.success && data.events) {
                } else if(!data.success && data.errorMessage) {
                    var message = "We encountered an error while attempting to query the database.  Here's what the server said: " + data.errorMessage + ""
                    showErrorMessage("Error while querying server!", message, [retryButton])
                }

                currentRequest = null
            },
            error: function(xhr, textStatus, errorThrown) {
                if(textStatus == "timeout") {
                    var message = "We timed out trying to get the most recent process list from the database.  You can try and reload the process list or choose another database server.";
                    showErrorMessage("Timeout!", message, [retryButton])
                }

                currentRequuest = null
            },
            timeout: 6000,
            spinner: "#spinner"
        })
    })
})

function showErrorMessage(title, message, appends) {
    var alertBlock = $("

")
    alertBlock.addClass("alert alert-block alert-error fade in")
    alertBlock.html(
        '
' + title + '
' +
        '
' + message + '
'
    )

    // Append our appends if we have any.
    if(appends) {
        var appendBlock = $("

")
        $.each(appends, function(i, append) {
            appendBlock.append(append)
        })

        alertBlock.append(appendBlock)
    }

    // Clear any previous errors before showing this one.
    $("#errors").empty()
    $("#errors").append(alertBlock)
}
<commit_msg>Fixed a JS error that didn't properly use the group name when building the server dropdown.<commit_after>var dataHistory = {}
var currentRequest = null

jQuery.ajaxPrefilter(function(options, originalOptions, xhr) {
    if(options.spinner) {
        var spinner = jQuery(options.spinner);
        if(spinner && spinner.length > 0) {
            var timeoutId = setTimeout(function() { spinner.show(); }, 250);
            xhr.always(function() {
                clearTimeout(timeoutId);
                spinner.hide();
            });
        }
    }
});

$(document).ready(function() {
    // Load up our list of servers in the dropdown.
    $.ajax("/_getServerGroups", {
        success: function(data, statusCode, xhr) {
            if(data.success && data.payload.groups) {
                $.each(data.payload.groups, function(groupName, group) {
                    // Add in the category name and divider if this isn't the default category.
                    if(groupName != "") {
                        $("#serverList")
                        .append($("<option></option>").html(groupName).val("empty"))
                        .append($("<option></option>").html("--------------").val("empty"))
                    }

                    // Add in the servers now.
                    $.each(group.servers, function(key, server) {
                        $("#serverList").append($("<option></option>").html(server.displayName).val(server.internalName))
                    })

                    // Add in a spacer at the end.
                    $("#serverList").append($("<option></option>").html("").val("empty"))
                })

                // Remove the last empty option to tidy up the dropdown.
                $("#serverList option:last-child").remove()
            }
        }
    })

    $("#serverList").on('change', function(e) {
        e.preventDefault()

        // Short circuit if this isn't an actual server selection.
        var selection = $("#serverList option:selected")
        if(selection.val() == "empty") {
            return
        }

        // Clear out any existing errors.
        $("#errors").empty()

        // If we have an existing loading call, abort it.
        if(currentRequest != null) {
            currentRequest.abort()
        }

        var retryButton = $("<button></button>").addClass("btn").html("Reload")
            .on('click', function(e) { $("#serverList").change() })

        // Try and get a current process list snapshot for the selected server.
        currentRequest = $.ajax("/_getCurrentSnapshot/" + selection.val(), {
            success: function(data, statusCode, xhr) {
                if(data.success && data.events) {
                } else if(!data.success && data.errorMessage) {
                    var message = "We encountered an error while attempting to query the database.  Here's what the server said: " + data.errorMessage + ""
                    showErrorMessage("Error while querying server!", message, [retryButton])
                }

                currentRequest = null
            },
            error: function(xhr, textStatus, errorThrown) {
                if(textStatus == "timeout") {
                    var message = "We timed out trying to get the most recent process list from the database.  You can try and reload the process list or choose another database server.";
                    showErrorMessage("Timeout!", message, [retryButton])
                }

                currentRequuest = null
            },
            timeout: 6000,
            spinner: "#spinner"
        })
    })
})

function showErrorMessage(title, message, appends) {
    var alertBlock = $("

")
    alertBlock.addClass("alert alert-block alert-error fade in")
    alertBlock.html(
        '
' + title + '
' +
        '
' + message + '
'
    )

    // Append our appends if we have any.
    if(appends) {
        var appendBlock = $("

")
        $.each(appends, function(i, append) {
            appendBlock.append(append)
        })

        alertBlock.append(appendBlock)
    }

    // Clear any previous errors before showing this one.
    $("#errors").empty()
    $("#errors").append(alertBlock)
}
<|endoftext|>


<commit_before>const list = require('../../models').list;
const listsubscriber = require('../../models').listsubscriber;

module.exports = (req, res) => {
  // Find all subscribers belonging to a list
  const userId = req.user.id;
  const listId = req.query.listId;

  list.findOne({
    where: {
      userId,
      id: listId
    },
    attributes: ['name', 'createdAt', 'updatedAt'],
    raw: true
  }).then(instancesArray => {
    if (!instancesArray) {
      res.status(401)  //??
        .send({
          message: 'not authorised to view list or list does not exist'
        });
      return;
    } else {
      listsubscriber.findAll({
        where: { listId },
        attributes: ['email', 'subscribed', 'createdAt', 'updatedAt'],
        raw: true
      }).then(instancesArray => {
        res.send({ subscribers: instancesArray });
      });
    }
  });
};
<commit_msg>Send most recent status in GET list-subscribers<commit_after>const list = require('../../models').list;
const listsubscriber = require('../../models').listsubscriber;

module.exports = (req, res) => {
  // Find all subscribers belonging to a list
  const userId = req.user.id;
  const listId = req.query.listId;

  list.findOne({
    where: {
      userId,
      id: listId
    },
    attributes: ['name', 'createdAt', 'updatedAt'],
    raw: true
  }).then(instancesArray => {
    if (!instancesArray) {
      res.status(401)  //??
        .send({
          message: 'not authorised to view list or list does not exist'
        });
      return;
    } else {
      listsubscriber.findAll({
        where: { listId },
        attributes: ['email', 'subscribed', 'createdAt', 'updatedAt', 'mostRecentStatus'],
        raw: true
      }).then(instancesArray => {
        res.send({ subscribers: instancesArray });
      });
    }
  });
};
<|endoftext|>


<commit_before>$(function() {
    $('select').selectpicker();
});
<commit_msg>Update admin.js<commit_after>
<|endoftext|>