<commit_before>import gulp from 'gulp';
import gulpif from 'gulp-if';
import sourcemaps from 'gulp-sourcemaps';
import sass from 'gulp-sass';
import notify from 'gulp-notify';
import rename from 'gulp-rename';
import browserSync from 'browser-sync';
import autoprefixer from 'gulp-autoprefixer';
// import sassGlob from 'gulp-sass-glob';
import moduleImporter from 'sass-module-importer';
import globImporter from 'sass-glob-importer';

import config from './../gulpfile.babel';

gulp.task('styles', function () {

    return gulp.src(config.styles.src)
        .pipe(gulpif(config.styles.sourcemaps, sourcemaps.init()))
        // .pipe(sassGlob())
        .pipe(sass({
            outputStyle: 'extended',
            importer: [moduleImporter(), globImporter()]
        }))
        .on('error', notify.onError('<%= error.message %>'))
        .pipe(autoprefixer('last 2 versions', '> 1%', 'ie 9'))
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulpif(config.styles.sourcemaps, sourcemaps.write()))
        .pipe(gulp.dest(config.styles.dest))
        .pipe(gulpif(config.autoreload, browserSync.stream()));
});<commit_msg>fixed issue #1 and fixed sourcemaps not working correctly<commit_after>import gulp from 'gulp';
import gulpif from 'gulp-if';
import sourcemaps from 'gulp-sourcemaps';
import sass from 'gulp-sass';
import notify from 'gulp-notify';
import rename from 'gulp-rename';
import browserSync from 'browser-sync';
import autoprefixer from 'gulp-autoprefixer';
import moduleImporter from 'sass-module-importer';
import globImporter from 'sass-glob-importer';

import config from './../gulpfile.babel';

gulp.task('styles', function () {

    // TODO set it 'compressed' when this issue is solved https://github.com/sass/node-sass/issues/957
    const outputStyle = global.isProduction ? 'compressed' : 'expanded';

    return gulp.src(config.styles.src)
        .pipe(gulpif(config.styles.sourcemaps, sourcemaps.init()))
        .pipe(sass({
            outputStyle,
            importer: [moduleImporter, globImporter]
        }))
        .on('error', notify.onError('<%= error.message %>'))
        .pipe(autoprefixer({ browsers: ['last 2 versions', '> 1%', 'ie 9'] }))
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulpif(config.styles.sourcemaps, sourcemaps.write()))
        .pipe(gulp.dest(config.styles.dest))
        .pipe(gulpif(config.autoreload, browserSync.stream()));
});<|endoftext|>


<commit_before>angular.module('angular-growl', [])
	.config(['$httpProvider', function ($httpProvider) {
		$httpProvider.responseInterceptors.push(['$q', 'growl', function ($q, growl) {
			function success(response) {
				if (response.messages) {
					growl.addServerMessages(response.messages);
				}
				return response;
			}

			function error(response) {
				if (response.messages) {
					growl.addServerMessages(response.messages);
				}

				return $q.reject(response);

			}

			return function (promise) {
				return promise.then(success, error);
			};
		}]);
	}]);

angular.module("angular-growl").directive(["$rootScope", function ($rootScope) {

	return {
		restrict: 'A',
		template:   '
' +
			'
' +
			'		<button type="button" class="close" ng-click="deleteMessage(message)">×</button>' +
			'            {{ message.text | translate}}' +
			'
' +
			'
',
		replace: false,
		scope: true,
		controller: function ($scope) {
			$scope.messages = [];

			$scope.showMessages = function () {
				return $scope.messages.length > 0;
			};

			$rootScope.$on("growlMessage", function (event, message) {
				$scope.messages.push(message);
			});

			$rootScope.$on("growlMessages", function (event, messages) {
				$scope.messages = $scope.messages.concat(messages);
			});

			$scope.deleteMessage = function (message) {
				var index = $scope.messages.indexOf(message);
				if (index > -1) {
					$scope.messages.splice(index, 1);
				}

			};

			$scope.computeClasses = function (message) {
				return {
					'alert-success': message.isSuccess,
					'alert-error': message.isError,
					'alert-info': message.isInfo
				};
			}
		}
	};
}]);

angular.module("angular-growl").directive(["$rootScope", function ($rootScope) {

	function broadcastMessage(message) {
		$rootScope.$broadcast("growlMessage", message);
	}

	function broadcastMessages(messages) {
		$rootScope.$broadcast("growlMessages", messages);
	}

	function sendMessage(text, severity) {
		var message = {
			text: text,
			isWarn: severity.isWarn,
			isError: severity.isError,
			isInfo: severity.isInfo,
			isSuccess: severity.isSuccess
		};

		broadcastMessage(message);
	}

	function addWarnMessage(text) {
		sendMessage(text, {isWarn: true});
	}

	function addErrorMessage(text) {
		sendMessage(text, {isError: true});
	}

	function addInfoMessage(text) {
		sendMessage(text, {isInfo: true});
	}

	function addSuccessMessage(text) {
		sendMessage(text, {isSuccess: true});
	}

	function addServerMessages(messages) {
		if (messages && messages.length > 0) {
			broadcastMessages(messages);
		}
	}

	return {
		addWarnMessage: addWarnMessage,
		addErrorMessage: addErrorMessage,
		addInfoMessage: addInfoMessage,
		addSuccessMessage: addSuccessMessage,
		addServerMessages: addServerMessages

	};
}]);
<commit_msg>correctly calling angular to create modules<commit_after>angular.module('angular-growl', [])
	.config(['$httpProvider', function ($httpProvider) {
		$httpProvider.responseInterceptors.push(['$q', 'growl', function ($q, growl) {
			function success(response) {
				if (response.messages) {
					growl.addServerMessages(response.messages);
				}
				return response;
			}

			function error(response) {
				if (response.messages) {
					growl.addServerMessages(response.messages);
				}

				return $q.reject(response);

			}

			return function (promise) {
				return promise.then(success, error);
			};
		}]);
	}]);

angular.module("angular-growl").directive("growl", ["$rootScope", function ($rootScope) {

	return {
		restrict: 'A',
		template:   '
' +
			'
' +
			'		<button type="button" class="close" ng-click="deleteMessage(message)">×</button>' +
			'            {{ message.text}}' +
			'
' +
			'
',
		replace: false,
		scope: true,
		controller: function ($scope) {
			$scope.messages = [];

			$scope.showMessages = function () {
				return $scope.messages.length > 0;
			};

			$rootScope.$on("growlMessage", function (event, message) {
				$scope.messages.push(message);
			});

			$rootScope.$on("growlMessages", function (event, messages) {
				$scope.messages = $scope.messages.concat(messages);
			});

			$scope.deleteMessage = function (message) {
				var index = $scope.messages.indexOf(message);
				if (index > -1) {
					$scope.messages.splice(index, 1);
				}

			};

			$scope.computeClasses = function (message) {
				return {
					'alert-success': message.isSuccess,
					'alert-error': message.isError,
					'alert-info': message.isInfo
				};
			}
		}
	};
}]);

angular.module("angular-growl").factory("growl", ["$rootScope", function ($rootScope) {

	function broadcastMessage(message) {
		$rootScope.$broadcast("growlMessage", message);
	}

	function broadcastMessages(messages) {
		$rootScope.$broadcast("growlMessages", messages);
	}

	function sendMessage(text, severity) {
		var message = {
			text: text,
			isWarn: severity.isWarn,
			isError: severity.isError,
			isInfo: severity.isInfo,
			isSuccess: severity.isSuccess
		};

		broadcastMessage(message);
	}

	function addWarnMessage(text) {
		sendMessage(text, {isWarn: true});
	}

	function addErrorMessage(text) {
		sendMessage(text, {isError: true});
	}

	function addInfoMessage(text) {
		sendMessage(text, {isInfo: true});
	}

	function addSuccessMessage(text) {
		sendMessage(text, {isSuccess: true});
	}

	function addServerMessages(messages) {
		if (messages && messages.length > 0) {
			broadcastMessages(messages);
		}
	}

	return {
		addWarnMessage: addWarnMessage,
		addErrorMessage: addErrorMessage,
		addInfoMessage: addInfoMessage,
		addSuccessMessage: addSuccessMessage,
		addServerMessages: addServerMessages

	};
}]);
<|endoftext|>


<commit_before>const publicFields = require('../data/enterprise.model').enterprisePublicFields;
const privateFields = require('../data/enterprise.model').enterprisePrivateFields;
const internationalPrivateFields = require('../data/enterprise.model').internationalEnterprisePrivateFields;
const SUPPORTED_LANGUAGES = require('../helpers/language/constants').SUPPORTED_LANGUAGES;
const jsonMergePatch = require('json8-merge-patch');

function transformDbEnterprisesToApiFormat(dbEnterprise) {

  // clone the object
  let apiEnterprise = JSON.parse(JSON.stringify(dbEnterprise));

  delete apiEnterprise.lowercase_name;

  // if there was a "score" field due to text index lookup, remove it
  delete apiEnterprise.score;

  // if there was a "distance" field due to location index lookup, remove it
  delete apiEnterprise.dis;

  return apiEnterprise;
}

function copyLocations(source, dest) {
  if (source['locations']) {
    dest['locations'] = source['locations'];
  }
}

function copyAdminEmails(source, dest) {
  if (source['admin_emails']) {
    dest['admin_emails'] = source['admin_emails'];
  }
}

function transformDbEnterpriseToApiFormatForLanguage(dbInternationalEnterprise, language) {
  let apiEnterprise = {};

  if (dbInternationalEnterprise[language]) {
    let enterpriseFields = transformDbEnterprisesToApiFormat(dbInternationalEnterprise[language]);
    apiEnterprise = enterpriseFields;
  }

  apiEnterprise['id'] = dbInternationalEnterprise._id.toString();
  copyLocations(dbInternationalEnterprise, apiEnterprise);

  return apiEnterprise;
}

module.exports.transformDBIntlEnterpriseToApiFormatForLanguage = function(dbInternationalEnterprise, language) {
  return transformDbEnterpriseToApiFormatForLanguage(dbInternationalEnterprise, language);
};

module.exports.transformDbEnterprisesToApiFormatForLanguage = function(dbInternationalEnterprises, language) {
  let apiEnterprises = [];
  dbInternationalEnterprises.forEach(
    function(dbInternationalEnterprise) {
      apiEnterprises.push(transformDbEnterpriseToApiFormatForLanguage(dbInternationalEnterprise, language));
    }
  );
  return apiEnterprises;
};

module.exports.transformDbEnterprisesToApiFormat = function(dbEnterprises) {
  let enterprises = [];
  dbEnterprises.forEach(
      function(currentItem) {
        enterprises.push(transformDbEnterprisesToApiFormat(currentItem));
      }
  );
  return enterprises;
};

