<commit_before>'use strict';

const names = [
  [
    // Month: January
    ['Laimnesis','Solvita','Solvija'],
    ['Indulis','Ivo','Iva','Ivis'],
    ['Miervaldis','Miervalda','Ringolds'],
    ['Spodra','Ilva','Ilvita'],
    ['Sīmanis','Zintis'],
    ['Spulga','Arnita'],
    ['Rota','Zigmārs','Juliāns','Digmārs'],
    ['Gatis','Ivanda'],
    ['Kaspars','Aksels','Alta'],
    ['Tatjana','Dorisa'],
    ['Smaida','Franciska'],
    ['Reinis','Reina','Reinholds','Renāts'],
    ['Harijs','Ārijs','Āris','Aira'],
    ['Roberts','Roberta','Raitis','Raits'],
    ['Fēlikss','Felicita'],
    ['Lidija','Lida'],
    ['Tenis','Dravis'],
    ['Antons','Antis','Antonijs'],
    ['Andulis','Alnis'],
    ['Oļģerts','Orests','Aļģirds','Aļģis'],
    ['Agnese','Agnija','Agne'],
    ['Austris'],
    ['Grieta','Strauta','Rebeka'],
    ['Krišs','Ksenija','Eglons','Egle'],
    ['Zigurds','Sigurds','Sigvards'],
    ['Ansis','Agnis','Agneta'],
    ['Ilze','Ildze','Izolde'],
    ['Kārlis','Spodris'],
    ['Aivars','Valērijs','Bille'],
    ['Tīna','Valentīna','Pārsla'],
    ['Tekla','Violeta']
  ],
  [
    // Month: February
    ['Brigita','Indra','Indars','Indris'],
    ['Spīdola','Sonora'],
    ['Aīda','Ida','Vida'],
    ['Daila','Veronika','Dominiks'],
    ['Agate','Selga','Silga','Sinilga'],
    ['Dace','Dārta','Dora'],
    ['Nelda','Rihards','Ričards','Rišards'],
    ['Aldona','Česlavs'],
    ['Simona','Apolonija'],
    ['Paulīne','Paula','Jasmīna'],
    ['Laima','Laimdota'],
    ['Karlīna','Līna'],
    ['Malda','Melita'],
    ['Valentīns'],
    ['Alvils','Olafs','Aloizs','Olavs'],
    ['Jūlija','Džuljeta'],
    ['Donats','Konstance'],
    ['Kora','Kintija'],
    ['Zane','Zuzanna'],
    ['Vitauts','Smuidra','Smuidris'],
    ['Eleonora','Ariadne'],
    ['Ārija','Rigonda','Adrians','Adriāna','Adrija'],
    ['Haralds','Almants'],
    ['Diāna','Dina','Dins'],
    ['Alma','Annemarija'],
    ['Evelīna','Aurēlija','Mētra'],
    ['Līvija','Līva','Andra'],
    ['Skaidrīte','Justs','Skaidra'],
    ['–']
  ],
  [
    // Month: March
    ['Ivars','Ilgvars'],
    ['Lavīze','Luīze','Laila'],
    ['Tālis','Tālavs','Marts'],
    ['Alise','Auce','Enija'],
    ['Austra','Aurora'],
    ['Vents','Centis','Gotfrīds'],
    ['Ella','Elmīra'],
    ['Dagmāra','Marga','Margita'],
    ['Ēvalds'],
    ['Silvija','Laimrota','Liliāna'],
    ['Konstantīns','Agita'],
    ['Aija','Aiva','Aivis'],
    ['Ernests','Balvis'],
    ['Matilde','Ulrika'],
    ['Amilda','Amalda','Imalda'],
    ['Guntis','Guntars','Guntris'],
    ['Ģertrūde','Gerda'],
    ['Ilona','Adelīna'],
    ['Jāzeps','Juzefa'],
    ['Made','Irbe'],
    ['Una','Unigunde','Dzelme','Benedikts','Benedikta'],
    ['Tamāra','Dziedra','Gabriels','Gabriela'],
    ['Mirdza','Žanete','Žanna'],
    ['Kazimirs','Izidors'],
    ['Māra','Mārīte','Marita','Mare','Ģedimins'],
    ['Eiženija','Ženija'],
    ['Gustavs','Gusts','Tālrīts','Saulis'],
    ['Gunta','Ginta','Gunda'],
    ['Aldonis','Agija'],
    ['Nanija','Ilgmārs'],
    ['Gvido','Atvars']
  ],
  [
    // Month: April
    ['Dagnis','Dagne'],
    ['Irmgarde'],
    ['Daira','Dairis','Daiva','Daivis'],
    ['Valda','Herta','Ārvalda','Ārvalds','Ārvaldis'],
    ['Vija','Vidaga','Aivija'],
    ['Zinta','Vīlips','Filips','Dzinta'],
    ['Zina','Zinaīda','Helmuts'],
    ['Edgars','Danute','Dana','Dans'],
    ['Valērija','Žubīte','Alla'],
    ['Anita','Anitra','Zīle','Annika'],
    ['Hermanis','Vilmārs'],
    ['Jūlijs','Ainis'],
    ['Egils','Egīls','Nauris'],
    ['Strauja','Gudrīte'],
    ['Aelita','Gastons'],
    ['Mintauts','Alfs','Bernadeta'],
    ['Rūdolfs','Viviāna','Rūdis'],
    ['Laura','Jadviga'],
    ['Vēsma','Fanija'],
    ['Mirta','Ziedīte'],
    ['Marģers','Anastasija'],
    ['Armands','Armanda'],
    ['Jurģis','Juris','Georgs'],
    ['Visvaldis','Nameda','Ritvaldis','Ritums'],
    ['Līksma','Bārbala'],
    ['Alīna','Sandris','Rūsiņš'],
    ['Tāle','Raimonda','Raina','Klementīne'],
    ['Gundega','Terēze'],
    ['Vilnis','Raimonds','Laine'],
    ['Lilija','Liāna']
  ]
];
<commit_msg>Add - may & jun. names<commit_after>'use strict';

const names = [
  [
    // Month: January
    ['Laimnesis','Solvita','Solvija'],
    ['Indulis','Ivo','Iva','Ivis'],
    ['Miervaldis','Miervalda','Ringolds'],
    ['Spodra','Ilva','Ilvita'],
    ['Sīmanis','Zintis'],
    ['Spulga','Arnita'],
    ['Rota','Zigmārs','Juliāns','Digmārs'],
    ['Gatis','Ivanda'],
    ['Kaspars','Aksels','Alta'],
    ['Tatjana','Dorisa'],
    ['Smaida','Franciska'],
    ['Reinis','Reina','Reinholds','Renāts'],
    ['Harijs','Ārijs','Āris','Aira'],
    ['Roberts','Roberta','Raitis','Raits'],
    ['Fēlikss','Felicita'],
    ['Lidija','Lida'],
    ['Tenis','Dravis'],
    ['Antons','Antis','Antonijs'],
    ['Andulis','Alnis'],
    ['Oļģerts','Orests','Aļģirds','Aļģis'],
    ['Agnese','Agnija','Agne'],
    ['Austris'],
    ['Grieta','Strauta','Rebeka'],
    ['Krišs','Ksenija','Eglons','Egle'],
    ['Zigurds','Sigurds','Sigvards'],
    ['Ansis','Agnis','Agneta'],
    ['Ilze','Ildze','Izolde'],
    ['Kārlis','Spodris'],
    ['Aivars','Valērijs','Bille'],
    ['Tīna','Valentīna','Pārsla'],
    ['Tekla','Violeta']
  ],
  [
    // Month: February
    ['Brigita','Indra','Indars','Indris'],
    ['Spīdola','Sonora'],
    ['Aīda','Ida','Vida'],
    ['Daila','Veronika','Dominiks'],
    ['Agate','Selga','Silga','Sinilga'],
    ['Dace','Dārta','Dora'],
    ['Nelda','Rihards','Ričards','Rišards'],
    ['Aldona','Česlavs'],
    ['Simona','Apolonija'],
    ['Paulīne','Paula','Jasmīna'],
    ['Laima','Laimdota'],
    ['Karlīna','Līna'],
    ['Malda','Melita'],
    ['Valentīns'],
    ['Alvils','Olafs','Aloizs','Olavs'],
    ['Jūlija','Džuljeta'],
    ['Donats','Konstance'],
    ['Kora','Kintija'],
    ['Zane','Zuzanna'],
    ['Vitauts','Smuidra','Smuidris'],
    ['Eleonora','Ariadne'],
    ['Ārija','Rigonda','Adrians','Adriāna','Adrija'],
    ['Haralds','Almants'],
    ['Diāna','Dina','Dins'],
    ['Alma','Annemarija'],
    ['Evelīna','Aurēlija','Mētra'],
    ['Līvija','Līva','Andra'],
    ['Skaidrīte','Justs','Skaidra'],
    ['–']
  ],
  [
    // Month: March
    ['Ivars','Ilgvars'],
    ['Lavīze','Luīze','Laila'],
    ['Tālis','Tālavs','Marts'],
    ['Alise','Auce','Enija'],
    ['Austra','Aurora'],
    ['Vents','Centis','Gotfrīds'],
    ['Ella','Elmīra'],
    ['Dagmāra','Marga','Margita'],
    ['Ēvalds'],
    ['Silvija','Laimrota','Liliāna'],
    ['Konstantīns','Agita'],
    ['Aija','Aiva','Aivis'],
    ['Ernests','Balvis'],
    ['Matilde','Ulrika'],
    ['Amilda','Amalda','Imalda'],
    ['Guntis','Guntars','Guntris'],
    ['Ģertrūde','Gerda'],
    ['Ilona','Adelīna'],
    ['Jāzeps','Juzefa'],
    ['Made','Irbe'],
    ['Una','Unigunde','Dzelme','Benedikts','Benedikta'],
    ['Tamāra','Dziedra','Gabriels','Gabriela'],
    ['Mirdza','Žanete','Žanna'],
    ['Kazimirs','Izidors'],
    ['Māra','Mārīte','Marita','Mare','Ģedimins'],
    ['Eiženija','Ženija'],
    ['Gustavs','Gusts','Tālrīts','Saulis'],
    ['Gunta','Ginta','Gunda'],
    ['Aldonis','Agija'],
    ['Nanija','Ilgmārs'],
    ['Gvido','Atvars']
  ],
  [
    // Month: April
    ['Dagnis','Dagne'],
    ['Irmgarde'],
    ['Daira','Dairis','Daiva','Daivis'],
    ['Valda','Herta','Ārvalda','Ārvalds','Ārvaldis'],
    ['Vija','Vidaga','Aivija'],
    ['Zinta','Vīlips','Filips','Dzinta'],
    ['Zina','Zinaīda','Helmuts'],
    ['Edgars','Danute','Dana','Dans'],
    ['Valērija','Žubīte','Alla'],
    ['Anita','Anitra','Zīle','Annika'],
    ['Hermanis','Vilmārs'],
    ['Jūlijs','Ainis'],
    ['Egils','Egīls','Nauris'],
    ['Strauja','Gudrīte'],
    ['Aelita','Gastons'],
    ['Mintauts','Alfs','Bernadeta'],
    ['Rūdolfs','Viviāna','Rūdis'],
    ['Laura','Jadviga'],
    ['Vēsma','Fanija'],
    ['Mirta','Ziedīte'],
    ['Marģers','Anastasija'],
    ['Armands','Armanda'],
    ['Jurģis','Juris','Georgs'],
    ['Visvaldis','Nameda','Ritvaldis','Ritums'],
    ['Līksma','Bārbala'],
    ['Alīna','Sandris','Rūsiņš'],
    ['Tāle','Raimonda','Raina','Klementīne'],
    ['Gundega','Terēze'],
    ['Vilnis','Raimonds','Laine'],
    ['Lilija','Liāna']
  ],
  [
    // Month: May
    ['Ziedonis'],
    ['Zigmunds','Sigmunds','Zigismunds'],
    ['Gints','Uvis'],
    ['Vizbulīte','Viola','Vijolīte'],
    ['Ģirts','Ģederts'],
    ['Gaidis','Didzis'],
    ['Henriete','Henrijs','Jete','Enriko'],
    ['Staņislavs','Staņislava','Stefānija'],
    ['Klāvs','Einārs','Ervīns'],
    ['Maija','Paija'],
    ['Milda','Karmena','Manfreds'],
    ['Valija','Ināra','Ina','Inārs'],
    ['Irēna','Irīna','Ira','Iraīda'],
    ['Krišjānis','Elfa','Aivita','Elvita'],
    ['Sofija','Taiga','Airita','Arita'],
    ['Edvīns','Edijs'],
    ['Herberts','Dailis','Umberts'],
    ['Inese','Inesis','Ēriks'],
    ['Lita','Sibilla','Teika'],
    ['Venta','Salvis','Selva'],
    ['Ernestīne','Ingmārs','Akvelīna'],
    ['Emīlija'],
    ['Leontīne','Leokādija','Lonija','Ligija'],
    ['Ilvija','Marlēna','Ziedone'],
    ['Anšlavs','Junora'],
    ['Edvards','Edvarts','Eduards','Varis'],
    ['Dzidra','Gunita','Loreta','Dzidris'],
    ['Vilis','Vilhelms'],
    ['Maksis','Maksims','Raivis','Raivo'],
    ['Vitolds','Lolita','Letīcija'],
    ['Alīda','Jūsma']
  ],
  [
    // Month: June
    ['Biruta','Mairita','Bernedīne'],
    ['Lība','Emma'],
    ['Inta','Ineta','Intra'],
    ['Elfrīda','Sintija','Sindija'],
    ['Igors','Margots','Ingvars'],
    ['Ingrīda','Ardis'],
    ['Gaida','Arnis','Arno'],
    ['Frīdis','Frīda','Mundra'],
    ['Ligita','Gita'],
    ['Malva','Anatols','Anatolijs'],
    ['Ingus','Mairis','Vidvuds'],
    ['Nora','Lenora','Ija'],
    ['Zigfrīds','Ainārs','Uva'],
    ['Tija','Saiva','Sentis','Santis','Saivis'],
    ['Baņuta','Žermēna','Vilija','Vits'],
    ['Justīne','Juta'],
    ['Artūrs','Artis'],
    ['Alberts','Madis'],
    ['Viktors','Nils'],
    ['Rasma','Rasa','Maira'],
    ['Emīls','Egita','Monvīds'],
    ['Ludmila','Laimdots','Laimiņš'],
    ['Līga'],
    ['Jānis'],
    ['Milija','Maiga'],
    ['Ausma','Inguna','Ingūna','Inguns','Ausmis'],
    ['Malvīne','Malvis'],
    ['Viesturs','Kitija','Viestards'],
    ['Pēteris','Pāvils','Pauls','Paulis'],
    ['Tālivaldis','Mareks']
  ]
];
<|endoftext|>


