<commit_before>var session = {};

$(document).ready(function(){/* off-canvas sidebar toggle */

    $('[data-toggle=offcanvas]').click(function() {
        $(this).toggleClass('visible-xs text-center');
        $(this).find('i').toggleClass('glyphicon-chevron-right glyphicon-chevron-left');
        $('.row-offcanvas').toggleClass('active');
        $('#lg-menu').toggleClass('hidden-xs').toggleClass('visible-xs');
        $('#xs-menu').toggleClass('visible-xs').toggleClass('hidden-xs');
        $('#btnShow').toggle();
    });

    $('#logout').click(function () {
        sessionStorage['bitbucket-issues-plus_session'] = undefined;
        location.reload();
    });

    $('#go-auth').click(function (e) {
        e.preventDefault();
        var hash = btoa($('#username').val() + ':' + $('#password').val());
        $.ajax({
            url : 'https://api.bitbucket.org/1.0/user',
            headers : {
                'Authorization' : 'Basic ' + hash
            },
            success : function (data, status, xhr) {
                session.basicAuth = { 'Authorization' : 'Basic ' + hash }
                session.user = data.user;
                session.repositories = data.repositories;

                sessionStorage['bitbucket-issues-plus_session'] = JSON.stringify(session);

                $('#display_name').html(session.user.display_name);
                $('#issue_count').html(data.length);
                $('#avatar').attr('src', session.user.avatar);

                var repos = "";
                for( var i in session.repositories ){
                    var repo = session.repositories[i];
                    repos += '
' + repo.name + '
'
                }

                $('#repos').html(repos);

                $('#form').hide();
                $('#mainnav').show();

                //refreshTable();
            },
            error : function (err) {
                console.error(err);
            }
        });
    });

    if( sessionStorage['bitbucket-issues-plus_session'] !== "undefined" ){
        session = JSON.parse(sessionStorage['bitbucket-issues-plus_session']);
        $('#display_name').html(session.user.display_name);

        var repos = "";
        for( var i in session.repositories ){
            var repo = session.repositories[i];
            repos += '
' + repo.name + '
'
        }

        $('#repos').html(repos);

        $('#form').hide();
        $('#mainnav').show();

        if( session.selectedRepo !== undefined ){
            refreshTable();
        }

    }

    $('#edit').click(function () {
        $('#editModal').modal();
    });

});

function selectRepo(repo){
    session.selectedRepo = repo;
    refreshTable();
}

function refreshTable(){
    $.ajax({
        url: 'https://api.bitbucket.org/1.0/repositories/' + session.user.username + '/' + session.selectedRepo + '/issues',
        method : 'GET',
        headers: session.basicAuth,
        success : function (data, status, xhr) {
            var table = "";
            for( var i in data.issues ){
                var issue = data.issues[i];

                var priorityIcon = "glyphicon ";

                switch (issue.priority){
                    case "trivial":
                        priorityIcon += "glyphicon-thumbs-up text-color-black";
                        break;
                    case "minor":
                        priorityIcon += "glyphicon-arrow-down text-color-black";
                        break;
                    case "major":
                        priorityIcon += "glyphicon-arrow-up text-color-black";
                        break;
                    case "critical":
                        priorityIcon += "glyphicon-warning-sign text-color-yellow";
                        break;
                    case "blocker":
                        priorityIcon += "glyphicon-ban-circle text-color-red";
                        break;
                }

                var statusLabel = '';
                        break;
                    case "open":
                        statusLabel += 'label-danger">';
                        break;
                    case "resolved":
                        statusLabel += 'label-success">';
                        break;
                    default:
                        statusLabel += 'label-default">';
                        break;
                }
                statusLabel += issue.status.toUpperCase() + '';

                table +=
                    '
' +
                    '	' +
                    '' + issue.title + '	' +
                    '' + issue.metadata.kind + '	' +
                    '' + statusLabel + '	' +
                    '' + issue.metadata.milestone + '	' +
                    '
\n';
            }

            $('#issues-table tbody').html(table);

            $('tr.clickable').click(function () {
                var tr = $(this);
                var isSelected = tr.attr('selected');
                tr.css('background-color', (isSelected ? '' : '#d1fbff') );
                tr.attr('selected', !isSelected);

            });

        },
        error : function (xhr, status, error) {
            var errMsg = JSON.parse(xhr.responseText);

            var alert = '
' +
                '×' +
            '' + errMsg.error.message + '
';

            $('#message')
                .html(alert);
        }
    });

}
<commit_msg>Validation before refresh tasks from a repository<commit_after>var session = {};

$(document).ready(function(){

    /* off-canvas sidebar toggle */
    $('[data-toggle=offcanvas]').click(function() {
        $(this).toggleClass('visible-xs text-center');
        $(this).find('i').toggleClass('glyphicon-chevron-right glyphicon-chevron-left');
        $('.row-offcanvas').toggleClass('active');
        $('#lg-menu').toggleClass('hidden-xs').toggleClass('visible-xs');
        $('#xs-menu').toggleClass('visible-xs').toggleClass('hidden-xs');
        $('#btnShow').toggle();
    });

    $('#logout').click(function () {
        sessionStorage['bitbucket-issues-plus_session'] = undefined;
        location.reload();
    });

    $('#go-auth').click(function (e) {
        e.preventDefault();
        var hash = btoa($('#username').val() + ':' + $('#password').val());
        $.ajax({
            url : 'https://api.bitbucket.org/1.0/user',
            headers : {
                'Authorization' : 'Basic ' + hash
            },
            success : function (data, status, xhr) {
                session.basicAuth = { 'Authorization' : 'Basic ' + hash }
                session.user = data.user;
                session.repositories = data.repositories;

                sessionStorage['bitbucket-issues-plus_session'] = JSON.stringify(session);

                $('#display_name').html(session.user.display_name);
                $('#issue_count').html(data.length);
                $('#avatar').attr('src', session.user.avatar);

                var repos = "";
                for( var i in session.repositories ){
                    var repo = session.repositories[i];
                    repos += '
' + repo.name + '
'
                }

                $('#repos').html(repos);

                $('#form').hide();
                $('#mainnav').show();

                //refreshTable();
            },
            error : function (err) {
                console.error(err);
            }
        });
    });

    if( sessionStorage['bitbucket-issues-plus_session'] !== "undefined" ){
        session = JSON.parse(sessionStorage['bitbucket-issues-plus_session']);
        $('#display_name').html(session.user.display_name);

        var repos = "";
        for( var i in session.repositories ){
            var repo = session.repositories[i];
            repos += '
' + repo.name + '
'
        }

        $('#repos').html(repos);

        $('#form').hide();
        $('#mainnav').show();

        if( session.selectedRepo !== undefined ){
            refreshTable();
        }

    }

    $('#edit').click(function () {
        $('#editModal').modal();
    });

});

function selectRepo(repo){
    session.selectedRepo = repo;
    refreshTable();
}

function refreshTable(){
    if( session.user.username != undefined && session.selectedRepo != undefined ){
        $.ajax({
            url: 'https://api.bitbucket.org/1.0/repositories/' + session.user.username + '/' + session.selectedRepo + '/issues',
            method : 'GET',
            headers: session.basicAuth,
            success : function (data, status, xhr) {
                var table = "";
                for( var i in data.issues ){
                    var issue = data.issues[i];

                    var priorityIcon = "glyphicon ";

                    switch (issue.priority){
                        case "trivial":
                            priorityIcon += "glyphicon-thumbs-up text-color-black";
                            break;
                        case "minor":
                            priorityIcon += "glyphicon-arrow-down text-color-black";
                            break;
                        case "major":
                            priorityIcon += "glyphicon-arrow-up text-color-black";
                            break;
                        case "critical":
                            priorityIcon += "glyphicon-warning-sign text-color-yellow";
                            break;
                        case "blocker":
                            priorityIcon += "glyphicon-ban-circle text-color-red";
                            break;
                    }

                    var statusLabel = '';
                            break;
                        case "open":
                            statusLabel += 'label-danger">';
                            break;
                        case "resolved":
                            statusLabel += 'label-success">';
                            break;
                        default:
                            statusLabel += 'label-default">';
                            break;
                    }
                    statusLabel += issue.status.toUpperCase() + '';

                    table +=
                        '
' +
                        '	' +
                        '' + issue.title + '	' +
                        '' + issue.metadata.kind + '	' +
                        '' + statusLabel + '	' +
                        '' + issue.metadata.milestone + '	' +
                        '
\n';
                }

                $('#issues-table tbody').html(table);

                $('tr.clickable').click(function () {
                    var tr = $(this);
                    var isSelected = tr.attr('selected');
                    tr.css('background-color', (isSelected ? '' : '#d1fbff') );
                    tr.attr('selected', !isSelected);

                });

            },
            error : function (xhr, status, error) {
                var errMsg = JSON.parse(xhr.responseText);

                var alert = '
' +
                    '×' +
                    '' + errMsg.error.message + '
';

                $('#message')
                    .html(alert);
            }
        });
    }

}
<|endoftext|>