module.exports.transformDbIntlEnterpriseToApiIntlFormat = function(dbEnterprise) {
  let apiInternationalEnterprise = {};

  apiInternationalEnterprise['id'] = dbEnterprise._id.toString();
  copyLocations(dbEnterprise, apiInternationalEnterprise);
  copyAdminEmails(dbEnterprise, apiInternationalEnterprise);

  SUPPORTED_LANGUAGES.forEach( function(language) {
    if (dbEnterprise[language]) {
      let apiEnterprise = transformDbEnterprisesToApiFormat(dbEnterprise[language]);
      apiInternationalEnterprise[language] = apiEnterprise;
    }
  });
  return apiInternationalEnterprise;
};

// Throws exception on error.
module.exports.transformCompleteEnterpriseToInternationalPublicDBFormat = function(enterprise) {
  let dbInternationalPublicEnterprise = {};
  copyLocations(enterprise, dbInternationalPublicEnterprise);

  SUPPORTED_LANGUAGES.forEach( function(language) {
    if (enterprise[language]) {
      let dbEnterprise = transformCompleteEnterpriseToPublicDBFormat(enterprise[language]);
      dbInternationalPublicEnterprise[language] = dbEnterprise;
    }
  });

  return dbInternationalPublicEnterprise;
};

function transformCompleteEnterpriseToPublicDBFormat(enterprise) {
  let dbPublicEnterprise = {};
  publicFields.forEach( function(field) {
    if (enterprise[field]) {
      dbPublicEnterprise[field] = JSON.parse(JSON.stringify(enterprise[field]));
    }
  });

  // create lower case name field
  dbPublicEnterprise.lowercase_name = dbPublicEnterprise.name.toLowerCase();

  // remove private fields
  ['emails', 'phones', 'faxes', 'addresses'].forEach(field => {
    if (dbPublicEnterprise[field]) {
      dbPublicEnterprise[field] = dbPublicEnterprise[field].filter(value => 'public' in value && value.public);
    }
  });

  return dbPublicEnterprise;
}

// Throws exception on error.
module.exports.transformCompleteEnterpriseToInternationalPrivateDBFormat = function(enterprise) {
  let dbInternationalPrivateEnterprise = {};
  if (enterprise['admin_emails']) {
    dbInternationalPrivateEnterprise['admin_emails'] = enterprise['admin_emails'];
  }

  SUPPORTED_LANGUAGES.forEach( function(language) {
    if (enterprise[language]) {
      let dbPrivateEnterprise = transformCompleteEnterpriseToPrivateDBFormat(enterprise[language]);
      dbInternationalPrivateEnterprise[language] = dbPrivateEnterprise;
    }
  });

  return dbInternationalPrivateEnterprise;
};

function transformCompleteEnterpriseToPrivateDBFormat(enterprise) {

  let dbPrivateEnterprise = {};
  privateFields.forEach( field => {
    if (enterprise[field]) {
      dbPrivateEnterprise[field] = JSON.parse(JSON.stringify(enterprise[field]));
    }
  });

  // remove public fields
  ['emails', 'phones', 'faxes', 'addresses'].forEach(field => {
    if (dbPrivateEnterprise[field]) {
      dbPrivateEnterprise[field] = dbPrivateEnterprise[field].filter(value => 'public' in value && !value.public);
    }
  });

  return dbPrivateEnterprise;
}

module.exports.applyMerge = function(dbEnterprise, mergeRequest) {
  let mergedEnterprise = jsonMergePatch.apply(dbEnterprise, mergeRequest);
  return mergedEnterprise;
};

module.exports.mergePublicAndPrivateDBInfo = function(
                    dbPublicInternationalEnterprise,
                    dbPrivateInternationalEnterprise) {
  let clone = JSON.parse(JSON.stringify(dbPublicInternationalEnterprise));

  internationalPrivateFields.forEach(field => {
    if (SUPPORTED_LANGUAGES.includes(field)) {
      return;
    }
    if (dbPrivateInternationalEnterprise[field] == null) {
      return;
    }
    clone[field] = dbPrivateInternationalEnterprise[field];
  });

  SUPPORTED_LANGUAGES.forEach(lang => {
    privateFields.forEach(field => {
      let value = dbPrivateInternationalEnterprise[lang][field];
      if (value == null) {
        return;
      }
      if (clone[lang][field]) {
        clone[lang][field] = clone[lang][field].concat(value);
      } else {
        clone[lang][field] = value;
      }
    });
  });

  return clone;
};
<commit_msg>add null check<commit_after>const publicFields = require('../data/enterprise.model').enterprisePublicFields;
const privateFields = require('../data/enterprise.model').enterprisePrivateFields;
const internationalPrivateFields = require('../data/enterprise.model').internationalEnterprisePrivateFields;
const SUPPORTED_LANGUAGES = require('../helpers/language/constants').SUPPORTED_LANGUAGES;
const jsonMergePatch = require('json8-merge-patch');

function transformDbEnterprisesToApiFormat(dbEnterprise) {

  // clone the object
  let apiEnterprise = JSON.parse(JSON.stringify(dbEnterprise));

  delete apiEnterprise.lowercase_name;

  // if there was a "score" field due to text index lookup, remove it
  delete apiEnterprise.score;

  // if there was a "distance" field due to location index lookup, remove it
  delete apiEnterprise.dis;

  return apiEnterprise;
}

function copyLocations(source, dest) {
  if (source['locations']) {
    dest['locations'] = source['locations'];
  }
}

function copyAdminEmails(source, dest) {
  if (source['admin_emails']) {
    dest['admin_emails'] = source['admin_emails'];
  }
}

function transformDbEnterpriseToApiFormatForLanguage(dbInternationalEnterprise, language) {
  let apiEnterprise = {};

  if (dbInternationalEnterprise[language]) {
    let enterpriseFields = transformDbEnterprisesToApiFormat(dbInternationalEnterprise[language]);
    apiEnterprise = enterpriseFields;
  }

  apiEnterprise['id'] = dbInternationalEnterprise._id.toString();
  copyLocations(dbInternationalEnterprise, apiEnterprise);

  return apiEnterprise;
}

module.exports.transformDBIntlEnterpriseToApiFormatForLanguage = function(dbInternationalEnterprise, language) {
  return transformDbEnterpriseToApiFormatForLanguage(dbInternationalEnterprise, language);
};

module.exports.transformDbEnterprisesToApiFormatForLanguage = function(dbInternationalEnterprises, language) {
  let apiEnterprises = [];
  dbInternationalEnterprises.forEach(
    function(dbInternationalEnterprise) {
      apiEnterprises.push(transformDbEnterpriseToApiFormatForLanguage(dbInternationalEnterprise, language));
    }
  );
  return apiEnterprises;
};

module.exports.transformDbEnterprisesToApiFormat = function(dbEnterprises) {
  let enterprises = [];
  dbEnterprises.forEach(
      function(currentItem) {
        enterprises.push(transformDbEnterprisesToApiFormat(currentItem));
      }
  );
  return enterprises;
};

module.exports.transformDbIntlEnterpriseToApiIntlFormat = function(dbEnterprise) {
  let apiInternationalEnterprise = {};

  apiInternationalEnterprise['id'] = dbEnterprise._id.toString();
  copyLocations(dbEnterprise, apiInternationalEnterprise);
  copyAdminEmails(dbEnterprise, apiInternationalEnterprise);

  SUPPORTED_LANGUAGES.forEach( function(language) {
    if (dbEnterprise[language]) {
      let apiEnterprise = transformDbEnterprisesToApiFormat(dbEnterprise[language]);
      apiInternationalEnterprise[language] = apiEnterprise;
    }
  });
  return apiInternationalEnterprise;
};

// Throws exception on error.
module.exports.transformCompleteEnterpriseToInternationalPublicDBFormat = function(enterprise) {
  let dbInternationalPublicEnterprise = {};
  copyLocations(enterprise, dbInternationalPublicEnterprise);

  SUPPORTED_LANGUAGES.forEach( function(language) {
    if (enterprise[language]) {
      let dbEnterprise = transformCompleteEnterpriseToPublicDBFormat(enterprise[language]);
      dbInternationalPublicEnterprise[language] = dbEnterprise;
    }
  });

  return dbInternationalPublicEnterprise;
};

function transformCompleteEnterpriseToPublicDBFormat(enterprise) {
  let dbPublicEnterprise = {};
  publicFields.forEach( function(field) {
    if (enterprise[field]) {
      dbPublicEnterprise[field] = JSON.parse(JSON.stringify(enterprise[field]));
    }
  });

  // create lower case name field
  dbPublicEnterprise.lowercase_name = dbPublicEnterprise.name.toLowerCase();

  // remove private fields
  ['emails', 'phones', 'faxes', 'addresses'].forEach(field => {
    if (dbPublicEnterprise[field]) {
      dbPublicEnterprise[field] = dbPublicEnterprise[field].filter(value => 'public' in value && value.public);
    }
  });

  return dbPublicEnterprise;
}

// Throws exception on error.
module.exports.transformCompleteEnterpriseToInternationalPrivateDBFormat = function(enterprise) {
  let dbInternationalPrivateEnterprise = {};
  if (enterprise['admin_emails']) {
    dbInternationalPrivateEnterprise['admin_emails'] = enterprise['admin_emails'];
  }

  SUPPORTED_LANGUAGES.forEach( function(language) {
    if (enterprise[language]) {
      let dbPrivateEnterprise = transformCompleteEnterpriseToPrivateDBFormat(enterprise[language]);
      dbInternationalPrivateEnterprise[language] = dbPrivateEnterprise;
    }
  });

  return dbInternationalPrivateEnterprise;
};

function transformCompleteEnterpriseToPrivateDBFormat(enterprise) {

  let dbPrivateEnterprise = {};
  privateFields.forEach( field => {
    if (enterprise[field]) {
      dbPrivateEnterprise[field] = JSON.parse(JSON.stringify(enterprise[field]));
    }
  });

  // remove public fields
  ['emails', 'phones', 'faxes', 'addresses'].forEach(field => {
    if (dbPrivateEnterprise[field]) {
      dbPrivateEnterprise[field] = dbPrivateEnterprise[field].filter(value => 'public' in value && !value.public);
    }
  });

  return dbPrivateEnterprise;
}

module.exports.applyMerge = function(dbEnterprise, mergeRequest) {
  let mergedEnterprise = jsonMergePatch.apply(dbEnterprise, mergeRequest);
  return mergedEnterprise;
};