<commit_before>var define, requireModule, require, requirejs;

(function() {

  var _isArray;
  if (!Array.isArray) {
    _isArray = function (x) {
      return Object.prototype.toString.call(x) === "[object Array]";
    };
  } else {
    _isArray = Array.isArray;
  }

  var registry = {}, seen = {};
  var FAILED = false;

  var uuid = 0;

  function Module(name, deps, callback, exports) {
    var defaultDeps = ['require', 'exports', 'module'];

    this.id       = uuid++;
    this.name     = name;
    this.deps     = !deps.length && callback.length ? defaultDeps : deps;
    this.exports  = exports || { };
    this.callback = callback;
    this.state    = undefined;
  }

  define = function(name, deps, callback) {
    if (!Array.isArray(deps)) {
      callback = deps;
      deps     =  [];
    }

    registry[name] = new Module(name, deps, callback);
  };

  define.amd = {};

  function reify(mod, name, seen) {
    var deps = mod.deps;
    var length = deps.length;
    var reified = new Array(length);
    var dep;
    // TODO: new Module
    // TODO: seen refactor
    var module = { };

    for (var i = 0, l = length; i < l; i++) {
      dep = deps[i];
      if (dep === 'exports') {
        module.exports = reified[i] = seen;
      } else if (dep === 'require') {
        reified[i] = require;
      } else if (dep === 'module') {
        mod.exports = seen;
        module = reified[i] = mod;
      } else {
        reified[i] = require(resolve(dep, name));
      }
    }

    return {
      deps: reified,
      module: module
    };
  }

  requirejs = require = requireModule = function(name) {
    var mod = registry[name];
    if (!mod) {
      throw new Error('Could not find module ' + name);
    }

    if (mod.state !== FAILED &&
        seen.hasOwnProperty(name)) {
      return seen[name];
    }

    var reified;
    var module;
    var loaded = false;

    seen[name] = { }; // placeholder for run-time cycles

    try {
      reified = reify(mod, name, seen[name]);
      module = mod.callback.apply(this, reified.deps);
      loaded = true;
    } finally {
      if (!loaded) {
        mod.state = FAILED;
      }
    }

    if (module === undefined && reified.module.exports) {
      return (seen[name] = reified.module.exports);
    } else {
      return (seen[name] = module);
    }
  };

  function resolve(child, name) {
    if (child.charAt(0) !== '.') { return child; }

    var parts = child.split('/');
    var nameParts = name.split('/');
    var parentBase = nameParts.slice(0, -1);

    for (var i = 0, l = parts.length; i < l; i++) {
      var part = parts[i];

      if (part === '..') { parentBase.pop(); }
      else if (part === '.') { continue; }
      else { parentBase.push(part); }
    }

    return parentBase.join('/');
  }

  requirejs.entries = requirejs._eak_seen = registry;
  requirejs.clear = function(){
    requirejs.entries = requirejs._eak_seen = registry = {};
    seen = state = {};
  };
})();
<commit_msg>Use Array polyfill if needed.<commit_after>var define, requireModule, require, requirejs;

(function() {

  var _isArray;
  if (!Array.isArray) {
    _isArray = function (x) {
      return Object.prototype.toString.call(x) === "[object Array]";
    };
  } else {
    _isArray = Array.isArray;
  }

  var registry = {}, seen = {};
  var FAILED = false;

  var uuid = 0;

  function Module(name, deps, callback, exports) {
    var defaultDeps = ['require', 'exports', 'module'];

    this.id       = uuid++;
    this.name     = name;
    this.deps     = !deps.length && callback.length ? defaultDeps : deps;
    this.exports  = exports || { };
    this.callback = callback;
    this.state    = undefined;
  }

  define = function(name, deps, callback) {
    if (!_isArray(deps)) {
      callback = deps;
      deps     =  [];
    }

    registry[name] = new Module(name, deps, callback);
  };

  define.amd = {};

  function reify(mod, name, seen) {
    var deps = mod.deps;
    var length = deps.length;
    var reified = new Array(length);
    var dep;
    // TODO: new Module
    // TODO: seen refactor
    var module = { };

    for (var i = 0, l = length; i < l; i++) {
      dep = deps[i];
      if (dep === 'exports') {
        module.exports = reified[i] = seen;
      } else if (dep === 'require') {
        reified[i] = require;
      } else if (dep === 'module') {
        mod.exports = seen;
        module = reified[i] = mod;
      } else {
        reified[i] = require(resolve(dep, name));
      }
    }

    return {
      deps: reified,
      module: module
    };
  }

  requirejs = require = requireModule = function(name) {
    var mod = registry[name];
    if (!mod) {
      throw new Error('Could not find module ' + name);
    }

    if (mod.state !== FAILED &&
        seen.hasOwnProperty(name)) {
      return seen[name];
    }

    var reified;
    var module;
    var loaded = false;

    seen[name] = { }; // placeholder for run-time cycles

    try {
      reified = reify(mod, name, seen[name]);
      module = mod.callback.apply(this, reified.deps);
      loaded = true;
    } finally {
      if (!loaded) {
        mod.state = FAILED;
      }
    }

    if (module === undefined && reified.module.exports) {
      return (seen[name] = reified.module.exports);
    } else {
      return (seen[name] = module);
    }
  };

  function resolve(child, name) {
    if (child.charAt(0) !== '.') { return child; }

    var parts = child.split('/');
    var nameParts = name.split('/');
    var parentBase = nameParts.slice(0, -1);

    for (var i = 0, l = parts.length; i < l; i++) {
      var part = parts[i];

      if (part === '..') { parentBase.pop(); }
      else if (part === '.') { continue; }
      else { parentBase.push(part); }
    }

    return parentBase.join('/');
  }

  requirejs.entries = requirejs._eak_seen = registry;
  requirejs.clear = function(){
    requirejs.entries = requirejs._eak_seen = registry = {};
    seen = state = {};
  };
})();
<|endoftext|>


<commit_before>dojo.provide("dijit.form.Select");

dojo.require("dijit.form.AutoCompleter");
//dojo.require("dojo.widget.*");
//dojo.require("dojo.widget.html.stabile");