<commit_before>(function(angular) {

	var module = angular.module('net.enzey.service.css.editor', []);

	module.service('nzCssRuleEditor', function($window, $http, $q) {
		// Create a new style sheet to hold custom styles
		angular.element($window.document.head).append( angular.element('<style></style>') );

		// Get last loaded style sheet (the style sheet just added)
		var styleSheet = $window.document.styleSheets[document.styleSheets.length - 1];

		var cssRuleCode = $window.document.all ? 'rules' : 'cssRules'; //account for IE and FF
		var styleSetter = $window.document.all ? 'value' : 'style'; //account for IE and FF

		var CssRuleEditor = this;
		var cssRuleCache = {};

		var getJsStyleName = function(styleName) {
			var firstCharacterRegex = new RegExp('^.');
			styleName = styleName.split('-');
			for (var i = 1; i < styleName.length; i++) {
				styleName[i] = styleName[i].replace(firstCharacterRegex, styleName[i][0].toUpperCase());
			}

			return styleName.join('');
		};

		var getCssRules = function(styleSheet) {
			var cssRules;
			if (styleSheet['rules']) {
				cssRules = styleSheet['rules'];
			} else {
				cssRules = styleSheet['cssRules'];
			}
			return cssRules;
		};

		var extractStyles = function(styles) {
			var extractedStyles = {};
			for (var i = 0; i < styles.length; i++) {
				var styleName = getJsStyleName(styles[i]);
				extractedStyles[ styleName ] = styles[ styleName ];
			}
			return extractedStyles;
		};

		var parseStyleSheet = function(styleSheet) {
			var cssRules = getCssRules(styleSheet);

			for (var iRule = 0; iRule < cssRules.length; iRule++) {
				var cssRule = cssRules[iRule];
				if (cssRule instanceof CSSStyleRule) {
					var styles;
					if (cssRule['value']) {
						styles = cssRule['value'];
					} else {
						styles = cssRule['style'];
					}
					styles = extractStyles(styles);
					cssRule.selectorText.split(',').forEach(function(selector) {
						selector = selector.replace(new RegExp('^ *'), '');
						selector = selector.replace(new RegExp(' *$'), '');

						if (!allCssRules[selector]) {
							allCssRules[selector] = {};
						}
						angular.extend(allCssRules[selector], styles);
					});
				}
			};
		};

		var cacheStyleSheets = function() {
			var allStyleSheets = $window.document.styleSheets;
			var styleSheetCache = new Array(allStyleSheets.length-1);

			var promises = [];
			for (var i = 0; i < allStyleSheets.length-1; i++) {
				(function () {
					var index = i;
					var currentStyleSheet = allStyleSheets[i];
					var deferred = $q.defer();
					promises.push(deferred.promise);

					try {
						getCssRules(currentStyleSheet);
						styleSheetCache[index] = currentStyleSheet;
						deferred.resolve(currentStyleSheet);
					} catch (e) {
						$http.get(currentStyleSheet.href).success(function(data, status, headers, config) {
							var tempStyle = angular.element("<style></style>");
							tempStyle.html(data);
							angular.element($window.document.head).prepend(tempStyle);

							var allStyleSheets = $window.document.styleSheets;
							var lastStyleSheet = allStyleSheets[0];

							styleSheetCache[index] = lastStyleSheet;

							tempStyle.remove();
							deferred.resolve(lastStyleSheet);
						}).error(function(data, status, headers, config) {
							deferred.reject();
						});
					}
				})()
			}
			var allPromises = $q.all(promises).then(function(foo, bar) {
				return styleSheetCache;
			});

			return allPromises;
		};

		var allCssRules = {};
		var baseStyleSheets = [];

		this.getBaseRules = function() {
			var promise = cacheStyleSheets().then(function(styleSheetCache) {
				baseStyleSheets = styleSheetCache;
				styleSheetCache.forEach(function(styleSheet) {
					parseStyleSheet(styleSheet);
				});
				return angular.extend({}, allCssRules);
			});

			return promise;
		};

		this.getCustomRule = function(ruleName) {
			if (!ruleName) return;

			var cssRule = cssRuleCache[ruleName];
			if (!cssRule) {
				// Rules does not exist
				styleSheet.insertRule(ruleName + ' {}', 0);

				var cssRules;
				if (styleSheet['rules']) {
					cssRules = styleSheet['rules'];
				} else {
					cssRules = styleSheet['cssRules'];
				}
				cssRuleCache[ruleName] = cssRules[0];
				//cssRuleCache[ruleName] = styleSheet[cssRuleCode][0];
				cssRule = cssRuleCache[ruleName];
			}
			var styles;
			if (cssRule['value']) {
				styles = cssRule['value'];
			} else {
				styles = cssRule['style'];
			}
			return styles;
			//return cssRule[styleSetter];
		};

		this.removeCustomRule = function(ruleName) {
			if (!ruleName) return;

			var cssRules = styleSheet[cssRuleCode];
			for (var i = 0; i < cssRules.length; i++) {
				var cssRule = cssRules[i];
				if (cssRule.selectorText.toLowerCase() === ruleName.toLowerCase()) {
					styleSheet.deleteRule(i);
					cssRuleCache[ruleName] = null;
					delete cssRuleCache[ruleName];
				}
			}
		};

		this.getAllCustomRules = function() {
			return $.extend({}, cssRuleCache);
		};

		this.removeAllCustomRules = function() {
			Object.keys(cssRuleCache).forEach(function (ruleName){
				CssRuleEditor.removeRule(ruleName);
			});
		};
	});

})(angular);<commit_msg>Remove dependency on JQuery<commit_after>(function(angular) {

	var module = angular.module('net.enzey.service.css.editor', []);

	module.service('nzCssRuleEditor', function($window, $http, $q) {
		// Create a new style sheet to hold custom styles
		angular.element($window.document.head).append( angular.element('<style></style>') );

		// Get last loaded style sheet (the style sheet just added)
		var styleSheet = $window.document.styleSheets[document.styleSheets.length - 1];

		var cssRuleCode = $window.document.all ? 'rules' : 'cssRules'; //account for IE and FF
		var styleSetter = $window.document.all ? 'value' : 'style'; //account for IE and FF

		var CssRuleEditor = this;
		var cssRuleCache = {};

		var getJsStyleName = function(styleName) {
			var firstCharacterRegex = new RegExp('^.');
			styleName = styleName.split('-');
			for (var i = 1; i < styleName.length; i++) {
				styleName[i] = styleName[i].replace(firstCharacterRegex, styleName[i][0].toUpperCase());
			}

			return styleName.join('');
		};

		var getCssRules = function(styleSheet) {
			var cssRules;
			if (styleSheet['rules']) {
				cssRules = styleSheet['rules'];
			} else {
				cssRules = styleSheet['cssRules'];
			}
			return cssRules;
		};

		var extractStyles = function(styles) {
			var extractedStyles = {};
			for (var i = 0; i < styles.length; i++) {
				var styleName = getJsStyleName(styles[i]);
				extractedStyles[ styleName ] = styles[ styleName ];
			}
			return extractedStyles;
		};

		var parseStyleSheet = function(styleSheet) {
			var cssRules = getCssRules(styleSheet);

			for (var iRule = 0; iRule < cssRules.length; iRule++) {
				var cssRule = cssRules[iRule];
				if (cssRule instanceof CSSStyleRule) {
					var styles;
					if (cssRule['value']) {
						styles = cssRule['value'];
					} else {
						styles = cssRule['style'];
					}
					styles = extractStyles(styles);
					cssRule.selectorText.split(',').forEach(function(selector) {
						selector = selector.replace(new RegExp('^ *'), '');
						selector = selector.replace(new RegExp(' *$'), '');

						if (!allCssRules[selector]) {
							allCssRules[selector] = {};
						}
						angular.extend(allCssRules[selector], styles);
					});
				}
			};
		};

		var cacheStyleSheets = function() {
			var allStyleSheets = $window.document.styleSheets;
			var styleSheetCache = new Array(allStyleSheets.length-1);

			var promises = [];
			for (var i = 0; i < allStyleSheets.length-1; i++) {
				(function () {
					var index = i;
					var currentStyleSheet = allStyleSheets[i];
					var deferred = $q.defer();
					promises.push(deferred.promise);

					try {
						getCssRules(currentStyleSheet);
						styleSheetCache[index] = currentStyleSheet;
						deferred.resolve(currentStyleSheet);
					} catch (e) {
						$http.get(currentStyleSheet.href).success(function(data, status, headers, config) {
							var tempStyle = angular.element("<style></style>");
							tempStyle.html(data);
							angular.element($window.document.head).prepend(tempStyle);

							var allStyleSheets = $window.document.styleSheets;
							var lastStyleSheet = allStyleSheets[0];

							styleSheetCache[index] = lastStyleSheet;

							tempStyle.remove();
							deferred.resolve(lastStyleSheet);
						}).error(function(data, status, headers, config) {
							deferred.reject();
						});
					}
				})()
			}
			var allPromises = $q.all(promises).then(function(foo, bar) {
				return styleSheetCache;
			});

			return allPromises;
		};

		var allCssRules = {};
		var baseStyleSheets = [];

		this.getBaseRules = function() {
			var promise = cacheStyleSheets().then(function(styleSheetCache) {
				baseStyleSheets = styleSheetCache;
				styleSheetCache.forEach(function(styleSheet) {
					parseStyleSheet(styleSheet);
				});
				return angular.extend({}, allCssRules);
			});

			return promise;
		};

		this.getCustomRule = function(ruleName) {
			if (!ruleName) return;

			var cssRule = cssRuleCache[ruleName];
			if (!cssRule) {
				// Rules does not exist
				styleSheet.insertRule(ruleName + ' {}', 0);

				var cssRules;
				if (styleSheet['rules']) {
					cssRules = styleSheet['rules'];
				} else {
					cssRules = styleSheet['cssRules'];
				}
				cssRuleCache[ruleName] = cssRules[0];
				//cssRuleCache[ruleName] = styleSheet[cssRuleCode][0];
				cssRule = cssRuleCache[ruleName];
			}
			var styles;
			if (cssRule['value']) {
				styles = cssRule['value'];
			} else {
				styles = cssRule['style'];
			}
			return styles;
			//return cssRule[styleSetter];
		};

		this.removeCustomRule = function(ruleName) {
			if (!ruleName) return;

			var cssRules = styleSheet[cssRuleCode];
			for (var i = 0; i < cssRules.length; i++) {
				var cssRule = cssRules[i];
				if (cssRule.selectorText.toLowerCase() === ruleName.toLowerCase()) {
					styleSheet.deleteRule(i);
					cssRuleCache[ruleName] = null;
					delete cssRuleCache[ruleName];
				}
			}
		};

		this.getAllCustomRules = function() {
			return angular.extend({}, cssRuleCache);
		};

		this.removeAllCustomRules = function() {
			Object.keys(cssRuleCache).forEach(function (ruleName){
				CssRuleEditor.removeRule(ruleName);
			});
		};

	});

})(angular);<|endoftext|>


<commit_before>var map = d3.select('#map');

var reliefRatio = 734 / 1170;
var lonRotate = 100;
var latRotate = -45;
var lonCenter = -97.74;
var latTop = 51.75;
var scaleRatio = 1297 / 956.4032697547684;