module.exports.mergePublicAndPrivateDBInfo = function(
                    dbPublicInternationalEnterprise,
                    dbPrivateInternationalEnterprise) {
  let clone = JSON.parse(JSON.stringify(dbPublicInternationalEnterprise));

  internationalPrivateFields.forEach(field => {
    if (SUPPORTED_LANGUAGES.includes(field)) {
      return;
    }
    if (dbPrivateInternationalEnterprise[field] == null) {
      return;
    }
    clone[field] = dbPrivateInternationalEnterprise[field];
  });

  SUPPORTED_LANGUAGES.forEach(lang => {
    privateFields.forEach(field => {
      if (dbPrivateInternationalEnterprise[lang] == null || dbPrivateInternationalEnterprise[lang][field] == null) {
        return;
      }
      let value = dbPrivateInternationalEnterprise[lang][field];
      if (clone[lang][field]) {
        clone[lang][field] = clone[lang][field].concat(value);
      } else {
        clone[lang][field] = value;
      }
    });
  });

  return clone;
};
<|endoftext|>


<commit_before>/* Timetable for Paris local transport Module */

/* Magic Mirror
 * Module: MMM-Paris-RATP-PG
 *
 * By da4throux
 * based on a script from Georg Peters (https://lane6.de)
 * and a script from Benjamin Angst http://www.beny.ch
 * MIT Licensed.
 */

Module.register("MMM-Paris-RATP-PG",{

  // Define module defaults
  defaults: {
    maximumEntries: 2, // Total Maximum Entries per transport
    maxTimeOffset: 200, // Max time in the future for entries
    useRealtime: true,
    updateInterval: 1 * 60 * 1000, // Update every minute.
    animationSpeed: 2000,
    convertToWaitingTime: true,
    initialLoadDelay: 0, // start delay seconds.
    apiBase: 'https://api-ratp.pierre-grimaud.fr/v2/',
    maxLettersForDestination: 22,
    concatenateArrivals: true,
    showSecondsToNextUpdate: true,
    showLastUpdateTime: false,
    oldUpdateOpacity: 0.5,
    debug: false,
  },

  // Define required scripts.
  getStyles: function() {
    return ["MMM-Paris-RATP-Transport.css", "font-awesome.css"];
  },

  // Define start sequence.
  start: function() {
    Log.info("Starting module: " + this.name);
    this.sendSocketNotification('SET_CONFIG', this.config);
    this.busSchedules = {};
    this.busLastUpdate = {};
    this.loaded = false;
    this.updateTimer = null;
    var self = this;
    setInterval(function () {
      self.updateDom();
    }, 1000);
  },

  getHeader: function () {
    var header = this.data.header;
    if (this.config.showSecondsToNextUpdate) {
      var timeDifference = Math.round((this.config.updateInterval - new Date() + Date.parse(this.config.lastUpdate)) / 1000);
      if (timeDifference > 0) {
        header += ', next update in ' + timeDifference + 's';
      } else {
        header += ', update requested ' + Math.abs(timeDifference) + 's ago';
      }
    }
    if (this.config.showLastUpdateTime) {
      var now = this.config.lastUpdate;
      header += (now ? (' @ ' + now.getHours() + ':' + (now.getMinutes() > 9 ? '' : '0') + now.getMinutes() + ':' + (now.getSeconds() > 9 ? '' : '0') + now.getSeconds()) : '');
    }
    return header;
  },

  // Override dom generator.
  getDom: function() {
    var now = new Date();
    var wrapper = document.createElement("div");

    if (!this.loaded) {
      wrapper.innerHTML = "Loading connections ...";
      wrapper.className = "dimmed light small";
      return wrapper;
    }

    var table = document.createElement("table");
    wrapper.appendChild(table);
    table.className = "small";

    for (var busIndex = 0; busIndex < this.config.busStations.length; busIndex++) {
      var firstLine = true;
      var stop = this.config.busStations[busIndex];
      var stopIndex = stop.line + '/' + stop.stations + '/' + stop.destination;
      var previousRow, previousDestination, previousMessage, row, comingBus;
      var comingBuses = this.busSchedules[stopIndex] || [{message:'N/A', destination: 'N/A'}];
      var comingBusLastUpdate = this.busLastUpdate[stopIndex];
      for (var comingIndex = 0; (comingIndex < this.config.maximumEntries) && (comingIndex < comingBuses.length); comingIndex++) {
        row = document.createElement("tr");
        comingBus = comingBuses[comingIndex];

        var busNameCell = document.createElement("td");
        busNameCell.className = "align-right bright";
        if (firstLine) {
          busNameCell.innerHTML = stop.label || stop.line;
        } else {
          busNameCell.innerHTML = ' ';
        }
        row.appendChild(busNameCell);

        var busDestination = document.createElement("td");
        busDestination.innerHTML = comingBus.destination.substr(0, this.config.maxLettersForDestination);
        busDestination.className = "align-left";
        row.appendChild(busDestination);

        var depCell = document.createElement("td");
        depCell.className = "bright";
        if (!this.busSchedules[stopIndex]) {
          depCell.innerHTML = "N/A ";
        } else {
          if (this.config.convertToWaitingTime && /^\d{1,2}[:][0-5][0-9]$/.test(comingBus.message)) {
            var transportTime = comingBus.message.split(':');
            var endDate = new Date(0, 0, 0, transportTime[0], transportTime[1]);
            var startDate = new Date(0, 0, 0, now.getHours(), now.getMinutes(), now.getSeconds());
            var waitingTime = endDate - startDate;
            if (startDate > endDate) {
              waitingTime += 1000 * 60 * 60 * 24;
            }
            waitingTime = Math.floor(waitingTime / 1000 / 60);
            depCell.innerHTML = waitingTime + ' mn';
          } else {
            depCell.innerHTML = comingBus.message;
          }
        }
        row.appendChild(depCell);
        if ((new Date() - Date.parse(comingBusLastUpdate)) > (this.config.oldUpdateThreshold ? this.config.oldUpdateThreshold : (this.config.updateInterval * 1.1) )) {
          busDestination.style.opacity = this.config.oldUpdateOpacity;
          depCell.style.opacity = this.config.oldUpdateOpacity;
        }
        if (this.config.concatenateArrivals && !firstLine && (comingBus.destination == previousDestination)) {
          previousMessage += ' / ' + comingBus.message;
          previousRow.getElementsByTagName('td')[2].innerHTML = previousMessage;
        } else {
          table.appendChild(row);
          previousRow = row;
          previousMessage = comingBus.message;
          previousDestination = comingBus.destination;
        }
        firstLine = false;
      }
    }
    return wrapper;
  },

  socketNotificationReceived: function(notification, payload) {
    switch (notification) {
      case "BUS":
        this.busSchedules[payload.id] = payload.schedules;
        this.busLastUpdate[payload.id] = payload.lastUpdate;
        this.loaded = true;
        this.updateDom();
        break;
      case "UPDATE":
        this.config.lastUpdate = payload.lastUpdate;
        this.updateDom();
        break;
    }
  }
});
<commit_msg>Update MMM-Paris-RATP-PG.js<commit_after>/* Timetable for Paris local transport Module */

/* Magic Mirror
 * Module: MMM-Paris-RATP-PG
 *
 * By da4throux
 * based on a script from Georg Peters (https://lane6.de)
 * and a script from Benjamin Angst http://www.beny.ch
 * MIT Licensed.
 */

Module.register("MMM-Paris-RATP-PG",{

  // Define module defaults
  defaults: {
    maximumEntries: 2, //if the APIs sends several results for the incoming transport how many should be displayed
    maxTimeOffset: 200, // Max time in the future for entries
    useRealtime: true,
    updateInterval: 1 * 60 * 1000, //time in ms between pulling request for new times (update request)
    animationSpeed: 2000,
    convertToWaitingTime: true, // messages received from API can be 'hh:mm' in that case convert it in the waiting time 'x mn'
    initialLoadDelay: 0, // start delay seconds.
    apiBase: 'https://api-ratp.pierre-grimaud.fr/v2/',
    maxLettersForDestination: 22, //will limit the length of the destination string
    concatenateArrivals: true, //if for a transport there is the same destination and several times, they will be displayed on one line
    showSecondsToNextUpdate: true,  // display a countdown to the next update pull (should I wait for a refresh before going ?)
    showLastUpdateTime: false,  //display the time when the last pulled occured (taste & color...)
    oldUpdateOpacity: 0.5, //when a displayed time age has reached a threshold their display turns darker (i.e. less reliable)
    oldThreshold: 0.1, //if (1+x) of the updateInterval has passed since the last refresh... then the oldUpdateOpacity is applied
    debug: false, //console.log more things to help debugging
  },

  // Define required scripts.
  getStyles: function() {
    return ["MMM-Paris-RATP-Transport.css", "font-awesome.css"];
  },

  // Define start sequence.
  start: function() {
    Log.info("Starting module: " + this.name);
    this.sendSocketNotification('SET_CONFIG', this.config);
    this.busSchedules = {};
    this.busLastUpdate = {};
    this.loaded = false;
    this.updateTimer = null;
    var self = this;
    setInterval(function () {
      self.updateDom();
    }, 1000);
  },

  getHeader: function () {
    var header = this.data.header;
    if (this.config.showSecondsToNextUpdate) {
      var timeDifference = Math.round((this.config.updateInterval - new Date() + Date.parse(this.config.lastUpdate)) / 1000);
      if (timeDifference > 0) {
        header += ', next update in ' + timeDifference + 's';
      } else {
        header += ', update requested ' + Math.abs(timeDifference) + 's ago';
      }
    }
    if (this.config.showLastUpdateTime) {
      var now = this.config.lastUpdate;
      header += (now ? (' @ ' + now.getHours() + ':' + (now.getMinutes() > 9 ? '' : '0') + now.getMinutes() + ':' + (now.getSeconds() > 9 ? '' : '0') + now.getSeconds()) : '');
    }
    return header;
  },

  // Override dom generator.
  getDom: function() {
    var now = new Date();
    var wrapper = document.createElement("div");

    if (!this.loaded) {
      wrapper.innerHTML = "Loading connections ...";
      wrapper.className = "dimmed light small";
      return wrapper;
    }

    var table = document.createElement("table");
    wrapper.appendChild(table);
    table.className = "small";

    for (var busIndex = 0; busIndex < this.config.busStations.length; busIndex++) {
      var firstLine = true;
      var stop = this.config.busStations[busIndex];
      var stopIndex = stop.line + '/' + stop.stations + '/' + stop.destination;
      var previousRow, previousDestination, previousMessage, row, comingBus;
      var comingBuses = this.busSchedules[stopIndex] || [{message:'N/A', destination: 'N/A'}];
      var comingBusLastUpdate = this.busLastUpdate[stopIndex];
      for (var comingIndex = 0; (comingIndex < this.config.maximumEntries) && (comingIndex < comingBuses.length); comingIndex++) {
        row = document.createElement("tr");
        comingBus = comingBuses[comingIndex];

        var busNameCell = document.createElement("td");
        busNameCell.className = "align-right bright";
        if (firstLine) {
          busNameCell.innerHTML = stop.label || stop.line;
        } else {
          busNameCell.innerHTML = ' ';
        }
        row.appendChild(busNameCell);

        var busDestination = document.createElement("td");
        busDestination.innerHTML = comingBus.destination.substr(0, this.config.maxLettersForDestination);
        busDestination.className = "align-left";
        row.appendChild(busDestination);

        var depCell = document.createElement("td");
        depCell.className = "bright";
        if (!this.busSchedules[stopIndex]) {
          depCell.innerHTML = "N/A ";
        } else {
          if (this.config.convertToWaitingTime && /^\d{1,2}[:][0-5][0-9]$/.test(comingBus.message)) {
            var transportTime = comingBus.message.split(':');
            var endDate = new Date(0, 0, 0, transportTime[0], transportTime[1]);
            var startDate = new Date(0, 0, 0, now.getHours(), now.getMinutes(), now.getSeconds());
            var waitingTime = endDate - startDate;
            if (startDate > endDate) {
              waitingTime += 1000 * 60 * 60 * 24;
            }
            waitingTime = Math.floor(waitingTime / 1000 / 60);
            depCell.innerHTML = waitingTime + ' mn';
          } else {
            depCell.innerHTML = comingBus.message;
          }
        }
        row.appendChild(depCell);
        if ((new Date() - Date.parse(comingBusLastUpdate)) > (this.config.oldUpdateThreshold ? this.config.oldUpdateThreshold : (this.config.updateInterval * (1 + this.config.oldThreshold)) )) {
          busDestination.style.opacity = this.config.oldUpdateOpacity;
          depCell.style.opacity = this.config.oldUpdateOpacity;
        }
        if (this.config.concatenateArrivals && !firstLine && (comingBus.destination == previousDestination)) {
          previousMessage += ' / ' + comingBus.message;
          previousRow.getElementsByTagName('td')[2].innerHTML = previousMessage;
        } else {
          table.appendChild(row);
          previousRow = row;
          previousMessage = comingBus.message;
          previousDestination = comingBus.destination;
        }
        firstLine = false;
      }
    }
    return wrapper;
  },

  socketNotificationReceived: function(notification, payload) {
    switch (notification) {
      case "BUS":
        this.busSchedules[payload.id] = payload.schedules;
        this.busLastUpdate[payload.id] = payload.lastUpdate;
        this.loaded = true;
        this.updateDom();
        break;
      case "UPDATE":
        this.config.lastUpdate = payload.lastUpdate;
        this.updateDom();
        break;
    }
  }
});
<|endoftext|>