dojo.declare(
	"dijit.form.Select",
	dijit.form.AutoCompleter,
	{
		/*
		 * summary
		 *	Enhanced version of HTML's <select> tag.
		 *
		 *	Similar features:
		 *	  - There is a drop down list of possible values.
		 *    - You can only enter a value from the drop down list.  (You can't enter an arbitrary value.)
		 *    - The value submitted with the form is the hidden value (ex: CA),
		 *      not the displayed value a.k.a. label (ex: California)
		 *
		 *	Enhancements over plain HTML version:
		 *    - If you type in some text then it will filter down the list of possible values in the drop down list.
		 *    - List can be specified either as a static list or via a javascript function (that can get the list from a server)
		 */

		// labelField: String
		//		The text that actually appears in the drop down
		labelField: "name",

		// labelType: String
		//		"html" or "text"
		labelType: "text",

		// keyField: String
		//		The field of the selected object that the client should send to the server on submit
		keyField: "value",
		//templatePath: dojo.uri.moduleUri("dijit.form", "templates/AutoCompleter.html"),
		_callbackSetLabel: function(/*Object*/ result){
			// summary
			//	Callback function that dynamically sets the label of the AutoCompleter

			if(!result.length){
				this._setLabel("");
			}else{
				this._setLabel(result[0]);
			}
		},
		getState: function(){
			// summary:
			//	Used for saving state of AutoCompleter when navigates to a new
			//	page, in case they then hit the browser's "Back" button.
			var state={};
			state[this.keyField]=this.getValue();
			return state;
		},

		setState: function(/*Object*/ state){
			// summary:
			//	Used for restoring state of AutoCompleter when has navigated to a new
			//	page but then hits browser's "Back" button.
			this.setValue(state[this.keyField]);
		},
		_setTextFieldValue:function(/*String*/ value){
			// do NOT set the text field to the hidden value!
		},
		_setValue:function(/*String*/ value){
			dijit.form.Select.superclass.setValue.apply(this, arguments);
			this.comboBoxSelectionValue.setAttribute("value",value);
		},
		setValue: function(/*String*/ value){
			// summary
			//	Sets the value of the select.
			//	Also sets the label to the corresponding value by reverse lookup.
			this._setValue(value);
			if(/^\s*$/.test(value)){
				var label=[];
				label[this.searchField]="";
				label[this.keyField]=value;
				this._setLabel(label);
				return;
			}
			// Defect #1451: set the label by reverse lookup
			var query={};
			query[this.keyField]=value;
			function find_onError(e){
				console.log("Error trying to find: "+e);
			}
			// do not use case sensitivity for the hidden value
			this.store.fetch({queryIgnoreCase:false, query:query, onComplete:dojo.hitch(this, "_callbackSetLabel"), onError:find_onError});
		},

		_isInputEqualToResult: function(/*Object*/ result){
			var input = this.textInputNode.value;
			var testlabel=this.store.getValue(result, this.searchField);
			if(!this.ignoreCase){
				input = input.toLowerCase();
				testlabel = testlabel.toLowerCase();
			}
			return (input == testlabel);
		},
		_setLabel: function(/*Object*/ item){
			// summary
			//	Users shouldn't call this function; they should be calling setTextValue() instead

			// get the actual label to display
			var textlabel;
			try {
				// throws exception if item not in store (item created by internal processes)
				textlabel=this.store.getValue(item, this.searchField);
			}
			catch(e) {
				// item might have been created by Select (not by store)
				// in this case, use associative array access
				textlabel=item[this.searchField];
			}
			// if custom label function present, call it
			if(this.textInputNode.value!=textlabel&&this.labelFunc){
				textlabel=this.labelFunc(item);
				this.textInputNode.value = textlabel;
			}
		},
		labelFunc: function(/*Object*/ item){
			// summary: Event handler called when the label changes
			// returns the label that the AutoCompleter should display
			return item[this.searchField];
		},
		getState: function(){
			// summary: returns current value and label

			// state variables for Select and AutoCompleter are actually backwards
			// that is why there is code duplication
			var obj={};
			obj[this.keyField]=this.getValue();
			obj[this.searchField]=this.getTextValue();
			return obj;
		},
		_createOption:function(/*Object*/ tr){
			// summary: creates an option to appear on the popup menu

			var td=dijit.form.Select.superclass._createOption.apply(this, arguments);
			if(this.labelType=="html"){
				td.innerHTML=tr[this.labelField];
			}
			td[this.keyField]=tr[this.keyField];
			return td;
		},
		_onKeyUp: function(/*Event*/ evt){
			// summary: internal function
			// Select needs to wait for the complete label before committing to a reverse lookup
			//this.setTextValue(this.textInputNode.value);
		},

		setState: function(/*Object*/ state){
			// summary: internal function to set both value and label
			this.setValue(state[this.keyField]);
		},

		postCreate: function(){
			this.comboBoxSelectionValue = document.createElement('input');
			this.comboBoxSelectionValue.setAttribute("type", "hidden");
			this.comboBoxSelectionValue.setAttribute("tabindex", -1);
			this.comboBoxSelectionValue.setAttribute("name", this.name);
			this.comboBoxSelectionValue.setAttribute("value", "");
			this.comboBoxSelectionValue.setAttribute("dojoAttachPoint","comboBoxSelectionValue");
			this.domNode.appendChild(this.comboBoxSelectionValue);
			dijit.form.Select.superclass.postCreate.apply(this, arguments);
			this.textInputNode.removeAttribute("name");
			//console.log(this.value);
			//this.setValue(this.value);
		},
		_assignHiddenValue:function(/*Object*/ keyValArr, /*DomNode*/ option){
			keyValArr[this.keyField]=option.value;
		},
		_doSelect: function(/*Event*/ tgt){
			this._setValue(tgt[this.keyField]);
			this._setLabel(tgt);
		},

		_isValidOption: function(){
			// deprecated validation
			// using _validateOption now
			var isValidOption = false;
			// this test doesn't work if optionsListNode is empty (page first loaded)
			//var tgt = dojo.html.firstElement(this.optionsListNode); //PORT
			var tgt=this.optionsListNode.firstChild;
			while(!isValidOption && tgt){
				if(this._isInputEqualToResult(tgt)){
					isValidOption = true;
				}else{
					//tgt = dojo.html.nextElement(tgt); //PORT
					tgt=this.optionsListNode.nextSibling;
				}
			}

			return isValidOption;
		},
		getTextValue: function(){
			// summary: returns current label
			return this.textInputNode.value;	// String
		},
		setTextValue:function(/*String*/ label){
			// summary: set the label to the passed label.
			// The hidden value is set by reverse lookup
			var query={};
			query[this.searchField]=label;
			this.store.fetch({queryIgnoreCase:this.ignoreCase, query: query, onComplete:dojo.hitch(this, this._validateOption) });
		},
		_validateOption: function(/*Object*/ ret){
			// summary: callback function.  Checks if user input is valid
			//		after the store checks to see if the user input exists

			// find the user's input in the search results to see if it is valid
			var isValidOption=false;
			for(var i=0; i<ret.length; i++){
				if(this._isInputEqualToResult(ret[i])){
					isValidOption=true;
					// set value by reverse lookup
					this._setValue(this.store.getValue(ret[i], this.keyField));
					this._setLabel(ret[i]);
					break;
				}
			}
			// enforce selection from option list
			if(!isValidOption){
				this.setValue("");
			}

		},

		_checkBlurred: function(){
			if(!this._hasFocus && !this._mouseover_list){
				this._hideResultList();
				// clear the list if the user empties field and moves away. (no need to search)
				if(!this.textInputNode.value.length){
					this.setValue("");
					return;
				}

				// asynchronously validate the user input using store's default search method
				this.setTextValue(this.textInputNode.value);
			}
		}
	}
);
<commit_msg>Refs #2727<commit_after>dojo.provide("dijit.form.Select");

dojo.require("dijit.form.AutoCompleter");
//dojo.require("dojo.widget.*");
//dojo.require("dojo.widget.html.stabile");