var width, height;

var reliefReady = false;
var atReady = false;
var momdadReady = false;

var projection = d3.geo.azimuthalEqualArea();

var path = d3.geo.path()
    .projection(projection);

var svg = map.append("svg");
var defs = svg.append('defs');

function display() {
	if (reliefReady && atReady && momdadReady) {
		// Add paths to map
		svg.append("use")
			.attr('class', 'momdad')
			.attr("xlink:href", "#momdad");

		svg.append("use")
			.attr('class', 'glow momdad')
			.attr('filter', 'url(#glow)')
			.attr('xlink:href', '#momdad');

		svg.append("use")
			.attr('class', 'at')
			.attr("xlink:href", "#at");

		svg.append("use")
			.attr('class', 'glow at')
			.attr('filter', 'url(#glow)')
			.attr('xlink:href', '#at');

		// Add resize event handler and run for the first time
		d3.select(window).on('resize', resize);

		resize();
	}
}

function resize() {

	width = parseInt(map.style('width'));
	height = Math.round(width * reliefRatio);

	projection
	    .rotate([lonRotate, latRotate])
	    .center([lonRotate + lonCenter, latRotate + latTop])
	    .translate([width / 2, 0])
	    .scale(width * scaleRatio)
	    .precision(.1);

	svg
		.attr("width", width)
		.attr("height", height);

	svg.select('.relief')
		.attr('width', width)
		.attr('height', height);

	d3.select(self.frameElement).style("height", height + "px");

	svg.select('#land').attr('d', path);

	svg.select('#at').attr('d', path);
	svg.select('#momdad').attr('d', path);

}

d3.json("../data/us.json", function(error, us) {

	defs.append("path")
		.attr("id", "land")
		.datum(topojson.feature(us, us.objects.land));

	defs.append('filter')
		.attr('id', 'glow')
		.append('feGaussianBlur')
			.attr('in', 'SourceGraphic')
			.attr('stdDeviation', '5');

    svg.append('clipPath')
    	.attr('id', 'clip')
    	.append('use')
    	.attr('xlink:href', '#land');

    svg.insert("image", ":first-child")
    	.attr('class', 'relief')
		.attr("clip-path", "url(#clip)")
		.attr("xlink:href", "../images/relief.png");

	svg.append("use")
		.attr("xlink:href", "#land");

	reliefReady = true;

	display();

});

d3.json("../data/at.json", function(error, at) {

	defs.append('path')
		.attr('id', 'at')
		.datum(topojson.feature(at, at.objects.at));

	atReady = true;

	display();

});

d3.json("../data/momdad.json", function(error, momdad) {

	defs.append('path')
		.attr('id', 'momdad')
		.datum(topojson.feature(momdad, momdad.objects.momdad));

	momdadReady = true;

	display();

});
<commit_msg>Reduced blur radius<commit_after>var map = d3.select('#map');

var reliefRatio = 734 / 1170;
var lonRotate = 100;
var latRotate = -45;
var lonCenter = -97.74;
var latTop = 51.75;
var scaleRatio = 1297 / 956.4032697547684;

var width, height;

var reliefReady = false;
var atReady = false;
var momdadReady = false;

var projection = d3.geo.azimuthalEqualArea();

var path = d3.geo.path()
    .projection(projection);

var svg = map.append("svg");
var defs = svg.append('defs');

function display() {
	if (reliefReady && atReady && momdadReady) {
		// Add paths to map
		svg.append("use")
			.attr('class', 'momdad')
			.attr("xlink:href", "#momdad");

		svg.append("use")
			.attr('class', 'glow momdad')
			.attr('filter', 'url(#glow)')
			.attr('xlink:href', '#momdad');

		svg.append("use")
			.attr('class', 'at')
			.attr("xlink:href", "#at");

		svg.append("use")
			.attr('class', 'glow at')
			.attr('filter', 'url(#glow)')
			.attr('xlink:href', '#at');

		// Add resize event handler and run for the first time
		d3.select(window).on('resize', resize);

		resize();
	}
}

function resize() {

	width = parseInt(map.style('width'));
	height = Math.round(width * reliefRatio);

	projection
	    .rotate([lonRotate, latRotate])
	    .center([lonRotate + lonCenter, latRotate + latTop])
	    .translate([width / 2, 0])
	    .scale(width * scaleRatio)
	    .precision(.1);

	svg
		.attr("width", width)
		.attr("height", height);

	svg.select('.relief')
		.attr('width', width)
		.attr('height', height);

	d3.select(self.frameElement).style("height", height + "px");

	svg.select('#land').attr('d', path);

	svg.select('#at').attr('d', path);
	svg.select('#momdad').attr('d', path);

}

d3.json("../data/us.json", function(error, us) {

	defs.append("path")
		.attr("id", "land")
		.datum(topojson.feature(us, us.objects.land));

	defs.append('filter')
		.attr('id', 'glow')
		.append('feGaussianBlur')
			.attr('in', 'SourceGraphic')
			.attr('stdDeviation', '3');

    svg.append('clipPath')
    	.attr('id', 'clip')
    	.append('use')
    	.attr('xlink:href', '#land');

    svg.insert("image", ":first-child")
    	.attr('class', 'relief')
		.attr("clip-path", "url(#clip)")
		.attr("xlink:href", "../images/relief.png");

	svg.append("use")
		.attr("xlink:href", "#land");

	reliefReady = true;

	display();

});

d3.json("../data/at.json", function(error, at) {

	defs.append('path')
		.attr('id', 'at')
		.datum(topojson.feature(at, at.objects.at));

	atReady = true;

	display();

});

d3.json("../data/momdad.json", function(error, momdad) {

	defs.append('path')
		.attr('id', 'momdad')
		.datum(topojson.feature(momdad, momdad.objects.momdad));

	momdadReady = true;

	display();

});
<|endoftext|>


<commit_before>// (function(){
  var btnCrypt = $('.glyphicon-lock')
  var cryptedText
  var pgpMessage
  var preparedMessage

  function prepareText () {
    preparedMessage = text.value.split("\n")
  }

  function textDecrypt () {
    console.log('Decrypted')
    console.log(text.value)
    prepareText()
    pgpMessage = openpgp.message.readAmored(preparedMessage)
    text.value = openpgp.decryptMessage(privateKey, pgpMessage)
  }

  function textEncrypt () {
    console.log('Encrypted')
    console.log(text.value)
    cryptedText = openpgp.encryptMessage(publicKey.keys, text.value);
    text.value = cryptedText
  }

  btnCrypt.on('click', function(){
    if( $(this).hasClass('btn-danger') ) {
      textEncrypt()
      $(this).text('Verschlüsselt')
    } else {
      textDecrypt()
      $(this).text('Verschlüsseln')
    }
    $(this).toggleClass('btn-danger')
    $(this).toggleClass('btn-success')
  })

// })()
<commit_msg>De- and encryption works now.<commit_after>// (function(){
  var btnCrypt = $('.glyphicon-lock')
  var cryptedText
  var decryptedText
  var pgpMessage
  var preparedMessage

  function textDecrypt () {
    console.log('Decrypted')
    pgpMessage = openpgp.message.readArmored(text.value)
    text.value = openpgp.decryptMessage(privateKey, pgpMessage)
  }

  function textEncrypt () {
    console.log('Encrypting')
    cryptedText = openpgp.encryptMessage(publicKey.keys, text.value);
    text.value = cryptedText
  }

  btnCrypt.on('click', function(){
    if( $(this).hasClass('btn-danger') ) {
      textEncrypt()
      $(this).text('Verschlüsselt')
    } else {
      textDecrypt()
      $(this).text('Verschlüsseln')
    }
    $(this).toggleClass('btn-danger')
    $(this).toggleClass('btn-success')
  })

// })()
<|endoftext|>


<commit_before>const request = require('../requests');

/**
 * The service which provides build information by using the VSTS REST API
 *  v2.0. Although the naming of the variables suggest usage with VSTS, the
 *  code is compatible with both VSTS and TFS. The naming is simply the
 *  artifact of making the code generalised for both after initial usage
 *  with VSTS.
 * @public
 * @constructor
 * @see https://www.visualstudio.com/en-us/docs/integrate/api/build/overview
 */