<commit_before>import './module.js';

angular.module('anol.savesettings')

/**
 * @ngdoc object
 * @name anol.savemanager.SaveManagerServiceProvider
 */
    .provider('SaveSettingsService', [function() {
        var _saveManagerInstance;
        var _saveUrl;
        var _loadUrl;
        var _deleteUrl;
        var _projectName;

        /**
     * @ngdoc method
     * @name setSaveUrl
     * @methodOf anol.savemanager.SaveManagerServiceProvider
     * @param {String} saveUrl url to save changes to. Might be overwritten by layer.saveUrl
     */
        this.setSaveUrl = function(saveUrl) {
            _saveUrl = saveUrl;
        };
        this.setLoadUrl = function(loadUrl) {
            _loadUrl = loadUrl;
        };
        this.setDeleteUrl = function(deleteUrl) {
            _deleteUrl = deleteUrl;
        };
        this.setProjectName = function(projectName) {
            _projectName = projectName;
        };
        this.$get = ['$rootScope', '$q', '$http', '$timeout', '$translate', 'PermalinkService', 'PrintPageService', 'ProjectSettings', 'LayersService',
            function($rootScope, $q, $http, $timeout, $translate, PermalinkService, PrintPageService, ProjectSettings, LayersService) {
                /**
         * @ngdoc service
         * @name anol.savemanager.SaveManagerService
         *
         * @description
         * Collects changes in saveable layers and send them to given saveUrl
         */
                var SaveSettings = function(saveUrl, loadUrl, deleteUrl, projectName) {
                    var self = this;
                    this.saveUrl = saveUrl;
                    this.loadUrl = loadUrl;
                    this.deleteUrl = deleteUrl;
                    this.projectName = projectName;
                    // this.changedLayers = {};
                    // this.changedFeatures = {};
                    var translate = function() {
                        $translate('anol.savemanager.SERVICE_UNAVAILABLE').then(
                            function(translation) {
                                self.serviceUnavailableMessage = translation;
                            });
                    };
                    $rootScope.$on('$translateChangeSuccess', translate);
                    translate();
                };

                SaveSettings.prototype.applySaveSettings = function(data) {
                    if (data.settings.new) {
                        ProjectSettings.push({
                            'id': data.settings.id,
                            'name': data.settings.name
                        });
                    }
                };

                SaveSettings.prototype.applyDeleteSettings = function(data) {
                    var index = -1;
                    angular.forEach(ProjectSettings, function(value, idx) {
                        if (value.id == data.settings.id) {
                            index = idx;
                        }
                    });

                    if (index > -1) {
                        ProjectSettings.splice(index, 1);
                    }
                };

                SaveSettings.prototype.applyLoadSettings = function(settings) {
                    PermalinkService.setPermalinkParameters(settings.map);
                    LayersService.deleteLayers(settings.layerswitcher.deleted);
                    LayersService.setLayerOrder(settings.layerswitcher.order);
                    LayersService.setCollapsedGroups(settings.layerswitcher.open);

                    // save print settings and check if print tab is open
                    PrintPageService.loadSettings(settings);

                    $rootScope.$broadcast('updateSidebar', settings);
                    // load control settings
                    $rootScope.pointMeasureResultSrs = settings.controls.measureSrs;
                };

                SaveSettings.prototype.load = function(id) {
                    var self = this;
                    var deferred = $q.defer();
                    var data = {
                        'id': id
                    };
                    var promise = $http.post(self.loadUrl, data);
                    promise.then(function(response) {
                        self.applyLoadSettings(response.data.settings);
                        deferred.resolve(response.data);
                    }, function(response) {
                        if(response.status === -1) {
                            deferred.reject({'message': self.serviceUnavailableMessage});
                        } else {
                            deferred.reject(response.data);
                        }
                    });

                    return deferred.promise;
                };

                SaveSettings.prototype.save = function(name) {
                    var self = this;
                    var deferred = $q.defer();

                    // save all map settings from permalink
                    var permalinkData = PermalinkService.getSettings();
                    // save all layer settings
                    var layers = LayersService.overLayersAsArray();
                    var deletedLayers = LayersService.deletedOverlayLayers;

                    var groups = LayersService.getCollapsedGroups();
                    // save print settings
                    var printData = PrintPageService.getSettings();
                    // save control settings
                    var controls = {
                        'measureSrs': $rootScope.pointMeasureResultSrs
                    };
                    var data = {
                        'projectName': self.projectName,
                        'name': name,
                        'map': permalinkData,
                        'layerswitcher': {
                            'order': layers,
                            'deleted': deletedLayers,
                            'open': groups
                        },
                        'controls': controls,
                        'print': printData
                    };

                    var promise = $http.post(self.saveUrl, data);
                    promise.then(function(response) {
                        self.applySaveSettings(response.data);
                        deferred.resolve(response.data);
                    }, function(response) {
                        if(response.status === -1) {
                            deferred.reject({'message': self.serviceUnavailableMessage});
                        } else {
                            deferred.reject(response.data);
                        }
                    });

                    return deferred.promise;
                };

                SaveSettings.prototype.delete = function(id) {
                    var self = this;
                    var deferred = $q.defer();
                    var data = {
                        'id': id
                    };
                    var promise = $http.post(self.deleteUrl, data);
                    promise.then(function(response) {
                        self.applyDeleteSettings(response.data);
                        deferred.resolve(response.data);
                    }, function(response) {
                        if(response.status === -1) {
                            deferred.reject({'message': self.serviceUnavailableMessage});
                        } else {
                            deferred.reject(response.data);
                        }
                    });

                    return deferred.promise;
                };

                _saveManagerInstance = new SaveSettings(_saveUrl, _loadUrl, _deleteUrl, _projectName);
                return _saveManagerInstance;
            }];
    }]);<commit_msg>udpate save settings manager to use it without ajax<commit_after>import './module.js';

angular.module('anol.savesettings')