dojo.declare(
	"dijit.form.Select",
	dijit.form.AutoCompleter,
	{
		/*
		 * summary
		 *	Enhanced version of HTML's <select> tag.
		 *
		 *	Similar features:
		 *	  - There is a drop down list of possible values.
		 *    - You can only enter a value from the drop down list.  (You can't enter an arbitrary value.)
		 *    - The value submitted with the form is the hidden value (ex: CA),
		 *      not the displayed value a.k.a. label (ex: California)
		 *
		 *	Enhancements over plain HTML version:
		 *    - If you type in some text then it will filter down the list of possible values in the drop down list.
		 *    - List can be specified either as a static list or via a javascript function (that can get the list from a server)
		 */

		// labelField: String
		//		The text that actually appears in the drop down
		labelField: "name",

		// labelType: String
		//		"html" or "text"
		labelType: "text",

		// keyField: String
		//		The field of the selected object that the client should send to the server on submit
		keyField: "value",
		//templatePath: dojo.uri.moduleUri("dijit.form", "templates/AutoCompleter.html"),
		_callbackSetLabel: function(/*Object*/ result){
			// summary
			//	Callback function that dynamically sets the label of the AutoCompleter

			if(!result.length){
				this._setLabel("");
			}else{
				this._setLabel(result[0]);
			}
		},
		getState: function(){
			// summary:
			//	Used for saving state of AutoCompleter when navigates to a new
			//	page, in case they then hit the browser's "Back" button.
			var state={};
			state[this.keyField]=this.getValue();
			return state;
		},

		setState: function(/*Object*/ state){
			// summary:
			//	Used for restoring state of AutoCompleter when has navigated to a new
			//	page but then hits browser's "Back" button.
			this.setValue(state[this.keyField]);
		},
		_setTextFieldValue:function(/*String*/ value){
			// do NOT set the text field to the hidden value!
		},
		_setValue:function(/*String*/ value){
			dijit.form.Select.superclass.setValue.apply(this, arguments);
			this.comboBoxSelectionValue.setAttribute("value",value);
		},
		setValue: function(/*String*/ value){
			// summary
			//	Sets the value of the select.
			//	Also sets the label to the corresponding value by reverse lookup.
			this._setValue(value);
			if(/^\s*$/.test(value)){
				var label=[];
				label[this.searchField]="";
				label[this.keyField]=value;
				this._setLabel(label);
				return;
			}
			// Defect #1451: set the label by reverse lookup
			var query={};
			query[this.keyField]=value;
			function find_onError(e){
				console.log("Error trying to find: "+e);
			}
			// do not use case sensitivity for the hidden value
			this.store.fetch({queryIgnoreCase:false, query:query, onComplete:dojo.hitch(this, "_callbackSetLabel"), onError:find_onError});
		},

		_isInputEqualToResult: function(/*Object*/ result){
			var input = this.textInputNode.value;
			var testlabel=this.store.getValue(result, this.searchField);
			if(!this.ignoreCase){
				input = input.toLowerCase();
				testlabel = testlabel.toLowerCase();
			}
			return (input == testlabel);
		},
		_setLabel: function(/*Object*/ item){
			// summary
			//	Users shouldn't call this function; they should be calling setTextValue() instead

			// get the actual label to display
			var textlabel;
			try {
				// throws exception if item not in store (item created by internal processes)
				textlabel=this.store.getValue(item, this.searchField);
			}
			catch(e) {
				// item might have been created by Select (not by store)
				// in this case, use associative array access
				textlabel=item[this.searchField];
			}
			// if custom label function present, call it
			if(this.textInputNode.value!=textlabel&&this.labelFunc){
				textlabel=this.labelFunc(item);
				this.textInputNode.value = textlabel;
			}
		},
		labelFunc: function(/*Object*/ item){
			// summary: Event handler called when the label changes
			// returns the label that the AutoCompleter should display
			return item[this.searchField];
		},
		getState: function(){
			// summary: returns current value and label

			// state variables for Select and AutoCompleter are actually backwards
			// that is why there is code duplication
			var obj={};
			obj[this.keyField]=this.getValue();
			obj[this.searchField]=this.getTextValue();
			return obj;
		},
		_createOption:function(/*Object*/ tr){
			// summary: creates an option to appear on the popup menu

			var td=dijit.form.Select.superclass._createOption.apply(this, arguments);
			if(this.labelType=="html"){
				td.innerHTML=tr[this.labelField];
			}
			td[this.keyField]=tr[this.keyField];
			return td;
		},
		_onKeyUp: function(/*Event*/ evt){
			// summary: internal function
			// Select needs to wait for the complete label before committing to a reverse lookup
			//this.setTextValue(this.textInputNode.value);
		},

		setState: function(/*Object*/ state){
			// summary: internal function to set both value and label
			this.setValue(state[this.keyField]);
		},

		postCreate: function(){
			this.comboBoxSelectionValue = document.createElement('input');
			this.comboBoxSelectionValue.setAttribute("type", "hidden");
			this.comboBoxSelectionValue.setAttribute("tabindex", -1);
			this.comboBoxSelectionValue.setAttribute("name", this.name);
			this.comboBoxSelectionValue.setAttribute("value", "");
			this.comboBoxSelectionValue.setAttribute("dojoAttachPoint","comboBoxSelectionValue");
			this.domNode.appendChild(this.comboBoxSelectionValue);
			dijit.form.Select.superclass.postCreate.apply(this, arguments);
			this.textInputNode.removeAttribute("name");
			//console.log(this.value);
			//this.setValue(this.value);
		},
		_assignHiddenValue:function(/*Object*/ keyValArr, /*DomNode*/ option){
			keyValArr[this.keyField]=option.value;
		},
		_doSelect: function(/*Event*/ tgt){
			this._setValue(tgt[this.keyField]);
			this._setLabel(tgt);
		},

		_isValidOption: function(){
			// deprecated validation
			// using _validateOption now
			var isValidOption = false;
			// this test doesn't work if optionsListNode is empty (page first loaded)
			var tgt = this.optionsListNode.firstChild;
			while(!isValidOption && tgt){
				if(this._isInputEqualToResult(tgt)){
					isValidOption = true;
				}else{
					tgt=this.optionsListNode.nextSibling;
				}
			}

			return isValidOption;
		},
		getTextValue: function(){
			// summary: returns current label
			return this.textInputNode.value;	// String
		},
		setTextValue:function(/*String*/ label){
			// summary: set the label to the passed label.
			// The hidden value is set by reverse lookup
			var query={};
			query[this.searchField]=label;
			this.store.fetch({queryIgnoreCase:this.ignoreCase, query: query, onComplete:dojo.hitch(this, this._validateOption) });
		},
		_validateOption: function(/*Object*/ ret){
			// summary: callback function.  Checks if user input is valid
			//		after the store checks to see if the user input exists

			// find the user's input in the search results to see if it is valid
			var isValidOption=false;
			for(var i=0; i<ret.length; i++){
				if(this._isInputEqualToResult(ret[i])){
					isValidOption=true;
					// set value by reverse lookup
					this._setValue(this.store.getValue(ret[i], this.keyField));
					this._setLabel(ret[i]);
					break;
				}
			}
			// enforce selection from option list
			if(!isValidOption){
				this.setValue("");
			}

		},

		_checkBlurred: function(){
			if(!this._hasFocus && !this._mouseover_list){
				this._hideResultList();
				// clear the list if the user empties field and moves away. (no need to search)
				if(!this.textInputNode.value.length){
					this.setValue("");
					return;
				}

				// asynchronously validate the user input using store's default search method
				this.setTextValue(this.textInputNode.value);
			}
		}
	}
);
<|endoftext|>


<commit_before>$(start);

function start(){
  technologiesPage();
  setupEvents();
}

function technologiesPage(){
  return $.each([
    "#understanding",
    "#gaIntro",
    "#titles"
  ], function(element, value){
    $(value).show();
  });
}

function setupEvents(){
  var $confident      = $("#confident");
  var $learning       = $("#learning");
  var $intrigued      = $("#intrigued");

  var $confidentTech  = $("#confidentTech");
  var $learningTech   = $("#learningTech");
  var $intriguedTech  = $("#intriguedTech");

  var $titles         = $("#titles");

  $confident.on("click", showConfident);
  $learning.on("click", showLearning);
  $intrigued.on("click", showIntrigued);

  $confidentTech.hide();
  $learningTech.hide();
  $intriguedTech.hide();

  $titles.hide();
}

function showConfident(){
  var $confident      = $("#confident");
  var $learning       = $("#learning");
  var $intrigued      = $("#intrigued");
  var $understanding  = $("#understanding");

  var $confidentTech  = $("#confidentTech");
  var $learningTech   = $("#learningTech");
  var $intriguedTech  = $("#intriguedTech");
  var $gaIntro        = $("#gaIntro");

  var $intriguedTitle = $("#intriguedTitle");
  var $confidentTitle = $("#confidentTitle");
  var $learningTitle  = $("#learningTitle");

  $(this).hide();
  $confident.fadeOut("100", function(){
    $learningTech.hide();
    $intriguedTech.hide();
    $confidentTech.show();

    $learning.show();
    $intrigued.show();

    $intriguedTitle.hide();
    $confidentTitle.show();
    $learningTitle.hide();
  });
}

function showLearning(){
  var $confident      = $("#confident");
  var $learning       = $("#learning");
  var $intrigued      = $("#intrigued");

  var $understanding  = $("#understanding");
  var $confidentTech  = $("#confidentTech");
  var $learningTech   = $("#learningTech");
  var $intriguedTech  = $("#intriguedTech");

  var $intriguedTitle = $("#intriguedTitle");
  var $confidentTitle = $("#confidentTitle");
  var $learningTitle  = $("#learningTitle");

  $(this).hide();
  $learning.fadeOut("100", function(){
    $learningTech.show();
    $intriguedTech.hide();
    $confidentTech.hide();
    $confident.show();
    $intrigued.show();
    $intriguedTitle.hide();
    $confidentTitle.hide();
    $learningTitle.show();
  });
}

function showIntrigued(){
  var $confident      = $("#confident");
  var $learning       = $("#learning");
  var $intrigued      = $("#intrigued");
  var $understanding  = $("#understanding");

  var $confidentTech  = $("#confidentTech");
  var $learningTech   = $("#learningTech");
  var $intriguedTech  = $("#intriguedTech");

  var $intriguedTitle = $("#intriguedTitle");
  var $confidentTitle = $("#confidentTitle");
  var $learningTitle  = $("#learningTitle");

  $(this).hide();
  $intrigued.fadeOut("500", function(){
    $learningTech.hide();
    $intriguedTech.show();
    $confidentTech.hide();
    $confident.show();
    $learning.show();
    $intriguedTitle.show();
    $confidentTitle.hide();
    $learningTitle.hide();
  });
}
<commit_msg>functionality tech page<commit_after>$(start);

function start(){
  technologiesPage();
  setupEvents();
}

function technologiesPage(){
  return $.each([
    "#understanding",
    "#gaIntro",
    "#intriguedTitle",
    "#confidentTitle",
    "#learningTitle"
   ], function(element, value){
    $(value).show();
  });
}

function setupEvents(){
  var $confident      = $("#confident");
  var $learning       = $("#learning");
  var $intrigued      = $("#intrigued");

  var $confidentTech  = $("#confidentTech");
  var $learningTech   = $("#learningTech");
  var $intriguedTech  = $("#intriguedTech");

  var $intriguedTitle = $("#intriguedTitle");
  var $confidentTitle = $("#confidentTitle");
  var $learningTitle  = $("#learningTitle");

  $confident.on("click", showConfident);
  $learning.on("click", showLearning);
  $intrigued.on("click", showIntrigued);

  $confidentTech.hide();
  $learningTech.hide();
  $intriguedTech.hide();

  $intriguedTitle.hide();
  $confidentTitle.hide();
  $learningTitle.hide();
}

function showConfident(){
  var $confident      = $("#confident");
  var $learning       = $("#learning");
  var $intrigued      = $("#intrigued");
  var $understanding  = $("#understanding");

  var $confidentTech  = $("#confidentTech");
  var $learningTech   = $("#learningTech");
  var $intriguedTech  = $("#intriguedTech");

  var $intriguedTitle = $("#intriguedTitle");
  var $confidentTitle = $("#confidentTitle");
  var $learningTitle  = $("#learningTitle");

  $(this).hide();
  $confident.fadeOut("100", function(){
    $learningTech.hide();
    $intriguedTech.hide();
    $confidentTech.show();

    $learning.show();
    $intrigued.show();

    $intriguedTitle.hide();
    $confidentTitle.show();
    $learningTitle.hide();
  });
}

function showLearning(){
  var $confident      = $("#confident");
  var $learning       = $("#learning");
  var $intrigued      = $("#intrigued");

  var $understanding  = $("#understanding");
  var $confidentTech  = $("#confidentTech");
  var $learningTech   = $("#learningTech");
  var $intriguedTech  = $("#intriguedTech");

  var $intriguedTitle = $("#intriguedTitle");
  var $confidentTitle = $("#confidentTitle");
  var $learningTitle  = $("#learningTitle");

  $(this).hide();
  $learning.fadeOut("100", function(){
    $learningTech.show();
    $intriguedTech.hide();
    $confidentTech.hide();
    $confident.show();
    $intrigued.show();
    $intriguedTitle.hide();
    $confidentTitle.hide();
    $learningTitle.show();
  });
}