function VSTSRestBuilds() {
  let basicAuth = null;
  let instance = null;
  let project = null;
  let collection = null;
  let params = null;

  /**
   * This object is the representation of resultFilter mentioned in the docs
   * @private
   * @see https://www.visualstudio.com/en-us/docs/integrate/api/build/builds
   */
  const resultFilter = Object.freeze({
    succeeded:          'succeeded',
    partiallySucceeded: 'partiallySucceeded',
    failed:             'failed',
    canceled:           'canceled'
  });

  /** This object is the representation of statusFilter mentioned in the docs
   * @private
   * @see https://www.visualstudio.com/en-us/docs/integrate/api/build/builds
   */
  const statusFilter = Object.freeze({
    inProgress: 'inProgress',
    completed:  'completed',
    cancelling: 'cancelling',
    postponed:  'postponed',
    notStarted: 'notStarted',
    all:        'all',
  });

  /**
   * This object defines the color scheme used.
   * @private
   */
  const colorScheme = Object.freeze({
    succeeded:          'Green',
    partiallySucceeded: '#F8A800',
    failed:             'Red',
    canceled:           'Gray',
    inProgress:         '#0078D7',
    completed:          'Green',
    notStarted:         'Gray'
  });

  /**
   * @typedef {Object} Build
   * @property {Date} startedAt Build start time
   * @property {Date} finishedAt Build finish time
   * @property {boolean} hasErrors Does the resulting build have errors?
   * @property {boolean} hasWarnings Did the build give some warnings?
   * @property {boolean} isRunning Is the build currently running?
   * @property {boolean} isQueued Is the build currently waiting in the queue?
   * @property {string} id Unique ID of the build
   * @property {string} number Build number
   * @property {string} project Name of the project
   * @property {string} reason Reason for building the project
   * @property {string} requestedFor Name of the Requester
   * @property {string} status The color to be used for displaying
   * @property {string} statusText The status of the build
   * @property {string} url URL of the project
   */

  /**
   * It is a node-style callback.
   * @callback buildsInfoRequestCallback
   * @param {Error|null} err It is an instance of Error
   * @param {Array<Build>} listOfBuilds It is an array of {@link Build}
   */

  /**
   * It exposes the API needed by the application to check the status of builds.
   * @name check
   * @function
   * @public
   * @instance
   * @memberOf VSTSRestBuilds
   * @param {buildsInfoRequestCallback} cb Callback which handles the
   *  requested build information
   */
  this.check = (callback) => {
    if (basicAuth && instance && project) {
      getListOfBuilds(callback);
      return;
    }
    callback('incomplete configuration');
    return;
  };

  /**
   * @typedef {Object} VSTSRestBuildsConfiguration
   * @property {string} instance VS Team Services account
   *  ({account}.visualstudio.com) or TFS server ({server:port}).
   * @property {string} project Team project ID or name
   * @property {string} queryparams Additional queryparams to filter the data
   *  and provide additional options
   * @property {string} username Username
   * @property {string} pat Personal Access Token with access to Builds
   *  information
   */

  /**
   * It exposes the API needed by the application to provide
   *  configuration parameters.
   * @name check
   * @function
   * @public
   * @instance
   * @memberOf VSTSRestBuilds
   * @param {VSTSRestBuildsConfiguration} config Configuration parameters
   */
  this.configure = (config) => {
    /**
     * It exposes the configuration passed to the
     * configure instance method.
     * @public
     * @instance
     */
    this.configuration = config;
    basicAuth = new Buffer(`${config.username}:${config.pat}`)
      .toString('base64');
    instance = config.instance;
    params = config.queryparams;
    project = config.project;
    collection = config.collection || 'DefaultCollection';

    console.log(config);
  };

  /**
   * @private
   * @param {buildsInfoRequestCallback} cb Callback which handles the
   *  requested build information
   */
  const getListOfBuilds = (callback) => {
    const url = `https://${instance}/${collection}/${project}/_apis/build/builds?api-version=2.0${params}`;
    const options = {
      url,
      headers: {
        Authorization: `Basic ${basicAuth}`,
      },
    };
    request.makeRequest(options, (err, body) => {
      transformData(err, body, callback);
    });

    /**
     * Transforms the data received from the request to VSTS REST API
     * @private
     * @param {any} err If the value is truthy, it indicates an error has
     *  occurred.
     * @param {object} body It contains the response body from VSTS REST API
     * @param {buildsInfoRequestCallback} cb Callback which handles the
     *  requested build information
     * @return {null}
     */
    const transformData = (err, body, callback) => {
      if (err) {
        callback(err);
        return;
      }
      if (!(body && body.value)) {
        callback('No values found');
        return;
      }
      const transformedData = body.value.map(transformer);
      callback(null, transformedData);
    };

    /**
     * The function transforms the data from VSTS API to
     *  the accepted by callback
     * @name transformer
     * @private
     * @param {object} build individual build information object returned
     *  from API
     * @returns {Build} the object is in the format accepted by the application
     */
    const transformer = (build) => {
      let color = colorScheme[
        build.result ?
          resultFilter[build.result] :
          (build.status === statusFilter.notStarted ?
            statusFilter[statusFilter.notStarted] :
            statusFilter[statusFilter.inProgress]
          )
      ];

      let text = build.result ?
      build.result :
        (build.status === statusFilter.notStarted ?
          statusFilter.notStarted :
          statusFilter.inProgress
        );

      let webUrl = build._links ?
        (build._links.web ? build._links.web.href : build.url) :
        build.url;

      let result = {
        finishedAt: build.finishTime ? new Date(build.finishTime) : new Date(),
        hasErrors: build.result === resultFilter.failed,
        hasWarnings: build.result === resultFilter.partiallySucceeded,
        id: build.id,
        isRunning: build.status === statusFilter.inProgress,
        isQueued: build.status === statusFilter.notStarted,
        number: build.buildNumber,
        project: build.definition.name,
        queuedAt: build.queueTime ? new Date(build.queueTime) : new Date(),
        reason: build.reason,
        requestedFor: build.requestedFor ? build.requestedFor.displayName : '',
        startedAt: new Date(build.startTime),
        status: color,
        statusText: text,
        url: webUrl
      };

      return result;
    };
  };
}

module.exports = VSTSRestBuilds;
<commit_msg>Added missing colors just in case we happen to 'start' when a build is in a particular status<commit_after>const request = require('../requests');

/**
 * The service which provides build information by using the VSTS REST API
 *  v2.0. Although the naming of the variables suggest usage with VSTS, the
 *  code is compatible with both VSTS and TFS. The naming is simply the
 *  artifact of making the code generalised for both after initial usage
 *  with VSTS.
 * @public
 * @constructor
 * @see https://www.visualstudio.com/en-us/docs/integrate/api/build/overview
 */
function VSTSRestBuilds() {
  let basicAuth = null;
  let instance = null;
  let project = null;
  let collection = null;
  let params = null;

  /**
   * This object is the representation of resultFilter mentioned in the docs
   * @private
   * @see https://www.visualstudio.com/en-us/docs/integrate/api/build/builds
   */
  const resultFilter = Object.freeze({
    succeeded:          'succeeded',
    partiallySucceeded: 'partiallySucceeded',
    failed:             'failed',
    canceled:           'canceled'
  });

  /** This object is the representation of statusFilter mentioned in the docs
   * @private
   * @see https://www.visualstudio.com/en-us/docs/integrate/api/build/builds
   */
  const statusFilter = Object.freeze({
    inProgress: 'inProgress',
    completed:  'completed',
    cancelling: 'cancelling',
    postponed:  'postponed',
    notStarted: 'notStarted',
    all:        'all',
  });

  /**
   * This object defines the color scheme used.
   * @private
   */
  const colorScheme = Object.freeze({
    succeeded:          'Green',
    partiallySucceeded: '#F8A800',
    failed:             'Red',
    canceled:           'Gray',
    inProgress:         '#0078D7',
    completed:          'Green',
    cancelling:         '#0078D7',
    postponed:          'Gray',
    notStarted:         'Gray',
    all:                'Gray'
  });

  /**
   * @typedef {Object} Build
   * @property {Date} startedAt Build start time
   * @property {Date} finishedAt Build finish time
   * @property {boolean} hasErrors Does the resulting build have errors?
   * @property {boolean} hasWarnings Did the build give some warnings?
   * @property {boolean} isRunning Is the build currently running?
   * @property {boolean} isQueued Is the build currently waiting in the queue?
   * @property {string} id Unique ID of the build
   * @property {string} number Build number
   * @property {string} project Name of the project
   * @property {string} reason Reason for building the project
   * @property {string} requestedFor Name of the Requester
   * @property {string} status The color to be used for displaying
   * @property {string} statusText The status of the build
   * @property {string} url URL of the project
   */

  /**
   * It is a node-style callback.
   * @callback buildsInfoRequestCallback
   * @param {Error|null} err It is an instance of Error
   * @param {Array<Build>} listOfBuilds It is an array of {@link Build}
   */

  /**
   * It exposes the API needed by the application to check the status of builds.
   * @name check
   * @function
   * @public
   * @instance
   * @memberOf VSTSRestBuilds
   * @param {buildsInfoRequestCallback} cb Callback which handles the
   *  requested build information
   */
  this.check = (callback) => {
    if (basicAuth && instance && project) {
      getListOfBuilds(callback);
      return;
    }
    callback('incomplete configuration');
    return;
  };

  /**
   * @typedef {Object} VSTSRestBuildsConfiguration
   * @property {string} instance VS Team Services account
   *  ({account}.visualstudio.com) or TFS server ({server:port}).
   * @property {string} project Team project ID or name
   * @property {string} queryparams Additional queryparams to filter the data
   *  and provide additional options
   * @property {string} username Username
   * @property {string} pat Personal Access Token with access to Builds
   *  information
   */

  /**
   * It exposes the API needed by the application to provide
   *  configuration parameters.
   * @name check
   * @function
   * @public
   * @instance
   * @memberOf VSTSRestBuilds
   * @param {VSTSRestBuildsConfiguration} config Configuration parameters
   */
  this.configure = (config) => {
    /**
     * It exposes the configuration passed to the
     * configure instance method.
     * @public
     * @instance
     */
    this.configuration = config;
    basicAuth = new Buffer(`${config.username}:${config.pat}`)
      .toString('base64');
    instance = config.instance;
    params = config.queryparams;
    project = config.project;
    collection = config.collection || 'DefaultCollection';

    console.log(config);
  };

  /**
   * @private
   * @param {buildsInfoRequestCallback} cb Callback which handles the
   *  requested build information
   */
  const getListOfBuilds = (callback) => {
    const url = `https://${instance}/${collection}/${project}/_apis/build/builds?api-version=2.0${params}`;
    const options = {
      url,
      headers: {
        Authorization: `Basic ${basicAuth}`,
      },
    };
    request.makeRequest(options, (err, body) => {
      transformData(err, body, callback);
    });

    /**
     * Transforms the data received from the request to VSTS REST API
     * @private
     * @param {any} err If the value is truthy, it indicates an error has
     *  occurred.
     * @param {object} body It contains the response body from VSTS REST API
     * @param {buildsInfoRequestCallback} cb Callback which handles the
     *  requested build information
     * @return {null}
     */
    const transformData = (err, body, callback) => {
      if (err) {
        callback(err);
        return;
      }
      if (!(body && body.value)) {
        callback('No values found');
        return;
      }
      const transformedData = body.value.map(transformer);
      callback(null, transformedData);
    };

    /**
     * The function transforms the data from VSTS API to
     *  the accepted by callback
     * @name transformer
     * @private
     * @param {object} build individual build information object returned
     *  from API
     * @returns {Build} the object is in the format accepted by the application
     */
    const transformer = (build) => {
      let color = colorScheme[
        build.result ?
          resultFilter[build.result] :
          (build.status === statusFilter.notStarted ?
            statusFilter[statusFilter.notStarted] :
            statusFilter[statusFilter.inProgress]
          )
      ];

      let text = build.result ?
      build.result :
        (build.status === statusFilter.notStarted ?
          statusFilter.notStarted :
          statusFilter.inProgress
        );

      let webUrl = build._links ?
        (build._links.web ? build._links.web.href : build.url) :
        build.url;

      let result = {
        finishedAt: build.finishTime ? new Date(build.finishTime) : new Date(),
        hasErrors: build.result === resultFilter.failed,
        hasWarnings: build.result === resultFilter.partiallySucceeded,
        id: build.id,
        isRunning: build.status === statusFilter.inProgress,
        isQueued: build.status === statusFilter.notStarted,
        number: build.buildNumber,
        project: build.definition.name,
        queuedAt: build.queueTime ? new Date(build.queueTime) : new Date(),
        reason: build.reason,
        requestedFor: build.requestedFor ? build.requestedFor.displayName : '',
        startedAt: new Date(build.startTime),
        status: color,
        statusText: text,
        url: webUrl
      };

      return result;
    };
  };
}