/**
 * @ngdoc object
 * @name anol.savemanager.SaveManagerServiceProvider
 */
    .provider('SaveSettingsService', [function() {
        var _saveManagerInstance;
        var _saveUrl;
        var _loadUrl;
        var _deleteUrl;
        var _projectName;

        /**
     * @ngdoc method
     * @name setSaveUrl
     * @methodOf anol.savemanager.SaveManagerServiceProvider
     * @param {String} saveUrl url to save changes to. Might be overwritten by layer.saveUrl
     */
        this.setSaveUrl = function(saveUrl) {
            _saveUrl = saveUrl;
        };
        this.setLoadUrl = function(loadUrl) {
            _loadUrl = loadUrl;
        };
        this.setDeleteUrl = function(deleteUrl) {
            _deleteUrl = deleteUrl;
        };
        this.setProjectName = function(projectName) {
            _projectName = projectName;
        };
        this.$get = ['$rootScope', '$window', '$q', '$http', '$timeout', '$translate', 'PermalinkService', 'PrintPageService', 'ProjectSettings', 'LayersService',
            function($rootScope, $window, $q, $http, $timeout, $translate, PermalinkService, PrintPageService, ProjectSettings, LayersService) {
                /**
         * @ngdoc service
         * @name anol.savemanager.SaveManagerService
         *
         * @description
         * Collects changes in saveable layers and send them to given saveUrl
         */
                var SaveSettings = function(saveUrl, loadUrl, deleteUrl, projectName) {
                    var self = this;
                    this.saveUrl = saveUrl;
                    this.loadUrl = loadUrl;
                    this.deleteUrl = deleteUrl;
                    this.projectName = projectName;
                    // this.changedLayers = {};
                    // this.changedFeatures = {};
                    var translate = function() {
                        $translate('anol.savemanager.SERVICE_UNAVAILABLE').then(
                            function(translation) {
                                self.serviceUnavailableMessage = translation;
                            });
                    };
                    $rootScope.$on('$translateChangeSuccess', translate);
                    translate();
                };

                SaveSettings.prototype.applySaveSettings = function(data) {
                    if (data.settings.new) {
                        ProjectSettings.push({
                            'id': data.settings.id,
                            'name': data.settings.name
                        });
                    }
                };

                SaveSettings.prototype.applyDeleteSettings = function(data) {
                    var index = -1;
                    angular.forEach(ProjectSettings, function(value, idx) {
                        if (value.id == data.settings.id) {
                            index = idx;
                        }
                    });

                    if (index > -1) {
                        ProjectSettings.splice(index, 1);
                    }
                };

                SaveSettings.prototype.applyLoadSettings = function(settings) {
                    PermalinkService.setPermalinkParameters(settings.map);
                    LayersService.deleteLayers(settings.layerswitcher.deleted);
                    LayersService.setLayerOrder(settings.layerswitcher.order);
                    LayersService.setCollapsedGroups(settings.layerswitcher.open);

                    // save print settings and check if print tab is open
                    PrintPageService.loadSettings(settings);

                    $rootScope.$broadcast('updateSidebar', settings);
                    // load control settings
                    $rootScope.pointMeasureResultSrs = settings.controls.measureSrs;
                };

                SaveSettings.prototype.load = function(id) {
                    var self = this;
                    var deferred = $q.defer();
                    // if ajax is false we use redirect to load page settings
                    var ajax = false;
                    var data = {
                        'id': id,
                        'ajax': false,
                        'project_name': self.projectName
                    };
                    var promise = $http.post(self.loadUrl, data);
                    promise.then(function(response) {
                        if (ajax) {
                            self.applyLoadSettings(response.data.settings);
                        } else {
                            $window.location.href = response.data.redirect;
                        }
                        deferred.resolve(response.data);
                    }, function(response) {
                        if(response.status === -1) {
                            deferred.reject({'message': self.serviceUnavailableMessage});
                        } else {
                            deferred.reject(response.data);
                        }
                    });

                    return deferred.promise;
                };

                SaveSettings.prototype.save = function(name) {
                    var self = this;
                    var deferred = $q.defer();

                    // save all map settings from permalink
                    var permalinkData = PermalinkService.getSettings();
                    // save all layer settings
                    var layers = LayersService.overLayersAsArray();
                    var deletedLayers = LayersService.deletedOverlayLayers;

                    var groups = LayersService.getCollapsedGroups();
                    // save print settings
                    var printData = PrintPageService.getSettings();
                    // save control settings
                    var controls = {
                        'measureSrs': $rootScope.pointMeasureResultSrs
                    };
                    var data = {
                        'projectName': self.projectName,
                        'name': name,
                        'map': permalinkData,
                        'layerswitcher': {
                            'order': layers,
                            'deleted': deletedLayers,
                            'open': groups
                        },
                        'controls': controls,
                        'print': printData
                    };

                    var promise = $http.post(self.saveUrl, data);
                    promise.then(function(response) {
                        self.applySaveSettings(response.data);
                        deferred.resolve(response.data);
                    }, function(response) {
                        if(response.status === -1) {
                            deferred.reject({'message': self.serviceUnavailableMessage});
                        } else {
                            deferred.reject(response.data);
                        }
                    });

                    return deferred.promise;
                };

                SaveSettings.prototype.delete = function(id) {
                    var self = this;
                    var deferred = $q.defer();
                    var data = {
                        'id': id
                    };
                    var promise = $http.post(self.deleteUrl, data);
                    promise.then(function(response) {
                        self.applyDeleteSettings(response.data);
                        deferred.resolve(response.data);
                    }, function(response) {
                        if(response.status === -1) {
                            deferred.reject({'message': self.serviceUnavailableMessage});
                        } else {
                            deferred.reject(response.data);
                        }
                    });

                    return deferred.promise;
                };

                _saveManagerInstance = new SaveSettings(_saveUrl, _loadUrl, _deleteUrl, _projectName);
                return _saveManagerInstance;
            }];
    }]);<|endoftext|>


<commit_before>import { Meteor } from 'meteor/meteor'
import { Roles } from 'meteor/alanning:roles'

import Permissions from '../../framework/Constants/Permissions'
import { checkPermissions } from '../../framework/Functions/Security'

function publisherPermissionsGet ({ projectId, userId }) {
  checkPermissions(projectId, userId)

  const project = Projects.findOne(projectId, {
    fields: {
      'tags._id': 1,
      'tags.name': 1
    }
  })

  let tags = []

  for (let tag of project.tags) {
    const tagPermissions = Roles.getRolesForUser(userId, tag._id)

    if (tagPermissions.length > 0) {
      tags.push({
        _id: tag._id,
        tag: tag.name,
        role: tagPermissions[0]
      })
    } else {
      tags.push({
        _id: tag._id,
        tag: tag.name,
        role: 'none'
      })
    }
  }

  return {
    project: Roles.getRolesForUser(userId, projectId)[0],
    tags: tags
  }
}

// PROJECT

function publisherPermissionsProjectGet ({ projectId, userId }) {
  checkPermissions(projectId, userId)

  return Roles.getRolesForUser(userId, projectId)[0]
}

function publisherPermissionsUpdate ({ projectId, userId }, key, value) {
  checkPermissions(projectId, userId)

  if (Permissions.member.includes(value)) {
    Roles.removeUsersFromRoles(userId, Permissions.member, projectId)
    Roles.setUserRoles(userId, value, projectId)
    return true
  }

  throw new Meteor.Error('Permission type not supported')
}

// TAG

function publisherPermissionsTagsGet ({ projectId, userId, tagId }) {
  checkPermissions(projectId, userId)

  const role = Roles.getRolesForUser(userId, tagId)[0]

  return {
    role: role
  }
}

function publisherPermissionsTagGet ({ projectId, userId, tagId }) {
  checkPermissions(projectId, userId)

  return Roles.getRolesForUser(userId, tagId)[0]
}

function publisherPermissionsTagUpdate ({ projectId, userId, tagId }, key, value) {
  checkPermissions(projectId, userId)

  if (Permissions.participantWithNone.includes(value)) {
    Roles.removeUsersFromRoles(userId, Permissions.participant, tagId)

    if (value !== 'none') {
      Roles.setUserRoles(userId, value, tagId)
    }

    return true
  }

  throw new Meteor.Error('Permission type not supported')
}

export {
  publisherPermissionsGet,
  publisherPermissionsProjectGet,
  publisherPermissionsUpdate,
  publisherPermissionsTagsGet,
  publisherPermissionsTagGet,
  publisherPermissionsTagUpdate
}
<commit_msg>add missing old logic to update the shifts and set the teamleader permissions there; #272<commit_after>import { Meteor } from 'meteor/meteor'
import { Roles } from 'meteor/alanning:roles'
import moment from 'moment'
import Permissions from '../../framework/Constants/Permissions'
import { checkPermissions } from '../../framework/Functions/Security'

function publisherPermissionsGet ({ projectId, userId }) {
  checkPermissions(projectId, userId)

  const project = Projects.findOne(projectId, {
    fields: {
      'tags._id': 1,
      'tags.name': 1
    }
  })

  let tags = []

  for (let tag of project.tags) {
    const tagPermissions = Roles.getRolesForUser(userId, tag._id)

    if (tagPermissions.length > 0) {
      tags.push({
        _id: tag._id,
        tag: tag.name,
        role: tagPermissions[0]
      })
    } else {
      tags.push({
        _id: tag._id,
        tag: tag.name,
        role: 'none'
      })
    }
  }

  return {
    project: Roles.getRolesForUser(userId, projectId)[0],
    tags: tags
  }
}

// PROJECT

function publisherPermissionsProjectGet ({ projectId, userId }) {
  checkPermissions(projectId, userId)

  return Roles.getRolesForUser(userId, projectId)[0]
}

function publisherPermissionsUpdate ({ projectId, userId }, key, value) {
  checkPermissions(projectId, userId)

  if (Permissions.member.includes(value)) {
    Roles.removeUsersFromRoles(userId, Permissions.member, projectId)
    Roles.setUserRoles(userId, value, projectId)
    return true
  }

  throw new Meteor.Error('Permission type not supported')
}

// TAG

function publisherPermissionsTagsGet ({ projectId, userId, tagId }) {
  checkPermissions(projectId, userId)

  const role = Roles.getRolesForUser(userId, tagId)[0]

  return {
    role: role
  }
}

function publisherPermissionsTagGet ({ projectId, userId, tagId }) {
  checkPermissions(projectId, userId)

  return Roles.getRolesForUser(userId, tagId)[0]
}

