<commit_before>/**
 * cbpAnimatedHeader.js v1.0.0
 * http://www.codrops.com
 *
 * Licensed under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright 2013, Codrops
 * http://www.codrops.com
 */
var cbpAnimatedHeader = (function () {

    alert("made it to animated header");

	var docElem = document.documentElement,
		header = document.querySelector( '.navbar-default' ),
		didScroll = false,
		changeHeaderOn = 300;

	function init() {
		window.addEventListener( 'scroll', function( event ) {
			if( !didScroll ) {
				didScroll = true;
				setTimeout( scrollPage, 250 );
			}
		}, false );
	}

	function scrollPage() {
		var sy = scrollY();
		if ( sy >= changeHeaderOn ) {
			classie.add( header, 'navbar-shrink' );
		}
		else {
			classie.remove( header, 'navbar-shrink' );
		}
		didScroll = false;
	}

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

	init();

})();<commit_msg>testing alert<commit_after>/**
 * cbpAnimatedHeader.js v1.0.0
 * http://www.codrops.com
 *
 * Licensed under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright 2013, Codrops
 * http://www.codrops.com
 */
var cbpAnimatedHeader = (function () {

    alert("made it to animated header");

	var docElem = document.documentElement,
		header = document.querySelector( '.navbar-default' ),
		didScroll = false,
		changeHeaderOn = 300;

	function init() {

	    alert("made it to init");

		window.addEventListener( 'scroll', function( event ) {
			if( !didScroll ) {
				didScroll = true;
				setTimeout( scrollPage, 250 );
			}
		}, false );
	}

	function scrollPage() {
		var sy = scrollY();
		if ( sy >= changeHeaderOn ) {
			classie.add( header, 'navbar-shrink' );
		}
		else {
			classie.remove( header, 'navbar-shrink' );
		}
		didScroll = false;
	}

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

	init();

})();<|endoftext|>