module.exports = VSTSRestBuilds;
<|endoftext|>


<commit_before>'use strict';
(function() {

	// detect if IE : from http://stackoverflow.com/a/16657946
	var ie = (function(){
		var undef,rv = -1; // Return value assumes failure.
		var ua = window.navigator.userAgent;
		var msie = ua.indexOf('MSIE ');
		var trident = ua.indexOf('Trident/');

		if (msie > 0) {
			// IE 10 or older => return version number
			rv = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
		} else if (trident > 0) {
			// IE 11 (or newer) => return version number
			var rvNum = ua.indexOf('rv:');
			rv = parseInt(ua.substring(rvNum + 3, ua.indexOf('.', rvNum)), 10);
		}

		return ((rv > -1) ? rv : undef);
	}());

	// disable/enable scroll (mousewheel and keys) from http://stackoverflow.com/a/4770179
	// left: 37, up: 38, right: 39, down: 40,
	// spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36
	var keys = [32, 37, 38, 39, 40], wheelIter = 0;

	function preventDefault(e) {
		e = e || window.event;
		if (e.preventDefault){
      e.preventDefault();
    }

		e.returnValue = false;
	}

	function keydown(e) {
		for (var i = keys.length; i--;) {
			if (e.keyCode === keys[i]) {
				preventDefault(e);
				return;
			}
		}
	}

	function touchmove(e) {
		preventDefault(e);
	}

	function wheel(e) {
		// for IE
		//if( ie ) {
			//preventDefault(e);
		//}
	}

	function disable_scroll() {
		window.onmousewheel = document.onmousewheel = wheel;
		document.onkeydown = keydown;
		document.body.ontouchmove = touchmove;
	}

	function enable_scroll() {
		window.onmousewheel = document.onmousewheel = document.onkeydown = document.body.ontouchmove = null;
	}

	var docElem = window.document.documentElement,
		scrollVal,
		isRevealed,
		noscroll,
		isAnimating,
		container = document.getElementById( 'container' ),
		trigger = container.querySelector( 'button.trigger' );

	function scrollY() {
		return window.pageYOffset || docElem.scrollTop;
	}

	function scrollPage() {
		scrollVal = scrollY();

		if( noscroll && !ie ) {
			if( scrollVal < 0 ) return false;
			// keep it that way
			window.scrollTo( 0, 0 );
		}

		if( classie.has( container, 'notrans' ) ) {
			classie.remove( container, 'notrans' );
			return false;
		}

		if( isAnimating ) {
			return false;
		}

		if( scrollVal <= 0 && isRevealed ) {
			toggle(0);
		}
		else if( scrollVal > 0 && !isRevealed ){
			toggle(1);
		}
	}

	function toggle( reveal ) {
		isAnimating = true;

		if( reveal ) {
			classie.add( container, 'modify' );
      $("#navigation").removeClass("effect");
		}
		else {
			noscroll = true;
			disable_scroll();
			classie.remove( container, 'modify' );
      $("#navigation").addClass("effect");
		}

		// simulating the end of the transition:
		setTimeout( function() {
			isRevealed = !isRevealed;
			isAnimating = false;
			if( reveal ) {
				noscroll = false;
				enable_scroll();
			}
		}, 1200 );
	}

	// refreshing the page...
	var pageScroll = scrollY();
	noscroll = pageScroll === 0;

	disable_scroll();

	if( pageScroll ) {
		isRevealed = true;
		classie.add( container, 'notrans' );
		classie.add( container, 'modify' );
	}

	window.addEventListener( 'scroll', scrollPage );
	trigger.addEventListener( 'click', function() { toggle( 'reveal' ); } );
})();

(function(win, doc) {
  if ($('#gmap').size()) {
    var request = {
      placeId: 'ChIJlfzkL8hLj18R_M1MhUnKXqg'
    };
    var google = win.google,
    elm = $('#gmap'),
    mapOptions = {
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      scrollwheel: false,
      scaleControl: true
    },
    styles = [
      {
        'stylers': [
          {'saturation': 0}
        ]
      }
    ],
    map = new google.maps.Map(elm.get(0), mapOptions),
    geocoder = new google.maps.Geocoder(),
    STYLE_NAME = 'monochrome';
    var service = new google.maps.places.PlacesService(map);
    service.getDetails(request, function(place, status) {
      if (status === google.maps.places.PlacesServiceStatus.OK) {
        geocoder.geocode({
          'address':'サンアイ精機'
        }, function(results, status){
          if (status === google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
              map: map,
              position: place.geometry.location
            });
            var infowindow = new google.maps.InfoWindow();
            infowindow.setContent(place.adr_address);
            infowindow.open(map, marker);
          }
        });
      }
    });
  }
})(this, document);

(function(){
  $('.player').YTPlayer();

  // handle the mouseenter functionality
  $('.img').mouseenter(function(){
    $(this).addClass('hover');
  });
  // handle the mouseleave functionality
  $('.img').mouseleave(function(){
    $(this).removeClass('hover');
  });

  //smooth scroll
  $('nav#navigation a').smoothScroll();

  $('.effect-left').onScreen({
    container: window,
    direction: 'vertical',
    doIn: function() {
     // Do something to the matched elements as they come in
    },
    doOut: function() {
     // Do something to the matched elements as they get off scren
    },
    tolerance: 0,
    throttle: 50,
    toggleClass: 'onScreen',
    lazyAttr: null,
    lazyPlaceholder: 'someImage.jpg',
    debug: false
  });
});
<commit_msg>add doller mark<commit_after>'use strict';
(function() {

	// detect if IE : from http://stackoverflow.com/a/16657946
	var ie = (function(){
		var undef,rv = -1; // Return value assumes failure.
		var ua = window.navigator.userAgent;
		var msie = ua.indexOf('MSIE ');
		var trident = ua.indexOf('Trident/');

		if (msie > 0) {
			// IE 10 or older => return version number
			rv = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
		} else if (trident > 0) {
			// IE 11 (or newer) => return version number
			var rvNum = ua.indexOf('rv:');
			rv = parseInt(ua.substring(rvNum + 3, ua.indexOf('.', rvNum)), 10);
		}

		return ((rv > -1) ? rv : undef);
	}());

	// disable/enable scroll (mousewheel and keys) from http://stackoverflow.com/a/4770179
	// left: 37, up: 38, right: 39, down: 40,
	// spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36
	var keys = [32, 37, 38, 39, 40], wheelIter = 0;

	function preventDefault(e) {
		e = e || window.event;
		if (e.preventDefault){
      e.preventDefault();
    }

		e.returnValue = false;
	}

	function keydown(e) {
		for (var i = keys.length; i--;) {
			if (e.keyCode === keys[i]) {
				preventDefault(e);
				return;
			}
		}
	}

	function touchmove(e) {
		preventDefault(e);
	}

	function wheel(e) {
		// for IE
		//if( ie ) {
			//preventDefault(e);
		//}
	}

	function disable_scroll() {
		window.onmousewheel = document.onmousewheel = wheel;
		document.onkeydown = keydown;
		document.body.ontouchmove = touchmove;
	}

	function enable_scroll() {
		window.onmousewheel = document.onmousewheel = document.onkeydown = document.body.ontouchmove = null;
	}

	var docElem = window.document.documentElement,
		scrollVal,
		isRevealed,
		noscroll,
		isAnimating,
		container = document.getElementById( 'container' ),
		trigger = container.querySelector( 'button.trigger' );

	function scrollY() {
		return window.pageYOffset || docElem.scrollTop;
	}

	function scrollPage() {
		scrollVal = scrollY();

		if( noscroll && !ie ) {
			if( scrollVal < 0 ) return false;
			// keep it that way
			window.scrollTo( 0, 0 );
		}

		if( classie.has( container, 'notrans' ) ) {
			classie.remove( container, 'notrans' );
			return false;
		}

		if( isAnimating ) {
			return false;
		}

		if( scrollVal <= 0 && isRevealed ) {
			toggle(0);
		}
		else if( scrollVal > 0 && !isRevealed ){
			toggle(1);
		}
	}

	function toggle( reveal ) {
		isAnimating = true;

		if( reveal ) {
			classie.add( container, 'modify' );
      $("#navigation").removeClass("effect");
		}
		else {
			noscroll = true;
			disable_scroll();
			classie.remove( container, 'modify' );
      $("#navigation").addClass("effect");
		}

		// simulating the end of the transition:
		setTimeout( function() {
			isRevealed = !isRevealed;
			isAnimating = false;
			if( reveal ) {
				noscroll = false;
				enable_scroll();
			}
		}, 1200 );
	}

	// refreshing the page...
	var pageScroll = scrollY();
	noscroll = pageScroll === 0;

	disable_scroll();

	if( pageScroll ) {
		isRevealed = true;
		classie.add( container, 'notrans' );
		classie.add( container, 'modify' );
	}

	window.addEventListener( 'scroll', scrollPage );
	trigger.addEventListener( 'click', function() { toggle( 'reveal' ); } );
})();