function publisherPermissionsTagUpdate ({ projectId, userId, tagId }, key, value) {
  checkPermissions(projectId, userId)

  if (Permissions.participantWithNone.includes(value)) {
    Roles.removeUsersFromRoles(userId, Permissions.participant, tagId)

    if (value !== 'none') {
      Roles.setUserRoles(userId, value, tagId)
    }

    let i
    let j
    let k
    let l
    let len
    let len1
    let len2
    let len3
    let len4
    let m
    let ref
    let ref1
    let setSubstituteTeamleader
    let setTeamleader
    let shift
    let shifts
    let team
    let u
    let updatedDeclined
    let updatedParticipants
    let updatedPending
    let user
    let indexOf = [].indexOf
    const permission = value

    let tagPermissions = Permissions.participant

    const project = Projects.findOne({ 'tags._id': tagId }, { fields: { _id: 1 } })

    if (indexOf.call(tagPermissions, permission) >= 0) {
      if (Roles.userIsInRole(userId, tagPermissions, tagId)) {
        Roles.removeUsersFromRoles(userId, tagPermissions, tagId)
        if (permission === 'teamleader') {
          setTeamleader = true
          setSubstituteTeamleader = false
        } else if (permission === 'substituteTeamleader') {
          setTeamleader = false
          setSubstituteTeamleader = true
        } else if (permission === 'participant') {
          setTeamleader = false
          setSubstituteTeamleader = false
        }
        shifts = Shifts.find({
          projectId: project._id,
          tagId: tagId,
          $or: [
            {
              'teams.participants._id': userId
            },
            {
              'teams.pending._id': userId
            },
            {
              'teams.declined._id': userId
            }
          ]
        })

        ref = shifts.fetch()

        for (i = 0, len = ref.length; i < len; i++) {
          shift = ref[i]
          ref1 = shift.teams

          for (j = 0, len1 = ref1.length; j < len1; j++) {
            team = ref1[j]

            if (indexOf.call((function () {
              var k, len2, ref2, results
              ref2 = team.participants
              results = []
              for (k = 0, len2 = ref2.length; k < len2; k++) {
                u = ref2[k]
                results.push(u._id)
              }
              return results
            })(), userId) >= 0) {
              updatedParticipants = team.participants

              for (k = 0, len2 = updatedParticipants.length; k < len2; k++) {
                user = updatedParticipants[k]
                if (!(user._id === userId)) {
                  continue
                }
                user.teamleader = setTeamleader
                user.substituteTeamleader = setSubstituteTeamleader
              }

              Shifts.update({
                _id: shift._id,
                'teams._id': team._id
              }, {
                $set: {
                  'teams.$.participants': updatedParticipants
                }
              })
            }
            if (indexOf.call((function () {
              var l, len3, ref2, results
              ref2 = team.pending
              results = []

              for (l = 0, len3 = ref2.length; l < len3; l++) {
                u = ref2[l]
                results.push(u._id)
              }
              return results
            })(), userId) >= 0) {
              updatedPending = team.pending
              for (l = 0, len3 = updatedPending.length; l < len3; l++) {
                user = updatedPending[l]
                if (!(user._id === userId)) {
                  continue
                }
                user.teamleader = setTeamleader
                user.substituteTeamleader = setSubstituteTeamleader
              }
              Shifts.update({
                _id: shift._id,
                'teams._id': team._id
              }, {
                $set: {
                  'teams.$.pending': updatedPending
                }
              })
            }
            if (indexOf.call((function () {
              var len4, m, ref2, results
              ref2 = team.declined.filter(function (u) {
                return u != null
              })
              results = []
              for (m = 0, len4 = ref2.length; m < len4; m++) {
                u = ref2[m]
                results.push(u._id)
              }
              return results
            })(), userId) >= 0) {
              updatedDeclined = team.participants
              for (m = 0, len4 = updatedDeclined.length; m < len4; m++) {
                user = updatedDeclined[m]
                if (!(user._id === userId)) {
                  continue
                }
                user.teamleader = setTeamleader
                user.substituteTeamleader = setSubstituteTeamleader
              }
              Shifts.update({
                _id: shift._id,
                'teams._id': team._id
              }, {
                $set: {
                  'teams.$.declined': updatedDeclined
                }
              })
            }
          }
        }
      }

      Roles.addUsersToRoles(userId, permission, tagId)
    } else if (permission === 'none') {
      if (Roles.userIsInRole(userId, tagPermissions, tagId)) {
        Roles.removeUsersFromRoles(userId, tagPermissions, tagId)

        Shifts.update({
          projectId: project._id,
          tagId: tagId,
          date: {
            $gt: parseInt(moment(new Date()).format('YYYYDDDD'))
          },
          'teams.participants._id': userId
        }, {
          $pull: {
            'teams.$.participants': {
              _id: userId
            }
          }
        }, {
          multi: true
        })

        Shifts.update({
          projectId: project._id,
          tagId: tagId,
          date: {
            $gt: parseInt(moment(new Date()).format('YYYYDDDD'))
          },
          'teams.pending._id': userId
        }, {
          $pull: {
            'teams.$.pending': {
              _id: userId
            }
          }
        }, {
          multi: true
        })

        Shifts.update({
          projectId: project._id,
          tagId: tagId,
          date: {
            $gt: parseInt(moment(new Date()).format('YYYYDDDD'))
          },
          'teams.declined._id': userId
        }, {
          $pull: {
            'teams.$.declined': {
              _id: userId
            }
          }
        }, {
          multi: true
        })
      }
    } else {
      throw new Meteor.Error(500, 'Role ' + permission + ' invalid')
    }

    return true
  }

  throw new Meteor.Error('Permission type not supported')
}

export {
  publisherPermissionsGet,
  publisherPermissionsProjectGet,
  publisherPermissionsUpdate,
  publisherPermissionsTagsGet,
  publisherPermissionsTagGet,
  publisherPermissionsTagUpdate
}
<|endoftext|>


<commit_before>// = require jquery
// = require jquery_ujs
//= require_tree .
//= require bootstrap
//= require bootstrap-sprockets

$(document).ready(function(){
  $('.dropdown-toggle').dropdown();
});<commit_msg>added tooltip toggle jquery to main application.js.<commit_after>// = require jquery
// = require jquery_ujs
//= require_tree .
//= require bootstrap
//= require bootstrap-sprockets

$(document).ready(function(){
  $('.dropdown-toggle').dropdown();
  $('[data-toggle="tooltip"]').tooltip()
});<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
<commit_msg>Add jquery<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require jquery-ui/effect-highlight
//= require turbolinks
//= require bootstrap-sprockets
//= require editable/bootstrap-editable
//= require editable/rails
//= require_tree .

var activate_editables = function () {
  $('.editable').editable({success: function(response, newValue) {
    if(!response.success) return response.msg; //msg will be shown in editable form
    var vals = response.additionalValues;
    if(vals) {
      $('#total').text(vals.total);
      $('#sum').text(vals.sum);
      $('#buffer').text(vals.buffer);
      $('#actual_sum').text(vals.actual_sum);
      $('#buffer_health').text(vals.buffer_health);
      document.getElementById('buffer_health').className = vals.buffer_health_class;
    }
  }});
}

$(document).ready(activate_editables);
$(document).on('page:load', activate_editables);
<commit_msg>It's too early to abandon jQuery<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require jquery-ui/effect-highlight
//= require turbolinks
//= require bootstrap-sprockets
//= require editable/bootstrap-editable
//= require editable/rails
//= require_tree .

var activate_editables = function () {
  $('.editable').editable({success: function(response, newValue) {
    if(!response.success) return response.msg; //msg will be shown in editable form
    var vals = response.additionalValues;
    if(vals) {
      $('#total').text(vals.total);
      $('#sum').text(vals.sum);
      $('#buffer').text(vals.buffer);
      $('#actual_sum').text(vals.actual_sum);
      $('#buffer_health').text(vals.buffer_health);
      $('#buffer_health').attr('class', vals.buffer_health_class);
    }
  }});
}

$(document).ready(activate_editables);
$(document).on('page:load', activate_editables);
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require jquery.turbolinks
//= require bootstrap/transition
//= require bootstrap/collapse
//= require turbolinks
//= require_tree .
<commit_msg>Enable bootstrap's dropdown<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require jquery.turbolinks
//= require bootstrap/transition
//= require bootstrap/collapse
//= require bootstrap/dropdown
//= require turbolinks
//= require_tree .
<|endoftext|>


<commit_before>//= require jquery

$(function() {
  $('.login-trello').click(function() {
    Trello.authorize({
      type: "redirect",
      name: "Reportrello",
      scope: {
        read: true,
        write: true
      }
    });
  });
})<commit_msg>Add JS to authentication and get user information by token<commit_after>//= require jquery

$(function() {
  $('.login-trello').click(function() {
    Reportrello.authorize();
  });

  Reportrello = {
    authorize: function() {
      var self = this

      Trello.authorize({
        type: 'popup',
        name: 'Reportrello',
        fragment: 'postmessage',
        scope: {
          read: true,
          write: true
        },
        expiration: 'never',
        success: function() {
          self.getMe();
        },
        error: function() {
          alert("Failed authentication");
        }
      });
    },

    getMe: function() {
      var token = localStorage.getItem('trello_token');

      Trello.rest(
        'GET',
        'members/me',
        {
          fields: 'username,fullName,avatar',
          token: token
        },
        function (object) {
          location.href = '/authentication/?user[token]=' + token + '&user[username]=' + object.username + '&user[fullname]=' + object.fullName
        },
        function (a) { alert("Failed authentication"); }
      );
    },

    newReport: function() {

    }
  }
})<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require jquery
//= require jquery_ujs
//= require dataTables/jquery.dataTables
//= require dataTables/bootstrap/3/jquery.dataTables.bootstrap
//= require d3
//= require twitter/bootstrap
//= require kaui/bootstrap-tweaks
//= require kaui/validation
//= require kaui/datatables-tweaks
<commit_msg>Remove unused asset datatables-tweaks<commit_after>// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require jquery
//= require jquery_ujs
//= require dataTables/jquery.dataTables
//= require dataTables/bootstrap/3/jquery.dataTables.bootstrap
//= require d3
//= require twitter/bootstrap
//= require kaui/bootstrap-tweaks
//= require kaui/validation
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
<commit_msg>Enable JavaScript code of bootstrap<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require turbolinks
//= require_tree .
<|endoftext|>


<commit_before>/**
 * Created by Smiley on 27.08.14.
 */

var defaultConfig = {
	ajaxUrl: 'http://gw2location.buildwars.net/',
	channelKey: '',
	cKeySHA1: phpjs.sha1(''),
	lang: 'en',
	worldID: 0,
	regionID: 0,
	ajaxInterval: 5,
	senderInterval: 5,
	receiverInterval: 5,
	statsInterval: 3,
	accname: '',
	guildID: '00000000-0000-0000-0000-000000000000',
	guildName: '',
	guildTag: '',
	colorSelf: '00FFFF',
	colorOnline: '00FF00',
	colorAway: 'FFE000',
	colorAfk: 'FF9000',
	colorOffline: 'FF0000',
	colorCommander: '2966FF',
	colorGuild: 'FF00CC',
	enableSender: true,
	enableReceiver: true
};

var professionIcons = {
	0: 'unknown.png',
	1: 'guardian.png',
	2: 'warrior.png',
	3: 'engineer.png',
	4: 'ranger.png',
	5: 'thief.png',
	6: 'elementalist.png',
	7: 'mesmer.png',
	8: 'necromancer.png'
};

/**
 * Get rid of the message "Refused to get unsafe header X-JSON"
 * https://gist.github.com/codemasher/8373493
 */
Ajax.Response.prototype._getHeaderJSON = Prototype.emptyFunction;

var ajaxRequest = function(url, method, async, params, callback, onLoadingCallback){
	new Ajax.Request(url, {
		method: method || 'get',
		parameters: params || {},
		asynchronous: async !== false,
		requestHeaders: {
			'X-Requested-With': null,
			'X-Prototype-Version': null
		},
		onLoading: onLoadingCallback || Prototype.emptyFunction,
		onSuccess: callback || Prototype.emptyFunction
	});
};

Element.addMethods({
	/**
	 * a counter, bound to an element
	 * just make it more convinient to use
	 *
	 * @param element
	 * @param timestamp
	 * @returns {*}
	 */
	countdown: function(element, timestamp){
		if(!(element = $(element))){
			return;
		}

		new PeriodicalExecuter(function(pe){
			var now = phpjs.time();
			if(timestamp <= now){
				element.update('');
				pe.stop();
			}
			else{
				var end = phpjs.mktime(
					phpjs.date('G', timestamp),
					phpjs.date('i', timestamp),
					phpjs.date('s', timestamp),
					phpjs.date('n', timestamp),
					phpjs.date('j', timestamp),
					phpjs.date('Y', timestamp)
				);
				var diff = end-now;
				var days = Math.floor(diff/(24*3600));
				diff = diff%(24*3600);
				var hours = Math.floor(diff/(60*60));
				diff = diff%(60*60);

				var str = days > 0 ? days+':' : '';
				str += hours > 0 ? phpjs.sprintf('%1$02d', hours)+':' : '';
				str += phpjs.sprintf('%1$02d', Math.floor(diff/60))+':'+phpjs.sprintf('%1$02d', Math.floor(diff%60));

				element.update(str);
			}
		}, 1);

		return element;
	}
});