<commit_before>function carregaLivroAberto() {

  // Criando um aliase de scene[2].item
  var item = scene[2].item;

  var livro = {};
  var paginaAtual = null;

  scene[2].openBook = function(titulo) {
    disableInteractiveness();

    // Desabilita interação com os livros do armario
    groupDisable(scene[2].livros);
    item.setaSalaDeAula.setInteractive(false);

    // Mostra o livro
    item.livroAberto.enable();
    item.livroAberto.changeAlpha(1, 600);
    item.fechaLivro.enable();
    item.fechaLivro.changeAlpha(1, 600);

    livro[titulo].abre();

    setTimeout(function() {
      enableInteractiveness();
    }, 700);
  }

  // Conteudo dos livros

  // LIVRO: OBJETO DE APRENDIZAGEM
  livro.ObjetoDeApendizagem = {};
  livro.ObjetoDeApendizagem.abre = function() {
    item.livroObjetoDeApendizagemPagina0.show();
    paginaAtual = livro.ObjetoDeApendizagem;
  }
  livro.ObjetoDeApendizagem.fecha = function() {
    item.livroObjetoDeApendizagemPagina0.hide();
  }

  // Conteúdo do livro Objeto de Aprendizagem
  item.livroObjetoDeApendizagemPagina0 = new Game.Page();
  item.livroObjetoDeApendizagemPagina0.titulo = new Game.Text(
    "       O Objeto de Aprendizagem"
  , estiloTitulo);
  item.livroObjetoDeApendizagemPagina0.titulo.setPosition(248, 120);
  item.livroObjetoDeApendizagemPagina0.titulo.setAlpha(0);
  item.livroObjetoDeApendizagemPagina0.titulo.disable();

  item.livroObjetoDeApendizagemPagina0.texto1 = new Game.Text(
    "     Os Objetos de Aprendizagem são uma\n" +
    "tecnologia recente que abre caminhos na\n" +
    "educação à distância e que serve de material\n" +
    "de apoio a aula presencial tradicional. São\n" +
    "elementos de uma nova metodologia de\n" +
    "ensino e aprendizagem baseada no uso do\n" +
    "computador e da Internet.\n" +
    "     Apesar de sua definição ainda ser vaga, o\n" +
    "o consenso é de que o Objeto de Aprendiza-\n" +
    "gem deva possuir um propósito educacional\n" +
    "definido, um elemento que estimule a refle-\n" +
    "xão do estudante e que sua construção seja\n" +
    "de forma a facilitar a reutilização dentro de\n" +
    "outros contextos de aprendizagem.\n" +
    "     Desta forma, as autoras apresentam o\n" +
    "presente Objeto de Aprendizagem em Para-\n" +
    "sitologia.\n" +
    "     O software (ou “jogo”) conta com regiões\n" +
    "clicáveis e interativas, as quais revelarão ao\n" +
    "usuário informações adicionais sobre o objeto\n" +
    "interativo, como os ciclos de vida dos para-\n" +
    "sitas em questão e as suas consequentes doen-"
    , estiloTextoLivro);
  item.livroObjetoDeApendizagemPagina0.texto1.setPosition(248, 190);
  item.livroObjetoDeApendizagemPagina0.texto1.setAlpha(0);
  item.livroObjetoDeApendizagemPagina0.texto1.disable();

  item.livroObjetoDeApendizagemPagina0.texto2 = new Game.Text(
    "ças. Visualmente, o jogo é repleto de imagens\n" +
    "e se é intencionado que estas sejam autoexpli-\n" +
    "cativas, contando, num primeiro momento,\n" +
    "com os auxílios das legendas.\n" +
    "     São expostas três telas: a principal, a sala\n" +
    "de aula, na qual serão encontradas representa-\n" +
    "ções de quatro doenças e seus respectivos\n" +
    "parasitas. À direita da tela principal será ex-\n" +
    "posto o exterior da escola, com mais quatro\n" +
    "doenças e seus três parasitas. À esquerda da\n" +
    "sala de aula será apresentada uma estante re-\n" +
    "pleta de livros interativos, nos quais serão\n" +
    "explicadas as teorias sobre o Parasitismo e\n" +
    "cada parasita abordado neste Objeto de Apren-\n" +
    "dizagem."
    , estiloTextoLivro);
  item.livroObjetoDeApendizagemPagina0.texto2.setPosition(990, 120);
  item.livroObjetoDeApendizagemPagina0.texto2.setAlpha(0);
  item.livroObjetoDeApendizagemPagina0.texto2.disable();

  item.livroObjetoDeApendizagemPagina0.texto3 = new Game.Text(
    "Vamos lá!"
    , estiloTextoLivro);
  item.livroObjetoDeApendizagemPagina0.texto3.setPosition(1414, 669);
  item.livroObjetoDeApendizagemPagina0.texto3.setAlpha(0);
  item.livroObjetoDeApendizagemPagina0.texto3.disable();

  // LIVRO: PARASITOLOGIA
  livro.Parasitologia = {};
  livro.Parasitologia.abre = function() {
    item.livroParasitologiaPagina0.show();
    paginaAtual = livro.Parasitologia;
  }
  livro.Parasitologia.fecha = function() {
    item.livroParasitologiaPagina0.hide();
  }

  // Conteúdo do livro Objeto de Aprendizagem
  item.livroParasitologiaPagina0 = new Game.Page();
  item.livroParasitologiaPagina0.titulo = new Game.Text(
    "                   Parasitologia"
  , estiloTitulo);
  item.livroParasitologiaPagina0.titulo.setPosition(248, 120);
  item.livroParasitologiaPagina0.titulo.setAlpha(0);
  item.livroParasitologiaPagina0.titulo.disable();

  item.livroParasitologiaPagina0.texto1 = new Game.Text(
    "     A parasitologia é o estudo dos parasitas\n" +
    "animais e vegetais e da relação entre parasi-\n" +
    "tas e seus hospedeiros.\n" +
    "     O parasitismo é a associação entre os se-\n" +
    "res vivos, na qual existe unilateralidade de\n" +
    "benefícios, ou seja, apenas um dos lados é\n" +
    "beneficiado. Neste sentido, o hospedeiro\n" +
    "provê abrigo e proteção ao parasita, o qual\n" +
    "prejudica e promove danos ao hospedeiro.\n" +
    "De um modo geral, afirma-se que a associa-\n" +
    "ção parasitária tende ao equilíbrio porque se\n" +
    "o hospedeiro morre, o parasita também morre.\n" +
    "Entretanto, percebe-se que na prática tal fato\n" +
    "não ocorre, visto que ao evitar a morte, o pa-\n" +
    "rasita não mata seu hospedeiro.\n" +
    "     Para haver doenças parasitárias é necessá-\n" +
    "rio que existam alguns fatores, quanto:\n" +
    "     - ao parasito: como o número de indivídu-\n" +
    "os que atingirão o hospedeiro, a sua virulência\n" +
    "e a localização do parasito;\n" +
    "     - ao hospedeiro: idade, nutrição, tipo de\n" +
    "resposta imune."
    , estiloTextoLivro);
  item.livroParasitologiaPagina0.texto1.setPosition(248, 190);
  item.livroParasitologiaPagina0.texto1.setAlpha(0);
  item.livroParasitologiaPagina0.texto1.disable();

  // Margem direita - Para debug
  item.margemDir1 = new Game.Line(800, 120, 800, 950, 2);
  item.margemDir1.setZorder(1);

  item.margemDir2 = new Game.Line(1550, 120, 1550, 950, 2);
  item.margemDir2.setZorder(1);

  // Imagens do livro e do X de fechar
  item.livroAberto = new Game.Image("livroAberto.png");
  item.livroAberto.setZorder(4);
  item.livroAberto.setPosition(960, 540);
  item.livroAberto.setAlpha(0);
  item.livroAberto.disable();

  item.fechaLivro = new Game.Item("botaoFechar.png");
  item.fechaLivro.setPosition(1840, 70);
  item.fechaLivro.setZorder(1);
  item.fechaLivro.setAlpha(0);
  item.fechaLivro.disable();
  item.fechaLivro.onMouseOver = function() {
    item.fechaLivro.addGlow();
  }
  item.fechaLivro.onMouseOut = function() {
    item.fechaLivro.removeGlow();
  }
  item.fechaLivro.onClick = function(mouse) {
    disableInteractiveness();

    // Habilita interação com os livros do armario
    groupEnable(scene[2].livros);
    item.setaSalaDeAula.setInteractive(true);

    // Esconde o livro
    item.livroAberto.changeAlpha(0, 600);
    item.fechaLivro.changeAlpha(0, 600);

    // Esconde o texto
    paginaAtual.fecha();
    paginaAtual = null;

    setTimeout(function() {
      item.livroAberto.disable();
      item.fechaLivro.disable();
      enableInteractiveness();
    }, 700);
  }

}
<commit_msg>Parasitologia book first part done<commit_after>function carregaLivroAberto() {

  // Criando um aliase de scene[2].item
  var item = scene[2].item;

  var livro = {};
  var paginaAtual = null;

  scene[2].openBook = function(titulo) {
    disableInteractiveness();

    // Desabilita interação com os livros do armario
    groupDisable(scene[2].livros);
    item.setaSalaDeAula.setInteractive(false);

    // Mostra o livro
    item.livroAberto.enable();
    item.livroAberto.changeAlpha(1, 600);
    item.fechaLivro.enable();
    item.fechaLivro.changeAlpha(1, 600);

    livro[titulo].abre();

    setTimeout(function() {
      enableInteractiveness();
    }, 700);
  }

  // Conteudo dos livros

  // LIVRO: OBJETO DE APRENDIZAGEM
  livro.ObjetoDeApendizagem = {};
  livro.ObjetoDeApendizagem.abre = function() {
    item.livroObjetoDeApendizagemPagina0.show();
    paginaAtual = livro.ObjetoDeApendizagem;
  }
  livro.ObjetoDeApendizagem.fecha = function() {
    item.livroObjetoDeApendizagemPagina0.hide();
  }

  // Conteúdo do livro Objeto de Aprendizagem
  item.livroObjetoDeApendizagemPagina0 = new Game.Page();
  item.livroObjetoDeApendizagemPagina0.titulo = new Game.Text(
    "       O Objeto de Aprendizagem"
  , estiloTitulo);
  item.livroObjetoDeApendizagemPagina0.titulo.setPosition(248, 120);
  item.livroObjetoDeApendizagemPagina0.titulo.setAlpha(0);
  item.livroObjetoDeApendizagemPagina0.titulo.disable();

  item.livroObjetoDeApendizagemPagina0.texto1 = new Game.Text(
    "     Os Objetos de Aprendizagem são uma\n" +
    "tecnologia recente que abre caminhos na\n" +
    "educação à distância e que serve de material\n" +
    "de apoio a aula presencial tradicional. São\n" +
    "elementos de uma nova metodologia de\n" +
    "ensino e aprendizagem baseada no uso do\n" +
    "computador e da Internet.\n" +
    "     Apesar de sua definição ainda ser vaga, o\n" +
    "o consenso é de que o Objeto de Aprendiza-\n" +
    "gem deva possuir um propósito educacional\n" +
    "definido, um elemento que estimule a refle-\n" +
    "xão do estudante e que sua construção seja\n" +
    "de forma a facilitar a reutilização dentro de\n" +
    "outros contextos de aprendizagem.\n" +
    "     Desta forma, as autoras apresentam o\n" +
    "presente Objeto de Aprendizagem em Para-\n" +
    "sitologia.\n" +
    "     O software (ou “jogo”) conta com regiões\n" +
    "clicáveis e interativas, as quais revelarão ao\n" +
    "usuário informações adicionais sobre o objeto\n" +
    "interativo, como os ciclos de vida dos para-\n" +
    "sitas em questão e as suas consequentes doen-"
    , estiloTextoLivro);
  item.livroObjetoDeApendizagemPagina0.texto1.setPosition(248, 190);
  item.livroObjetoDeApendizagemPagina0.texto1.setAlpha(0);
  item.livroObjetoDeApendizagemPagina0.texto1.disable();

  item.livroObjetoDeApendizagemPagina0.texto2 = new Game.Text(
    "ças. Visualmente, o jogo é repleto de imagens\n" +
    "e se é intencionado que estas sejam autoexpli-\n" +
    "cativas, contando, num primeiro momento,\n" +
    "com os auxílios das legendas.\n" +
    "     São expostas três telas: a principal, a sala\n" +
    "de aula, na qual serão encontradas representa-\n" +
    "ções de quatro doenças e seus respectivos\n" +
    "parasitas. À direita da tela principal será ex-\n" +
    "posto o exterior da escola, com mais quatro\n" +
    "doenças e seus três parasitas. À esquerda da\n" +
    "sala de aula será apresentada uma estante re-\n" +
    "pleta de livros interativos, nos quais serão\n" +
    "explicadas as teorias sobre o Parasitismo e\n" +
    "cada parasita abordado neste Objeto de Apren-\n" +
    "dizagem."
    , estiloTextoLivro);
  item.livroObjetoDeApendizagemPagina0.texto2.setPosition(990, 120);
  item.livroObjetoDeApendizagemPagina0.texto2.setAlpha(0);
  item.livroObjetoDeApendizagemPagina0.texto2.disable();

  item.livroObjetoDeApendizagemPagina0.texto3 = new Game.Text(
    "Vamos lá!"
    , estiloTextoLivro);
  item.livroObjetoDeApendizagemPagina0.texto3.setPosition(1414, 669);
  item.livroObjetoDeApendizagemPagina0.texto3.setAlpha(0);
  item.livroObjetoDeApendizagemPagina0.texto3.disable();

  // LIVRO: PARASITOLOGIA
  livro.Parasitologia = {};
  livro.Parasitologia.abre = function() {
    item.livroParasitologiaPagina0.show();
    paginaAtual = livro.Parasitologia;
  }
  livro.Parasitologia.fecha = function() {
    item.livroParasitologiaPagina0.hide();
  }

  // Conteúdo do livro Objeto de Aprendizagem
  item.livroParasitologiaPagina0 = new Game.Page();
  item.livroParasitologiaPagina0.titulo = new Game.Text(
    "                   Parasitologia"
  , estiloTitulo);
  item.livroParasitologiaPagina0.titulo.setPosition(248, 120);
  item.livroParasitologiaPagina0.titulo.setAlpha(0);
  item.livroParasitologiaPagina0.titulo.disable();

  item.livroParasitologiaPagina0.texto1 = new Game.Text(
    "     A parasitologia é o estudo dos parasitas\n" +
    "animais e vegetais e da relação entre parasi-\n" +
    "tas e seus hospedeiros.\n" +
    "     O parasitismo é a associação entre os se-\n" +
    "res vivos, na qual existe unilateralidade de\n" +
    "benefícios, ou seja, apenas um dos lados é\n" +
    "beneficiado. Neste sentido, o hospedeiro\n" +
    "provê abrigo e proteção ao parasita, o qual\n" +
    "prejudica e promove danos ao hospedeiro.\n" +
    "De um modo geral, afirma-se que a associa-\n" +
    "ção parasitária tende ao equilíbrio porque se\n" +
    "o hospedeiro morre, o parasita também morre.\n" +
    "Entretanto, percebe-se que na prática tal fato\n" +
    "não ocorre, visto que ao evitar a morte, o pa-\n" +
    "rasita não mata seu hospedeiro.\n" +
    "     Para haver doenças parasitárias é necessá-\n" +
    "rio que existam alguns fatores, quanto:\n" +
    "     - ao parasito: como o número de indivídu-\n" +
    "os que atingirão o hospedeiro, a sua virulência\n" +
    "e a localização do parasito;\n" +
    "     - ao hospedeiro: idade, nutrição, tipo de\n" +
    "resposta imune."
    , estiloTextoLivro);
  item.livroParasitologiaPagina0.texto1.setPosition(248, 190);
  item.livroParasitologiaPagina0.texto1.setAlpha(0);
  item.livroParasitologiaPagina0.texto1.disable();

  item.livroParasitologiaPagina0.texto2 = new Game.Text(
    "     A ação do parasita no hospedeiro é de gran-\n" +
    "de importância na parasitologia, visto que é\n" +
    "através dela que ocorrem as doenças. Dentre os\n" +
    "tipos de ação dos parasitos, os principais são:\n" +
    "     - Mecânica: ação obstrutiva ou destrutiva\n" +
    "que parasito exerce sobre algum órgão do hos-\n" +
    "pedeiro;\n" +
    "      - Espoliativa: ocorre quando o parasito re-\n" +
    "tira nutrientes do hospedeiro;\n" +
    "      - Traumática: quando o parasito promove\n" +
    "traumas no hospedeiro, como fixação e migra-\n" +
    "ção;\n" +
    "      - Tóxica: produtos do metabolismo do pa-\n" +
    "rasito é tóxico ao hospedeiro."
    , estiloTextoLivro);
  item.livroParasitologiaPagina0.texto2.setPosition(990, 120);
  item.livroParasitologiaPagina0.texto2.setAlpha(0);
  item.livroParasitologiaPagina0.texto2.disable();

  // Margem direita - Para debug
  item.margemDir1 = new Game.Line(800, 120, 800, 950, 2);
  item.margemDir1.setZorder(1);

  item.margemDir2 = new Game.Line(1550, 120, 1550, 950, 2);
  item.margemDir2.setZorder(1);

  // Imagens do livro e do X de fechar
  item.livroAberto = new Game.Image("livroAberto.png");
  item.livroAberto.setZorder(4);
  item.livroAberto.setPosition(960, 540);
  item.livroAberto.setAlpha(0);
  item.livroAberto.disable();

  item.fechaLivro = new Game.Item("botaoFechar.png");
  item.fechaLivro.setPosition(1840, 70);
  item.fechaLivro.setZorder(1);
  item.fechaLivro.setAlpha(0);
  item.fechaLivro.disable();
  item.fechaLivro.onMouseOver = function() {
    item.fechaLivro.addGlow();
  }
  item.fechaLivro.onMouseOut = function() {
    item.fechaLivro.removeGlow();
  }
  item.fechaLivro.onClick = function(mouse) {
    disableInteractiveness();

    // Habilita interação com os livros do armario
    groupEnable(scene[2].livros);
    item.setaSalaDeAula.setInteractive(true);

    // Esconde o livro
    item.livroAberto.changeAlpha(0, 600);
    item.fechaLivro.changeAlpha(0, 600);

    // Esconde o texto
    paginaAtual.fecha();
    paginaAtual = null;

    setTimeout(function() {
      item.livroAberto.disable();
      item.fechaLivro.disable();
      enableInteractiveness();
    }, 700);
  }

}
<|endoftext|>


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

  var jCore = require('jcore');
  var helper = app.helper || require('../helper.js');
  var dom = app.dom || require('../dom.js');
  var ModulePort = app.ModulePort || require('./module-port.js');

  var Module = helper.inherits(function(props) {
    Module.super_.call(this);

    this.title = this.prop(props.title);
    this.name = this.prop(props.name);
    this.x = this.prop(props.x);
    this.y = this.prop(props.y);
    this.zIndex = this.prop('auto');
    this.ports = this.prop([]);
    this.portListHeight = this.prop(0);
    this.element = this.prop(null);
    this.parentElement = this.prop(null);
    this.cache = this.prop({});
    this.draggable = this.prop(null);
    this.dragContext = this.prop({});

    this.onchange = Module.prototype.onchange.bind(this);

    this.optionDeselector = Module.prototype.deselectOption.bind(this);
    this.optGroupSorter = Module.prototype.sortOptGroup.bind(this);

    this.deleter = props.deleter;
  }, jCore.Component);

  Module.prototype.titleElement = function() {
    return dom.child(this.element(), 0, 0);
  };

  Module.prototype.deleteButtonElement = function() {
    return dom.child(this.element(), 0, 1);
  };

  Module.prototype.componentElement = function() {
    return dom.child(this.element(), 1, 0);
  };

  Module.prototype.portListElement = function() {
    return dom.child(this.element(), 1, 1);
  };

  Module.prototype.portSelectElement = function() {
    return dom.child(this.element(), 2, 1);
  };

  Module.prototype.portOptGroupElement = function(type) {
    var index = ({ prop: 0, event: 1 })[type];
    return dom.child(this.element(), 2, 1, index);
  };

  Module.prototype.circuitElement = function() {
    return helper.dig(dom.contentWindow(this.componentElement()), 'modular', 'exports');
  };

  Module.prototype.loadComponent = function() {
    var url = [
      'modular_modules/',
      this.name().split('/').map(function(s) {
        return encodeURIComponent(s);
      }).join('/'),
      '.html'
    ].join('');

    dom.addClass(this.element(), 'module-loading');

    return dom.ajax({
      type: 'GET',
      url: url
    }).then(function(text) {
      var componentElement = this.componentElement();
      var contentWindow = dom.contentWindow(componentElement);
      var data = Date.now().toString();

      dom.name(contentWindow, data);
      dom.writeContent(componentElement, text);

      var onmessage;

      return Promise.race([
        new Promise(function(resolve, reject) {
          onmessage = function(event) {
            try {
              if (event.origin !== dom.origin())
                throw new Error('Invalid content origin');

              if (event.data !== data)
                throw new Error('Invalid content data');

              var circuitElement = this.circuitElement();

              if (!circuitElement)
                throw new Error('Invalid circuit element');

              this.ports(circuitElement.getAll().map(function(member) {
                var props = member.props();
                props.parentListElement = this.portListElement();
                props.parentOptGroupElement = this.portOptGroupElement(props.type);
                props.optionDeselector = this.optionDeselector;
                props.optGroupSorter = this.optGroupSorter;
                return new ModulePort(props);
              }.bind(this)));

              resolve();
            } catch(e) {
              reject(e);
            }
          }.bind(this);

          dom.on(contentWindow, 'message', onmessage);
        }.bind(this)),
        new Promise(function(resolve, reject) {
          setTimeout(reject, 30 * 1000, new Error('Load timeout for content'));
        })
      ]).then(function() {
        dom.off(contentWindow, 'message', onmessage);
        dom.removeClass(this.element(), 'module-loading');
        dom.fillContentHeight(componentElement);
      }.bind(this)).catch(function(e) {
        dom.off(contentWindow, 'message', onmessage);
        throw e;
      });
    }.bind(this)).catch(function(e) {
      dom.addClass(this.element(), 'module-error');
      throw e;
    }.bind(this));
  };

  Module.prototype.showPort = function(name) {
    var port = this.ports().filter(function(port) {
      return port.name() === name;
    })[0];

    if (!port || port.visible())
      return;

    // add the port to the end of the list
    var portListHeight = this.portListHeight();
    this.portListHeight(portListHeight + port.height());
    port.top(portListHeight);
    port.visible(true);
  };

  Module.prototype.hidePort = function(name) {
    var visiblePorts = this.ports().slice().filter(function(port) {
      return port.visible();
    }).sort(function(a, b) {
      return a.top() - b.top();
    });

    var hiddenPort = null;

    visiblePorts.forEach(function(port) {
      if (hiddenPort) {
        // move up the ports below the hidden port
        port.top(port.top() - hiddenPort.height());
      } else if (port.name() === name) {
        port.visible(false);
        hiddenPort = port;
      }
    });

    if (hiddenPort)
      this.portListHeight(this.portListHeight() - hiddenPort.height());
  };

  Module.prototype.deselectOption = function() {
    dom.value(this.portSelectElement(), '');
  };

  Module.prototype.sortOptGroup = function(type) {
    var element = this.portOptGroupElement(type);

    helper.sortBy(dom.children(element), 'textContent').forEach(function(child) {
      dom.append(element, child);
    });
  };

  Module.prototype.redraw = function() {
    var element = this.element();
    var parentElement = this.parentElement();

    if (!parentElement && !element)
      return;

    // add element
    if (parentElement && !element) {
      element = dom.el('
');
      dom.addClass(element, 'module');
      dom.html(element, Module.TEMPLATE_HTML);
      this.draggable(new dom.Draggable({
        element: element,
        onstart: Module.prototype.onstart.bind(this),
        onmove: Module.prototype.onmove.bind(this),
        onend: Module.prototype.onend.bind(this)
      }));
      this.element(element);
      dom.on(this.portSelectElement(), 'change', this.onchange);
      this.redraw();
      dom.append(parentElement, element);
      return;
    }

    // remove element
    if (!parentElement && element) {
      this.draggable().destroy();
      dom.off(this.portSelectElement(), 'change', this.onchange);
      dom.remove(element);
      this.element(null);
      this.cache({});
      this.dragContext({});
      return;
    }

    // update element
    this.redrawTitle();
    this.redrawPosition();
    this.redrawZIndex();
    this.redrawPortList();
    this.redrawPortSelect();
  };

  Module.prototype.redrawTitle = function() {
    var title = this.title();
    var cache = this.cache();

    if (title === cache.title)
      return;

    dom.text(this.titleElement(), title);
    cache.title = title;
  };

  Module.prototype.redrawPosition = function() {
    var x = this.x();
    var y = this.y();
    var cache = this.cache();

    if (x === cache.x && y === cache.y)
      return;

    var translate = 'translate(' + x + 'px, ' + y + 'px)';

    dom.css(this.element(), {
      transform: translate,
      webkitTransform: translate
    });

    cache.x = x;
    cache.y = y;
  };

  Module.prototype.redrawZIndex = function() {
    var zIndex = this.zIndex();
    var cache = this.cache();

    if (zIndex === cache.zIndex)
      return;

    dom.css(this.element(), {
      zIndex: zIndex
    });

    cache.zIndex = zIndex;
  };

  Module.prototype.redrawPortList = function() {
    var portListHeight = this.portListHeight();
    var cache = this.cache();

    if (portListHeight === cache.portListHeight)
      return;

    dom.css(this.portListElement(), {
      height: portListHeight + 'px'
    });

    cache.portListHeight = portListHeight;
  };

  Module.prototype.redrawPortSelect = function() {
    var cache = this.cache();

    var isAllPortsVisible = this.ports().every(function(port) {
      return port.visible();
    });

    if (isAllPortsVisible === cache.isAllPortsVisible)
      return;

    if (isAllPortsVisible)
      dom.addClass(this.element(), 'module-all-ports-visible');
    else
      dom.removeClass(this.element(), 'module-all-ports-visible');
  };

  Module.prototype.onstart = function(x, y, event) {
    var context = this.dragContext();
    var target = dom.target(event);

    if (target === this.titleElement())
      context.type = 'position';
    else if (target === this.deleteButtonElement())
      context.type = 'delete';
    else if (dom.hasClass(target, 'module-port-hide-button'))
      context.type = 'hidePort';
    else if (dom.hasClass(target, 'module-port-label'))
      context.type = 'sortPort';
    else
      context.type = null;

    var type = context.type;

    if (!type)
      return;

    dom.cancel(event);

    if (type === 'position') {
      context.x = this.x();
      context.y = this.y();
      dom.addClass(this.element(), 'module-dragging');
    } else if (type === 'delete') {
      context.target = target;
      dom.addClass(this.element(), 'module-deleting');
    } else if (type === 'hidePort') {
      context.target = target;
      context.port = this.ports().filter(function(port) {
        return dom.contains(port.listItemElement(), target);
      })[0];
    } else if (type === 'sortPort') {
      var port = this.ports().filter(function(port) {
        return dom.contains(port.listItemElement(), target);
      })[0];
      var top = port.top();
      context.port = port;
      context.top = top;
      context.placeholderTop = top;
      dom.addClass(port.listItemElement(), 'module-port-sorting');
      dom.addClass(this.element(), 'module-port-sorting');
    }
  };

  Module.prototype.onmove = function(dx, dy) {
    var context = this.dragContext();
    var type = context.type;

    if (!type)
      return;

    if (type === 'position') {
      this.x(context.x + dx);
      this.y(context.y + dy);
    } else if (type === 'delete') {
      if (dom.target(event) === context.target)
        dom.addClass(this.element(), 'module-deleting');
      else
        dom.removeClass(this.element(), 'module-deleting');
    } else if (type === 'sortPort') {
      var targetPort = context.port;
      var targetPortHeight = targetPort.height();

      // move the target port within the port list
      var targetPortTop = Math.min(Math.max(context.top + dy, 0), this.portListHeight() - targetPortHeight);

      targetPort.top(targetPortTop);

      var targetPortCenter = targetPortTop + targetPortHeight / 2;
      var placeholderTop = context.placeholderTop;
      var nextPlaceholderTop = placeholderTop;
      var isDown = (targetPortTop - placeholderTop > 0);

      this.ports().forEach(function(port) {
        if (!port.visible() || port === targetPort)
          return;

        var top = port.top();
        var bottom = port.bottom();

        if (isDown && placeholderTop <= top && top < targetPortCenter) {
          // move up the ports over the target port
          port.top(top - targetPortHeight);
          nextPlaceholderTop = Math.max(nextPlaceholderTop, port.bottom());
        } else if (!isDown && targetPortCenter < bottom && bottom <= placeholderTop) {
          // move down the ports under the target port
          port.top(top + targetPortHeight);
          nextPlaceholderTop = Math.min(nextPlaceholderTop, top);
        }
      });

      context.placeholderTop = nextPlaceholderTop;
    }
  };

  Module.prototype.onend = function(dx, dy, event) {
    var context = this.dragContext();
    var type = context.type;
    var target = dom.target(event);

    if (!type)
      return;

    if (type === 'position') {
      dom.removeClass(this.element(), 'module-dragging');
    } else if (type === 'delete') {
      if (target === context.target) {
        this.parentElement(null);
        this.deleter(this);
      } else {
        dom.removeClass(this.element(), 'module-deleting');
      }
    } else if (type === 'hidePort') {
      if (target === context.target)
        this.hidePort(context.port.name());
    } else if (type === 'sortPort') {
      var port = context.port;
      port.top(context.placeholderTop);
      dom.removeClass(port.listItemElement(), 'module-port-sorting');
      dom.removeClass(this.element(), 'module-port-sorting');
    }
  };

  Module.prototype.onchange = function(event) {
    this.showPort(dom.value(dom.target(event)));
    this.deselectOption();
    dom.removeFocus();
  };

  Module.TEMPLATE_HTML = [
    '
',
      '

',
      '

',
    '
',
    '
',
      '',
      '

',
    '
',
    '
',
      '',
      '<select class="module-port-select">',
        '<optgroup label="Property"></optgroup>',
        '<optgroup label="Event"></optgroup>',
      '</select>',
    '
'
  ].join('');

  if (typeof module !== 'undefined' && module.exports)
    module.exports = Module;
  else
    app.Module = Module;
})(this.app || (this.app = {}));
<commit_msg>Modify method for updating a footer of the module<commit_after>(function(app) {
  'use strict';

  var jCore = require('jcore');
  var helper = app.helper || require('../helper.js');
  var dom = app.dom || require('../dom.js');
  var ModulePort = app.ModulePort || require('./module-port.js');

  var Module = helper.inherits(function(props) {
    Module.super_.call(this);

    this.title = this.prop(props.title);
    this.name = this.prop(props.name);
    this.x = this.prop(props.x);
    this.y = this.prop(props.y);
    this.zIndex = this.prop('auto');
    this.ports = this.prop([]);
    this.portListHeight = this.prop(0);
    this.element = this.prop(null);
    this.parentElement = this.prop(null);
    this.cache = this.prop({});
    this.draggable = this.prop(null);
    this.dragContext = this.prop({});

    this.onchange = Module.prototype.onchange.bind(this);

    this.optionDeselector = Module.prototype.deselectOption.bind(this);
    this.optGroupSorter = Module.prototype.sortOptGroup.bind(this);

    this.deleter = props.deleter;
  }, jCore.Component);

  Module.prototype.titleElement = function() {
    return dom.child(this.element(), 0, 0);
  };

  Module.prototype.deleteButtonElement = function() {
    return dom.child(this.element(), 0, 1);
  };

  Module.prototype.componentElement = function() {
    return dom.child(this.element(), 1, 0);
  };

  Module.prototype.portListElement = function() {
    return dom.child(this.element(), 1, 1);
  };

  Module.prototype.footerElement = function() {
    return dom.child(this.element(), 2);
  };

  Module.prototype.portSelectElement = function() {
    return dom.child(this.element(), 2, 1);
  };

  Module.prototype.portOptGroupElement = function(type) {
    var index = ({ prop: 0, event: 1 })[type];
    return dom.child(this.element(), 2, 1, index);
  };

  Module.prototype.circuitElement = function() {
    return helper.dig(dom.contentWindow(this.componentElement()), 'modular', 'exports');
  };

  Module.prototype.loadComponent = function() {
    var url = [
      'modular_modules/',
      this.name().split('/').map(function(s) {
        return encodeURIComponent(s);
      }).join('/'),
      '.html'
    ].join('');

    dom.addClass(this.element(), 'module-loading');

    return dom.ajax({
      type: 'GET',
      url: url
    }).then(function(text) {
      var componentElement = this.componentElement();
      var contentWindow = dom.contentWindow(componentElement);
      var data = Date.now().toString();

      dom.name(contentWindow, data);
      dom.writeContent(componentElement, text);

      var onmessage;

      return Promise.race([
        new Promise(function(resolve, reject) {
          onmessage = function(event) {
            try {
              if (event.origin !== dom.origin())
                throw new Error('Invalid content origin');

              if (event.data !== data)
                throw new Error('Invalid content data');

              var circuitElement = this.circuitElement();

              if (!circuitElement)
                throw new Error('Invalid circuit element');

              this.ports(circuitElement.getAll().map(function(member) {
                var props = member.props();
                props.parentListElement = this.portListElement();
                props.parentOptGroupElement = this.portOptGroupElement(props.type);
                props.optionDeselector = this.optionDeselector;
                props.optGroupSorter = this.optGroupSorter;
                return new ModulePort(props);
              }.bind(this)));

              resolve();
            } catch(e) {
              reject(e);
            }
          }.bind(this);

          dom.on(contentWindow, 'message', onmessage);
        }.bind(this)),
        new Promise(function(resolve, reject) {
          setTimeout(reject, 30 * 1000, new Error('Load timeout for content'));
        })
      ]).then(function() {
        dom.off(contentWindow, 'message', onmessage);
        dom.removeClass(this.element(), 'module-loading');
        dom.fillContentHeight(componentElement);
      }.bind(this)).catch(function(e) {
        dom.off(contentWindow, 'message', onmessage);
        throw e;
      });
    }.bind(this)).catch(function(e) {
      dom.addClass(this.element(), 'module-error');
      throw e;
    }.bind(this));
  };

  Module.prototype.showPort = function(name) {
    var port = this.ports().filter(function(port) {
      return port.name() === name;
    })[0];

    if (!port || port.visible())
      return;

    // add the port to the end of the list
    var portListHeight = this.portListHeight();
    this.portListHeight(portListHeight + port.height());
    port.top(portListHeight);
    port.visible(true);
  };

  Module.prototype.hidePort = function(name) {
    var visiblePorts = this.ports().slice().filter(function(port) {
      return port.visible();
    }).sort(function(a, b) {
      return a.top() - b.top();
    });

    var hiddenPort = null;

    visiblePorts.forEach(function(port) {
      if (hiddenPort) {
        // move up the ports below the hidden port
        port.top(port.top() - hiddenPort.height());
      } else if (port.name() === name) {
        port.visible(false);
        hiddenPort = port;
      }
    });

    if (hiddenPort)
      this.portListHeight(this.portListHeight() - hiddenPort.height());
  };

  Module.prototype.deselectOption = function() {
    dom.value(this.portSelectElement(), '');
  };

  Module.prototype.sortOptGroup = function(type) {
    var element = this.portOptGroupElement(type);

    helper.sortBy(dom.children(element), 'textContent').forEach(function(child) {
      dom.append(element, child);
    });
  };

  Module.prototype.redraw = function() {
    var element = this.element();
    var parentElement = this.parentElement();

    if (!parentElement && !element)
      return;

    // add element
    if (parentElement && !element) {
      element = dom.el('
');
      dom.addClass(element, 'module');
      dom.html(element, Module.TEMPLATE_HTML);
      this.draggable(new dom.Draggable({
        element: element,
        onstart: Module.prototype.onstart.bind(this),
        onmove: Module.prototype.onmove.bind(this),
        onend: Module.prototype.onend.bind(this)
      }));
      this.element(element);
      dom.on(this.portSelectElement(), 'change', this.onchange);
      this.redraw();
      dom.append(parentElement, element);
      return;
    }

    // remove element
    if (!parentElement && element) {
      this.draggable().destroy();
      dom.off(this.portSelectElement(), 'change', this.onchange);
      dom.remove(element);
      this.element(null);
      this.cache({});
      this.dragContext({});
      return;
    }

    // update element
    this.redrawTitle();
    this.redrawPosition();
    this.redrawZIndex();
    this.redrawPortList();
    this.redrawFooter();
  };

  Module.prototype.redrawTitle = function() {
    var title = this.title();
    var cache = this.cache();

    if (title === cache.title)
      return;

    dom.text(this.titleElement(), title);
    cache.title = title;
  };

  Module.prototype.redrawPosition = function() {
    var x = this.x();
    var y = this.y();
    var cache = this.cache();

    if (x === cache.x && y === cache.y)
      return;

    var translate = 'translate(' + x + 'px, ' + y + 'px)';

    dom.css(this.element(), {
      transform: translate,
      webkitTransform: translate
    });

    cache.x = x;
    cache.y = y;
  };

  Module.prototype.redrawZIndex = function() {
    var zIndex = this.zIndex();
    var cache = this.cache();

    if (zIndex === cache.zIndex)
      return;

    dom.css(this.element(), {
      zIndex: zIndex
    });

    cache.zIndex = zIndex;
  };

  Module.prototype.redrawPortList = function() {
    var portListHeight = this.portListHeight();
    var cache = this.cache();

    if (portListHeight === cache.portListHeight)
      return;

    dom.css(this.portListElement(), {
      height: portListHeight + 'px'
    });

    cache.portListHeight = portListHeight;
  };

  Module.prototype.redrawFooter = function() {
    var cache = this.cache();

    var isAllPortsVisible = this.ports().every(function(port) {
      return port.visible();
    });

    if (isAllPortsVisible === cache.isAllPortsVisible)
      return;

    if (isAllPortsVisible)
      dom.addClass(this.footerElement(), 'module-footer-hide');
    else
      dom.removeClass(this.footerElement(), 'module-footer-hide');
  };

  Module.prototype.onstart = function(x, y, event) {
    var context = this.dragContext();
    var target = dom.target(event);

    if (target === this.titleElement())
      context.type = 'position';
    else if (target === this.deleteButtonElement())
      context.type = 'delete';
    else if (dom.hasClass(target, 'module-port-hide-button'))
      context.type = 'hidePort';
    else if (dom.hasClass(target, 'module-port-label'))
      context.type = 'sortPort';
    else
      context.type = null;

    var type = context.type;

    if (!type)
      return;

    dom.cancel(event);

    if (type === 'position') {
      context.x = this.x();
      context.y = this.y();
      dom.addClass(this.element(), 'module-dragging');
    } else if (type === 'delete') {
      context.target = target;
      dom.addClass(this.element(), 'module-deleting');
    } else if (type === 'hidePort') {
      context.target = target;
      context.port = this.ports().filter(function(port) {
        return dom.contains(port.listItemElement(), target);
      })[0];
    } else if (type === 'sortPort') {
      var port = this.ports().filter(function(port) {
        return dom.contains(port.listItemElement(), target);
      })[0];
      var top = port.top();
      context.port = port;
      context.top = top;
      context.placeholderTop = top;
      dom.addClass(port.listItemElement(), 'module-port-sorting');
      dom.addClass(this.element(), 'module-port-sorting');
    }
  };

  Module.prototype.onmove = function(dx, dy) {
    var context = this.dragContext();
    var type = context.type;

    if (!type)
      return;

    if (type === 'position') {
      this.x(context.x + dx);
      this.y(context.y + dy);
    } else if (type === 'delete') {
      if (dom.target(event) === context.target)
        dom.addClass(this.element(), 'module-deleting');
      else
        dom.removeClass(this.element(), 'module-deleting');
    } else if (type === 'sortPort') {
      var targetPort = context.port;
      var targetPortHeight = targetPort.height();

      // move the target port within the port list
      var targetPortTop = Math.min(Math.max(context.top + dy, 0), this.portListHeight() - targetPortHeight);

      targetPort.top(targetPortTop);

      var targetPortCenter = targetPortTop + targetPortHeight / 2;
      var placeholderTop = context.placeholderTop;
      var nextPlaceholderTop = placeholderTop;
      var isDown = (targetPortTop - placeholderTop > 0);

      this.ports().forEach(function(port) {
        if (!port.visible() || port === targetPort)
          return;

        var top = port.top();
        var bottom = port.bottom();

        if (isDown && placeholderTop <= top && top < targetPortCenter) {
          // move up the ports over the target port
          port.top(top - targetPortHeight);
          nextPlaceholderTop = Math.max(nextPlaceholderTop, port.bottom());
        } else if (!isDown && targetPortCenter < bottom && bottom <= placeholderTop) {
          // move down the ports under the target port
          port.top(top + targetPortHeight);
          nextPlaceholderTop = Math.min(nextPlaceholderTop, top);
        }
      });

      context.placeholderTop = nextPlaceholderTop;
    }
  };

  Module.prototype.onend = function(dx, dy, event) {
    var context = this.dragContext();
    var type = context.type;
    var target = dom.target(event);

    if (!type)
      return;

    if (type === 'position') {
      dom.removeClass(this.element(), 'module-dragging');
    } else if (type === 'delete') {
      if (target === context.target) {
        this.parentElement(null);
        this.deleter(this);
      } else {
        dom.removeClass(this.element(), 'module-deleting');
      }
    } else if (type === 'hidePort') {
      if (target === context.target)
        this.hidePort(context.port.name());
    } else if (type === 'sortPort') {
      var port = context.port;
      port.top(context.placeholderTop);
      dom.removeClass(port.listItemElement(), 'module-port-sorting');
      dom.removeClass(this.element(), 'module-port-sorting');
    }
  };

  Module.prototype.onchange = function(event) {
    this.showPort(dom.value(dom.target(event)));
    this.deselectOption();
    dom.removeFocus();
  };

  Module.TEMPLATE_HTML = [
    '
',
      '

',
      '

',
    '
',
    '
',
      '',
      '

',
    '
',
    '
',
      '',
      '<select class="module-port-select">',
        '<optgroup label="Property"></optgroup>',
        '<optgroup label="Event"></optgroup>',
      '</select>',
    '
'
  ].join('');

  if (typeof module !== 'undefined' && module.exports)
    module.exports = Module;
  else
    app.Module = Module;
})(this.app || (this.app = {}));
<|endoftext|>


<commit_before>/*eslint-env browser */
/*global require: false, module: false */

'use strict';

var _ = require('../underscore_ext');
var paths = require('./paths');
var widgets = require('../columnWidgets');

function cmpString(s1, s2) {
	if (s1 > s2) {
		return 1;
	} else if (s2 > s1) {
		return -1;
	}
	return 0;
}

function updateColumnDisplay(state, colID) {
	var col = _.getIn(state, [...paths.columns, colID]),
		{dsID} = col,
		viz = _.getIn(state, [...paths.vizSettings, dsID]),
		samples = _.getIn(state, paths.samples),
		dataset = _.getIn(state, [...paths.datasets, 'datasets', dsID]),
		data = _.getIn(state, [...paths.data, colID]);
	return _.assocIn(state, [...paths.data, colID, 'display'],
			widgets.transform(col, viz, data, samples, dataset));
}

function updateAllColumns(state) {
	return _.keys(_.getIn(state, paths.columns)).reduce(updateColumnDisplay, state);
}

function sortSamples(state) {
	const order = _.getIn(state, paths.columnOrder),
		columns = _.getIn(state, paths.columns),
		data = _.getIn(state, paths.data),
		samples = _.getIn(state, paths.samples);

	var cmpFns = _.fmap(columns, (c, id) => widgets.cmp(columns[id], data[id])),
		cmpFn = (s1, s2) =>
			_.findValue(order, id => cmpFns[id](s1, s2)) ||
			cmpString(s1, s2); // XXX add cohort as well

	return updateAllColumns(_.assocIn(state, paths.samples, samples.slice(0).sort(cmpFn)));
}

module.exports = {
	sortSamples,
	updateAllColumns
};
<commit_msg>Drop unused file.<commit_after><|endoftext|>


<commit_before>
  function db_webdb2js_aux ( day_arr, qs, qs_index, vector_details, ok_handler )
  {
        html5sql.process(
             qs[qs_index],
	     function(transaction, results, v)
	     {
                if (qs_index < (qs.length-1))
                    db_webdb2js_aux(day_arr,qs,qs_index+1,vector_details,ok_handler);

		for (var i=0; i<results.rows.length; i++)
		{
                   // non-timestamp event
                   if (results.rows.item(i).rt == 'basaldef')
                   {
		       if (typeof vector_details['basaldef'] === 'undefined')
		           vector_details['basaldef'] = new Array() ;

		       vector_details["basaldef"].push({"id":         results.rows.item(i).id,
						        "pattern":    results.rows.item(i).pattern,
						        "neltos":     results.rows.item(i).neltos,
						        "segments":   results.rows.item(i).segments,
						        "user":       results.rows.item(i).user,
						        "sync":       results.rows.item(i).sync,
						        "device":     results.rows.item(i).device });
		       continue;
                   }

                   if (results.rows.item(i).rt == 'last_basalact')
                   { // TODO: check this part is what we expected of it
		       js_record = { "id":         results.rows.item(i).id,
				     "pattern":    results.rows.item(i).pattern,
				     "neltos":     results.rows.item(i).neltos,
				     "segments":   results.rows.item(i).segments,
				     "percentage": results.rows.item(i).percentage,
				     "start":      results.rows.item(i).start,
				     "user":       results.rows.item(i).user,
				     "sync":       results.rows.item(i).sync,
				     "device":     results.rows.item(i).device };

		       if (typeof vector_details['basalact'] === 'undefined')
		           vector_details['basalact'] = new Array() ;

		       vector_details['basalact'].push(js_record) ;
		       continue;
                   }

                   // timestamp event
		   dt = new XDate(results.rows.item(i).start);

		   if ($.inArray(dt.getDate(), day_arr) == -1)
		       continue ;

		   i_h = dt.toUTCString('HH:mm') ;
		   i_d = dt.toUTCString('yyyy-MM-dd') ;

		   if (typeof vector_details[i_d] === 'undefined')
		       vector_details[i_d] = new Array() ;
		   if (typeof vector_details[i_d][i_h] === 'undefined')
		       vector_details[i_d][i_h] = new Array() ;

                   if (results.rows.item(i).rt == 'bolus')
                   {
		       vector_details[i_d][i_h]["bolus"]    = { "id":         results.rows.item(i).id,
							        "name":       results.rows.item(i).name,
						    	        "type":       results.rows.item(i).type,
							        "units":      results.rows.item(i).units,
							        "percentage": results.rows.item(i).percentage,
							        "start":      results.rows.item(i).start,
							        "stop":       results.rows.item(i).stop,
							        "user":       results.rows.item(i).user,
							        "sync":       results.rows.item(i).sync,
							        "device":     results.rows.item(i).device };
		       continue;
                   }

                   if (results.rows.item(i).rt == 'meal')
                   {
		       vector_details[i_d][i_h]["meal"]    =  { "id":         results.rows.item(i).id,
							        "name":       results.rows.item(i).name,
						        	"tag":        results.rows.item(i).tag,
						        	"image":      results.rows.item(i).image,
							        "measure":    results.rows.item(i).measure,
							        "start":      results.rows.item(i).start,
							        "stop":       results.rows.item(i).stop,
							        "user":       results.rows.item(i).user,
							        "sync":       results.rows.item(i).sync,
							        "device":     results.rows.item(i).device };
		       continue;
                   }

                   if (results.rows.item(i).rt == 'measure')
                   {
		       vector_details[i_d][i_h]["measure"]  = { "id":         results.rows.item(i).id,
							        "name":       results.rows.item(i).name,
							        "measure":    results.rows.item(i).measure,
							        "start":      results.rows.item(i).start,
							        "stop":       results.rows.item(i).stop,
							        "user":       results.rows.item(i).user,
							        "sync":       results.rows.item(i).sync,
							        "device":     results.rows.item(i).device };
		       continue;
                   }

                   if (results.rows.item(i).rt == 'event')
                   {
		       vector_details[i_d][i_h]["event"]    = { "id":         results.rows.item(i).id,
							        "name":       results.rows.item(i).name,
							        "event":      results.rows.item(i).event,
							        "type":       results.rows.item(i).type,
							        "measure":    results.rows.item(i).measure,
							        "start":      results.rows.item(i).start,
							        "stop":       results.rows.item(i).stop,
							        "user":       results.rows.item(i).user,
							        "image":      results.rows.item(i).image,
							        "sync":       results.rows.item(i).sync,
							        "device":     results.rows.item(i).device };
		       continue;
                   }

                   if (results.rows.item(i).rt == 'basalact')
                   {
		       js_record = { "id":         results.rows.item(i).id,
				     "pattern":    results.rows.item(i).pattern,
				     "neltos":     results.rows.item(i).neltos,
				     "segments":   results.rows.item(i).segments,
				     "percentage": results.rows.item(i).percentage,
				     "start":      results.rows.item(i).start,
				     "user":       results.rows.item(i).user,
				     "sync":       results.rows.item(i).sync,
				     "device":     results.rows.item(i).device };

		       vector_details[i_d][i_h]["basalact"] = js_record ;

		       if (typeof vector_details['basalact'] === 'undefined')
		           vector_details['basalact'] = new Array() ;

		       vector_details["basalact"].push(js_record) ;
		       continue;
                   }
		}

                if (qs_index == (qs.length-1))
	            ok_handler();
	     },
	     function(error, statement)
	     {
		   console.error('Error: ' + error.message + '.');
	     }
	);
  }

  function db_webdb2js ( working_grid, login_id, ok_handler )
  {
          // no var because it is global...
          vector_details = new Array();

          html5sql.openDatabase("em", "Event Monitor", 4*1024*1024) ;

          var first_period = 1;
          for (year in working_grid)
          {
               for (month in working_grid[year])
               {
                   var min_day = 32 ;
                   var day_arr = new Array() ;
		   for (day in working_grid[year][month]) {
                        var nday = parseInt(day) ;
                        if (nday < min_day)
                            min_day = nday ;
                        day_arr.push(nday, 10) ;
                   }

		   var twodigits_month = ("0" + month).slice(-2) ;
		   var twodigits_mday  = ("0" + min_day).slice(-2) ;

		   qs = new Array() ;
		   qs.push(" SELECT 'bolus' as 'rt',* FROM bolus " +
			   " WHERE strftime('%Y',start)='" + year + "' " +
			   " AND   strftime('%m',start)='" + twodigits_month + "' " +
			   " AND   user='" + login_id + "' " +
			   " AND   units!=0" +
			   " ORDER BY start;") ;
		   qs.push(" SELECT 'meal' as 'rt',* FROM meals " +
			   " WHERE strftime('%Y',start)='" + year + "' " +
			   " AND   strftime('%m',start)='" + twodigits_month + "' " +
			   " AND   user='" + login_id + "' " +
			   " AND   measure!=0" +
			   " ORDER BY start;") ;
	           qs.push(" SELECT 'measure' as 'rt',* FROM measures " +
			   " WHERE strftime('%Y',start)='" + year + "' " +
			   " AND   strftime('%m',start)='" + twodigits_month + "' " +
			   " AND   user='" + login_id + "' " +
			   " AND   measure!=0" +
			   " ORDER BY start;") ;
	           qs.push(" SELECT 'event' as 'rt',* FROM events " +
			   " WHERE strftime('%Y',start)='" + year + "' " +
			   " AND   strftime('%m',start)='" + twodigits_month + "' " +
			   " AND   user='" + login_id + "' " +
			   " AND   event!=''" +
			   " ORDER BY start;") ;
	           qs.push(" SELECT 'basalact' as 'rt',* FROM basal_activations " +
			   " WHERE strftime('%Y',start)='" + year + "' " +
			   " AND   strftime('%m',start)='" + twodigits_month + "' " +
			   " AND   user='" + login_id + "' " +
			   " AND   percentage!=0" +
			   " ORDER BY start;") ;

                   if (1 == first_period)
		      {
		         qs.push(" SELECT 'last_basalact' as 'rt',* FROM basal_activations " +
		                 " WHERE strftime('%Y',start)<='" + year + "' " +
		                 " AND   strftime('%m',start)<='" + twodigits_month + "' " +
		                 " AND   strftime('%d',start)<'"  + twodigits_mday  + "' " +
		                 " AND   user='" + login_id + "' " +
                                 " AND   percentage!=0 " +
                                 " ORDER BY start DESC " +
                                 " LIMIT 1 ");
			 qs.push(" SELECT 'basaldef' as 'rt',* FROM basal_definitions " +
				 " WHERE user='" + login_id + "' " +
				 " AND   neltos!=0" +
				 " ORDER BY sync;") ;
                         first_period = 0;
                      }

                   db_webdb2js_aux(day_arr,qs,0,vector_details,ok_handler) ;
               }
          }

          return vector_details;
  }

<commit_msg>minor changes<commit_after>
  function db_webdb2js_aux ( day_arr, qs, qs_index, vector_details, ok_handler )
  {
        html5sql.process(
             qs[qs_index],
	     function(transaction, results, v)
	     {
                if (qs_index < (qs.length-1))
                    db_webdb2js_aux(day_arr,qs,qs_index+1,vector_details,ok_handler);

		for (var i=0; i<results.rows.length; i++)
		{
                   // non-timestamp event
                   if (results.rows.item(i).rt == 'basaldef')
                   {
		       if (typeof vector_details['basaldef'] === 'undefined')
		           vector_details['basaldef'] = new Array() ;

		       vector_details["basaldef"].push({"id":         results.rows.item(i).id,
						        "pattern":    results.rows.item(i).pattern,
						        "neltos":     results.rows.item(i).neltos,
						        "segments":   results.rows.item(i).segments,
						        "user":       results.rows.item(i).user,
						        "sync":       results.rows.item(i).sync,
						        "device":     results.rows.item(i).device });
		       continue;
                   }

                   if (results.rows.item(i).rt == 'last_basalact')
                   { // TODO: check this part is what we expected of it
		       js_record = { "id":         results.rows.item(i).id,
				     "pattern":    results.rows.item(i).pattern,
				     "neltos":     results.rows.item(i).neltos,
				     "segments":   results.rows.item(i).segments,
				     "percentage": results.rows.item(i).percentage,
				     "start":      results.rows.item(i).start,
				     "user":       results.rows.item(i).user,
				     "sync":       results.rows.item(i).sync,
				     "device":     results.rows.item(i).device };

		       if (typeof vector_details['basalact'] === 'undefined')
		           vector_details['basalact'] = new Array() ;

		       vector_details['basalact'].push(js_record) ;
		       continue;
                   }

                   // timestamp event
		   dt = new XDate(results.rows.item(i).start);

		   if ($.inArray(dt.getDate(), day_arr) == -1)
		       continue ;

		   i_h = dt.toUTCString('HH:mm') ;
		   i_d = dt.toUTCString('yyyy-MM-dd') ;

		   if (typeof vector_details[i_d] === 'undefined')
		       vector_details[i_d] = new Array() ;
		   if (typeof vector_details[i_d][i_h] === 'undefined')
		       vector_details[i_d][i_h] = new Array() ;

                   if (results.rows.item(i).rt == 'bolus')
                   {
		       vector_details[i_d][i_h]["bolus"]    = { "id":         results.rows.item(i).id,
							        "name":       results.rows.item(i).name,
						    	        "type":       results.rows.item(i).type,
							        "units":      results.rows.item(i).units,
							        "percentage": results.rows.item(i).percentage,
							        "start":      results.rows.item(i).start,
							        "stop":       results.rows.item(i).stop,
							        "user":       results.rows.item(i).user,
							        "sync":       results.rows.item(i).sync,
							        "device":     results.rows.item(i).device };
		       continue;
                   }

                   if (results.rows.item(i).rt == 'meal')
                   {
		       vector_details[i_d][i_h]["meal"]    =  { "id":         results.rows.item(i).id,
							        "name":       results.rows.item(i).name,
						        	"tag":        results.rows.item(i).tag,
						        	"image":      results.rows.item(i).image,
							        "measure":    results.rows.item(i).measure,
							        "start":      results.rows.item(i).start,
							        "stop":       results.rows.item(i).stop,
							        "user":       results.rows.item(i).user,
							        "sync":       results.rows.item(i).sync,
							        "device":     results.rows.item(i).device };
		       continue;
                   }

                   if (results.rows.item(i).rt == 'measure')
                   {
		       vector_details[i_d][i_h]["measure"]  = { "id":         results.rows.item(i).id,
							        "name":       results.rows.item(i).name,
							        "measure":    results.rows.item(i).measure,
							        "start":      results.rows.item(i).start,
							        "stop":       results.rows.item(i).stop,
							        "user":       results.rows.item(i).user,
							        "sync":       results.rows.item(i).sync,
							        "device":     results.rows.item(i).device };
		       continue;
                   }

                   if (results.rows.item(i).rt == 'event')
                   {
		       vector_details[i_d][i_h]["event"]    = { "id":         results.rows.item(i).id,
							        "name":       results.rows.item(i).name,
							        "event":      results.rows.item(i).event,
							        "type":       results.rows.item(i).type,
							        "measure":    results.rows.item(i).measure,
							        "start":      results.rows.item(i).start,
							        "stop":       results.rows.item(i).stop,
							        "user":       results.rows.item(i).user,
							        "image":      results.rows.item(i).image,
							        "sync":       results.rows.item(i).sync,
							        "device":     results.rows.item(i).device };
		       continue;
                   }

                   if (results.rows.item(i).rt == 'basalact')
                   {
		       js_record = { "id":         results.rows.item(i).id,
				     "pattern":    results.rows.item(i).pattern,
				     "neltos":     results.rows.item(i).neltos,
				     "segments":   results.rows.item(i).segments,
				     "percentage": results.rows.item(i).percentage,
				     "start":      results.rows.item(i).start,
				     "user":       results.rows.item(i).user,
				     "sync":       results.rows.item(i).sync,
				     "device":     results.rows.item(i).device };

		       vector_details[i_d][i_h]["basalact"] = js_record ;

		       if (typeof vector_details['basalact'] === 'undefined')
		           vector_details['basalact'] = new Array() ;

		       vector_details["basalact"].push(js_record) ;
		       continue;
                   }
		}

                if (qs_index == (qs.length-1))
	            ok_handler();
	     },
	     function(error, statement)
	     {
		   console.error('Error: ' + error.message + '.');
	     }
	);
  }

  function db_webdb2js ( working_grid, login_id, ok_handler )
  {
          // no var because it is global...
          vector_details = new Array();

          html5sql.openDatabase("em", "Event Monitor", 4*1024*1024) ;

          var first_period = 1;
          for (year in working_grid)
          {
               for (month in working_grid[year])
               {
                   var min_day = 32 ;
                   var day_arr = new Array() ;
		   for (day in working_grid[year][month]) {
                        var nday = parseInt(day) ;
                        if (nday < min_day)
                            min_day = nday ;
                        day_arr.push(nday, 10) ;
                   }

		   var twodigits_month = ("0" + month).slice(-2) ;
		   var twodigits_mday  = ("0" + min_day).slice(-2) ;

		   qs = new Array() ;
		   qs.push(" SELECT 'bolus' as 'rt',* FROM bolus " +
			   " WHERE strftime('%Y-%m',start)='" + year + "-" + twodigits_month + "' " +
			   " AND   user='" + login_id + "' " +
			   " AND   units!=0" +
			   " ORDER BY start;") ;
		   qs.push(" SELECT 'meal' as 'rt',* FROM meals " +
			   " WHERE strftime('%Y-%m',start)='" + year + "-" + twodigits_month + "' " +
			   " AND   user='" + login_id + "' " +
			   " AND   measure!=0" +
			   " ORDER BY start;") ;
	           qs.push(" SELECT 'measure' as 'rt',* FROM measures " +
			   " WHERE strftime('%Y-%m',start)='" + year + "-" + twodigits_month + "' " +
			   " AND   user='" + login_id + "' " +
			   " AND   measure!=0" +
			   " ORDER BY start;") ;
	           qs.push(" SELECT 'event' as 'rt',* FROM events " +
			   " WHERE strftime('%Y-%m',start)='" + year + "-" + twodigits_month + "' " +
			   " AND   user='" + login_id + "' " +
			   " AND   event!=''" +
			   " ORDER BY start;") ;
	           qs.push(" SELECT 'basalact' as 'rt',* FROM basal_activations " +
			   " WHERE strftime('%Y-%m',start)='" + year + "-" + twodigits_month + "' " +
			   " AND   user='" + login_id + "' " +
			   " AND   percentage!=0" +
			   " ORDER BY start;") ;

                   if (1 == first_period)
		      {
		         qs.push(" SELECT 'last_basalact' as 'rt',* FROM basal_activations " +
		                 " WHERE strftime('%Y-%m-%d',start)<='" + year + "-" + twodigits_month + "-" + twodigits_mday + "' " +
		                 " AND   user='" + login_id + "' " +
                                 " AND   percentage!=0 " +
                                 " ORDER BY start DESC " +
                                 " LIMIT 1 ");
			 qs.push(" SELECT 'basaldef' as 'rt',* FROM basal_definitions " +
				 " WHERE user='" + login_id + "' " +
				 " AND   neltos!=0" +
				 " ORDER BY sync;") ;
                         first_period = 0;
                      }

                   db_webdb2js_aux(day_arr,qs,0,vector_details,ok_handler) ;
               }
          }

          return vector_details;
  }

<|endoftext|>


<commit_before>//= require "../chrome/storage"

// shortcut method
var push = Array.prototype.push;

var Libraries = function () {
  this.init();

  this.userSpecified = localStorage.getItem('libraries') || [];

  // read from storage
  for (i = 0; i < this.userSpecified.length; i++) {
    push.call(this, this.userSpecified[i]);
  }
};

Libraries.prototype.init = function () {
  var libs = {
    yui: {
      text: 'YUI',
      scripts: [
        { text: 'YUI 2.8.0r4', url: 'http://ajax.googleapis.com/ajax/libs/yui/2.8.0r4/build/yuiloader/yuiloader-min.js'},
        { text: 'YUI 2.7.0', url: 'http://ajax.googleapis.com/ajax/libs/yui/2.7.0/build/yuiloader/yuiloader-min.js' }
      ]
    },
    mootools: {
      text: 'MooTools',
      scripts: [
        { text: 'Mootools 1.2.4', url: 'http://ajax.googleapis.com/ajax/libs/mootools/1.2.4/mootools-yui-compressed.js' },
        { text: 'Mootools 1.2.3', url: 'http://ajax.googleapis.com/ajax/libs/mootools/1.2.3/mootools-yui-compressed.js'}
      ]
    },
    prototype: {
      text: 'Prototype',
      scripts: [
        { text: 'Prototype latest', url: 'http://ajax.googleapis.com/ajax/libs/prototype/1/prototype.js' },
        { text: 'Prototype 1.6.1.0', url: 'http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js' },
        { text: 'Prototype 1.6.0.3', url: 'http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js'}
      ]
    },
    jquery: {
      text: 'jQuery',
      scripts: [
        { text: 'jQuery latest', url: 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' },
        { text: 'jQuery 1.4.2', url: 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js' },
        { text: 'jQuery 1.4.0', url: 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js' },
        { text: 'jQuery 1.3.2', url: 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js' },
        { text: 'jQuery 1.2.6', url: 'http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js' }
      ]
    },
    jqueryui : {
      text: 'jQuery UI',
      requires: 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js',
      style: 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css',
      scripts: [
        { text: 'jQuery UI 1.7.2', url: 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js' }
        // { text: 'jQuery UI 1.6', url: 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.6/jquery-ui.min.js' }
      ]
    },
    scriptaculous: {
      text: 'script.aculo.us',
      requires: 'http://ajax.googleapis.com/ajax/libs/prototype/1/prototype.js',
      scripts: [
        { text: 'script.aculo.us 1.8.3', url: 'http://ajax.googleapis.com/ajax/libs/scriptaculous/1.8.3/scriptaculous.js' }
      ]
    },
    dojo : {
      text: 'Dojo',
      scripts: [
        { text: 'Dojo 1.4.1', url: 'http://ajax.googleapis.com/ajax/libs/dojo/1.4.1/dojo/dojo.xd.js' },
        { text: 'Dojo 1.3.2', url: 'http://ajax.googleapis.com/ajax/libs/dojo/1.3.2/dojo/dojo.xd.js' }
      ]
    },
    ext : {
      text: 'Ext Core',
      style: 'http://extjs.cachefly.net/ext-2.2/resources/css/ext-all.css',
      scripts: [
        { text: 'Ext Core 3.1', url: 'http://ajax.googleapis.com/ajax/libs/ext-core/3.1.0/ext-core.js' }
      ]
    }
  },
  order = 'jquery jqueryui prototype scriptaculous yui mootools dojo ext'.split(' '),
  i = 0;

  this.length = 0; // triggers support for length prop
  for (i = 0; i < order.length; i++) {
    push.call(this, libs[order[i]]);
  }
};

Libraries.prototype.add = function (lib) {
  // save to localStorage
  this.userSpecified.push(lib);
  try {
    localStorage.setItem('libraries', this.userSpecified);
  } catch (e) {} // just in case of DOM_22 error, makes me so sad to use this :(
  push.call(this, lib);
  $('#library').trigger('init');
};

Libraries.prototype.clear = function () {
  this.userSpecified = [];
  localStorage.removeItem('libraries');
  this.init();
  $('#library').trigger('init');
};

// OO based to all me to fiddle the object to resemble an array
var libraries = new Libraries();
window.libraries = libraries; // expose a command line API<commit_msg>User defined libraries weren't be JSONified. f:15 fixes #20<commit_after>//= require "../chrome/storage"

// shortcut method
var push = Array.prototype.push;

var Libraries = function () {
  this.init();

  this.userSpecified = JSON.parse(localStorage.getItem('libraries') || "[]");

  // read from storage
  for (i = 0; i < this.userSpecified.length; i++) {
    push.call(this, this.userSpecified[i]);
  }
};

Libraries.prototype.init = function () {
  var libs = {
    yui: {
      text: 'YUI',
      scripts: [
        { text: 'YUI 2.8.0r4', url: 'http://ajax.googleapis.com/ajax/libs/yui/2.8.0r4/build/yuiloader/yuiloader-min.js'},
        { text: 'YUI 2.7.0', url: 'http://ajax.googleapis.com/ajax/libs/yui/2.7.0/build/yuiloader/yuiloader-min.js' }
      ]
    },
    mootools: {
      text: 'MooTools',
      scripts: [
        { text: 'Mootools 1.2.4', url: 'http://ajax.googleapis.com/ajax/libs/mootools/1.2.4/mootools-yui-compressed.js' },
        { text: 'Mootools 1.2.3', url: 'http://ajax.googleapis.com/ajax/libs/mootools/1.2.3/mootools-yui-compressed.js'}
      ]
    },
    prototype: {
      text: 'Prototype',
      scripts: [
        { text: 'Prototype latest', url: 'http://ajax.googleapis.com/ajax/libs/prototype/1/prototype.js' },
        { text: 'Prototype 1.6.1.0', url: 'http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js' },
        { text: 'Prototype 1.6.0.3', url: 'http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js'}
      ]
    },
    jquery: {
      text: 'jQuery',
      scripts: [
        { text: 'jQuery latest', url: 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' },
        { text: 'jQuery 1.4.2', url: 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js' },
        { text: 'jQuery 1.4.0', url: 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js' },
        { text: 'jQuery 1.3.2', url: 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js' },
        { text: 'jQuery 1.2.6', url: 'http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js' }
      ]
    },
    jqueryui : {
      text: 'jQuery UI',
      requires: 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js',
      style: 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css',
      scripts: [
        { text: 'jQuery UI 1.7.2', url: 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js' }
        // { text: 'jQuery UI 1.6', url: 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.6/jquery-ui.min.js' }
      ]
    },
    scriptaculous: {
      text: 'script.aculo.us',
      requires: 'http://ajax.googleapis.com/ajax/libs/prototype/1/prototype.js',
      scripts: [
        { text: 'script.aculo.us 1.8.3', url: 'http://ajax.googleapis.com/ajax/libs/scriptaculous/1.8.3/scriptaculous.js' }
      ]
    },
    dojo : {
      text: 'Dojo',
      scripts: [
        { text: 'Dojo 1.4.1', url: 'http://ajax.googleapis.com/ajax/libs/dojo/1.4.1/dojo/dojo.xd.js' },
        { text: 'Dojo 1.3.2', url: 'http://ajax.googleapis.com/ajax/libs/dojo/1.3.2/dojo/dojo.xd.js' }
      ]
    },
    ext : {
      text: 'Ext Core',
      style: 'http://extjs.cachefly.net/ext-2.2/resources/css/ext-all.css',
      scripts: [
        { text: 'Ext Core 3.1', url: 'http://ajax.googleapis.com/ajax/libs/ext-core/3.1.0/ext-core.js' }
      ]
    }
  },
  order = 'jquery jqueryui prototype scriptaculous yui mootools dojo ext'.split(' '),
  i = 0;

  this.length = 0; // triggers support for length prop
  for (i = 0; i < order.length; i++) {
    push.call(this, libs[order[i]]);
  }
};

Libraries.prototype.add = function (lib) {
  // save to localStorage
  this.userSpecified.push(lib);
  try {
    localStorage.setItem('libraries', JSON.stringify(this.userSpecified));
  } catch (e) {} // just in case of DOM_22 error, makes me so sad to use this :(
  push.call(this, lib);
  $('#library').trigger('init');
};

Libraries.prototype.clear = function () {
  this.userSpecified = [];
  localStorage.removeItem('libraries');
  this.init();
  $('#library').trigger('init');
};

// OO based to all me to fiddle the object to resemble an array
var libraries = new Libraries();
window.libraries = libraries; // expose a command line API<|endoftext|>


<commit_before>define(["elaiJS/helper", "elaiJS/binder", "elaiJS/promise",
        "elaiJS/multicallback", "elaiJS/propertiesManagerFactory",
        "elaiJS/configuration", "elaiJS/ressources", "elaiJS/mode",
        "elaiJS/navigator", "elaiJS/webservice",
        "elaiJS/defaultWebservices","elaiJS/defaultConfiguration",
        "elaiJS/theme", "elaiJS/language", "elaiJS/localisation"],
        function(helper, b, Promise, c, p, config, r, m, navigator,
          w, defaultWebservices, defaultConfig, themeManager, lang, loc) {

	function initialize() {
	  loadWidgetModules();

    defaultWebservices.addDefaultWebservices();
	  defaultConfig.setDefaultConfiguration(function() {
	    launchDebugMode();
	    initalizeModules().then(start);
	  });
	}

	function loadWidgetModules() {
    require([ "elaiJS/plugin", "elaiJS/widget", "elaiJS/primaryWidget",
              "elaiJS/mustacherend", "elaiJS/polymerend"]);
	}

	function initalizeModules() {
	  initializeModule(navigator, undefined, config.elaiJS.skipNavigatorInitialization);

    return Promise.all([
    	initializeModule(themeManager),
    	initializeModule(lang, config.elaiJS.skipLanguageInitialization),
    	initializeModule(loc, config.elaiJS.skipLocalisationInitialization)
    ]);
	}

	function initializeModule(module, skipInit) {
	  if(skipInit === true)
      return Promise.resolve();

    return module.initialize();
	}

	function start() {
	  if(config.elaiJS.requireElaiJS)
      config.elaiJS.requireElaiJS.setConfig(config);

    if(console && console.timeEnd && config.elaiJS.isDebug)
      console.timeEnd("ElaiJS Start in");

    loadAppMain();
	}

	function loadAppMain() {
    var appModuleName = helper.getElaiJSAttribute("app");
    if(!appModuleName)
      return;

    require([appModuleName], function(appMain) {
      if(appMain && helper.isFunction(appMain.start))
        appMain.start();
    });
  }

  function launchDebugMode() {
    if(config.elaiJS.isDebug) {
      require(["elaiJS/debugManager"], function(debugManager) {
        debugManager.startDebugMode();
      });
    }
  }

  initialize();

  return {};
});

/*
  TODO:
  Ajouter 'on' and 'emit' for binder
*/

/*
  name
    Events - beforeName
    PluginsCall - nameBeforeWidget
    WidgetCall  - _name
    PluginsCall - nameAfterWidget
    ChildrenCallIsNeeded - name
    Events - afterName
*/<commit_msg>Adapt defaultConfig callback change and multicallback deletion<commit_after>define(["elaiJS/helper", "elaiJS/binder", "elaiJS/promise",
        "elaiJS/propertiesManagerFactory", "elaiJS/configuration",
        "elaiJS/ressources", "elaiJS/mode", "elaiJS/navigator",
        "elaiJS/webservice", "elaiJS/defaultWebservices",
        "elaiJS/defaultConfiguration", "elaiJS/theme",
        "elaiJS/language", "elaiJS/localisation"],
        function(helper, b, Promise, p, config, r, m, navigator,
          w, defaultWebservices, defaultConfig, themeManager, lang, loc) {

	function initialize() {
	  loadWidgetModules();

    defaultWebservices.addDefaultWebservices();
	  defaultConfig.setDefaultConfiguration().then(function() {
	    launchDebugMode();
	    initalizeModules().then(start);
	  });
	}

	function loadWidgetModules() {
    require([ "elaiJS/plugin", "elaiJS/widget", "elaiJS/primaryWidget",
              "elaiJS/mustacherend", "elaiJS/polymerend"]);
	}

	function initalizeModules() {
	  initializeModule(navigator, undefined, config.elaiJS.skipNavigatorInitialization);

    return Promise.all([
    	initializeModule(themeManager),
    	initializeModule(lang, config.elaiJS.skipLanguageInitialization),
    	initializeModule(loc, config.elaiJS.skipLocalisationInitialization)
    ]);
	}

	function initializeModule(module, skipInit) {
	  if(skipInit === true)
      return Promise.resolve();

    return module.initialize();
	}

	function start() {
	  if(config.elaiJS.requireElaiJS)
      config.elaiJS.requireElaiJS.setConfig(config);

    if(console && console.timeEnd && config.elaiJS.isDebug)
      console.timeEnd("ElaiJS Start in");

    loadAppMain();
	}

	function loadAppMain() {
    var appModuleName = helper.getElaiJSAttribute("app");
    if(!appModuleName)
      return;

    require([appModuleName], function(appMain) {
      if(appMain && helper.isFunction(appMain.start))
        appMain.start();
    });
  }

  function launchDebugMode() {
    if(config.elaiJS.isDebug) {
      require(["elaiJS/debugManager"], function(debugManager) {
        debugManager.startDebugMode();
      });
    }
  }

  initialize();

  return {};
});

/*
  TODO:
  Ajouter 'on' and 'emit' for binder
*/

/*
  name
    Events - beforeName
    PluginsCall - nameBeforeWidget
    WidgetCall  - _name
    PluginsCall - nameAfterWidget
    ChildrenCallIsNeeded - name
    Events - afterName
*/<|endoftext|>


<commit_before>/**
 * Player Entity
 */
game.PlayerEntity = me.Entity.extend({

    /**
     * constructor
     */
    init:function (x, y, settings) {
        // call the constructor
		settings.image = "player";

		var width = settings.width;
		var height = settings.height;

		settings.spritewidth = settings.width = 32;
		settings.spritewidth = settings.height = 32;

        this._super(me.Entity, 'init', [x, y , settings]);

		this.body.gravity = 0.0;

		this.body.setVelocity(3,3);

		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

		this.alwaysUpdate = true;

		this.renderable.addAnimation("run_right", [6,7,8] );
		this.renderable.addAnimation("run_left", [3,4,5]);
		this.renderable.addAnimation("run_down", [0,1,2]);
		this.renderable.addAnimation("run_up", [9, 10, 11]);
		this.renderable.addAnimation("stand", [6]);
		this.renderable.addAnimation("downstand", [0]);
		this.renderable.addAnimation("upstand", [9]);
		this.renderable.setCurrentAnimation("stand");

    },

    /**
     * update the entity
     */
    update : function (dt) {

		if(me.input.isKeyPressed('left')) {
			this.renderable.flipX(true);
			this.body.vel.x -= this.body.accel.x * me.timer.tick;

			if(!this.renderable.isCurrentAnimation("run_right")){
				this.renderable.setCurrentAnimation("run_right");
			}
		}
		else if(me.input.isKeyPressed('right')){
			this.renderable.flipX(false);
			this.body.vel.x += this.body.accel.x* me.timer.tick;
			if(!this.renderable.isCurrentAnimation("run_right")){
				this.renderable.setCurrentAnimation("run_right");
			}
		}
		else if(me.input.isKeyPressed('down')){
			this.renderable.setCurrentAnimation("run_down");
			this.renderable.flipY(false);
			this.body.vel.y += this.body.accel.y*me.timer.tick;
			if(!this.renderable.isCurrentAnimation("run_down")){
				this.renderable.setCurrentAnimation("run_down");
			}
		}
		else if(me.input.isKeyPressed('up')){
			this.renderable.setCurrentAnimation("run_up");
			this.body.vel.y -= this.body.accel.y* me.timer.tick;
			if(!this.renderable.isCurrentAnimation("run_up")){
				this.renderable.setCurrentAnimation("run_up");
			}
		}
		else{
			this.body.vel.x = 0;
			this.body.vel.y=0;
			this.renderable.setCurrentAnimation("stand");
		}

        // apply physics to the body (this moves the entity)
        this.body.update(dt);

        // handle collisions against other shapes
        me.collision.check(this);

        // return true if we moved or if the renderable was updated
        return (this._super(me.Entity, 'update', [dt]) || this.body.vel.x !== 0 || this.body.vel.y !== 0);
    },

   /**
     * colision handler
     * (called when colliding with other objects)
     */
    onCollision : function (response, other) {
        // Make all other objects solid
        return true;
    }
});<commit_msg>MAIN CHARACTER SPRITE<commit_after>/**
 * Player Entity
 */
game.PlayerEntity = me.Entity.extend({

    /**
     * constructor
     */
    init:function (x, y, settings) {
        // call the constructor
		settings.image = "player";

		var width = settings.width;
		var height = settings.height;

		settings.spritewidth = settings.width = 32;
		settings.spritewidth = settings.height = 32;

        this._super(me.Entity, 'init', [x, y , settings]);

		this.body.gravity = 0.0;

		this.body.setVelocity(3,3);

		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

		this.alwaysUpdate = true;

		this.renderable.addAnimation("run_right", [6,7,8] );
		this.renderable.addAnimation("run_left", [3,4,5]);
		this.renderable.addAnimation("run_down", [0,1,2]);
		this.renderable.addAnimation("run_up", [9, 10, 11]);
		this.renderable.addAnimation("left_stand", [3]);
		this.renderable.addAnimation("right_stand", [6]);
		this.renderable.addAnimation("down_stand", [0]);
		this.renderable.addAnimation("up_stand", [9]);
		this.renderable.setCurrentAnimation("right_stand");

    },

    /**
     * update the entity
     */
    update : function (dt) {

		if(me.input.isKeyPressed('left')) {
			this.renderable.flipX(true);
			this.body.vel.x -= this.body.accel.x * me.timer.tick;
			if(!this.renderable.isCurrentAnimation("run_right")){
				this.renderable.setCurrentAnimation("run_right");
			}
		}
		else if(me.input.isKeyPressed('right')){
			this.renderable.flipX(false);
			this.body.vel.x += this.body.accel.x* me.timer.tick;
			if(!this.renderable.isCurrentAnimation("run_right")){
				this.renderable.setCurrentAnimation("run_right");
			}
		}
		else if(me.input.isKeyPressed('down')){
			this.body.vel.y += this.body.accel.y*me.timer.tick;
			 if(!this.renderable.isCurrentAnimation("run_down")){
				this.renderable.setCurrentAnimation("run_down");
			}
		}
		else if(me.input.isKeyPressed('up')){
			this.body.vel.y -= this.body.accel.y* me.timer.tick;
			if(!this.renderable.isCurrentAnimation("run_up")){
				this.renderable.setCurrentAnimation("run_up");
			}
		}
		else{
			this.body.vel.x = 0;
			this.body.vel.y=0;

			if(me.input.isKeyPressed("up")){
				this.renderable.setCurrentAnimation("up_stand");
			}
			else if (me.input.isKeyPressed("down")){
				this.renderable.setCurrentAnimation("down_stand");
			}
			else{
				this.renderable.setCurrentAnimation("right_stand");
			}
		}

        // apply physics to the body (this moves the entity)
        this.body.update(dt);

        // handle collisions against other shapes
        me.collision.check(this);

        // return true if we moved or if the renderable was updated
        return (this._super(me.Entity, 'update', [dt]) || this.body.vel.x !== 0 || this.body.vel.y !== 0);
    },

   /**
     * colision handler
     * (called when colliding with other objects)
     */
    onCollision : function (response, other) {
        // Make all other objects solid
        return true;
    }
});<|endoftext|>


<commit_before>game.PlayerEntity = me.Entity.extend ({
	// constructer function to set us up
	init: function(x, y, settings) {
		this._super(me.Entity, 'init', [x, y, {
			image: "player",
			// what amount of space to preserve
			width: 64,
			height: 64,
			spritewidth: "64",
			spriteheight: "64",
			getShape: function () {
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);
		this.type = "PlayerEntity";
		// chooses velocity for our player
		this.health = game.data.playerHealth;
		this.body.setVelocity(game.data.playerMoveSpeed, 20);
		// keeps track of which direction your character is going
		this.facing = "right";
		this.now = new Date().getTime();
		this.lastHit = this.now;
		this.dead = false;
		this.attack = game.data.playerAttack;
		this.lastAttack = new Date().getTime();
		// no matter where the player goes it will will follow him
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
		// this is the standing animation
		this.renderable.addAnimation("idle", [78]);
		//this is to add the walking animation.
		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);
		// to set the walking animation.
		this.renderable.setCurrentAnimation("idle");
	},

	update: function(delta) {
		this.now = new Date().getTime();
		//
		if(this.health <= 0) {
			this.dead = true;

		}

		// to see if right key is pressed
		if(me.input.isKeyPressed("right")){
			// adds to the postion of my x by the velocity defined above in
			//setVelocity() and multiplying it by me.timer.tick
			//me.timer.tick makes the movement look smooth
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			//to face right
			this.facing = "right";
			// to flip the character the right way
			this.flipX(true);
			// to see if left key is pressed
		}else if(me.input.isKeyPressed("left")){
			this.facing = "left";
			// same things goes for the comments for right
			this.body.vel.x -=this.body.accel.x * me.timer.tick;
			// to not flip the character
			this.flipX(false);
		}else{
			// if youre not pressing the right key then the player wont move
			this.body.vel.x = 0;
		}
		// makes the player jump and fall back down
		if(me.input.isKeyPressed("jump") && !this.body.jumping && !this.body.falling) {
			this.jumping = true;
			this.body.vel.y -= this.body.accel.y * me.timer.tick;
		}
		// hold down attack button
		if(me.input.isKeyPressed("attack")){
			if(!this.renderable.isCurrentAnimation("attack")) {
				//sets the current animation to attack and once that is over
				// goes back to the idle animation
				this.renderable.setCurrentAnimation("attack", "idle");
				//makes it so that the next time we start this sequence
				//from the first animation, not wherever we left off or when we
				//switched to the other animation
				this.renderable.setAnimationFrame();
			}
		}

		// no attack animation going on
		else if(this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack")) {
		if(!this.renderable.isCurrentAnimation("walk")) {
			this.renderable.setCurrentAnimation("walk");
		}
		// if not attacking nothing will work
	}else if(!this.renderable.isCurrentAnimation("attack")) {
		this.renderable.setCurrentAnimation("idle");
	}

		// to collide with the base
		me.collision.check(this, true, this.collideHandler.bind(this), true);

		// delta is change in time
		this.body.update(delta);
		// this is to update our animation
		this._super(me.Entity, "update", [delta]);
		return true;
	},

	loseHealth: function(damage) {
		this.health = this.health - damage;
	},

	// info about the handler
	collideHandler: function(response) {
		// to see whatever were colliding with
		if(response.b.type==='EnemyBaseEntity') {
			//to see what we are dealing with
			// the difference between the player and the y position
			var ydif = this.pos.y - response.b.pos.y;
			// same for x as above
			// to keep track of both objects
			var xdif = this.pos.x - response.b.pos.x;
			// to collide to the top of the base
			// y var to come first
			// not to walk on the base first
			if(ydif<-40 && xdif< 70 && xdif>-35) {
				this.body.falling = false;
				this.body.vel.y = -1;
			}

			// if i gone far from 35 it will stop the character from moving
			else if(xdif>-35 && this.facing==='right' && (xdif<0)) {
				// stop my player from moving
				this.body.vel.x = 0;
				// move the player backwards
				//this.pos.x = this.pos.x -1;
				// keeping me from walking to the left and the right
			}else if(xdif<70 && this.facing==='left'&& (xdif>0)) {
				this.body.vel.x = 0;
				//this.pos.x = this.pos.x +1;

			}
			// if attacking
			// see if its 400 mili seconds since last hit
			if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer) {
				// then we lose health
				this.lastHit = this.now;
				response.b.loseHealth(game.data.playerAttack);
			}

		}else if(response.b.type==='EnemyCreep') {
			var xif = this.pos.x - response.b.pos.x;
			var ydif = this.posy - response.b.pos.y;

			if(xdif>0) {
				//this.pos.x = this.pos.x + 1;
				if(this.facing==="left") {
					this.body.vel.x = 0;
				}
			}else {
				//this.pos.x = this.pos.x - 1;
				if(this.facing==="right") {
					this.body.vel.x = 0;
				}
			}
			if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer
				&& (Math.abs(ydif) <=40) &&
				(((xdif>0) && this.facing==="left") || ((xdif<0) && this.facing==="right"))
				) {
				this.lastHit = this.now;
			//if the creeps health is less than our attack, execute code in if statement
				if(response.b.health <= game.data.playerAttack) {
					//adds one gold for a creep kill
					game.data.gold += 1;
					// keeps track of gold
					console.log("Current gold: " + game.data.gold);
				}

				response.b.loseHealth(game.data.playerAttack);
			}
		}

	}
});

<commit_msg>video 30 refactor init with comments<commit_after>game.PlayerEntity = me.Entity.extend ({
	// constructer function to set us up
	init: function(x, y, settings) {
		this.setSuper();
		this.setPlayerTimers();
		this.setAttributes();
		this.type = "PlayerEntity";
		this.setFlags();

		// no matter where the player goes it will will follow him
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

		this.addAnimation();

		// to set the walking animation.
		this.renderable.setCurrentAnimation("idle");
	},

	setSuper: function() {
		this._super(me.Entity, 'init', [x, y, {
			image: "player",
			// what amount of space to preserve
			width: 64,
			height: 64,
			spritewidth: "64",
			spriteheight: "64",
			getShape: function () {
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);
	},

	setPlayerTimers: function() {
		this.now = new Date().getTime();
		this.lastHit = this.now;
		this.lastAttack = new Date().getTime();
	},

	setAttributes: function() {
		// chooses velocity for our player
		this.health = game.data.playerHealth;
		this.body.setVelocity(game.data.playerMoveSpeed, 20);
		this.attack = game.data.playerAttack;
	},

	setFlags: function() {
		// keeps track of which direction your character is going
		this.facing = "right";
		this.dead = false;
	},

	addAnimation: function() {
		// this is the standing animation
		this.renderable.addAnimation("idle", [78]);
		//this is to add the walking animation.
		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);
	},

	update: function(delta) {
		this.now = new Date().getTime();
		//
		if(this.health <= 0) {
			this.dead = true;

		}

		// to see if right key is pressed
		if(me.input.isKeyPressed("right")){
			// adds to the postion of my x by the velocity defined above in
			//setVelocity() and multiplying it by me.timer.tick
			//me.timer.tick makes the movement look smooth
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			//to face right
			this.facing = "right";
			// to flip the character the right way
			this.flipX(true);
			// to see if left key is pressed
		}else if(me.input.isKeyPressed("left")){
			this.facing = "left";
			// same things goes for the comments for right
			this.body.vel.x -=this.body.accel.x * me.timer.tick;
			// to not flip the character
			this.flipX(false);
		}else{
			// if youre not pressing the right key then the player wont move
			this.body.vel.x = 0;
		}
		// makes the player jump and fall back down
		if(me.input.isKeyPressed("jump") && !this.body.jumping && !this.body.falling) {
			this.jumping = true;
			this.body.vel.y -= this.body.accel.y * me.timer.tick;
		}
		// hold down attack button
		if(me.input.isKeyPressed("attack")){
			if(!this.renderable.isCurrentAnimation("attack")) {
				//sets the current animation to attack and once that is over
				// goes back to the idle animation
				this.renderable.setCurrentAnimation("attack", "idle");
				//makes it so that the next time we start this sequence
				//from the first animation, not wherever we left off or when we
				//switched to the other animation
				this.renderable.setAnimationFrame();
			}
		}

		// no attack animation going on
		else if(this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack")) {
		if(!this.renderable.isCurrentAnimation("walk")) {
			this.renderable.setCurrentAnimation("walk");
		}
		// if not attacking nothing will work
	}else if(!this.renderable.isCurrentAnimation("attack")) {
		this.renderable.setCurrentAnimation("idle");
	}

		// to collide with the base
		me.collision.check(this, true, this.collideHandler.bind(this), true);

		// delta is change in time
		this.body.update(delta);
		// this is to update our animation
		this._super(me.Entity, "update", [delta]);
		return true;
	},

	loseHealth: function(damage) {
		this.health = this.health - damage;
	},

	// info about the handler
	collideHandler: function(response) {
		// to see whatever were colliding with
		if(response.b.type==='EnemyBaseEntity') {
			//to see what we are dealing with
			// the difference between the player and the y position
			var ydif = this.pos.y - response.b.pos.y;
			// same for x as above
			// to keep track of both objects
			var xdif = this.pos.x - response.b.pos.x;
			// to collide to the top of the base
			// y var to come first
			// not to walk on the base first
			if(ydif<-40 && xdif< 70 && xdif>-35) {
				this.body.falling = false;
				this.body.vel.y = -1;
			}

			// if i gone far from 35 it will stop the character from moving
			else if(xdif>-35 && this.facing==='right' && (xdif<0)) {
				// stop my player from moving
				this.body.vel.x = 0;
				// move the player backwards
				//this.pos.x = this.pos.x -1;
				// keeping me from walking to the left and the right
			}else if(xdif<70 && this.facing==='left'&& (xdif>0)) {
				this.body.vel.x = 0;
				//this.pos.x = this.pos.x +1;

			}
			// if attacking
			// see if its 400 mili seconds since last hit
			if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer) {
				// then we lose health
				this.lastHit = this.now;
				response.b.loseHealth(game.data.playerAttack);
			}

		}else if(response.b.type==='EnemyCreep') {
			var xif = this.pos.x - response.b.pos.x;
			var ydif = this.posy - response.b.pos.y;

			if(xdif>0) {
				//this.pos.x = this.pos.x + 1;
				if(this.facing==="left") {
					this.body.vel.x = 0;
				}
			}else {
				//this.pos.x = this.pos.x - 1;
				if(this.facing==="right") {
					this.body.vel.x = 0;
				}
			}
			if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer
				&& (Math.abs(ydif) <=40) &&
				(((xdif>0) && this.facing==="left") || ((xdif<0) && this.facing==="right"))
				) {
				this.lastHit = this.now;
			//if the creeps health is less than our attack, execute code in if statement
				if(response.b.health <= game.data.playerAttack) {
					//adds one gold for a creep kill
					game.data.gold += 1;
					// keeps track of gold
					console.log("Current gold: " + game.data.gold);
				}

				response.b.loseHealth(game.data.playerAttack);
			}
		}

	}
});

<|endoftext|>