(function(win, doc) {
  if ($('#gmap').size()) {
    var request = {
      placeId: 'ChIJlfzkL8hLj18R_M1MhUnKXqg'
    };
    var google = win.google,
    elm = $('#gmap'),
    mapOptions = {
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      scrollwheel: false,
      scaleControl: true
    },
    styles = [
      {
        'stylers': [
          {'saturation': 0}
        ]
      }
    ],
    map = new google.maps.Map(elm.get(0), mapOptions),
    geocoder = new google.maps.Geocoder(),
    STYLE_NAME = 'monochrome';
    var service = new google.maps.places.PlacesService(map);
    service.getDetails(request, function(place, status) {
      if (status === google.maps.places.PlacesServiceStatus.OK) {
        geocoder.geocode({
          'address':'サンアイ精機'
        }, function(results, status){
          if (status === google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
              map: map,
              position: place.geometry.location
            });
            var infowindow = new google.maps.InfoWindow();
            infowindow.setContent(place.adr_address);
            infowindow.open(map, marker);
          }
        });
      }
    });
  }
})(this, document);

$(function(){
  $('.player').YTPlayer();

  // handle the mouseenter functionality
  $('.img').mouseenter(function(){
    $(this).addClass('hover');
  });
  // handle the mouseleave functionality
  $('.img').mouseleave(function(){
    $(this).removeClass('hover');
  });

  //smooth scroll
  $('nav#navigation a').smoothScroll();

  $('.effect-left').onScreen({
    container: window,
    direction: 'vertical',
    doIn: function() {
     // Do something to the matched elements as they come in
    },
    doOut: function() {
     // Do something to the matched elements as they get off scren
    },
    tolerance: 0,
    throttle: 50,
    toggleClass: 'onScreen',
    lazyAttr: null,
    lazyPlaceholder: 'someImage.jpg',
    debug: false
  });
});
<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const Promise = require('bluebird');

const Facebook = require('./facebook');
const sessions = require('./sessions');
const keepr = require('./keepr');
const config = require('../../config');

module.exports = {
  actions: {
    send: ({sessionId}, {text}) => {
      const recipientId = sessions.getSessions()[sessionId].fbid;
      console.log('Response from Wit: ' + text);
      if (recipientId) {
          return Facebook.sendTextMessage(recipientId, text).then(() => null)
            .catch((err) => {
              console.error(
                'Oops! An error occurred while forwarding the response to',
                recipientId,
                ':',
                err.stack || err
                );
            });
      } else {
        console.error('Oops! Couldn\'t find user for session:', sessionId);
        return Promise.resolve();
      }
    },
    fetch_by_keyword(request) {
      const entities = request.entities;
      const sessionId = request.sessionId;
      const context = require.context;
      console.log(`entities: ${entities}`);
      console.log(`content: ${context}`);
      const keyword = entities.local_search_query[0].value;
      console.log('Keyword: ' + keyword);

      const recipientId = sessions.getSessions()[sessionId].fbid;
      if (recipientId) {
        return keepr.latestNewsByKeyword(keyword).then((response) => {
          const numbers = response.numbers;
          const newsWithUrls = _.filter(numbers, (tweet) => {
            return tweet.urls.length > 0;
          });

          return Facebook.sendTextMessage(recipientId, newsWithUrls.slice(0, 3)).catch((error) => {
            console.log(error);
          });
        });
      }
      return Promise.reject('Oops! Couldn\'t find user for session: ' + sessionId);
    },
  }
};
<commit_msg>More debug stuff<commit_after>'use strict';

const _ = require('lodash');
const Promise = require('bluebird');

const Facebook = require('./facebook');
const sessions = require('./sessions');
const keepr = require('./keepr');
const config = require('../../config');

module.exports = {
  actions: {
    send: ({sessionId}, {text}) => {
      const recipientId = sessions.getSessions()[sessionId].fbid;
      console.log('Response from Wit: ' + text);
      if (recipientId) {
          return Facebook.sendTextMessage(recipientId, text).then(() => null)
            .catch((err) => {
              console.error(
                'Oops! An error occurred while forwarding the response to',
                recipientId,
                ':',
                err.stack || err
                );
            });
      } else {
        console.error('Oops! Couldn\'t find user for session:', sessionId);
        return Promise.resolve();
      }
    },
    fetch_by_keyword(request) {
      const entities = request.entities;
      const sessionId = request.sessionId;
      const context = require.context;
      console.log(`entities: ${JSON.stringify(entities, null, 4)}`);
      console.log(`context: ${context}`);
      const keyword = entities.local_search_query[0].value;
      console.log('Keyword: ' + keyword);

      const recipientId = sessions.getSessions()[sessionId].fbid;
      if (recipientId) {
        return keepr.latestNewsByKeyword(keyword).then((response) => {
          const numbers = response.numbers;
          const newsWithUrls = _.filter(numbers, (tweet) => {
            return tweet.urls.length > 0;
          });

          return Facebook.sendTextMessage(recipientId, newsWithUrls.slice(0, 3)).catch((error) => {
            console.log(error);
          });
        });
      }
      return Promise.reject('Oops! Couldn\'t find user for session: ' + sessionId);
    },
  }
};
<|endoftext|>


<commit_before>'use strict';

(function($, leopard) {
	var imageTpl = new leopard.tpl($('#tpl-image-container').html()),
		streetviewTpl = new leopard.tpl(leopard.api.streetview),
		sliders = {
			$heading: $('#heading-slider'),
			$fov: $('#fov-slider'),
			$pitch: $('#pitch-slider')
		},
		directionTimers = [],
		displayImage = function($container, $image) {
			$container.spin(false).append($image);
		},
		generateDirectionsImages = function() {
			var origin = $('#address-origin').val(),
				destination = $('#address-destination').val(),
				directionsService = new google.maps.DirectionsService(),
				finishedSteps = 0,
				directionsRequest,
				timer,
				geocodeDirection = function(step) {
					var start = step.start_location;

					return leopard.getFormattedAddress(start);
				},
				geocodeCallback = function(address) {
					finishedSteps++;

					if (address !== 'RETRY') {
						generateImage(address);

						return true;
					}

					window.alert(address);
				};

			if (origin && destination) {
				directionsRequest = {
					origin: origin,
					destination: destination,
					travelMode: google.maps.TravelMode.DRIVING
				};

				directionsService.route(directionsRequest, function(result, status) {
					var steps, i, timeout;

					if (status === google.maps.DirectionsStatus.OK) {
						steps = result.routes[0].legs[0].steps;

						generateImage(origin);
						finishedSteps++;

						// Only steps in between origin & destination
						for (i = 1; i < steps.length - 1; i++) {
							// Ensure we don't exceed the 5 queries per second limit
							timeout = setTimeout(function(step) {
								geocodeDirection(step)
									.always(geocodeCallback);
								// TODO: Add failback for image from directions
							}, (i + 1) * 1500, steps[i]);

							directionTimers.push(timeout);
						}

						timer = setInterval(function() {
							if (finishedSteps === steps.length - 1) {
								clearInterval(timer);
								generateImage(destination);
								toggleButtons(false);
								leopard.buttons.$getDirections.spin(false);
								leopard.buttons.$cancelDirections.disable(true);
							}
						}, 3000);
					} else {
						// TODO: Display error message
					}
				});
			} else {
				// TODO: Throw error 'origin & destination are required'
			}

			return true;
		},
		generateImage = function(location) {
			var $imgContainer = $(imageTpl.apply()),
				imgUrl, $img, i;

			$(leopard.elements.imagesContainer).append($imgContainer);
			$imgContainer.spin('large');

			imgUrl = streetviewTpl.apply({
				location: location,
				heading: true,
				headingValue: getSliderValue('$heading'),
				imageWidth: leopard.images.streetview.width,
				imageHeight: leopard.images.streetview.width,
				fov: true,
				fovValue: getSliderValue('$fov'),
				pitch: true,
				pitchValue: getSliderValue('$pitch')
			});

			$img = $('<img>', {
				src: imgUrl,
				height: leopard.images.list.height,
				width: leopard.images.list.width,
				title: location
			});

			$img.load(displayImage.call(this, $imgContainer, $img));

			return;
		},
		getDirectionsCallback = function(e) {
			e.preventDefault();

			toggleButtons(true);
			leopard.buttons.$getDirections.spin('large');
			leopard.buttons.$cancelDirections.disable(false);

			generateDirectionsImages();

			return;
		},
		getSliderValue = function(name) {
			return parseInt(sliders[name].slider('value'), 10);
		},
		toggleButtons = function(action) {
			Object.getOwnPropertyNames(leopard.buttons).forEach(function(key) {
				if (leopard.buttons.hasOwnProperty(key)) {
					leopard.buttons[key].disable(action);
				};
			});

			return true;
		};

	/**
	 * [description]
	 * @param  {[type]} e [description]
	 * @return {[type]}   [description]
	 */
	leopard.buttons.$randomAddress.on('click', function(e) {
		var $element = $(e.target),
			$target = $element.attr('data-selector') ? $element : $element.parents('.button'),
			$input = $($target.data('selector')),
			latlong = leopard.getRandomLatLong(),
			addressDfd = $.Deferred(),
			/**
			 * Converts the given latitude/longitude values into a human
			 * readable address. Continues to loop if the values given
			 * do not return a valid address.
			 * @param  {Object} latlng
			 */
			getRandomAddress = function(latlng) {
				leopard.getFormattedAddress(latlng)
					.done(function(results) {
						addressDfd.resolve(results);
					})
					.fail(function(status) {
						if (status === 'RETRY') {
							getRandomAddress(leopard.getRandomLatLong());
						} else {
							addressDfd.fail(status);
						}
					});

				return addressDfd.promise();
			},
			randomAddressCallback = function(data) {
				$target.disable(false).spin(false);
				$input.val(data);
			};

		$input.val('');

		$target.disable(true).spin('small');

		// Wait for valid address to be returned
		getRandomAddress(latlong);

		addressDfd
			.done(randomAddressCallback)
			.fail(randomAddressCallback);
	});

	/**
	 * Get image from address button
	 */
	leopard.buttons.$getImage.on('click', function(e) {
		var $element = $(e.target),
			$target = $element.attr('data-selector') ? $element : $element.parent(),
			$input = $($target.data('selector')),
			address = $input.val();

		generateImage(address);
	});

	/**
	 * Form submit functionality
	 */
	$('form').on('submit', getDirectionsCallback);

	/**
	 * Cancel directions button
	 */
	leopard.buttons.$cancelDirections.on('click', function() {
		var $this = $(this),
			i;

		// Stop all running directions setTimeout calls
		for (i = 0; i < directionTimers.length; i++) {
			clearTimeout(directionTimers[i]);
		}

		leopard.buttons.$getDirections.spin(false);
		toggleButtons(false);

		directionTimers = [];

		$this.disable(true);
	});

	/**
	 * Remove image icon
	 */
	$(leopard.elements.imagesContainer).on('click', '.js-remove-image', function() {
		$(this).parents('.js-container-image').off().fadeOut().remove();
	});
})(jQuery, window.leopard);
<commit_msg>Add code for starting a slideshow<commit_after>'use strict';