var OW = {
	dragResize: function(edge){
		overwolf.windows.getCurrentWindow(function(result){
			if(result.status === 'success'){
				overwolf.windows.dragResize(result.window.id, edge);
			}
		});
	},

	dragMove: function(){
		overwolf.windows.getCurrentWindow(function(result){
			if(result.status === 'success'){
				overwolf.windows.dragMove(result.window.id);
			}
		});
	},

	closeWindow: function(){
		overwolf.windows.getCurrentWindow(function(result){
			if(result.status === 'success'){
				overwolf.windows.close(result.window.id);
			}
		});
	},

	openWindow: function(window){
		overwolf.windows.obtainDeclaredWindow(window, function(result){
			if(result.status === 'success'){
				overwolf.windows.restore(result.window.id, function(result){
//					console.log(result);
				});
			}
		});
	},

	getGame: function(callback){
		overwolf.games.getRunningGameInfo(function(result){
			if(result !== null){
				callback(result);
			}
		});
	}
};

var Overlay = Class.create({
	initialize: function(element, options){
		this.element = $(element);
		this.options = {
			containerID: 'overlay-inner',
			containerWidth: 600
		};

		Object.extend(this.options, options || {});

		this.element.setStyle({
			'display': 'none',
			'position': 'absolute',
			'top': '0px',
			'left': '0px',
			'width': '100%',
			'height': '100%',
			'z-index': 99
		});

		this.container = $(this.options.containerID);
		if(!this.container){
			this.container = new Element('div', {
				'id': this.options.containerID
			});
		}

		this.container.setStyle({
			'display': 'none',
			'position': 'fixed',
			'width': this.options.containerWidth+'px',
			'z-index': 100
		});

		this.element.insert(this.container).observe('click', function(event){
			if(event.target === this.element){
				this.hideOverlay();
			}
		}.bind(this));

		window.onresize = function(){
			var viewport = document.viewport.getDimensions();
			var dimensions = document.body.getDimensions();
			this.element.setStyle({
				width: viewport.width+'px',
				height: viewport.height+'px'
			});

			this.container.setStyle({
				'max-height': Math.ceil(viewport.height*0.8)+'px',
				'top': Math.ceil(viewport.height*0.1)+'px',
				'left': Math.ceil((dimensions.width-this.options.containerWidth)/2)+'px'
			});

		}.bind(this);
	},

	maximize: function(){
		var dimensions = document.body.getDimensions();
		var viewport = document.viewport.getDimensions();

		this.element.setStyle({
			width: (viewport.width > dimensions.width ? viewport.width : dimensions.width)+'px',
			height: (viewport.height > dimensions.height ? viewport.height : dimensions.height)+'px'
		});
	},

	showOverlay: function(content){
		var dimensions = this.element.getDimensions();
		var viewport = document.viewport.getDimensions();

		this.maximize();
		this.container.update(content).setStyle({
			'max-height': Math.ceil(viewport.height*0.8)+'px',
			'top': Math.ceil(viewport.height*0.1)+'px',
			'left': Math.ceil((dimensions.width-this.options.containerWidth)/2)+'px'
		});

		if(this.element.getStyle('display') === 'none'){
			Effect.Appear(this.element);
		}

		Effect.Appear(this.container);
	},

	hideOverlay: function(){
		Effect.Fade(this.container);
		Effect.Fade(this.element);
		this.container.update('');
	}

});

var WvW = {
	/**
	 * wvw matchdata refresh
	 */
	refreshMatches: function(){
		var config = localStorage.GW2LocationTracker.evalJSON(true);
		var matchdata = localStorage.GW2LocationWvWMatches.evalJSON(true);
		var now = phpjs.time();

		if(!matchdata.times || now > matchdata.times[2].end || now > matchdata.times[1].end){

			var ajaxCallback = function(request){
				var json = request.responseJSON;
				if(json.wvw_matches.length >= 17){
					// first get the mess in matches.json in the right order
					var matchdata = {
						regions: {
							1: 'NA',
							2: 'EU'
						},
						times: {},
						matches: {
							1: {}, // NA
							2: {}  // EU
						}
					};

					$A(json.wvw_matches).each(function(match){
						var rt = match.wvw_match_id.split('-'); // region/tier

						// add match end times
						if((rt[0] === '1' && rt[1] === '1') || (rt[0] === '2' && rt[1] === '1')){
							matchdata.times[rt[0]] = {
								start: phpjs.strtotime(match.start_time),
								end: phpjs.strtotime(match.end_time)
							};
						}

						var m = {
							green: match.green_world_id,
							blue: match.blue_world_id,
							red: match.red_world_id
						};
						matchdata.matches[rt[0]][rt[1]] = m;

						if(phpjs.in_array(config.worldID, m)){
							localStorage.GW2LocationCurrentWvWMatch = Object.toJSON({
								region: phpjs.intval(rt[0]),
								tier: phpjs.intval(rt[1]),
								match_id: match.wvw_match_id
							});
						}
					});

					// save to local storage
					localStorage.GW2LocationWvWMatches = Object.toJSON(matchdata);
				}
			};

			// we're doing this request synchronous to make sure we have the latest data
			ajaxRequest('https://api.guildwars2.com/v1/wvw/matches.json', 'get', false, {}, ajaxCallback);
		}
	},

	/**
	 * WvW stats parser
	 * https://github.com/codemasher/gw2-wvwstats/blob/master/classes/gw2api.class.php#L208
	 *
	 * @param matchDetails
	 */
	parseStats: function(matchDetails){
		var stats = WvW.statsObject();
		var rt = matchDetails.match_id.split('-');
		var matchdata = localStorage.GW2LocationWvWMatches.evalJSON(true);

		// add some base info
		stats.match.lastupdate = phpjs.time();
		stats.match.id = matchDetails.match_id;
		stats.match.region = phpjs.intval(rt[0]);
		stats.match.tier = phpjs.intval(rt[1]);

		// loop out the maps
		matchDetails.maps.each(function(map){
			['red', 'blue', 'green', 'neutral'].each(function(color, i){

				if(color !== 'neutral'){
					var world_id = matchdata.matches[rt[0]][rt[1]][color];
					var home = ('-'+color+'-home').camelize(); // name to match the maptype in match_details.json
					stats.match.maps[home] = world_id; // possibly redundant
					stats.worlds[color].id = world_id;
					stats.worlds[color].scores[map.type].score = phpjs.intval(map.scores[i]);
				}

				// check for bonuses and push them to their respective array
				map.bonuses.each(function(bonus){
					if(bonus.type === 'bloodlust' && bonus.owner.toLowerCase() === color){
						stats.worlds[color].bonus.bloodlust.push(map.type);
					}
					// other bonuses may come...
				});

				// loop the objectives out and calculate scores
				map.objectives.each(function(objective){
					if(objective.owner.toLowerCase() === color){
						var o = Objectives[objective.id];

						stats.worlds[color].objectives[objective.id] = {
							owner: {
								id: ''
							}
						};

						if(color !== 'neutral'){
							// assign owner guild
							if(objective.owner_guild){
								stats.worlds[color].objectives[objective.id].owner.id = objective.owner_guild;
							}

							// add the objective's score to the income
							stats.worlds[color].scores[map.type].income += o.score;

							// count up the objectives
							['camp', 'castle', 'keep', 'ruin', 'tower'].each(function(objective_type){
								if(o.type === objective_type){
									stats.worlds[color].scores[map.type][objective_type]++;
								}
							});
						}
					}
				});

				// add the income and type to the total scores
				if(color !== 'neutral'){
					['score', 'income', 'camp', 'castle', 'keep', 'tower'].each(function(score_type){
						stats.worlds[color].scores.Total[score_type] += stats.worlds[color].scores[map.type][score_type];
					});
				}

			});
		});
		return stats;
	},

	/**
	 * creates the stats object which holds the scores
	 * https://github.com/codemasher/gw2-wvwstats/blob/master/classes/gw2api.class.php#L302
	 *
	 * @returns object
	 */
	statsObject: function(){
		var obj = {
			match: {
				lastupdate: 0,
				id: '',
				region: 0,
				tier: 0,
				maps: {}
			},
			worlds: {}
		};

		// create base arrays for each color
		['red', 'blue', 'green', 'neutral'].each(function(color){
			// base objective and bonuses arrays
			obj['worlds'][color] = {
				bonus: {
					bloodlust: []
				},
				objectives: {}
			};

			if(color !== 'neutral'){
				obj['worlds'][color]['id'] = 0;
				obj['worlds'][color]['name'] = null;
				obj['worlds'][color]['scores'] = {};

				// create the scores array for each color except neutral
				['RedHome', 'BlueHome', 'GreenHome', 'Center', 'Total'].each(function(type){
					obj['worlds'][color]['scores'][type] = {
						score: 0,
						income: 0,
						camp: 0,
						castle: 0,
						keep: 0,
						ruin: 0,
						tower: 0
					};
				})
			}
		});
		return obj;
	}

};

<commit_msg>fixed https://github.com/codemasher/Overwolf-Locationtracker/issues/4<commit_after>/**
 * Created by Smiley on 27.08.14.
 */

var defaultConfig = {
	ajaxUrl: 'http://gw2location.buildwars.net/',
	channelKey: '',
	cKeySHA1: phpjs.sha1(''),
	lang: 'en',
	worldID: 0,
	regionID: 0,
	ajaxInterval: 5,
	senderInterval: 5,
	receiverInterval: 5,
	statsInterval: 3,
	accname: '',
	guildID: '00000000-0000-0000-0000-000000000000',
	guildName: '',
	guildTag: '',
	colorSelf: '00FFFF',
	colorOnline: '00FF00',
	colorAway: 'FFE000',
	colorAfk: 'FF9000',
	colorOffline: 'FF0000',
	colorCommander: '2966FF',
	colorGuild: 'FF00CC',
	enableSender: true,
	enableReceiver: true
};

var professionIcons = {
	0: 'unknown.png',
	1: 'guardian.png',
	2: 'warrior.png',
	3: 'engineer.png',
	4: 'ranger.png',
	5: 'thief.png',
	6: 'elementalist.png',
	7: 'mesmer.png',
	8: 'necromancer.png'
};

/**
 * Get rid of the message "Refused to get unsafe header X-JSON"
 * https://gist.github.com/codemasher/8373493
 */
Ajax.Response.prototype._getHeaderJSON = Prototype.emptyFunction;