function showIntrigued(){
  var $confident      = $("#confident");
  var $learning       = $("#learning");
  var $intrigued      = $("#intrigued");
  var $understanding  = $("#understanding");

  var $confidentTech  = $("#confidentTech");
  var $learningTech   = $("#learningTech");
  var $intriguedTech  = $("#intriguedTech");

  var $intriguedTitle = $("#intriguedTitle");
  var $confidentTitle = $("#confidentTitle");
  var $learningTitle  = $("#learningTitle");

  $(this).hide();
  $intrigued.fadeOut("500", function(){
    $learningTech.hide();
    $intriguedTech.show();
    $confidentTech.hide();
    $confident.show();
    $learning.show();
    $intriguedTitle.show();
    $confidentTitle.hide();
    $learningTitle.hide();
  });
}
<|endoftext|>


<commit_before>var request = require('request');

module.exports = function(err, data, finish) {
	var parsed = JSON.parse(data);
	request(parsed.url, function(err, data) {
		finish(err, JSON.parse(data.body));
	});
};<commit_msg>Fix argument<commit_after>var request = require('request');

module.exports = function(argv, data, finish) {
	var parsed = JSON.parse(data);
	request(parsed.url, function(err, data) {
		finish(err, JSON.parse(data.body));
	});
};<|endoftext|>


<commit_before>/*!
  TwentyFive - Minimal Pomodoro HTML5 time tracker
  Xavi Esteve, http://xaviesteve.com/
  Copyright (c) 2014 Xavi Esteve
  @license MIT Licensed
*/

var TF;

; (function (doc, win) {

    'use strict';

    var gId = function (id) {
        return document.getElementById(id);
    }

    var TT = {

        defaultDb: {
            config: {
                cycle: 25 * 60 * 1000, // ms
                status: 'idle', // idle, running,
                currentTask: {
                    start: 0,
                    end: 0,
                    duration: 0, // used on save
                    countdown: 0, // used during countdown, cleared on save
                    title: ''
                }
            },
            tasks: []
        },
        db: null,
        t: 0, // stores the timer instance
        tR: 0, // stores the resting timer instance

        notification: null, // stores the Desktop Browser Notification

        currentDay: null, // stores day for daySeparator
        currentMinute: null, // stores current countdown minute
        lastTaskStart: 0, //

        tinyconOptionsRunning: {
            width: 6,
            height: 9,
            font: '9px helvetica',
            colour: '#ffffff',
            background: '#1abc9c'
        },
        tinyconOptionsEnd: {
            width: 7,
            height: 70,
            font: '7px helvetica',
            colour: '#ffffff',
            background: '#e74c3c'
        },

        monthNames: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],

        /**
         * Displays the specified page and hides the others
         */
        selectView: function (page) {
            doc.body.className = page;

            if (page === 'list') {
                doc.title = 'TwentyFive';
                TT.timeResting();
                TT.tR = window.setInterval(function () { TT.timeResting(); }, 5000);
            } else if (page === 'welcome') {
                doc.title = 'TwentyFive';
            }
        },

        /**
         * Converts miliseconds to m:ss format
         */
        msToTime: function (ms) {
            var s = parseInt(ms / 1000);
            if (s > 3599) {
                var hh, mm, ss;
                hh = Math.floor(s / 3600);
                s %= 3600;
                mm = Math.floor(s / 60),
                    ss = s % 60;
                return hh + ':' + ('0' + mm).slice(-2) + ':' + ('0' + ss).slice(-2);
            } else {
                return parseInt(s / 60) + ':' + ('0' + s % 60).slice(-2);
            }
        },

        /**
         * Converts miliseconds to '8 minutes' format
         */
        niceTime: function (ms) {
            var i = 0,
                s = ms / 1000,
                periods = [
                    { name: "second", length: 1, max: 90 },
                    { name: "minute", length: 60, max: 60 * 90 },
                    { name: "hour", length: 3600, max: 3600 * 32 },
                    { name: "day", length: 86400, max: 86400 * 45 },
                    { name: "month", length: 3600 * 24 * 30, max: 3600 * 24 * 30 * 18 },
                    { name: "year", length: 3600 * 24 * 30 * 12 }
                ],
                result;

            for (; i < periods.length; i++) {
                if (typeof periods[i].max !== 'undefined' && s < periods[i].max) {
                    result = Math.round(s / periods[i].length);
                    result += (result !== 1) ? ' ' + periods[i].name + 's' : ' ' + periods[i].name;
                    return result;
                }
            }
            return '';
        },

        /**
         * User has clicked Start Task, get everything ready and start timer
         */
        startCountdown: function () {
            gId('clock').innerHTML = TT.msToTime(TT.db.config.cycle);

            clearInterval(TT.tR);

            gId('bar').style.width = 0;

            TT.startTimer();
            TT.selectView('countdown');
        },

        /**
         * User clicks Done
         */
        finishCountdown: function () {

            TT.selectView('naming');

            clearInterval(TT.t);

            Tinycon.setBubble('END');
            Tinycon.setOptions(TT.tinyconOptionsEnd);

        },

        /**
         * User clicks Cancel
         */
        cancelCountdown: function () {
            TT.selectView('list');
            TT.resetCountdown();
        },

        /**
         * Common operations when finishing or canceling countdown
         */
        resetCountdown: function () {
            clearInterval(TT.t);
            Tinycon.reset();
            TT.currentMinute = null;
            TT.db.config.status = 'idle';
            TT.saveDatabase();
        },

        /**
         * Create a timer interval instance
         */
        startTimer: function () {

            if (TT.db.config.status != 'running') {
                TT.db.config.currentTask = {
                    start: Date.now(),
                    countdown: TT.db.config.cycle,
                    end: Date.now() + TT.db.config.cycle
                };
            }

            Tinycon.setOptions(TT.tinyconOptionsRunning);

            gId('estimate').innerHTML = TT.timestampToDate(TT.db.config.currentTask.start) + ' - ' + TT.timestampToDate(TT.db.config.currentTask.end);

            TT.timerTick();
            TT.t = window.setInterval(TT.timerTick, 1000);
            TT.db.config.status = 'running';
        },

        /**
         * Take care of refreshing and monitoring
         */
        timerTick: function () {

            var progress = '',
                currentMinute;

            if (parseInt(TT.db.config.currentTask.countdown / 1000) == parseInt((TT.db.config.currentTask.start + TT.db.config.cycle - Date.now()) / 1000)) return false;

            TT.db.config.currentTask.countdown = parseInt(TT.db.config.currentTask.start + TT.db.config.cycle - Date.now());

            if (TT.db.config.currentTask.countdown < 1000 && doc.body.classList.contains('naming')) {
                doc.title = (doc.title.indexOf('Finished') > -1 && TF.audio.loop == true) ? '▉▉▉▉▉▉▉▉▉▉▉▉▉' : '[' + TT.msToTime(Date.now() - TT.db.config.currentTask.start) + '] Finished!';

                // will run only once when timer reaches 0
            } else if (TT.db.config.currentTask.countdown < 1000) {
                TT.selectView('naming');

                if (Notification && Notification.permission === 'default') {
                    Notification.requestPermission(function (permission) {
                        Notification.permission = permission;
                    });
                }

                if (Notification && Notification.permission === 'granted') {
                    TT.notification = new Notification('TwentyFive finished!', {
                        body: 'You have worked for 25 minutes in a task, take a rest.',
                        icon: 'assets/image/apple-touch-icon-72x72.png',
                        tag: 'timerFinished'
                    });
                }

                Tinycon.setBubble('END');
                Tinycon.setOptions(TT.tinyconOptionsEnd);

                doc.body.classList.add('danger');

                win.addEventListener('mousemove', TT.windowFocused);
                win.addEventListener('touchstart', TT.windowFocused);

                if (typeof TT.audio === 'undefined') { TT.audio = new Audio("assets/sound/alert.mp3"); }
                TT.audio.loop = true;
                TT.audio.play();

            } else {

                gId('clock').innerHTML = TT.msToTime(TT.db.config.currentTask.countdown);
                doc.title = '▶ [' + TT.msToTime(TT.db.config.currentTask.countdown) + '] TwentyFive';

                progress = (100 - (TT.db.config.currentTask.countdown / TT.db.config.cycle * 100));
                gId('bar').style.width = progress + '%';
                //gId('bar').innerHTML = Math.round(progress)+'%';
                gId('progress').title = Math.round(progress) + '%';

                // Updates bubble on minute change and not every second
                currentMinute = parseInt(TT.db.config.currentTask.countdown / 60 / 1000);
                if (TT.currentMinute != currentMinute) {
                    TT.currentMinute = currentMinute;
                    Tinycon.setBubble((TT.currentMinute === 0) ? 'O' : TT.currentMinute);
                }
            }

            TT.saveDatabase();
        },

        /**
         * Gets task title and stores the task in the DB
         */
        saveNaming: function () {

            //TT.windowFocused(); // remove if not needed

            TT.db.config.currentTask.title = gId('taskTitle').value;
            TT.db.config.currentTask.end = Date.now();
            TT.db.config.currentTask.duration = TT.db.config.cycle - TT.db.config.currentTask.countdown;
            delete TT.db.config.currentTask.countdown;

            // Add task at the beginning
            TT.db.tasks.unshift(TT.db.config.currentTask);

            TT.resetCountdown();

            TT.refreshList();
            TT.selectView('list');
        },

        /**
         * Reloads the task list
         */
        refreshList: function () {

            var taskListHtml = '',
                namingSuggestions = [],
                namingSuggestionsHtml = '',
                liPadding;

            TT.lastTaskStart = 0;
            if (TT.db.tasks.length === 0) {
                return false;
            }
            for (var i = 0; i < TT.db.tasks.length; i++) {

                if (TT.db.tasks[i].title && namingSuggestions.indexOf(TT.db.tasks[i].title) === -1 && namingSuggestions.length < 5) {
                    namingSuggestions.push(TT.db.tasks[i].title);
                    namingSuggestionsHtml += '
' + TT.db.tasks[i].title + '
';
                }

                liPadding = Math.round(TT.db.tasks[i].duration / 30000);
                liPadding = (liPadding < 30) ? 30 : liPadding;
                liPadding = (liPadding > 100) ? 100 : liPadding;

                taskListHtml +=
                    TT.timeBetween(TT.db.tasks[i].start, TT.db.tasks[i].end) +
                    '
' +
                    '
' + TT.db.tasks[i].title + '
' +
                    '
' +
                    '' + TT.niceTime(TT.db.tasks[i].duration) + '' +
                    TT.timestampToDate(TT.db.tasks[i].start) + ' - ' +
                    TT.timestampToDate(TT.db.tasks[i].end) +
                    '
' +
                    TT.daySeparator(TT.db.tasks[i].start) +
                    '✖' +
                    '
';
            }

            gId('taskList').innerHTML = taskListHtml;
            gId('suggestionList').innerHTML = namingSuggestionsHtml;
        },

        /**
         * Used in the taskList to show the user it is a new day
         * If date passed belongs to a new day it outputs it
         */
        timeBetween: function (start, end) {
            var result,
                padding,
                rest = TT.lastTaskStart - end;

            if (TT.lastTaskStart === 0) {
                result = '';
            } else {
                result = TT.niceTime(rest);
                padding = Math.round(rest / 180000);
                padding = (padding < 0) ? 0 : padding;
                padding = (padding > 100) ? 100 : padding;
            }

            TT.lastTaskStart = start;

            return '
' + result + '
';
        },

        /**
         * Calculates how much time has passed since last task and puts it on top of the list
         */
        timeResting: function () {
            if (TT.db.tasks.length == 0) return;
            gId('timeResting').innerHTML = '
' + TT.niceTime(Date.now() - TT.db.tasks[0].end) + '
';
        },

        /**
         * Used in the taskList to show the user it is a new day
         * If date passed belongs to a new day it outputs it
         */
        daySeparator: function (date) {
            var date = new Date(date);
            if (TT.currentDay != date.getDay()) {
                TT.currentDay = date.getDay();
                return '
' + date.getDate() + ' ' + TT.monthNames[date.getMonth()].substr(0, 3) + '
'
            }
            return '';
        },

        /**
         * User clicked on the ul#taskList
         */
        taskClick: function (e) {
            var data = e.target.dataset;

            // User clicked Delete button
            if (data.action === 'deleteTask') {
                if (!confirm('Do you want to delete this task?')) return false;
                TT.db.tasks.splice(data.id, 1);
                TT.saveDatabase();
                TT.refreshList();
                e.preventDefault();

                // Clicked somewhere else
            } else {
                return false;
            }
        },

        /**
         *
         */
        suggestionClick: function (e) {
            if (e.target.tagName !== 'LI') return;
            gId('taskTitle').value = e.target.innerHTML;
        },

        /**
         * Loads the database, if no database loads default values
         */
        loadDatabase: function () {
            var lsDb = localStorage.getItem('TwentyFive');
            TT.db = (lsDb) ? JSON.parse(lsDb) : TT.defaultDb;
        },

        /**
         * Stores the database in localStorage
         */
        saveDatabase: function () {
            localStorage.setItem('TwentyFive', JSON.stringify(TT.db));
        },

        exportDatabase: function () {
            win.prompt("Copy to clipboard: Ctrl+C, Enter", JSON.stringify(TT.db));
        },

        /**
         * Deletes the database
         */
        clearDatabase: function () {
            if (!confirm('Do you want to reset all data?')) return false;
            localStorage.removeItem('TwentyFive');
            TT.loadDatabase();
            TT.refreshList();
        },

        /**
         * Converts a timestamp to H:MM format
         */
        timestampToDate: function (timestamp) {
            var date = new Date(timestamp);
            return date.getHours() + ':' + ('0' + date.getMinutes()).slice(-2);
        },

        /**
         * When timer has finished an audio loop is started until the user
         * gets back to the window, then this is fired
         */
        windowFocused: function () {
            doc.body.classList.remove('danger');

            win.removeEventListener('mousemove', TT.windowFocused);
            win.removeEventListener('touchstart', TT.windowFocused);

            TT.audio.loop = false;
            TT.audio.pause();
        },

        /**
         * DOM Events
         */
        initEvents: function () {
            // Page Welcome
            gId('startCountdownWelcome').addEventListener('click', TT.startCountdown);

            // Page List
            gId('startCountdown').addEventListener('click', TT.startCountdown);
            gId('exportDatabase').addEventListener('click', TT.exportDatabase);
            gId('clearDatabase').addEventListener('click', TT.clearDatabase);
            gId('taskList').addEventListener('click', TT.taskClick);

            // Page Countdown
            gId('finishCountdown').addEventListener('click', TT.finishCountdown);
            gId('cancelCountdown').addEventListener('click', TT.cancelCountdown);

            // Page Naming
            gId('saveNaming').addEventListener('click', TT.saveNaming);
            gId('cancelNaming').addEventListener('click', TT.cancelCountdown);
            gId('suggestionList').addEventListener('click', TT.suggestionClick);

            // FastClick
            win.addEventListener('load', function () {
                FastClick.attach(doc.body);
            }, false);
        },

        /**
         * Starts app
         */
        init: function () {
            TT.initEvents();
            TT.db = TT.defaultDb;
            TT.loadDatabase();
            TT.refreshList();

            if (TT.db.config.status === 'idle' && TT.db.tasks.length == 0) {
                TT.selectView('welcome');
            } else {
                TT.startCountdown();
            }
        }
    };

    TF = TT;
    TF.init();

}(document, window));
<commit_msg>Autofocus the input field on the "naming" page<commit_after>/*!
  TwentyFive - Minimal Pomodoro HTML5 time tracker
  Xavi Esteve, http://xaviesteve.com/
  Copyright (c) 2014 Xavi Esteve
  @license MIT Licensed
*/