(function($, leopard) {
	var imageTpl = new leopard.tpl($('#tpl-image-container').html()),
		slideshowTpl = new leopard.tpl($('#tpl-slideshow-container').html()).apply(),
		streetviewTpl = new leopard.tpl(leopard.api.streetview),
		sliders = {
			$heading: $('#heading-slider'),
			$fov: $('#fov-slider'),
			$pitch: $('#pitch-slider')
		},
		directionTimers = [],
		displayImage = function($container, $image) {
			$container.spin(false).append($image);
		},
		generateDirectionsImages = function() {
			var origin = $('#address-origin').val(),
				destination = $('#address-destination').val(),
				directionsService = new google.maps.DirectionsService(),
				finishedSteps = 0,
				directionsRequest,
				timer,
				geocodeDirection = function(step) {
					var start = step.start_location;

					return leopard.getFormattedAddress(start);
				},
				geocodeCallback = function(address) {
					finishedSteps++;

					if (address !== 'RETRY') {
						generateImage(address);

						return true;
					}

					window.alert(address);
				};

			if (origin && destination) {
				directionsRequest = {
					origin: origin,
					destination: destination,
					travelMode: google.maps.TravelMode.DRIVING
				};

				directionsService.route(directionsRequest, function(result, status) {
					var steps, i, timeout;

					if (status === google.maps.DirectionsStatus.OK) {
						steps = result.routes[0].legs[0].steps;

						generateImage(origin);
						finishedSteps++;

						// Only steps in between origin & destination
						for (i = 1; i < steps.length - 1; i++) {
							// Ensure we don't exceed the 5 queries per second limit
							timeout = setTimeout(function(step) {
								geocodeDirection(step)
									.always(geocodeCallback);
								// TODO: Add failback for image from directions
							}, (i + 1) * 1500, steps[i]);

							directionTimers.push(timeout);
						}

						timer = setInterval(function() {
							if (finishedSteps === steps.length - 1) {
								clearInterval(timer);
								generateImage(destination);
								toggleButtons(false);
								leopard.buttons.$getDirections.spin(false);
								leopard.buttons.$cancelDirections.disable(true);
							}
						}, 3000);
					} else {
						// TODO: Display error message
					}
				});
			} else {
				// TODO: Throw error 'origin & destination are required'
			}

			return true;
		},
		generateImage = function(location) {
			var $imgContainer = $(imageTpl.apply()),
				imgUrl, $img, i;

			$(leopard.elements.imagesContainer).append($imgContainer);
			$imgContainer.spin('large');

			imgUrl = streetviewTpl.apply({
				location: location,
				heading: true,
				headingValue: getSliderValue('$heading'),
				imageWidth: leopard.images.streetview.width,
				imageHeight: leopard.images.streetview.width,
				fov: true,
				fovValue: getSliderValue('$fov'),
				pitch: true,
				pitchValue: getSliderValue('$pitch')
			});

			$img = $('<img>', {
				class: 'streetview-image',
				src: imgUrl,
				title: location
			});

			$img.load(displayImage.call(this, $imgContainer, $img));

			return;
		},
		getDirectionsCallback = function(e) {
			e.preventDefault();

			toggleButtons(true);
			leopard.buttons.$getDirections.spin('large');
			leopard.buttons.$cancelDirections.disable(false);

			generateDirectionsImages();

			return;
		},
		getSliderValue = function(name) {
			return parseInt(sliders[name].slider('value'), 10);
		},
		randomAddressClickCallback = function(e) {
			var $element = $(e.target),
				$target = $element.attr('data-selector') ? $element : $element.parents('.button'),
				$input = $($target.data('selector')),
				latlong = leopard.getRandomLatLong(),
				addressDfd = $.Deferred(),
				/**
				 * Converts the given latitude/longitude values into a human
				 * readable address. Continues to loop if the values given
				 * do not return a valid address.
				 * @param  {Object} latlng
				 */
				getRandomAddress = function(latlng) {
					leopard.getFormattedAddress(latlng)
						.done(function(results) {
							addressDfd.resolve(results);
						})
						.fail(function(status) {
							if (status === 'RETRY') {
								getRandomAddress(leopard.getRandomLatLong());
							} else {
								addressDfd.fail(status);
							}
						});

					return addressDfd.promise();
				},
				getRandomAddressCallback = function(data) {
					$target.disable(false).spin(false);
					$input.val(data);
				};

			$input.val('');

			$target.disable(true).spin('small');

			// Wait for valid address to be returned
			getRandomAddress(latlong);

			addressDfd
				.done(getRandomAddressCallback)
				.fail(getRandomAddressCallback);
		},
		toggleButtons = function(action) {
			Object.getOwnPropertyNames(leopard.buttons).forEach(function(key) {
				if (leopard.buttons.hasOwnProperty(key)) {
					leopard.buttons[key].disable(action);
				};
			});

			return true;
		};

	/**
	 * [description]
	 * @param  {[type]} e [description]
	 * @return {[type]}   [description]
	 */
	leopard.buttons.$randomAddress.on('click', randomAddressClickCallback);

	/**
	 * Get image from address button
	 */
	leopard.buttons.$getImage.on('click', function(e) {
		var $element = $(e.target),
			$target = $element.attr('data-selector') ? $element : $element.parent(),
			$input = $($target.data('selector')),
			address = $input.val();

		generateImage(address);
	});

	/**
	 * Form submit functionality
	 */
	$('form').on('submit', getDirectionsCallback);

	/**
	 * Cancel directions button
	 */
	leopard.buttons.$cancelDirections.on('click', function() {
		var $this = $(this),
			i;

		// Stop all running directions setTimeout calls
		for (i = 0; i < directionTimers.length; i++) {
			clearTimeout(directionTimers[i]);
		}

		leopard.buttons.$getDirections.spin(false);
		toggleButtons(false);

		directionTimers = [];

		$this.disable(true);
	});

	leopard.buttons.$startSlideshow.on('click', function() {
		var $images = $(leopard.elements.streetviewImage).clone(),
			slider = $(slideshowTpl).append($images.wrapAll($('<div/>')));

		$('.js-slideshow-dialog')
			.append(slider)
			.dialog(leopard.dialogOptions);
		slider.slick(leopard.slickOptions);
	});

	/**
	 * Remove image icon
	 */
	$(leopard.elements.imagesContainer).on('click', '.js-remove-image', function() {
		$(this).parents('.js-container-image').off().fadeOut().remove();
	});
})(jQuery, window.leopard);
<|endoftext|>


<commit_before>// app/socketRoutes.js

var Game = require('./game');

module.exports = function(io) {
  var sessionCounter = 0; // Temporary way to distinguish between games
  var sessions = {};

  io.on('connection', function (socket) {
    var sessionNumber, session, game;

    socket.on('register', function (data) {
      if (data.client === 'host') {
        sessions[sessionCounter] = {host: socket.id, clients: {}, game: new Game()};

        sessionNumber = sessionCounter;
        session = sessions[sessionNumber];
        game = session.game;

        socket.join(sessionCounter);
        socket.emit('sessionNumber', sessionNumber);

        sessionCounter++;
      } else {
        sessionNumber = data.sessionNumber;
        session = sessions[sessionNumber];
        game = session.game;

        socket.join(data.sessionNumber);
        session.clients[socket.id] = {};
      }
    });

    // Host events
    socket.on('question.submit', function() {
      if (!game.started) {
        // This is the first question of the game
        game.startGame(session.clients);
      } else {
        // This is not the first question - prepare the
        // game for a new question
        game.nextQuestion();
      }
      socket.broadcast.to(sessionNumber).emit('question.submit', game.currentQuestion);
    });

    socket.on('question.choose', function(questionId) {
      var choices = game.getChoices(questionId, function(choices) {
        socket.emit('choices', choices);
        socket.broadcast.to(sessionNumber).emit('question.choose', {currentQuestion: game.currentQuestion, choices: choices});
      });
    });

    socket.on('question.review', function() {
      var results = game.getQuestionResults();
      socket.emit('results', results);
      socket.broadcast.to(sessionNumber).emit('question.review', game.currentQuestion);
    });

    socket.on('final', function() {
      socket.broadcast.to(sessionNumber).emit('final');
    });

    // Client events
    socket.on('setName', function(name) {
      session.clients[socket.id]['name'] = name;

      if (!game.started) {
        socket.broadcast.to(session.host).emit('clientUpdate', session.clients);
      } else {
        game.addPlayer(socket.id, name);
      }
    });

    socket.on('submitAnswer', function(answer) {
      game.recordAnswer(socket.id, answer);
      socket.broadcast.to(session.host).emit('answerSubmitted', socket.id);
    });

    socket.on('submitChoice', function(choice) {
      game.recordChoice(socket.id, choice);
      socket.broadcast.to(session.host).emit('choiceSubmitted', socket.id);
    });

  });
};
<commit_msg>Adding some light error handling for joining non-existant sessions<commit_after>// app/socketRoutes.js

var Game = require('./game');