var ajaxRequest = function(url, method, async, params, callback, onLoadingCallback){
	new Ajax.Request(url, {
		method: method || 'get',
		parameters: params || {},
		asynchronous: async !== false,
		requestHeaders: {
			'X-Requested-With': null,
			'X-Prototype-Version': null
		},
		onLoading: onLoadingCallback || Prototype.emptyFunction,
		onSuccess: callback || Prototype.emptyFunction
	});
};

Element.addMethods({
	/**
	 * a counter, bound to an element
	 * just make it more convinient to use
	 *
	 * @param element
	 * @param timestamp
	 * @returns {*}
	 */
	countdown: function(element, timestamp){
		if(!(element = $(element))){
			return;
		}

		var timer = function(pe){
			var now = phpjs.time();
			if(timestamp <= now){
				pe.stop();
				element.update('');
				element.dataset.timer = 'false';
			}
			else{
				var end = phpjs.mktime(
					phpjs.date('G', timestamp),
					phpjs.date('i', timestamp),
					phpjs.date('s', timestamp),
					phpjs.date('n', timestamp),
					phpjs.date('j', timestamp),
					phpjs.date('Y', timestamp)
				);
				var diff = end-now;
				var days = Math.floor(diff/(24*3600));
				diff = diff%(24*3600);
				var hours = Math.floor(diff/(60*60));
				diff = diff%(60*60);

				var str = days > 0 ? days+':' : '';
				str += hours > 0 ? phpjs.sprintf('%1$02d', hours)+':' : '';
				str += phpjs.sprintf('%1$02d', Math.floor(diff/60))+':'+phpjs.sprintf('%1$02d', Math.floor(diff%60));

				element.update(str);
				element.dataset.timer = 'true';
			}
		};

		if(!element.dataset.timer || element.dataset.timer === 'false'){
			new PeriodicalExecuter(timer, 1);
		}

		return element;
	}
});

var OW = {
	dragResize: function(edge){
		overwolf.windows.getCurrentWindow(function(result){
			if(result.status === 'success'){
				overwolf.windows.dragResize(result.window.id, edge);
			}
		});
	},

	dragMove: function(){
		overwolf.windows.getCurrentWindow(function(result){
			if(result.status === 'success'){
				overwolf.windows.dragMove(result.window.id);
			}
		});
	},

	closeWindow: function(){
		overwolf.windows.getCurrentWindow(function(result){
			if(result.status === 'success'){
				overwolf.windows.close(result.window.id);
			}
		});
	},

	openWindow: function(window){
		overwolf.windows.obtainDeclaredWindow(window, function(result){
			if(result.status === 'success'){
				overwolf.windows.restore(result.window.id, function(result){
//					console.log(result);
				});
			}
		});
	},

	getGame: function(callback){
		overwolf.games.getRunningGameInfo(function(result){
			if(result !== null){
				callback(result);
			}
		});
	}
};

var Overlay = Class.create({
	initialize: function(element, options){
		this.element = $(element);
		this.options = {
			containerID: 'overlay-inner',
			containerWidth: 600
		};

		Object.extend(this.options, options || {});

		this.element.setStyle({
			'display': 'none',
			'position': 'absolute',
			'top': '0px',
			'left': '0px',
			'width': '100%',
			'height': '100%',
			'z-index': 99
		});

		this.container = $(this.options.containerID);
		if(!this.container){
			this.container = new Element('div', {
				'id': this.options.containerID
			});
		}

		this.container.setStyle({
			'display': 'none',
			'position': 'fixed',
			'width': this.options.containerWidth+'px',
			'z-index': 100
		});

		this.element.insert(this.container).observe('click', function(event){
			if(event.target === this.element){
				this.hideOverlay();
			}
		}.bind(this));

		window.onresize = function(){
			var viewport = document.viewport.getDimensions();
			var dimensions = document.body.getDimensions();
			this.element.setStyle({
				width: viewport.width+'px',
				height: viewport.height+'px'
			});

			this.container.setStyle({
				'max-height': Math.ceil(viewport.height*0.8)+'px',
				'top': Math.ceil(viewport.height*0.1)+'px',
				'left': Math.ceil((dimensions.width-this.options.containerWidth)/2)+'px'
			});

		}.bind(this);
	},

	maximize: function(){
		var dimensions = document.body.getDimensions();
		var viewport = document.viewport.getDimensions();

		this.element.setStyle({
			width: (viewport.width > dimensions.width ? viewport.width : dimensions.width)+'px',
			height: (viewport.height > dimensions.height ? viewport.height : dimensions.height)+'px'
		});
	},

	showOverlay: function(content){
		var dimensions = this.element.getDimensions();
		var viewport = document.viewport.getDimensions();

		this.maximize();
		this.container.update(content).setStyle({
			'max-height': Math.ceil(viewport.height*0.8)+'px',
			'top': Math.ceil(viewport.height*0.1)+'px',
			'left': Math.ceil((dimensions.width-this.options.containerWidth)/2)+'px'
		});

		if(this.element.getStyle('display') === 'none'){
			Effect.Appear(this.element);
		}

		Effect.Appear(this.container);
	},

	hideOverlay: function(){
		Effect.Fade(this.container);
		Effect.Fade(this.element);
		this.container.update('');
	}

});

var WvW = {
	/**
	 * wvw matchdata refresh
	 */
	refreshMatches: function(){
		var config = localStorage.GW2LocationTracker.evalJSON(true);
		var matchdata = localStorage.GW2LocationWvWMatches.evalJSON(true);
		var now = phpjs.time();

		if(!matchdata.times || now > matchdata.times[2].end || now > matchdata.times[1].end){

			var ajaxCallback = function(request){
				var json = request.responseJSON;
				if(json.wvw_matches.length >= 17){
					// first get the mess in matches.json in the right order
					var matchdata = {
						regions: {
							1: 'NA',
							2: 'EU'
						},
						times: {},
						matches: {
							1: {}, // NA
							2: {}  // EU
						}
					};

					$A(json.wvw_matches).each(function(match){
						var rt = match.wvw_match_id.split('-'); // region/tier

						// add match end times
						if((rt[0] === '1' && rt[1] === '1') || (rt[0] === '2' && rt[1] === '1')){
							matchdata.times[rt[0]] = {
								start: phpjs.strtotime(match.start_time),
								end: phpjs.strtotime(match.end_time)
							};
						}

						var m = {
							green: match.green_world_id,
							blue: match.blue_world_id,
							red: match.red_world_id
						};
						matchdata.matches[rt[0]][rt[1]] = m;

						if(phpjs.in_array(config.worldID, m)){
							localStorage.GW2LocationCurrentWvWMatch = Object.toJSON({
								region: phpjs.intval(rt[0]),
								tier: phpjs.intval(rt[1]),
								match_id: match.wvw_match_id
							});
						}
					});

					// save to local storage
					localStorage.GW2LocationWvWMatches = Object.toJSON(matchdata);
				}
			};

			// we're doing this request synchronous to make sure we have the latest data
			ajaxRequest('https://api.guildwars2.com/v1/wvw/matches.json', 'get', false, {}, ajaxCallback);
		}
	},

	/**
	 * WvW stats parser
	 * https://github.com/codemasher/gw2-wvwstats/blob/master/classes/gw2api.class.php#L208
	 *
	 * @param matchDetails
	 */
	parseStats: function(matchDetails){
		var stats = WvW.statsObject();
		var rt = matchDetails.match_id.split('-');
		var matchdata = localStorage.GW2LocationWvWMatches.evalJSON(true);

		// add some base info
		stats.match.lastupdate = phpjs.time();
		stats.match.id = matchDetails.match_id;
		stats.match.region = phpjs.intval(rt[0]);
		stats.match.tier = phpjs.intval(rt[1]);

		// loop out the maps
		matchDetails.maps.each(function(map){
			['red', 'blue', 'green', 'neutral'].each(function(color, i){

				if(color !== 'neutral'){
					var world_id = matchdata.matches[rt[0]][rt[1]][color];
					var home = ('-'+color+'-home').camelize(); // name to match the maptype in match_details.json
					stats.match.maps[home] = world_id; // possibly redundant
					stats.worlds[color].id = world_id;
					stats.worlds[color].scores[map.type].score = phpjs.intval(map.scores[i]);
				}

				// check for bonuses and push them to their respective array
				map.bonuses.each(function(bonus){
					if(bonus.type === 'bloodlust' && bonus.owner.toLowerCase() === color){
						stats.worlds[color].bonus.bloodlust.push(map.type);
					}
					// other bonuses may come...
				});

				// loop the objectives out and calculate scores
				map.objectives.each(function(objective){
					if(objective.owner.toLowerCase() === color){
						var o = Objectives[objective.id];

						stats.worlds[color].objectives[objective.id] = {
							owner: {
								id: ''
							}
						};

						if(color !== 'neutral'){
							// assign owner guild
							if(objective.owner_guild){
								stats.worlds[color].objectives[objective.id].owner.id = objective.owner_guild;
							}

							// add the objective's score to the income
							stats.worlds[color].scores[map.type].income += o.score;

							// count up the objectives
							['camp', 'castle', 'keep', 'ruin', 'tower'].each(function(objective_type){
								if(o.type === objective_type){
									stats.worlds[color].scores[map.type][objective_type]++;
								}
							});
						}
					}
				});

				// add the income and type to the total scores
				if(color !== 'neutral'){
					['score', 'income', 'camp', 'castle', 'keep', 'tower'].each(function(score_type){
						stats.worlds[color].scores.Total[score_type] += stats.worlds[color].scores[map.type][score_type];
					});
				}

			});
		});
		return stats;
	},

	/**
	 * creates the stats object which holds the scores
	 * https://github.com/codemasher/gw2-wvwstats/blob/master/classes/gw2api.class.php#L302
	 *
	 * @returns object
	 */
	statsObject: function(){
		var obj = {
			match: {
				lastupdate: 0,
				id: '',
				region: 0,
				tier: 0,
				maps: {}
			},
			worlds: {}
		};

		// create base arrays for each color
		['red', 'blue', 'green', 'neutral'].each(function(color){
			// base objective and bonuses arrays
			obj['worlds'][color] = {
				bonus: {
					bloodlust: []
				},
				objectives: {}
			};

			if(color !== 'neutral'){
				obj['worlds'][color]['id'] = 0;
				obj['worlds'][color]['name'] = null;
				obj['worlds'][color]['scores'] = {};

				// create the scores array for each color except neutral
				['RedHome', 'BlueHome', 'GreenHome', 'Center', 'Total'].each(function(type){
					obj['worlds'][color]['scores'][type] = {
						score: 0,
						income: 0,
						camp: 0,
						castle: 0,
						keep: 0,
						ruin: 0,
						tower: 0
					};
				})
			}
		});
		return obj;
	}

};

<|endoftext|>