var TF;

; (function (doc, win) {

    'use strict';

    var gId = function (id) {
        return document.getElementById(id);
    }

    var TT = {

        defaultDb: {
            config: {
                cycle: 25 * 60 * 1000, // ms
                status: 'idle', // idle, running,
                currentTask: {
                    start: 0,
                    end: 0,
                    duration: 0, // used on save
                    countdown: 0, // used during countdown, cleared on save
                    title: ''
                }
            },
            tasks: []
        },
        db: null,
        t: 0, // stores the timer instance
        tR: 0, // stores the resting timer instance

        notification: null, // stores the Desktop Browser Notification

        currentDay: null, // stores day for daySeparator
        currentMinute: null, // stores current countdown minute
        lastTaskStart: 0, //

        tinyconOptionsRunning: {
            width: 6,
            height: 9,
            font: '9px helvetica',
            colour: '#ffffff',
            background: '#1abc9c'
        },
        tinyconOptionsEnd: {
            width: 7,
            height: 70,
            font: '7px helvetica',
            colour: '#ffffff',
            background: '#e74c3c'
        },

        monthNames: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],

        /**
         * Displays the specified page and hides the others
         */
        selectView: function (page) {
            doc.body.className = page;

            if (page === 'list') {
                doc.title = 'TwentyFive';
                TT.timeResting();
                TT.tR = window.setInterval(function () { TT.timeResting(); }, 5000);
            } else if (page === 'welcome') {
                doc.title = 'TwentyFive';
            } else if (page == 'naming') {
                var element = gId('taskTitle');
                var past_the_end_pos = element.value.length;
                element.focus();
                element.setSelectionRange(past_the_end_pos, past_the_end_pos);
            }
        },

        /**
         * Converts miliseconds to m:ss format
         */
        msToTime: function (ms) {
            var s = parseInt(ms / 1000);
            if (s > 3599) {
                var hh, mm, ss;
                hh = Math.floor(s / 3600);
                s %= 3600;
                mm = Math.floor(s / 60),
                    ss = s % 60;
                return hh + ':' + ('0' + mm).slice(-2) + ':' + ('0' + ss).slice(-2);
            } else {
                return parseInt(s / 60) + ':' + ('0' + s % 60).slice(-2);
            }
        },

        /**
         * Converts miliseconds to '8 minutes' format
         */
        niceTime: function (ms) {
            var i = 0,
                s = ms / 1000,
                periods = [
                    { name: "second", length: 1, max: 90 },
                    { name: "minute", length: 60, max: 60 * 90 },
                    { name: "hour", length: 3600, max: 3600 * 32 },
                    { name: "day", length: 86400, max: 86400 * 45 },
                    { name: "month", length: 3600 * 24 * 30, max: 3600 * 24 * 30 * 18 },
                    { name: "year", length: 3600 * 24 * 30 * 12 }
                ],
                result;

            for (; i < periods.length; i++) {
                if (typeof periods[i].max !== 'undefined' && s < periods[i].max) {
                    result = Math.round(s / periods[i].length);
                    result += (result !== 1) ? ' ' + periods[i].name + 's' : ' ' + periods[i].name;
                    return result;
                }
            }
            return '';
        },

        /**
         * User has clicked Start Task, get everything ready and start timer
         */
        startCountdown: function () {
            gId('clock').innerHTML = TT.msToTime(TT.db.config.cycle);

            clearInterval(TT.tR);

            gId('bar').style.width = 0;

            TT.startTimer();
            TT.selectView('countdown');
        },

        /**
         * User clicks Done
         */
        finishCountdown: function () {

            TT.selectView('naming');

            clearInterval(TT.t);

            Tinycon.setBubble('END');
            Tinycon.setOptions(TT.tinyconOptionsEnd);

        },

        /**
         * User clicks Cancel
         */
        cancelCountdown: function () {
            TT.selectView('list');
            TT.resetCountdown();
        },

        /**
         * Common operations when finishing or canceling countdown
         */
        resetCountdown: function () {
            clearInterval(TT.t);
            Tinycon.reset();
            TT.currentMinute = null;
            TT.db.config.status = 'idle';
            TT.saveDatabase();
        },

        /**
         * Create a timer interval instance
         */
        startTimer: function () {

            if (TT.db.config.status != 'running') {
                TT.db.config.currentTask = {
                    start: Date.now(),
                    countdown: TT.db.config.cycle,
                    end: Date.now() + TT.db.config.cycle
                };
            }

            Tinycon.setOptions(TT.tinyconOptionsRunning);

            gId('estimate').innerHTML = TT.timestampToDate(TT.db.config.currentTask.start) + ' - ' + TT.timestampToDate(TT.db.config.currentTask.end);

            TT.timerTick();
            TT.t = window.setInterval(TT.timerTick, 1000);
            TT.db.config.status = 'running';
        },

        /**
         * Take care of refreshing and monitoring
         */
        timerTick: function () {

            var progress = '',
                currentMinute;

            if (parseInt(TT.db.config.currentTask.countdown / 1000) == parseInt((TT.db.config.currentTask.start + TT.db.config.cycle - Date.now()) / 1000)) return false;

            TT.db.config.currentTask.countdown = parseInt(TT.db.config.currentTask.start + TT.db.config.cycle - Date.now());

            if (TT.db.config.currentTask.countdown < 1000 && doc.body.classList.contains('naming')) {
                doc.title = (doc.title.indexOf('Finished') > -1 && TF.audio.loop == true) ? '▉▉▉▉▉▉▉▉▉▉▉▉▉' : '[' + TT.msToTime(Date.now() - TT.db.config.currentTask.start) + '] Finished!';

                // will run only once when timer reaches 0
            } else if (TT.db.config.currentTask.countdown < 1000) {
                TT.selectView('naming');

                if (Notification && Notification.permission === 'default') {
                    Notification.requestPermission(function (permission) {
                        Notification.permission = permission;
                    });
                }

                if (Notification && Notification.permission === 'granted') {
                    TT.notification = new Notification('TwentyFive finished!', {
                        body: 'You have worked for 25 minutes in a task, take a rest.',
                        icon: 'assets/image/apple-touch-icon-72x72.png',
                        tag: 'timerFinished'
                    });
                }

                Tinycon.setBubble('END');
                Tinycon.setOptions(TT.tinyconOptionsEnd);

                doc.body.classList.add('danger');

                win.addEventListener('mousemove', TT.windowFocused);
                win.addEventListener('touchstart', TT.windowFocused);

                if (typeof TT.audio === 'undefined') { TT.audio = new Audio("assets/sound/alert.mp3"); }
                TT.audio.loop = true;
                TT.audio.play();

            } else {

                gId('clock').innerHTML = TT.msToTime(TT.db.config.currentTask.countdown);
                doc.title = '▶ [' + TT.msToTime(TT.db.config.currentTask.countdown) + '] TwentyFive';

                progress = (100 - (TT.db.config.currentTask.countdown / TT.db.config.cycle * 100));
                gId('bar').style.width = progress + '%';
                //gId('bar').innerHTML = Math.round(progress)+'%';
                gId('progress').title = Math.round(progress) + '%';

                // Updates bubble on minute change and not every second
                currentMinute = parseInt(TT.db.config.currentTask.countdown / 60 / 1000);
                if (TT.currentMinute != currentMinute) {
                    TT.currentMinute = currentMinute;
                    Tinycon.setBubble((TT.currentMinute === 0) ? 'O' : TT.currentMinute);
                }
            }

            TT.saveDatabase();
        },

        /**
         * Gets task title and stores the task in the DB
         */
        saveNaming: function () {

            //TT.windowFocused(); // remove if not needed

            TT.db.config.currentTask.title = gId('taskTitle').value;
            TT.db.config.currentTask.end = Date.now();
            TT.db.config.currentTask.duration = TT.db.config.cycle - TT.db.config.currentTask.countdown;
            delete TT.db.config.currentTask.countdown;

            // Add task at the beginning
            TT.db.tasks.unshift(TT.db.config.currentTask);

            TT.resetCountdown();

            TT.refreshList();
            TT.selectView('list');
        },

        /**
         * Reloads the task list
         */
        refreshList: function () {

            var taskListHtml = '',
                namingSuggestions = [],
                namingSuggestionsHtml = '',
                liPadding;

            TT.lastTaskStart = 0;
            if (TT.db.tasks.length === 0) {
                return false;
            }
            for (var i = 0; i < TT.db.tasks.length; i++) {

                if (TT.db.tasks[i].title && namingSuggestions.indexOf(TT.db.tasks[i].title) === -1 && namingSuggestions.length < 5) {
                    namingSuggestions.push(TT.db.tasks[i].title);
                    namingSuggestionsHtml += '
' + TT.db.tasks[i].title + '
';
                }

                liPadding = Math.round(TT.db.tasks[i].duration / 30000);
                liPadding = (liPadding < 30) ? 30 : liPadding;
                liPadding = (liPadding > 100) ? 100 : liPadding;

                taskListHtml +=
                    TT.timeBetween(TT.db.tasks[i].start, TT.db.tasks[i].end) +
                    '
' +
                    '
' + TT.db.tasks[i].title + '
' +
                    '
' +
                    '' + TT.niceTime(TT.db.tasks[i].duration) + '' +
                    TT.timestampToDate(TT.db.tasks[i].start) + ' - ' +
                    TT.timestampToDate(TT.db.tasks[i].end) +
                    '
' +
                    TT.daySeparator(TT.db.tasks[i].start) +
                    '✖' +
                    '
';
            }

            gId('taskList').innerHTML = taskListHtml;
            gId('suggestionList').innerHTML = namingSuggestionsHtml;
        },

        /**
         * Used in the taskList to show the user it is a new day
         * If date passed belongs to a new day it outputs it
         */
        timeBetween: function (start, end) {
            var result,
                padding,
                rest = TT.lastTaskStart - end;

            if (TT.lastTaskStart === 0) {
                result = '';
            } else {
                result = TT.niceTime(rest);
                padding = Math.round(rest / 180000);
                padding = (padding < 0) ? 0 : padding;
                padding = (padding > 100) ? 100 : padding;
            }

            TT.lastTaskStart = start;

            return '
' + result + '
';
        },

        /**
         * Calculates how much time has passed since last task and puts it on top of the list
         */
        timeResting: function () {
            if (TT.db.tasks.length == 0) return;
            gId('timeResting').innerHTML = '
' + TT.niceTime(Date.now() - TT.db.tasks[0].end) + '
';
        },

        /**
         * Used in the taskList to show the user it is a new day
         * If date passed belongs to a new day it outputs it
         */
        daySeparator: function (date) {
            var date = new Date(date);
            if (TT.currentDay != date.getDay()) {
                TT.currentDay = date.getDay();
                return '
' + date.getDate() + ' ' + TT.monthNames[date.getMonth()].substr(0, 3) + '
'
            }
            return '';
        },

        /**
         * User clicked on the ul#taskList
         */
        taskClick: function (e) {
            var data = e.target.dataset;

            // User clicked Delete button
            if (data.action === 'deleteTask') {
                if (!confirm('Do you want to delete this task?')) return false;
                TT.db.tasks.splice(data.id, 1);
                TT.saveDatabase();
                TT.refreshList();
                e.preventDefault();

                // Clicked somewhere else
            } else {
                return false;
            }
        },

        /**
         *
         */
        suggestionClick: function (e) {
            if (e.target.tagName !== 'LI') return;
            gId('taskTitle').value = e.target.innerHTML;
        },

        /**
         * Loads the database, if no database loads default values
         */
        loadDatabase: function () {
            var lsDb = localStorage.getItem('TwentyFive');
            TT.db = (lsDb) ? JSON.parse(lsDb) : TT.defaultDb;
        },

        /**
         * Stores the database in localStorage
         */
        saveDatabase: function () {
            localStorage.setItem('TwentyFive', JSON.stringify(TT.db));
        },

        exportDatabase: function () {
            win.prompt("Copy to clipboard: Ctrl+C, Enter", JSON.stringify(TT.db));
        },

        /**
         * Deletes the database
         */
        clearDatabase: function () {
            if (!confirm('Do you want to reset all data?')) return false;
            localStorage.removeItem('TwentyFive');
            TT.loadDatabase();
            TT.refreshList();
        },

        /**
         * Converts a timestamp to H:MM format
         */
        timestampToDate: function (timestamp) {
            var date = new Date(timestamp);
            return date.getHours() + ':' + ('0' + date.getMinutes()).slice(-2);
        },

        /**
         * When timer has finished an audio loop is started until the user
         * gets back to the window, then this is fired
         */
        windowFocused: function () {
            doc.body.classList.remove('danger');

            win.removeEventListener('mousemove', TT.windowFocused);
            win.removeEventListener('touchstart', TT.windowFocused);

            TT.audio.loop = false;
            TT.audio.pause();
        },

        /**
         * DOM Events
         */
        initEvents: function () {
            // Page Welcome
            gId('startCountdownWelcome').addEventListener('click', TT.startCountdown);

            // Page List
            gId('startCountdown').addEventListener('click', TT.startCountdown);
            gId('exportDatabase').addEventListener('click', TT.exportDatabase);
            gId('clearDatabase').addEventListener('click', TT.clearDatabase);
            gId('taskList').addEventListener('click', TT.taskClick);

            // Page Countdown
            gId('finishCountdown').addEventListener('click', TT.finishCountdown);
            gId('cancelCountdown').addEventListener('click', TT.cancelCountdown);

            // Page Naming
            gId('saveNaming').addEventListener('click', TT.saveNaming);
            gId('cancelNaming').addEventListener('click', TT.cancelCountdown);
            gId('suggestionList').addEventListener('click', TT.suggestionClick);

            // FastClick
            win.addEventListener('load', function () {
                FastClick.attach(doc.body);
            }, false);
        },

        /**
         * Starts app
         */
        init: function () {
            TT.initEvents();
            TT.db = TT.defaultDb;
            TT.loadDatabase();
            TT.refreshList();

            if (TT.db.config.status === 'idle' && TT.db.tasks.length == 0) {
                TT.selectView('welcome');
            } else {
                TT.startCountdown();
            }
        }
    };

    TF = TT;
    TF.init();

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


<commit_before>$(function() {
    var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
    smoothScrollingInit();
    typedHeaderInit();
    chartInit();
    form.initialize($("#form"));
    toastr.options.positionClass = "toast-top-center";
    toastr.options.showMethod = 'slideDown';

});

function smoothScrollingInit() {
    $('a[href*="#"]:not([href="#"])').click(function() {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
            if (target.length) {
                $('html, body').animate({
                    scrollTop: target.offset().top
                }, 1000);
                return false;
            }
        }
    });
};