module.exports = function(io) {
  var sessionCounter = 0; // Temporary way to distinguish between games
  var sessions = {};

  io.on('connection', function (socket) {
    var sessionNumber, session, game;

    socket.on('register', function (data) {
      if (data.client === 'host') {
        sessions[sessionCounter] = {host: socket.id, clients: {}, game: new Game()};

        sessionNumber = sessionCounter;
        session = sessions[sessionNumber];
        game = session.game;

        socket.join(sessionCounter);
        socket.emit('sessionNumber', sessionNumber);

        sessionCounter++;
      } else {
        if (!sessions.hasOwnProperty(data.sessionNumber)) {
          console.error('Tried to join non-existant session');
          return;
        }

        sessionNumber = data.sessionNumber;
        session = sessions[sessionNumber];
        game = session.game;

        socket.join(data.sessionNumber);
        session.clients[socket.id] = {};
      }
    });

    // Host events
    socket.on('question.submit', function() {
      if (!game.started) {
        // This is the first question of the game
        game.startGame(session.clients);
      } else {
        // This is not the first question - prepare the
        // game for a new question
        game.nextQuestion();
      }
      socket.broadcast.to(sessionNumber).emit('question.submit', game.currentQuestion);
    });

    socket.on('question.choose', function(questionId) {
      var choices = game.getChoices(questionId, function(choices) {
        socket.emit('choices', choices);
        socket.broadcast.to(sessionNumber).emit('question.choose', {currentQuestion: game.currentQuestion, choices: choices});
      });
    });

    socket.on('question.review', function() {
      var results = game.getQuestionResults();
      socket.emit('results', results);
      socket.broadcast.to(sessionNumber).emit('question.review', game.currentQuestion);
    });

    socket.on('final', function() {
      socket.broadcast.to(sessionNumber).emit('final');
    });

    // Client events
    socket.on('setName', function(name) {
      session.clients[socket.id]['name'] = name;

      if (!game.started) {
        socket.broadcast.to(session.host).emit('clientUpdate', session.clients);
      } else {
        game.addPlayer(socket.id, name);
      }
    });

    socket.on('submitAnswer', function(answer) {
      game.recordAnswer(socket.id, answer);
      socket.broadcast.to(session.host).emit('answerSubmitted', socket.id);
    });

    socket.on('submitChoice', function(choice) {
      game.recordChoice(socket.id, choice);
      socket.broadcast.to(session.host).emit('choiceSubmitted', socket.id);
    });

  });
};
<|endoftext|>


<commit_before>// app/socketRoutes.js

var Game = require('./game');

module.exports = function(io) {
  var host;
  var clients = {};
  var game = new Game();

  io.on('connection', function (socket) {

    socket.on('register', function (message) {
      if (message === 'host') {
        host = socket.id;
      } else {
        socket.join('gameRoom');
        clients[socket.id] = {};
      }
    });

    // Host events
    socket.on('question.submit', function() {
      if (!game.started) {
        // This is the first question of the game
        game.startGame(clients);
      } else {
        // This is not the first question - prepare the
        // game for a new question
        game.nextQuestion();
      }
      console.log("CURRENTQUESTION" + game.currentQuestion);
      socket.broadcast.emit('question.submit', game.currentQuestion);
    });

    socket.on('question.choose', function(questionId) {
      var choices = game.getChoices(questionId, function(choices) {
        socket.emit('choices', choices);
        socket.broadcast.emit('question.choose', {currentQuestion: game.currentQuestion, choices: choices});
      });
    });

    socket.on('question.review', function() {
      var results = game.getQuestionResults();
      socket.emit('results', results);
      socket.broadcast.emit('question.review', game.currentQuestion);
    });

    socket.on('final', function() {
      socket.broadcast.emit('final');
    });

    // Client events
    socket.on('setName', function(name) {
      clients[socket.id]['name'] = name;
      socket.broadcast.to(host).emit('clientUpdate', clients);
    });

    socket.on('submitAnswer', function(answer) {
      game.recordAnswer(socket.id, answer);
      socket.broadcast.to(host).emit('answerSubmitted', socket.id);
    });

    socket.on('submitChoice', function(choice) {
      game.recordChoice(socket.id, choice);
      socket.broadcast.to(host).emit('choiceSubmitted', socket.id);
    });

  });
};
<commit_msg>No longer have to restart the server to start a new game. Wooo<commit_after>// app/socketRoutes.js

var Game = require('./game');

module.exports = function(io) {
  var sessionCounter = 0; // Temporary way to distinguish between games
  var sessions = {};

  io.on('connection', function (socket) {
    var session, game;

    socket.on('register', function (message) {
      if (message === 'host') {
        sessionCounter++;
        sessions[sessionCounter] = {host: socket.id, clients: {}, game: new Game()};

        session = sessions[sessionCounter];
        game = session.game;
      } else {
        // socket.join('gameRoom');
        session = sessions[sessionCounter];
        game = session.game;

        session.clients[socket.id] = {};
      }
    });

    // Host events
    socket.on('question.submit', function() {
      if (!game.started) {
        // This is the first question of the game
        game.startGame(session.clients);
      } else {
        // This is not the first question - prepare the
        // game for a new question
        game.nextQuestion();
      }
      socket.broadcast.emit('question.submit', game.currentQuestion);
    });

    socket.on('question.choose', function(questionId) {
      var choices = game.getChoices(questionId, function(choices) {
        socket.emit('choices', choices);
        socket.broadcast.emit('question.choose', {currentQuestion: game.currentQuestion, choices: choices});
      });
    });

    socket.on('question.review', function() {
      var results = game.getQuestionResults();
      socket.emit('results', results);
      socket.broadcast.emit('question.review', game.currentQuestion);
    });

    socket.on('final', function() {
      socket.broadcast.emit('final');
    });

    // Client events
    socket.on('setName', function(name) {
      session.clients[socket.id]['name'] = name;
      socket.broadcast.to(session.host).emit('clientUpdate', session.clients);
    });

    socket.on('submitAnswer', function(answer) {
      game.recordAnswer(socket.id, answer);
      socket.broadcast.to(session.host).emit('answerSubmitted', socket.id);
    });

    socket.on('submitChoice', function(choice) {
      game.recordChoice(socket.id, choice);
      socket.broadcast.to(session.host).emit('choiceSubmitted', socket.id);
    });

  });
};
<|endoftext|>


<commit_before>'use strict';
const request = require('request');
const cheerio = require('cheerio');

class SVPageParser{
    parseToday(url, callback) {
        const self = this;
        request(url, function(err, resp, body){
            let $ = cheerio.load(body);
            let message = self.formatMessage($);
            callback(message);
        });
    }

    parseWeek(url, callback) {
        const self = this;
        request(url, function(err, resp, body){
            let $ = cheerio.load(body);
            let message = self.formatWeek($);
            callback(message);
        });
    }

    formatWeek($) {
        let offers = $('#menu-plan-tab1').find('.menu-item');
        let text = '';
        $(offers).each(function (i, offer) {
            let menuDescription = $(offer).find('.menu-description');
            menuDescription.find('br').replaceWith(' ');

            text += '*' + removeSpecialCharacters($(offer).find('.menu-title').text().trim()) + '*\n';
            text += removeSpecialCharacters(menuDescription.text()) + '\n';
            text += '_' + removeSpecialCharacters($(offer).find('.prices-3 .val').text() + ' ' + $(offer).find('.prices-3 .desc').text()) + "_\n";
            let provenance = removeSpecialCharacters($(offer).find('.menu-provenance').text());
            if (provenance.length > 1) {
                text += '_' + provenance + "_\n\n";
            } else {
                text += "\n";
            }

        });

        function removeSpecialCharacters(text) {
            return (text.replace(/`|\*|_|#|\r/g, ''));
        }

        return text;
    }

    formatMessage($) {
        let offers = $('#menu-plan-tab1').find('.menu-item');
        let text = '';
        $(offers).each(function (i, offer) {
            let menuDescription = $(offer).find('.menu-description');
            menuDescription.find('br').replaceWith(' ');

            text += '*' + removeSpecialCharacters($(offer).find('.menu-title').text().trim()) + '*\n';
            text += removeSpecialCharacters(menuDescription.text()) + '\n';
            text += '_' + removeSpecialCharacters($(offer).find('.prices-3 .val').text() + ' ' + $(offer).find('.prices-3 .desc').text()) + "_\n";
            let provenance = removeSpecialCharacters($(offer).find('.menu-provenance').text());
            if (provenance.length > 1) {
                text += '_' + provenance + "_\n\n";
            } else {
                text += "\n";
            }

        });

        function removeSpecialCharacters(text) {
            return (text.replace(/`|\*|_|#|\r/g, ''));
        }

        return text;
    }
}

module.exports = SVPageParser;
<commit_msg>feat(parser): send remaining weekdays<commit_after>'use strict';
const request = require('request');
const cheerio = require('cheerio');

class SVPageParser{

    parseToday(url, callback) {
        const self = this;
        request(url, function(err, resp, body){
            let $ = cheerio.load(body);
            let message = self.formatMessage($);
            callback(message);
        });
    }

    parseWeek(url, callback) {
        const self = this;
        request(url, function(err, resp, body){
            let $ = cheerio.load(body);
            let message = self.formatWeek($);
            callback(message);
        });
    }

    formatWeek($) {
        let days = $('.day-nav').find('li');

        let text = '';
        $(days).each(function (i, day) {
            let dayName = $(day).find('.day').text();
            let dayDate= $(day).find('.date').text();

            text += `*${dayName} ${dayDate} \n*`
        });

        return text;
    }

    formatMessage($) {
        let offers = $('#menu-plan-tab1').find('.menu-item');
        let text = '';
        $(offers).each(function (i, offer) {
            let menuDescription = $(offer).find('.menu-description');
            menuDescription.find('br').replaceWith(' ');

            text += '*' + removeSpecialCharacters($(offer).find('.menu-title').text().trim()) + '*\n';
            text += removeSpecialCharacters(menuDescription.text()) + '\n';
            text += '_' + removeSpecialCharacters($(offer).find('.prices-3 .val').text() + ' ' + $(offer).find('.prices-3 .desc').text()) + "_\n";
            let provenance = removeSpecialCharacters($(offer).find('.menu-provenance').text());
            if (provenance.length > 1) {
                text += '_' + provenance + "_\n\n";
            } else {
                text += "\n";
            }

        });

        function removeSpecialCharacters(text) {
            return (text.replace(/`|\*|_|#|\r/g, ''));
        }

        return text;
    }
}

module.exports = SVPageParser;
<|endoftext|>