function typedHeaderInit() {
    $("#headername").typed({
        strings: ["Web Developer", "Ninjaneer", "Pizza Lover","I'm ^1000", "Tirthankar Bhattacharjee"],
        typeSpeed: 0,
        preStringTyped: function() {
            $('#headerwrap h3').hide();
            $('#headerwrap h2').hide();
        },
        callback: function() {
            $('#headerwrap h3').fadeIn("slow");
            $('#headerwrap h2').fadeIn("slow");

        }
    });
}

function chartInit() {
    $('canvas').each(function(index, canvas) {
        drawChartForCanvas(canvas);
    });
};

function drawChartForCanvas(canvas) {
    var coverage = parseInt(canvas.dataset.coverage);
    var doughnutData = [{
        value: coverage,
        color: "#1abc9c"
    }, {
        value: 100 - coverage,
        color: "#ecf0f1"
    }];

    var myDoughnut = new Chart(canvas.getContext("2d")).Doughnut(doughnutData);
}
<commit_msg>remove typed-cursor node after complete typing<commit_after>$(function() {
    var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
    smoothScrollingInit();
    typedHeaderInit();
    chartInit();
    form.initialize($("#form"));
    toastr.options.positionClass = "toast-top-center";
    toastr.options.showMethod = 'slideDown';

});

function smoothScrollingInit() {
    $('a[href*="#"]:not([href="#"])').click(function() {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
            if (target.length) {
                $('html, body').animate({
                    scrollTop: target.offset().top
                }, 1000);
                return false;
            }
        }
    });
};

function typedHeaderInit() {
    $("#headername").typed({
        strings: ["Web Developer", "Ninjaneer", "Pizza Lover","I'm ^1000", "Tirthankar Bhattacharjee"],
        typeSpeed: 0,
        preStringTyped: function() {
            $('#headerwrap h3').hide();
            $('#headerwrap h2').hide();
        },
        callback: function() {
            $('#headerwrap h3').fadeIn("slow");
            $('#headerwrap h2').fadeIn("slow");
            $('.typed-cursor').remove();

        }
    });
}

function chartInit() {
    $('canvas').each(function(index, canvas) {
        drawChartForCanvas(canvas);
    });
};

function drawChartForCanvas(canvas) {
    var coverage = parseInt(canvas.dataset.coverage);
    var doughnutData = [{
        value: coverage,
        color: "#1abc9c"
    }, {
        value: 100 - coverage,
        color: "#ecf0f1"
    }];

    var myDoughnut = new Chart(canvas.getContext("2d")).Doughnut(doughnutData);
}
<|endoftext|>


<commit_before>var disableEuCookieComplianceBanner = function() {
    var date = new Date(); date.setTime(date.getTime() + (5*365*24*60*60*1000));
    var expires = "; expires=" + date.toGMTString();
    document.cookie = 'eu-cookie-compliance=true; path=/' + expires;
    $('#eu-cookie-compliance').remove();
};

$(document).ready(function() {
    if (!window.cordova && document.cookie.indexOf('eu-cookie-compliance=true') == -1) {
        $('body').append('
×'+
            gettext('Cookies help us deliver our services. By using our services, you agree to our use of cookies.')+
                    ' '+gettext('More information')+'
');
        $('#eu-cookie-compliance').click(function() {
            disableEuCookieComplianceBanner();
        });
    }
    if (!(cur_net.isAlpha || cur_net.isSegwit) && window.chrome && chrome.app) {
        $('#wallet-create, #wallet-login').click(function(ev) {
            ev.preventDefault();
            try {
                chrome.webstore.install();
            } catch (e) {
                location.href = $('link[rel="chrome-webstore-item"]').attr('href')
            }
        });
    }
});
if (window.cordova) { // outside document.ready for better performance
    $(document).ready(function() {
        $('a.navbar-brand').click(function() {
            localStorage.hasWallet = 'showMain'; // disable redirect for this click
        });
    });
    if (localStorage.hasWallet && path_with_no_lang == '') {
        if (localStorage.hasWallet == 'showMain') {
            // one time redirect disabled above
            localStorage.hasWallet = true;
        } else {
            location.href = '/wallet/';
        }
    }
  }
<commit_msg>Added support for launching the Chrome app from the web page<commit_after>var disableEuCookieComplianceBanner = function() {
    var date = new Date(); date.setTime(date.getTime() + (5*365*24*60*60*1000));
    var expires = "; expires=" + date.toGMTString();
    document.cookie = 'eu-cookie-compliance=true; path=/' + expires;
    $('#eu-cookie-compliance').remove();
};

$(document).ready(function() {
    var appInstalled = false;
    chrome.runtime.sendMessage(
        $('link[rel="chrome-webstore-item"]').attr('href').split('/detail/')[1],
        {greeting: true}, function(response) {
            appInstalled = (response == "GreenAddress installed");
        }
    );

    if (!window.cordova && document.cookie.indexOf('eu-cookie-compliance=true') == -1) {
        $('body').append('
×'+
            gettext('Cookies help us deliver our services. By using our services, you agree to our use of cookies.')+
                    ' '+gettext('More information')+'
');
        $('#eu-cookie-compliance').click(function() {
            disableEuCookieComplianceBanner();
        });
    }
    if (!(cur_net.isAlpha || cur_net.isSegwit) && window.chrome && chrome.app) {
        $('#wallet-create, #wallet-login').click(function(ev) {
            ev.preventDefault();
            if (appInstalled) {
                window.location.href = "/launch_chrome_app/";
                return;
            }
            try {
                chrome.webstore.install();
            } catch (e) {
                location.href = $('link[rel="chrome-webstore-item"]').attr('href')
            }
        });
    }
});
if (window.cordova) { // outside document.ready for better performance
    $(document).ready(function() {
        $('a.navbar-brand').click(function() {
            localStorage.hasWallet = 'showMain'; // disable redirect for this click
        });
    });
    if (localStorage.hasWallet && path_with_no_lang == '') {
        if (localStorage.hasWallet == 'showMain') {
            // one time redirect disabled above
            localStorage.hasWallet = true;
        } else {
            location.href = '/wallet/';
        }
    }
  }
<|endoftext|>


<commit_before>var mongoose = require('mongoose')
var bluebird = require('bluebird')
var Q = require('q')
var RSVP = require('rsvp')
var when = require('when')
var es6Promise = require('es6-promise')
var mongoomise = require('../src/main')
var bench = require('./bench')
var $ = require('lodash')

require('../test/feed')

var Feed = mongoose.model('Feed')
mongoose.connect('mongodb://localhost/mongoomise')

var testFunc = function(item, callback){
	Feed.findOneAsync().then(function(feed){
		feed.text = Math.random().toString()
		return feed.saveAsync()
	}).then(function(doc){
		callback(null, doc)
	})
}

var compareResults = function(results){
	var sl = $.sortBy(results, function(i){
		return i.elapsed
	})
	$.each(sl, function(task){
		console.log('#### task ' + task.name  + ' ####')
		var details = task.cycles + ' cycles, ' + task.elapsed + ' ms, ' +
			(1000*task.cycles/task.elapsed).toFixed(2) + ' ops/sec'
		console.log('  ' + details)
	})
}

bench.add('bluebird', testFunc, {
	setup: function(){
		bluebird.promisifyAll(mongoose)
		console.log('bluebird is running...')
	},
	complete: function(elapsed){
		console.log('bluebird has been proceeded in ' + elapsed + ' ms.')
	}
})

bench.add('mongoomise-bluebird', testFunc, {
	setup: function(){
		mongoomise.promisifyAll(mongoose, bluebird)
		console.log('mongoomise-bluebird is running...')
	},
	complete: function(elapsed){
		console.log('mongoomise-bluebird has been proceeded ' + elapsed + ' ms.')
	}
})

bench.add('mongoomise-Q', testFunc, {
	setup: function(){
		mongoomise.promisifyAll(mongoose, Q)
		console.log('mongoomise-Q is running...')
	},
	complete: function(elapsed){
		console.log('mongoomise-Q has been proceeded ' + elapsed + ' ms.')
	}
})

bench.add('mongoomise-RSVP', testFunc, {
	setup: function(){
		mongoomise.promisifyAll(mongoose, RSVP)
		console.log('mongoomise-RSVP is running...')
	},
	complete: function(elapsed){
		console.log('mongoomise-RSVP has been proceeded ' + elapsed + ' ms.')
	}
})

bench.add('mongoomise-when', testFunc, {
	setup: function(){
		mongoomise.promisifyAll(mongoose, when)
		console.log('mongoomise-when is running...')
	},
	complete: function(elapsed){
		console.log('mongoomise-when has been proceeded ' + elapsed + ' ms.')
	}
})

bench.add('mongoomise-es6Promise', testFunc, {
	setup: function(){
		mongoomise.promisifyAll(mongoose, es6Promise)
		console.log('mongoomise-es6Promise is running...')
	},
	complete: function(elapsed){
		console.log('mongoomise-es6Promise has been proceeded ' + elapsed + ' ms.')
	}
})

// this should be false, otherwise you may use the same promise library
var isParallel = false

bench.run(function(results){
	console.log('all task have been proceeded')
	compareResults(results)
	process.exit()
}, isParallel)<commit_msg>fixed typo<commit_after>var mongoose = require('mongoose')
var bluebird = require('bluebird')
var Q = require('q')
var RSVP = require('rsvp')
var when = require('when')
var es6Promise = require('es6-promise')
var mongoomise = require('../src/main')
var bench = require('./bench')
var $ = require('lodash')

require('../test/feed')

var Feed = mongoose.model('Feed')
mongoose.connect('mongodb://localhost/mongoomise')

var testFunc = function(item, callback){
	Feed.findOneAsync().then(function(feed){
		feed.text = Math.random().toString()
		return feed.saveAsync()
	}).then(function(doc){
		callback(null, doc)
	})
}

var compareResults = function(results){
	console.log('all tasks have been proceeded')
	var sl = $.sortBy(results, function(i){
		return i.elapsed
	})
	$.each(sl, function(task){
		console.log('#### task ' + task.name  + ' ####')
		var details = task.cycles + ' cycles, ' + task.elapsed + ' ms, ' +
			(1000*task.cycles/task.elapsed).toFixed(2) + ' ops/sec'
		console.log('  ' + details)
	})
}

bench.add('bluebird', testFunc, {
	setup: function(){
		bluebird.promisifyAll(mongoose)
		console.log('bluebird is running...')
	},
	complete: function(elapsed){
		console.log('bluebird has been proceeded in ' + elapsed + ' ms.')
	}
})

bench.add('mongoomise-bluebird', testFunc, {
	setup: function(){
		mongoomise.promisifyAll(mongoose, bluebird)
		console.log('mongoomise-bluebird is running...')
	},
	complete: function(elapsed){
		console.log('mongoomise-bluebird has been proceeded in ' + elapsed + ' ms.')
	}
})

bench.add('mongoomise-Q', testFunc, {
	setup: function(){
		mongoomise.promisifyAll(mongoose, Q)
		console.log('mongoomise-Q is running...')
	},
	complete: function(elapsed){
		console.log('mongoomise-Q has been proceeded in ' + elapsed + ' ms.')
	}
})

bench.add('mongoomise-RSVP', testFunc, {
	setup: function(){
		mongoomise.promisifyAll(mongoose, RSVP)
		console.log('mongoomise-RSVP is running...')
	},
	complete: function(elapsed){
		console.log('mongoomise-RSVP has been proceeded in' + elapsed + ' ms.')
	}
})

bench.add('mongoomise-when', testFunc, {
	setup: function(){
		mongoomise.promisifyAll(mongoose, when)
		console.log('mongoomise-when is running...')
	},
	complete: function(elapsed){
		console.log('mongoomise-when has been proceeded in' + elapsed + ' ms.')
	}
})

bench.add('mongoomise-es6Promise', testFunc, {
	setup: function(){
		mongoomise.promisifyAll(mongoose, es6Promise)
		console.log('mongoomise-es6Promise is running...')
	},
	complete: function(elapsed){
		console.log('mongoomise-es6Promise has been proceeded in' + elapsed + ' ms.')
	}
})

// this should be false, otherwise you may use the same promise library
var isParallel = false

bench.run(function(results){
	compareResults(results)
	process.exit()
}, isParallel)<|endoftext|>