<commit_before>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.projectDescription = ko.observable("Description");

    gvm.firstNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("firstNameTableTitle");}, gvm);
    gvm.lastNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("lastNameTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.scoreTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("scoreTableTitle")});
    gvm.filesTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("filesTableTitle")});

    gvm.searchStudent = ko.observable("");

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
            gvm.projectDescription(data[0].description);
        });
    };

    gvm.getStudentListBis = function() {
        $.getJSON('/api/project/' + gvm.projectId + '/students', function(data) {
            data.forEach(function(element){
                viewModel.addTableData(element.id, element.firstname, element.lastname, element.mail, element.assessCount);
            });
        });
    };

    gvm.getStudentList = function() {
        $.getJSON('/api/project/' + gvm.projectId + '/students/', function(data) {
            $.each(data, function(i, item) {

                $.getJSON('/api/project/' + gvm.projectid  + '/student/' + item.id + '/assessed', function(data)
                {
                    viewModel.users.removeAll();
                    data.forEach(function(element)
                    {
                        viewModel.users.push(element.firstname + " " + element.lastname);
                    });

                    viewModel.addTableData(item.id, item.firstname, item.lastname, item.mail, viewModel.users().length);
                });
            });
        });
    };

    gvm.users = ko.observableArray([]);

    gvm.assassedUsers = ko.observableArray([]);

    gvm.tabledata = ko.observableArray([]);

    gvm.tempTableData = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, firstname, lastname, email, countAssessed) {
        // Push data
        var data = countAssessed;
        var tblOject = {tid: id, tfirstname: firstname, tlastname: lastname, tScoreTableBtn: gvm.scoreTableTitle, tFilesTableBtn: gvm.filesTableTitle, tpid: gvm.projectId, email: email, tcountAssessed: data};
        gvm.tabledata.push(tblOject);
    };

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    };

    /*gvm.getAllData = function() {
        $.getJSON('/api/project/getAllData/' + $("#projectHeader").data('value'), function(data) {
            console.log(data);
        });
    }*/
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getStudentListBis();
    //viewModel.getStudentList();

    $("#searchField").bind("keypress", {}, keypressInBox);

}

function keypressInBox(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 13) { //Enter keycode
        $("#searchField").blur();
        getStudentByName();

    }
};

function createPDF(id,name,lastname,email, projectheader, projectdescription)
{
    /*$.getJSON('/api/finalscore/' + viewModel.projectId + '/' + id, function (data) {
        makePDF(id,name,lastname,email,projectheader,projectdescription,data);
        //console.log(data);
    });*/

    $.ajax({
        url: '/api/finalscore/' + viewModel.projectId + '/' + id,
        type: "GET",
        dataType: 'json',
        success: function(data) {
            makePDF(id,name,lastname,email,projectheader,projectdescription,data);
        },
        error: function()
        {
            alert("Please make sure points are given!");
        }
    });
}

function getStudentByName(){

    if(viewModel.tempTableData().length == 0) {
        viewModel.tempTableData(viewModel.tabledata.slice(0));
    }

    viewModel.tabledata([]);

    viewModel.tempTableData().forEach(function(item, element){
        var fullname = item.tfirstname + " " + item.tlastname;
        var fullnameReverse = item.tlastname + " " + item.tfirstname;

        if (item.tfirstname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || item.tlastname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || fullname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || fullnameReverse.toLowerCase().contains(viewModel.searchStudent().toLowerCase())){
            viewModel.tabledata.push(item);
        }
    });
}

function showFullList()
{
    viewModel.searchStudent = ko.observable("");
    getStudentByName();
}

function getData(id)
{
    $.getJSON('/api/project/' + viewModel.projectId  + '/student/' + id + '/assessed', function(data)
    {
        viewModel.users.removeAll();
        data.forEach(function(element)
        {
            viewModel.users.push(element.firstname + " " + element.lastname);
        });
    });

    return viewModel.users();
}

function getNrOfAssessing(){
    $.getJSON('/api/project/nrOfAssessing/' + viewModel.projectId , function(data)
    {
        console.log(data);

        data.forEach(function(item)
        {
           console.log(item.nrOfAssessing);

        });
    });
}

function getDataCount(projectid, id)
{
    $.getJSON('/api/project/' + projectid  + '/student/' + id + '/assessed', function(data)
    {
        viewModel.users.removeAll();
        data.forEach(function(element)
        {
            viewModel.users.push(element.firstname + " " + element.lastname);
        });

        return viewModel.users().length;
    });
}<commit_msg>nr of assessing color balls<commit_after>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.projectDescription = ko.observable("Description");

    gvm.firstNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("firstNameTableTitle");}, gvm);
    gvm.lastNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("lastNameTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.scoreTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("scoreTableTitle")});
    gvm.filesTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("filesTableTitle")});

    gvm.searchStudent = ko.observable("");

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
            gvm.projectDescription(data[0].description);
        });
    };

    gvm.getStudentListBis = function() {
        $.getJSON('/api/project/' + gvm.projectId + '/students', function(data) {
            data.forEach(function(element){
                viewModel.addTableData(element.id, element.firstname, element.lastname, element.mail, element.assessCount);
            });
        });
    };

    gvm.getStudentList = function() {
        $.getJSON('/api/project/' + gvm.projectId + '/students/', function(data) {
            $.each(data, function(i, item) {

                $.getJSON('/api/project/' + gvm.projectid  + '/student/' + item.id + '/assessed', function(data)
                {
                    viewModel.users.removeAll();
                    data.forEach(function(element)
                    {
                        viewModel.users.push(element.firstname + " " + element.lastname);
                    });

                    viewModel.addTableData(item.id, item.firstname, item.lastname, item.mail, viewModel.users().length);
                });
            });
        });
    };

    gvm.users = ko.observableArray([]);

    gvm.assassedUsers = ko.observableArray([]);

    gvm.tabledata = ko.observableArray([]);

    gvm.tempTableData = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, firstname, lastname, email, countAssessed) {
        // Push data
        var data = countAssessed;
        var tblOject = {tid: id, tfirstname: firstname, tlastname: lastname, tScoreTableBtn: gvm.scoreTableTitle, tFilesTableBtn: gvm.filesTableTitle, tpid: gvm.projectId, email: email, tcountAssessed: data};
        gvm.tabledata.push(tblOject);
    };

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    };

    /*gvm.getAllData = function() {
        $.getJSON('/api/project/getAllData/' + $("#projectHeader").data('value'), function(data) {
            console.log(data);
        });
    }*/
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getStudentListBis();
    //viewModel.getStudentList();

    $("#searchField").bind("keypress", {}, keypressInBox);

}

function keypressInBox(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 13) { //Enter keycode
        $("#searchField").blur();
        getStudentByName();

    }
};

function createPDF(id,name,lastname,email, projectheader, projectdescription)
{
    /*$.getJSON('/api/finalscore/' + viewModel.projectId + '/' + id, function (data) {
        makePDF(id,name,lastname,email,projectheader,projectdescription,data);
        //console.log(data);
    });*/

    $.ajax({
        url: '/api/finalscore/' + viewModel.projectId + '/' + id,
        type: "GET",
        dataType: 'json',
        success: function(data) {
            makePDF(id,name,lastname,email,projectheader,projectdescription,data);
        },
        error: function()
        {
            alert("Please make sure points are given!");
        }
    });
}

function getStudentByName(){

    if(viewModel.tempTableData().length == 0) {
        viewModel.tempTableData(viewModel.tabledata.slice(0));
    }

    viewModel.tabledata([]);

    viewModel.tempTableData().forEach(function(item, element){
        var fullname = item.tfirstname + " " + item.tlastname;
        var fullnameReverse = item.tlastname + " " + item.tfirstname;

        if (item.tfirstname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || item.tlastname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || fullname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || fullnameReverse.toLowerCase().contains(viewModel.searchStudent().toLowerCase())){
            viewModel.tabledata.push(item);
        }
    });
}

function showFullList()
{
    viewModel.searchStudent = ko.observable("");
    getStudentByName();
}

function getData(id)
{
    $.getJSON('/api/project/' + viewModel.projectId  + '/student/' + id + '/assessed', function(data)
    {
        viewModel.users.removeAll();
        data.forEach(function(element)
        {
            viewModel.users.push(element.firstname + " " + element.lastname);
        });
    });

    return viewModel.users();
}

function getNrOfAssessing(){
    $.getJSON('/api/project/nrOfAssessing/' + viewModel.projectId , function(data)
    {
        data.forEach(function(item)
        {
            return item.nrOfAssessing;
        });
    });
}

function getDataCount(projectid, id)
{
    $.getJSON('/api/project/' + projectid  + '/student/' + id + '/assessed', function(data)
    {
        viewModel.users.removeAll();
        data.forEach(function(element)
        {
            viewModel.users.push(element.firstname + " " + element.lastname);
        });

        return viewModel.users().length;
    });
}<|endoftext|>


<commit_before>define(['backend/services', 'backend/channels/catchan', 'util/protocol'],
function(Services, Channel, Protocol) {
  'use strict';

  /*
   * Service managing mixing.
   * @constructor
   */
  function MixerService(core) {
    var self = this;
    this.core = core;

    // Port for communication with other services
    Services.connect('obelisk', function(data) {
      // WakeUp when connected to obelisk
      if (data.type == 'connected') {
        self.checkMixing(data);
        // resume tasks
        self.resumeTasks();
      }

    });
  }

  /*
   * React to a new obelisk connection
   */
  MixerService.prototype.checkMixing = function() {
    var identity = this.core.getCurrentIdentity();

    // Check to see we have anything to mix
    var anyMixing = false;
    identity.wallet.pockets.forEach(function(pocket) {
      if (pocket.mixing) {
        anyMixing = true;
      }
    });

    // If we have active tasks should also connect
    anyMixing = anyMixing || this.pendingTasks();

    // If any is mixing make sure we are connected
    if (anyMixing) {
      this.ensureMixing();
    } else {
      this.stopMixing();
    }
  }

  /*
   * Initialize the mixer connection
   */
  MixerService.prototype.ensureMixing = function() {
    var self = this;
    console.log("[mixer] Check mixing...");
    var lobbyTransport = this.core.getLobbyTransport();
    if (!this.channel) {
      this.channel = lobbyTransport.initChannel('CoinJoin', Channel);
      this.channel.addCallback('CoinJoinOpen', function(_d) {self.onCoinJoinOpen(_d)});
      this.channel.addCallback('CoinJoin', function(_d) {self.onCoinJoin(_d)});
      this.channel.addCallback('CoinJoinFinish', function(_d) {self.onCoinJoinFinish(_d)});
    }
  }

  /*
   * Stop mixing
   */
  MixerService.prototype.stopMixing = function() {
    console.log("[mixer] Stop mixing...");
    if (this.channel) {
      var lobbyTransport = this.core.getLobbyTransport();
      lobbyTransport.closeChannel(this.channel.name);
      this.channel = null;
    }
  }

  // Tasks

  /*
   * Start a task either internally or by external command
   */
  MixerService.prototype.startTask = function(task) {
    // Make sure the mixer is enabled
    this.ensureMixing();

    // Now do stuff with the task...
    switch(task.state) {
      case 'announce':
        var msg = Protocol.CoinJoinOpenMsg(task.total);
        console.log("[mixer] Announce join");
        this.channel.postEncrypted(msg, function(err, data) {
          if (err) {
            console.log("[mixer] Error announcing join!");
          } else {
            console.log("[mixer] Join announced!");
          }
        });
        break;
      case 'paired':
      case 'finish':
      default:
        console.log('[mixer] start Task!', task.state, task);
        console.log();
        break;
    }
  }

  /*
   * Count the number of pending tasks
   */
  MixerService.prototype.pendingTasks = function() {
    var identity = this.core.getCurrentIdentity();
    console.log('[mixer] check Tasks!', identity);

    if (identity.tasks.tasks['mixer']) {
      return identity.tasks.tasks['mixer'].length;
    }
    return false;
  }

  /*
   * Resume available (pending) tasks
   */
  MixerService.prototype.resumeTasks = function() {
    var self = this;
    var identity = this.core.getCurrentIdentity();

    if (!identity.tasks.tasks.hasOwnProperty('mixer')) {
      return;
    }
    identity.tasks.tasks['mixer'].forEach(function(task) {
      self.startTask(task);
    });
  }

  /*
   * Evaluate a coinjoin opening and respond if appropriate.
   */
  MixerService.prototype.evaluateOpening = function(peer, opening) {
    var shouldPair = false;

    // Evaluate mixing pockets to see if we can pair

    // If we resulted in pairing, continue with protocol.
    if (shouldPair) {
      var msg = Protocol.CoinJoinMsg("deadbeef");

      // Post using end to end channel capabilities
      this.channel.postDH(peer.pubKey, msg, function(err, data) {
        // Pairing message sent successfully
      });
    }
  }

  /*
   * Process a message for an ongoing CoinJoin
   */
  MixerService.prototype.processCoinJoin = function(peer, opening) {
  }

  /*
   * Process a message finishing a coinjoin conversation
   */
  MixerService.prototype.processFinish = function(peer, opening) {
  }

  /*
   * Protocol messages arriving
   */
  MixerService.prototype.onCoinJoinOpen = function(msg) {
    var peer = this.channel.getPeer(msg.sender);
    if (!peer) {
      console.log("[mixer] Peer not found " + msg.sender);
      return;
    }
    if (msg.sender != this.channel.fingerprint) {
      console.log("[mixer] CoinJoinOpen", msg, peer);
      this.evaluateOpening(peer, msg);
    } else {
      console.log("[mixer] My CoinJoinOpen is back", msg);
    }
  }
  MixerService.prototype.onCoinJoin = function(msg) {
    var peer = this.channel.getPeer(msg.sender);
    if (msg.sender != this.channel.fingerprint) {
      console.log("[mixer] CoinJoin", msg);
      this.processCoinJoin(peer, msg);
    }
  }
  MixerService.prototype.onCoinJoinFinish = function(msg) {
    if (msg.sender != this.channel.fingerprint) {
      console.log("[mixer] CoinJoinFinish", msg);
      this.processFinish(peer, msg);
    }
  }

  return MixerService;

});
<commit_msg>peer now comes linked into the message.<commit_after>define(['backend/services', 'backend/channels/catchan', 'util/protocol'],
function(Services, Channel, Protocol) {
  'use strict';

  /*
   * Service managing mixing.
   * @constructor
   */
  function MixerService(core) {
    var self = this;
    this.core = core;

    // Port for communication with other services
    Services.connect('obelisk', function(data) {
      // WakeUp when connected to obelisk
      if (data.type == 'connected') {
        self.checkMixing(data);
        // resume tasks
        self.resumeTasks();
      }

    });
  }

  /*
   * React to a new obelisk connection
   */
  MixerService.prototype.checkMixing = function() {
    var identity = this.core.getCurrentIdentity();

    // Check to see we have anything to mix
    var anyMixing = false;
    identity.wallet.pockets.forEach(function(pocket) {
      if (pocket.mixing) {
        anyMixing = true;
      }
    });

    // If we have active tasks should also connect
    anyMixing = anyMixing || this.pendingTasks();

    // If any is mixing make sure we are connected
    if (anyMixing) {
      this.ensureMixing();
    } else {
      this.stopMixing();
    }
  }

  /*
   * Initialize the mixer connection
   */
  MixerService.prototype.ensureMixing = function() {
    var self = this;
    console.log("[mixer] Check mixing...");
    var lobbyTransport = this.core.getLobbyTransport();
    if (!this.channel) {
      this.channel = lobbyTransport.initChannel('CoinJoin', Channel);
      this.channel.addCallback('CoinJoinOpen', function(_d) {self.onCoinJoinOpen(_d)});
      this.channel.addCallback('CoinJoin', function(_d) {self.onCoinJoin(_d)});
      this.channel.addCallback('CoinJoinFinish', function(_d) {self.onCoinJoinFinish(_d)});
    }
  }

  /*
   * Stop mixing
   */
  MixerService.prototype.stopMixing = function() {
    console.log("[mixer] Stop mixing...");
    if (this.channel) {
      var lobbyTransport = this.core.getLobbyTransport();
      lobbyTransport.closeChannel(this.channel.name);
      this.channel = null;
    }
  }

  // Tasks

  /*
   * Start a task either internally or by external command
   */
  MixerService.prototype.startTask = function(task) {
    // Make sure the mixer is enabled
    this.ensureMixing();

    // Now do stuff with the task...
    switch(task.state) {
      case 'announce':
        var msg = Protocol.CoinJoinOpenMsg(task.total);
        console.log("[mixer] Announce join");
        this.channel.postEncrypted(msg, function(err, data) {
          if (err) {
            console.log("[mixer] Error announcing join!");
          } else {
            console.log("[mixer] Join announced!");
          }
        });
        break;
      case 'paired':
      case 'finish':
      default:
        console.log('[mixer] start Task!', task.state, task);
        console.log();
        break;
    }
  }

  /*
   * Count the number of pending tasks
   */
  MixerService.prototype.pendingTasks = function() {
    var identity = this.core.getCurrentIdentity();
    console.log('[mixer] check Tasks!', identity);

    if (identity.tasks.tasks['mixer']) {
      return identity.tasks.tasks['mixer'].length;
    }
    return false;
  }

  /*
   * Resume available (pending) tasks
   */
  MixerService.prototype.resumeTasks = function() {
    var self = this;
    var identity = this.core.getCurrentIdentity();

    if (!identity.tasks.tasks.hasOwnProperty('mixer')) {
      return;
    }
    identity.tasks.tasks['mixer'].forEach(function(task) {
      self.startTask(task);
    });
  }

  /*
   * Evaluate a coinjoin opening and respond if appropriate.
   */
  MixerService.prototype.evaluateOpening = function(peer, opening) {
    var shouldPair = false;

    // Evaluate mixing pockets to see if we can pair

    // If we resulted in pairing, continue with protocol.
    if (shouldPair) {
      var msg = Protocol.CoinJoinMsg("deadbeef");

      // Post using end to end channel capabilities
      this.channel.postDH(peer.pubKey, msg, function(err, data) {
        // Pairing message sent successfully
      });
    }
  }

  /*
   * Process a message for an ongoing CoinJoin
   */
  MixerService.prototype.processCoinJoin = function(peer, opening) {
  }

  /*
   * Process a message finishing a coinjoin conversation
   */
  MixerService.prototype.processFinish = function(peer, opening) {
  }

  /*
   * Protocol messages arriving
   */
  MixerService.prototype.onCoinJoinOpen = function(msg) {
    if (!msg.peer) {
      console.log("[mixer] Peer not found " + msg.sender);
      return;
    }
    if (msg.sender != this.channel.fingerprint) {
      console.log("[mixer] CoinJoinOpen", msg.peer, peer);
      this.evaluateOpening(msg.peer, msg);
    } else {
      console.log("[mixer] My CoinJoinOpen is back", msg);
    }
  }
  MixerService.prototype.onCoinJoin = function(msg) {
    if (msg.sender != this.channel.fingerprint) {
      console.log("[mixer] CoinJoin", msg);
      this.processCoinJoin(msg.peer, msg);
    }
  }
  MixerService.prototype.onCoinJoinFinish = function(msg) {
    if (msg.sender != this.channel.fingerprint) {
      console.log("[mixer] CoinJoinFinish", msg);
      this.processFinish(msg.peer, msg);
    }
  }

  return MixerService;

});
<|endoftext|>


<commit_before>/* ===========================================================
 * bootstrap-modalmanager.js v2.1
 * ===========================================================
 * Copyright 2012 Jordan Schroter.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================== */

!function ($) {

	"use strict"; // jshint ;_;

	/* MODAL MANAGER CLASS DEFINITION
	* ====================== */

	var ModalManager = function (element, options) {
		this.init(element, options);
	};

	ModalManager.prototype = {

		constructor: ModalManager,

		init: function (element, options) {
			this.$element = $(element);
			this.options = $.extend({}, $.fn.modalmanager.defaults, this.$element.data(), typeof options == 'object' && options);
			this.stack = [];
			this.backdropCount = 0;

			if (this.options.resize) {
				var resizeTimeout,
					that = this;

				$(window).on('resize.modal', function(){
					resizeTimeout && clearTimeout(resizeTimeout);
					resizeTimeout = setTimeout(function(){
						for (var i = 0; i < that.stack.length; i++){
							that.stack[i].isShown && that.stack[i].layout();
						}
					}, 10);
				});
			}
		},

		createModal: function (element, options) {
			$(element).modal($.extend({ manager: this }, options));
		},

		appendModal: function (modal) {
			this.stack.push(modal);

			var that = this;

			modal.$element.on('show.modalmanager', targetIsSelf(function (e) {

				var showModal = function(){
					modal.isShown = true;

					var transition = $.support.transition && modal.$element.hasClass('fade');

					that.$element
						.toggleClass('modal-open', that.hasOpenModal())
						.toggleClass('page-overflow', $(window).height() < that.$element.height());

					modal.$parent = modal.$element.parent();

					modal.$container = that.createContainer(modal);

					modal.$element.appendTo(modal.$container);

					that.backdrop(modal, function () {

						modal.$element.show();

						if (transition) {
							//modal.$element[0].style.display = 'run-in';
							modal.$element[0].offsetWidth;
							//modal.$element.one($.support.transition.end, function () { modal.$element[0].style.display = 'block' });
						}

						modal.layout();

						modal.$element
							.addClass('in')
							.attr('aria-hidden', false);

						var complete = function () {
							that.setFocus();
							modal.$element.triggerHandler('shown');
						};

						transition ?
							modal.$element.one($.support.transition.end, complete) :
							complete();
					});
				};

				modal.options.replace ?
					that.replace(showModal) :
					showModal();
			}));

			modal.$element.on('hidden.modalmanager', targetIsSelf(function (e) {

				that.backdrop(modal);

				if (modal.$backdrop){
					$.support.transition && modal.$element.hasClass('fade') ?
						modal.$backdrop.one($.support.transition.end, function () { that.destroyModal(modal) }) :
						that.destroyModal(modal);
				} else {
					that.destroyModal(modal);
				}

			}));

			modal.$element.on('destroy.modalmanager', targetIsSelf(function (e) {
				that.removeModal(modal);
			}));

		},

		destroyModal: function (modal) {

			modal.destroy();

			var hasOpenModal = this.hasOpenModal();

			this.$element.toggleClass('modal-open', hasOpenModal);

			if (!hasOpenModal){
				this.$element.removeClass('page-overflow');
			}

			this.removeContainer(modal);

			this.setFocus();
		},

		hasOpenModal: function () {
			for (var i = 0; i < this.stack.length; i++){
				if (this.stack[i].isShown) return true;
			}

			return false;
		},

		setFocus: function () {
			var topModal;

			for (var i = 0; i < this.stack.length; i++){
				if (this.stack[i].isShown) topModal = this.stack[i];
			}

			if (!topModal) return;

			topModal.focus();

		},

		removeModal: function (modal) {
			modal.$element.off('.modalmanager');
			if (modal.$backdrop) this.removeBackdrop.call(modal);
			this.stack.splice(this.getIndexOfModal(modal), 1);
		},

		getModalAt: function (index) {
			return this.stack[index];
		},

		getIndexOfModal: function (modal) {
			for (var i = 0; i < this.stack.length; i++){
				if (modal === this.stack[i]) return i;
			}
		},

		replace: function (callback) {
			var topModal;

			for (var i = 0; i < this.stack.length; i++){
				if (this.stack[i].isShown) topModal = this.stack[i];
			}

			if (topModal) {
				this.$backdropHandle = topModal.$backdrop;
				topModal.$backdrop = null;

				callback && topModal.$element.one('hidden',
					targetIsSelf( $.proxy(callback, this) ));

				topModal.hide();
			} else if (callback) {
				callback();
			}
		},

		removeBackdrop: function (modal) {
			modal.$backdrop.remove();
			modal.$backdrop = null;
		},

		createBackdrop: function (animate) {
			var $backdrop;

			if (!this.$backdropHandle) {
				$backdrop = $('
')
					.appendTo(this.$element);
			} else {
				$backdrop = this.$backdropHandle;
				$backdrop.off('.modalmanager');
				this.$backdropHandle = null;
				this.isLoading && this.removeSpinner();
			}

			return $backdrop
		},

		removeContainer: function (modal) {
			modal.$container.remove();
			modal.$container = null;
		},

		createContainer: function (modal) {
			var $container;

			$container = $('
')
				.css('z-index', getzIndex( 'modal',
					modal ? this.getIndexOfModal(modal) : this.stack.length ))
				.appendTo(this.$element);

			if (modal && modal.options.backdrop != 'static') {
				$container.on('click.modal', targetIsSelf(function (e) {
					modal.hide();
				}));
			} else if (modal) {
				$container.on('click.modal', targetIsSelf(function (e) {
					modal.attention();
				}));
			}

			return $container;

		},

		backdrop: function (modal, callback) {
			var animate = modal.$element.hasClass('fade') ? 'fade' : '',
				showBackdrop = modal.options.backdrop &&
					this.backdropCount < this.options.backdropLimit;

			if (modal.isShown && showBackdrop) {
				var doAnimate = $.support.transition && animate && !this.$backdropHandle;

				modal.$backdrop = this.createBackdrop(animate);

				modal.$backdrop.css('z-index', getzIndex( 'backdrop', this.getIndexOfModal(modal) ));

				if (doAnimate) modal.$backdrop[0].offsetWidth; // force reflow

				modal.$backdrop.addClass('in');

				this.backdropCount += 1;

				doAnimate ?
					modal.$backdrop.one($.support.transition.end, callback) :
					callback();

			} else if (!modal.isShown && modal.$backdrop) {
				modal.$backdrop.removeClass('in');

				this.backdropCount -= 1;

				var that = this;

				$.support.transition && modal.$element.hasClass('fade')?
					modal.$backdrop.one($.support.transition.end, function () { that.removeBackdrop(modal) }) :
					that.removeBackdrop(modal);

			} else if (callback) {
				callback();
			}
		},

		removeSpinner: function(){
			this.$spinner && this.$spinner.remove();
			this.$spinner = null;
			this.isLoading = false;
		},

		removeLoading: function () {
			this.$backdropHandle && this.$backdropHandle.remove();
			this.$backdropHandle = null;
			this.removeSpinner();
		},

		loading: function (callback) {
			callback = callback || function () { };

			this.$element
				.toggleClass('modal-open', !this.isLoading || this.hasOpenModal())
				.toggleClass('page-overflow', $(window).height() < this.$element.height());

			if (!this.isLoading) {

				this.$backdropHandle = this.createBackdrop('fade');

				this.$backdropHandle[0].offsetWidth; // force reflow

				this.$backdropHandle
					.css('z-index', getzIndex('backdrop', this.stack.length))
					.addClass('in');

				var $spinner = $(this.options.spinner)
					.css('z-index', getzIndex('modal', this.stack.length))
					.appendTo(this.$element)
					.addClass('in');

				this.$spinner = $(this.createContainer())
					.append($spinner)
					.on('click.modalmanager', $.proxy(this.loading, this));

				this.isLoading = true;

				$.support.transition ?
					this.$backdropHandle.one($.support.transition.end, callback) :
					callback();

			} else if (this.isLoading && this.$backdropHandle) {
				this.$backdropHandle.removeClass('in');

				var that = this;
				$.support.transition ?
					this.$backdropHandle.one($.support.transition.end, function () { that.removeLoading() }) :
					that.removeLoading();

			} else if (callback) {
				callback(this.isLoading);
			}
		}
	};

	/* PRIVATE METHODS
	* ======================= */

	// computes and caches the zindexes
	var getzIndex = (function () {
		var zIndexFactor,
			baseIndex = {};

		return function (type, pos) {

			if (typeof zIndexFactor === 'undefined'){
				var $baseModal = $('
').appendTo('body'),
					$baseBackdrop = $('
').appendTo('body');

				baseIndex['modal'] = +$baseModal.css('z-index');
				baseIndex['backdrop'] = +$baseBackdrop.css('z-index');
				zIndexFactor = baseIndex['modal'] - baseIndex['backdrop'];

				$baseModal.remove();
				$baseBackdrop.remove();
				$baseBackdrop = $baseModal = null;
			}

			return baseIndex[type] + (zIndexFactor * pos);

		}
	}());

	// make sure the event target is the modal itself in order to prevent
	// other components such as tabsfrom triggering the modal manager.
	// if Boostsrap namespaced events, this would not be needed.
	function targetIsSelf(callback){
		return function (e) {
			if (this === e.target){
				return callback.apply(this, arguments);
			}
		}
	}

	/* MODAL MANAGER PLUGIN DEFINITION
	* ======================= */

	$.fn.modalmanager = function (option, args) {
		return this.each(function () {
			var $this = $(this),
				data = $this.data('modalmanager');

			if (!data) $this.data('modalmanager', (data = new ModalManager(this, option)))
			if (typeof option === 'string') data[option].apply(data, [].concat(args))
		})
	};

	$.fn.modalmanager.defaults = {
		backdropLimit: 999,
		resize: true,
		spinner: '

'
	};

	$.fn.modalmanager.Constructor = ModalManager

}(jQuery);
<commit_msg>Added missing semicolon<commit_after>/* ===========================================================
 * bootstrap-modalmanager.js v2.1
 * ===========================================================
 * Copyright 2012 Jordan Schroter.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================== */

!function ($) {

	"use strict"; // jshint ;_;

	/* MODAL MANAGER CLASS DEFINITION
	* ====================== */

	var ModalManager = function (element, options) {
		this.init(element, options);
	};

	ModalManager.prototype = {

		constructor: ModalManager,

		init: function (element, options) {
			this.$element = $(element);
			this.options = $.extend({}, $.fn.modalmanager.defaults, this.$element.data(), typeof options == 'object' && options);
			this.stack = [];
			this.backdropCount = 0;

			if (this.options.resize) {
				var resizeTimeout,
					that = this;

				$(window).on('resize.modal', function(){
					resizeTimeout && clearTimeout(resizeTimeout);
					resizeTimeout = setTimeout(function(){
						for (var i = 0; i < that.stack.length; i++){
							that.stack[i].isShown && that.stack[i].layout();
						}
					}, 10);
				});
			}
		},

		createModal: function (element, options) {
			$(element).modal($.extend({ manager: this }, options));
		},

		appendModal: function (modal) {
			this.stack.push(modal);

			var that = this;

			modal.$element.on('show.modalmanager', targetIsSelf(function (e) {

				var showModal = function(){
					modal.isShown = true;

					var transition = $.support.transition && modal.$element.hasClass('fade');

					that.$element
						.toggleClass('modal-open', that.hasOpenModal())
						.toggleClass('page-overflow', $(window).height() < that.$element.height());

					modal.$parent = modal.$element.parent();

					modal.$container = that.createContainer(modal);

					modal.$element.appendTo(modal.$container);

					that.backdrop(modal, function () {

						modal.$element.show();

						if (transition) {
							//modal.$element[0].style.display = 'run-in';
							modal.$element[0].offsetWidth;
							//modal.$element.one($.support.transition.end, function () { modal.$element[0].style.display = 'block' });
						}

						modal.layout();

						modal.$element
							.addClass('in')
							.attr('aria-hidden', false);

						var complete = function () {
							that.setFocus();
							modal.$element.triggerHandler('shown');
						};

						transition ?
							modal.$element.one($.support.transition.end, complete) :
							complete();
					});
				};

				modal.options.replace ?
					that.replace(showModal) :
					showModal();
			}));

			modal.$element.on('hidden.modalmanager', targetIsSelf(function (e) {

				that.backdrop(modal);

				if (modal.$backdrop){
					$.support.transition && modal.$element.hasClass('fade') ?
						modal.$backdrop.one($.support.transition.end, function () { that.destroyModal(modal) }) :
						that.destroyModal(modal);
				} else {
					that.destroyModal(modal);
				}

			}));

			modal.$element.on('destroy.modalmanager', targetIsSelf(function (e) {
				that.removeModal(modal);
			}));

		},

		destroyModal: function (modal) {

			modal.destroy();

			var hasOpenModal = this.hasOpenModal();

			this.$element.toggleClass('modal-open', hasOpenModal);

			if (!hasOpenModal){
				this.$element.removeClass('page-overflow');
			}

			this.removeContainer(modal);

			this.setFocus();
		},

		hasOpenModal: function () {
			for (var i = 0; i < this.stack.length; i++){
				if (this.stack[i].isShown) return true;
			}

			return false;
		},

		setFocus: function () {
			var topModal;

			for (var i = 0; i < this.stack.length; i++){
				if (this.stack[i].isShown) topModal = this.stack[i];
			}

			if (!topModal) return;

			topModal.focus();

		},

		removeModal: function (modal) {
			modal.$element.off('.modalmanager');
			if (modal.$backdrop) this.removeBackdrop.call(modal);
			this.stack.splice(this.getIndexOfModal(modal), 1);
		},

		getModalAt: function (index) {
			return this.stack[index];
		},

		getIndexOfModal: function (modal) {
			for (var i = 0; i < this.stack.length; i++){
				if (modal === this.stack[i]) return i;
			}
		},

		replace: function (callback) {
			var topModal;

			for (var i = 0; i < this.stack.length; i++){
				if (this.stack[i].isShown) topModal = this.stack[i];
			}

			if (topModal) {
				this.$backdropHandle = topModal.$backdrop;
				topModal.$backdrop = null;

				callback && topModal.$element.one('hidden',
					targetIsSelf( $.proxy(callback, this) ));

				topModal.hide();
			} else if (callback) {
				callback();
			}
		},

		removeBackdrop: function (modal) {
			modal.$backdrop.remove();
			modal.$backdrop = null;
		},

		createBackdrop: function (animate) {
			var $backdrop;

			if (!this.$backdropHandle) {
				$backdrop = $('
')
					.appendTo(this.$element);
			} else {
				$backdrop = this.$backdropHandle;
				$backdrop.off('.modalmanager');
				this.$backdropHandle = null;
				this.isLoading && this.removeSpinner();
			}

			return $backdrop
		},

		removeContainer: function (modal) {
			modal.$container.remove();
			modal.$container = null;
		},

		createContainer: function (modal) {
			var $container;

			$container = $('
')
				.css('z-index', getzIndex( 'modal',
					modal ? this.getIndexOfModal(modal) : this.stack.length ))
				.appendTo(this.$element);

			if (modal && modal.options.backdrop != 'static') {
				$container.on('click.modal', targetIsSelf(function (e) {
					modal.hide();
				}));
			} else if (modal) {
				$container.on('click.modal', targetIsSelf(function (e) {
					modal.attention();
				}));
			}

			return $container;

		},

		backdrop: function (modal, callback) {
			var animate = modal.$element.hasClass('fade') ? 'fade' : '',
				showBackdrop = modal.options.backdrop &&
					this.backdropCount < this.options.backdropLimit;

			if (modal.isShown && showBackdrop) {
				var doAnimate = $.support.transition && animate && !this.$backdropHandle;

				modal.$backdrop = this.createBackdrop(animate);

				modal.$backdrop.css('z-index', getzIndex( 'backdrop', this.getIndexOfModal(modal) ));

				if (doAnimate) modal.$backdrop[0].offsetWidth; // force reflow

				modal.$backdrop.addClass('in');

				this.backdropCount += 1;

				doAnimate ?
					modal.$backdrop.one($.support.transition.end, callback) :
					callback();

			} else if (!modal.isShown && modal.$backdrop) {
				modal.$backdrop.removeClass('in');

				this.backdropCount -= 1;

				var that = this;

				$.support.transition && modal.$element.hasClass('fade')?
					modal.$backdrop.one($.support.transition.end, function () { that.removeBackdrop(modal) }) :
					that.removeBackdrop(modal);

			} else if (callback) {
				callback();
			}
		},

		removeSpinner: function(){
			this.$spinner && this.$spinner.remove();
			this.$spinner = null;
			this.isLoading = false;
		},

		removeLoading: function () {
			this.$backdropHandle && this.$backdropHandle.remove();
			this.$backdropHandle = null;
			this.removeSpinner();
		},

		loading: function (callback) {
			callback = callback || function () { };

			this.$element
				.toggleClass('modal-open', !this.isLoading || this.hasOpenModal())
				.toggleClass('page-overflow', $(window).height() < this.$element.height());

			if (!this.isLoading) {

				this.$backdropHandle = this.createBackdrop('fade');

				this.$backdropHandle[0].offsetWidth; // force reflow

				this.$backdropHandle
					.css('z-index', getzIndex('backdrop', this.stack.length))
					.addClass('in');

				var $spinner = $(this.options.spinner)
					.css('z-index', getzIndex('modal', this.stack.length))
					.appendTo(this.$element)
					.addClass('in');

				this.$spinner = $(this.createContainer())
					.append($spinner)
					.on('click.modalmanager', $.proxy(this.loading, this));

				this.isLoading = true;

				$.support.transition ?
					this.$backdropHandle.one($.support.transition.end, callback) :
					callback();

			} else if (this.isLoading && this.$backdropHandle) {
				this.$backdropHandle.removeClass('in');

				var that = this;
				$.support.transition ?
					this.$backdropHandle.one($.support.transition.end, function () { that.removeLoading() }) :
					that.removeLoading();

			} else if (callback) {
				callback(this.isLoading);
			}
		}
	};

	/* PRIVATE METHODS
	* ======================= */

	// computes and caches the zindexes
	var getzIndex = (function () {
		var zIndexFactor,
			baseIndex = {};

		return function (type, pos) {

			if (typeof zIndexFactor === 'undefined'){
				var $baseModal = $('
').appendTo('body'),
					$baseBackdrop = $('
').appendTo('body');

				baseIndex['modal'] = +$baseModal.css('z-index');
				baseIndex['backdrop'] = +$baseBackdrop.css('z-index');
				zIndexFactor = baseIndex['modal'] - baseIndex['backdrop'];

				$baseModal.remove();
				$baseBackdrop.remove();
				$baseBackdrop = $baseModal = null;
			}

			return baseIndex[type] + (zIndexFactor * pos);

		}
	}());

	// make sure the event target is the modal itself in order to prevent
	// other components such as tabsfrom triggering the modal manager.
	// if Boostsrap namespaced events, this would not be needed.
	function targetIsSelf(callback){
		return function (e) {
			if (this === e.target){
				return callback.apply(this, arguments);
			}
		}
	}

	/* MODAL MANAGER PLUGIN DEFINITION
	* ======================= */

	$.fn.modalmanager = function (option, args) {
		return this.each(function () {
			var $this = $(this),
				data = $this.data('modalmanager');

			if (!data) $this.data('modalmanager', (data = new ModalManager(this, option)));
			if (typeof option === 'string') data[option].apply(data, [].concat(args))
		})
	};

	$.fn.modalmanager.defaults = {
		backdropLimit: 999,
		resize: true,
		spinner: '

'
	};

	$.fn.modalmanager.Constructor = ModalManager

}(jQuery);
<|endoftext|>


<commit_before>/*jshint node:true, indent:2, curly:true eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true,
regexp:true, undef:true, trailing:true, white:true */
/*global XT:true, XV:true, XM:true, Backbone:true, window:true, enyo:true, _:true */

(function () {

  // ..........................................................
  // ACCOUNT
  //

  enyo.kind({
    name: "XV.AccountWidget",
    kind: "XV.RelationWidget",
    list: "XV.AccountList"
  });

  // ..........................................................
  // CONTACT
  //

  enyo.kind({
    name: "XV.ContactWidget",
    kind: "XV.RelationWidget",
    label: "_name".loc(),
    list: "XV.ContactList",
    keyAttribute: "name",
    nameAttribute: "jobTitle",
    descripAttribute: "phone",
    published: {
      showAddress: false
    },
    components: [
      {kind: "FittableColumns", components: [
        {name: "label", content: "", classes: "xv-decorated-label"},
        {kind: "onyx.InputDecorator", classes: "xv-input-decorator",
          components: [
          {name: 'input', kind: "onyx.Input", classes: "xv-subinput",
            onkeyup: "keyUp", onkeydown: "keyDown", onblur: "receiveBlur"
          },
          {kind: "onyx.MenuDecorator", onSelect: "itemSelected", components: [
            {kind: "onyx.IconButton", src: "assets/relation-icon-search.png"},
            {name: 'popupMenu', floating: true, kind: "onyx.Menu",
              components: [
              {kind: "XV.MenuItem", name: 'searchItem', content: "_search".loc()},
              {kind: "XV.MenuItem", name: 'openItem', content: "_open".loc(),
                disabled: true},
              {kind: "XV.MenuItem", name: 'newItem', content: "_new".loc(),
                disabled: true}
            ]}
          ]},
          {kind: "onyx.MenuDecorator", classes: "xv-relationwidget-completer",
            onSelect: "relationSelected", components: [
            {kind: "onyx.Menu", name: "autocompleteMenu", modal: false}
          ]}
        ]}
      ]},
      {kind: "FittableColumns", components: [
        {name: "labels", classes: "xv-relationwidget-column left",
          components: [
          {name: "jobTitleLabel", content: "_jobTitle".loc() + ":",
            classes: "xv-relationwidget-description label",
            showing: false},
          {name: "phoneLabel", content: "_phone".loc() + ":",
            classes: "xv-relationwidget-description label",
            showing: false},
          {name: "alternateLabel", content: "_alternate".loc() + ":",
            classes: "xv-relationwidget-description label",
            showing: false},
          {name: "faxLabel", content: "_fax".loc() + ":",
            classes: "xv-relationwidget-description label",
            showing: false},
          {name: "primaryEmailLabel", content: "_email".loc() + ":",
            classes: "xv-relationwidget-description label",
            showing: false},
          {name: "webAddressLabel", content: "_web".loc() + ":",
            classes: "xv-relationwidget-description label",
            showing: false},
          {name: "addressLabel", content: "_address".loc() + ":",
            classes: "xv-relationwidget-description label",
            showing: false}
        ]},
        {name: "data", fit: true, components: [
          {name: "name", classes: "xv-relationwidget-description hasLabel"},
          {name: "description", classes: "xv-relationwidget-description hasLabel"},
          {name: "alternate", classes: "xv-relationwidget-description hasLabel"},
          {name: "fax", classes: "xv-relationwidget-description hasLabel"},
          {name: "primaryEmail", ontap: "sendMail",
            classes: "xv-relationwidget-description hasLabel hyperlink"},
          {name: "webAddress", ontap: "openWindow",
            classes: "xv-relationwidget-description hasLabel hyperlink"},
          {name: "address", classes: "xv-relationwidget-description hasLabel",
            allowHtml: true}
        ]}
      ]}
    ],
    disabledChanged: function () {
      this.inherited(arguments);
      var disabled = this.getDisabled();
      if (this.$.phone) {
        this.$.jobTitle.addRemoveClass("disabled", disabled);
        this.$.phone.addRemoveClass("disabled", disabled);
        this.$.alternate.addRemoveClass("disabled", disabled);
        this.$.fax.addRemoveClass("disabled", disabled);
        this.$.primaryEmail.addRemoveClass("disabled", disabled);
        this.$.webAddress.addRemoveClass("disabled", disabled);
      }
    },
    setValue: function (value, options) {
      this.inherited(arguments);
      if (!value) { return; }
      var jobTitle = value.get('jobTitle'),
        phone = value.get('phone'),
        alternate = value.get('alternate'),
        fax = value.get('fax'),
        primaryEmail = value.get('primaryEmail'),
        webAddress = value.get('webAddress'),
        address = XM.Address.format(value.get('address')),
        showAddress = this.getShowAddress();
      if (value && value.get) {
        this.$.jobTitleLabel.setShowing(jobTitle);
        this.$.phoneLabel.setShowing(phone);
        this.$.alternate.setShowing(alternate);
        this.$.alternate.setContent(alternate);
        this.$.alternateLabel.setShowing(alternate);
        this.$.fax.setShowing(fax);
        this.$.fax.setContent(fax);
        this.$.faxLabel.setShowing(fax);
        this.$.primaryEmail.setShowing(primaryEmail);
        this.$.primaryEmail.setContent(primaryEmail);
        this.$.primaryEmailLabel.setShowing(primaryEmail);
        this.$.webAddress.setShowing(webAddress);
        this.$.webAddress.setContent(webAddress);
        this.$.webAddressLabel.setShowing(webAddress);
        this.$.address.setShowing(address && showAddress);
        this.$.addressLabel.setShowing(address && showAddress);
        if (showAddress) { this.$.address.setContent(address); }
      }
    },
    openWindow: function () {
      var address = this.value ? this.value.get('webAddress') : null;
      if (address) { window.open('http://' + address); }
      return true;
    },
    sendMail: function () {
      var email = this.value ? this.value.get('primaryEmail') : null,
        win;
      if (email) {
        win = window.open('mailto:' + email);
        win.close();
      }
      return true;
    }
  });

  // ..........................................................
  // INCIDENT
  //

  enyo.kind({
    name: "XV.IncidentWidget",
    kind: "XV.RelationWidget",
    list: "XV.IncidentList",
    nameAttribute: "description"
  });

  // ..........................................................
  // ITEM
  //

  enyo.kind({
    name: "XV.ItemWidget",
    kind: "XV.RelationWidget",
    list: "XV.ItemList",
    nameAttribute: "description1",
    descripAttribute: "description2"
  });

  // ..........................................................
  // OPPORTUNITY
  //

  enyo.kind({
    name: "XV.OpportunityWidget",
    kind: "XV.RelationWidget",
    list: "XV.OpportunityList"
  });

  // ..........................................................
  // PROJECT
  //

  enyo.kind({
    name: "XV.ProjectWidget",
    kind: "XV.RelationWidget",
    list: "XV.ProjectList"
  });

  // ..........................................................
  // USER ACCOUNT
  //

  enyo.kind({
    name: "XV.UserAccountWidget",
    kind: "XV.RelationWidget",
    list: "XV.UserAccountList",
    keyAttribute: "username",
    nameAttribute: "properName"
  });

}());
<commit_msg>Clear contact labels when name cleared.<commit_after>/*jshint node:true, indent:2, curly:true eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true,
regexp:true, undef:true, trailing:true, white:true */
/*global XT:true, XV:true, XM:true, Backbone:true, window:true, enyo:true, _:true */

(function () {

  // ..........................................................
  // ACCOUNT
  //

  enyo.kind({
    name: "XV.AccountWidget",
    kind: "XV.RelationWidget",
    list: "XV.AccountList"
  });

  // ..........................................................
  // CONTACT
  //

  enyo.kind({
    name: "XV.ContactWidget",
    kind: "XV.RelationWidget",
    label: "_name".loc(),
    list: "XV.ContactList",
    keyAttribute: "name",
    nameAttribute: "jobTitle",
    descripAttribute: "phone",
    published: {
      showAddress: false
    },
    components: [
      {kind: "FittableColumns", components: [
        {name: "label", content: "", classes: "xv-decorated-label"},
        {kind: "onyx.InputDecorator", classes: "xv-input-decorator",
          components: [
          {name: 'input', kind: "onyx.Input", classes: "xv-subinput",
            onkeyup: "keyUp", onkeydown: "keyDown", onblur: "receiveBlur"
          },
          {kind: "onyx.MenuDecorator", onSelect: "itemSelected", components: [
            {kind: "onyx.IconButton", src: "assets/relation-icon-search.png"},
            {name: 'popupMenu', floating: true, kind: "onyx.Menu",
              components: [
              {kind: "XV.MenuItem", name: 'searchItem', content: "_search".loc()},
              {kind: "XV.MenuItem", name: 'openItem', content: "_open".loc(),
                disabled: true},
              {kind: "XV.MenuItem", name: 'newItem', content: "_new".loc(),
                disabled: true}
            ]}
          ]},
          {kind: "onyx.MenuDecorator", classes: "xv-relationwidget-completer",
            onSelect: "relationSelected", components: [
            {kind: "onyx.Menu", name: "autocompleteMenu", modal: false}
          ]}
        ]}
      ]},
      {kind: "FittableColumns", components: [
        {name: "labels", classes: "xv-relationwidget-column left",
          components: [
          {name: "jobTitleLabel", content: "_jobTitle".loc() + ":",
            classes: "xv-relationwidget-description label",
            showing: false},
          {name: "phoneLabel", content: "_phone".loc() + ":",
            classes: "xv-relationwidget-description label",
            showing: false},
          {name: "alternateLabel", content: "_alternate".loc() + ":",
            classes: "xv-relationwidget-description label",
            showing: false},
          {name: "faxLabel", content: "_fax".loc() + ":",
            classes: "xv-relationwidget-description label",
            showing: false},
          {name: "primaryEmailLabel", content: "_email".loc() + ":",
            classes: "xv-relationwidget-description label",
            showing: false},
          {name: "webAddressLabel", content: "_web".loc() + ":",
            classes: "xv-relationwidget-description label",
            showing: false},
          {name: "addressLabel", content: "_address".loc() + ":",
            classes: "xv-relationwidget-description label",
            showing: false}
        ]},
        {name: "data", fit: true, components: [
          {name: "name", classes: "xv-relationwidget-description hasLabel"},
          {name: "description", classes: "xv-relationwidget-description hasLabel"},
          {name: "alternate", classes: "xv-relationwidget-description hasLabel"},
          {name: "fax", classes: "xv-relationwidget-description hasLabel"},
          {name: "primaryEmail", ontap: "sendMail",
            classes: "xv-relationwidget-description hasLabel hyperlink"},
          {name: "webAddress", ontap: "openWindow",
            classes: "xv-relationwidget-description hasLabel hyperlink"},
          {name: "address", classes: "xv-relationwidget-description hasLabel",
            allowHtml: true}
        ]}
      ]}
    ],
    disabledChanged: function () {
      this.inherited(arguments);
      var disabled = this.getDisabled();
      if (this.$.phone) {
        this.$.jobTitle.addRemoveClass("disabled", disabled);
        this.$.phone.addRemoveClass("disabled", disabled);
        this.$.alternate.addRemoveClass("disabled", disabled);
        this.$.fax.addRemoveClass("disabled", disabled);
        this.$.primaryEmail.addRemoveClass("disabled", disabled);
        this.$.webAddress.addRemoveClass("disabled", disabled);
      }
    },
    setValue: function (value, options) {
      this.inherited(arguments);
      var jobTitle = value ? value.get('jobTitle') : "",
        phone = value ? value.get('phone') : "",
        alternate = value ? value.get('alternate') : "",
        fax = value ? value.get('fax') : "",
        primaryEmail = value ? value.get('primaryEmail') : "",
        webAddress = value ? value.get('webAddress') : "",
        address = value ? XM.Address.format(value.get('address')) : "",
        showAddress = this.getShowAddress();
      this.$.jobTitleLabel.setShowing(jobTitle);
      this.$.phoneLabel.setShowing(phone);
      this.$.alternate.setShowing(alternate);
      this.$.alternate.setContent(alternate);
      this.$.alternateLabel.setShowing(alternate);
      this.$.fax.setShowing(fax);
      this.$.fax.setContent(fax);
      this.$.faxLabel.setShowing(fax);
      this.$.primaryEmail.setShowing(primaryEmail);
      this.$.primaryEmail.setContent(primaryEmail);
      this.$.primaryEmailLabel.setShowing(primaryEmail);
      this.$.webAddress.setShowing(webAddress);
      this.$.webAddress.setContent(webAddress);
      this.$.webAddressLabel.setShowing(webAddress);
      this.$.address.setShowing(address && showAddress);
      this.$.addressLabel.setShowing(address && showAddress);
      if (showAddress) { this.$.address.setContent(address); }
    },
    openWindow: function () {
      var address = this.value ? this.value.get('webAddress') : null;
      if (address) { window.open('http://' + address); }
      return true;
    },
    sendMail: function () {
      var email = this.value ? this.value.get('primaryEmail') : null,
        win;
      if (email) {
        win = window.open('mailto:' + email);
        win.close();
      }
      return true;
    }
  });

  // ..........................................................
  // INCIDENT
  //

  enyo.kind({
    name: "XV.IncidentWidget",
    kind: "XV.RelationWidget",
    list: "XV.IncidentList",
    nameAttribute: "description"
  });

  // ..........................................................
  // ITEM
  //

  enyo.kind({
    name: "XV.ItemWidget",
    kind: "XV.RelationWidget",
    list: "XV.ItemList",
    nameAttribute: "description1",
    descripAttribute: "description2"
  });

  // ..........................................................
  // OPPORTUNITY
  //

  enyo.kind({
    name: "XV.OpportunityWidget",
    kind: "XV.RelationWidget",
    list: "XV.OpportunityList"
  });

  // ..........................................................
  // PROJECT
  //

  enyo.kind({
    name: "XV.ProjectWidget",
    kind: "XV.RelationWidget",
    list: "XV.ProjectList"
  });

  // ..........................................................
  // USER ACCOUNT
  //

  enyo.kind({
    name: "XV.UserAccountWidget",
    kind: "XV.RelationWidget",
    list: "XV.UserAccountList",
    keyAttribute: "username",
    nameAttribute: "properName"
  });

}());
<|endoftext|>


<commit_before>define(function(require, module, exports) {
    main.consumes = ["Dialog", "util"];
    main.provides = ["dialog.filechange"];
    return main;

    function main(options, imports, register) {
        var Dialog = imports.Dialog;
        var util = imports.util;

        /***** Initialization *****/

        var plugin = new Dialog("Ajax.org", main.consumes, {
            name: "dialog.filechange",
            title: "File changed",
            body: "
You or a collaborator has changed this file.
"
                           + "Which version would you like to use?",
            allowClose: false,
            modal: false,
            width: 600,
            elements: [
                { type: "checkbox", id: "applyall", caption: "Apply to all changed files" },
                { type: "filler" },
                { type: "button", id: "keepmine", caption: "Keep Mine", color: "blue" },
                { type: "button", id: "useremote", caption: "Use Remote", color: "blue" },
                { type: "button", id: "mergeboth", caption: "Merge Both", color: "green", "default": true },
            ]
        });

        /***** Methods *****/

        function show(title, header, body, onlocal, onremote, onmerge, options) {
            options = options || {};
            return plugin.queue(function(){
                plugin.title = title;
                plugin.heading = util.escapeXml(header);
                if (body) plugin.body = util.escapeXml(body);

                var cb = plugin.getElement("applyall");
                cb.uncheck();
                cb.setAttribute("visible", options.all !== false);

                if (options.merge) {
                    var mergeBoth = plugin.getElement("mergeboth");
                    if (options.merge.caption) mergeBoth.setAttribute("caption", options.mergeBoth.caption);
                }

                plugin.update([
                    { id: "keepmine",  onclick: function(){ plugin.hide(); onlocal(cb.value); } },
                    { id: "useremote", onclick: function(){ plugin.hide(); onremote(cb.value); } },
                    { id: "mergeboth", visible: options.merge, onclick: function(){ plugin.hide(); onmerge(cb.value); } }
                ]);
            });
        }

        /***** Register *****/

        plugin.freezePublicAPI({
            /**
             *
             */
            set all(value) {
                plugin.update([
                    { id: "applyall", visible: value}
                ]);
            },

            /**
             *
             */
            show: show
        });

        register("", {
            "dialog.filechange": plugin,
        });
    }
});<commit_msg>Minor fixes<commit_after>define(function(require, module, exports) {
    main.consumes = ["Dialog", "util"];
    main.provides = ["dialog.filechange"];
    return main;

    function main(options, imports, register) {
        var Dialog = imports.Dialog;
        var util = imports.util;

        /***** Initialization *****/

        var plugin = new Dialog("Ajax.org", main.consumes, {
            name: "dialog.filechange",
            title: "File changed",
            body: "
You or a collaborator has changed this file.
"
                           + "Which version would you like to use?",
            allowClose: false,
            modal: false,
            width: 600,
            elements: [
                { type: "checkbox", id: "applyall", caption: "Apply to all changed files" },
                { type: "filler" },
                { type: "button", id: "keepmine", caption: "Keep Mine", color: "blue" },
                { type: "button", id: "useremote", caption: "Use Remote", color: "blue" },
                { type: "button", id: "mergeboth", caption: "Merge Both", color: "green", "default": true },
            ]
        });

        /***** Methods *****/

        function show(title, header, body, onlocal, onremote, onmerge, options) {
            options = options || {};
            return plugin.queue(function(){
                plugin.title = title;
                plugin.heading = util.escapeXml(header);
                if (body) plugin.body = util.escapeXml(body);

                var cb = plugin.getElement("applyall");
                cb.uncheck();
                cb.setAttribute("visible", options.all !== false);

                if (options.merge) {
                    var mergeBoth = plugin.getElement("mergeboth");
                    if (options.merge.caption) mergeBoth.setAttribute("caption", options.merge.caption);
                }

                plugin.update([
                    { id: "keepmine",  onclick: function(){ plugin.hide(); onlocal(cb.value); } },
                    { id: "useremote", onclick: function(){ plugin.hide(); onremote(cb.value); } },
                    { id: "mergeboth", visible: !!options.merge, onclick: function(){ plugin.hide(); onmerge(cb.value); } }
                ]);
            });
        }

        /***** Register *****/

        plugin.freezePublicAPI({
            /**
             *
             */
            set all(value) {
                plugin.update([
                    { id: "applyall", visible: value}
                ]);
            },

            /**
             *
             */
            show: show
        });

        register("", {
            "dialog.filechange": plugin,
        });
    }
});<|endoftext|>


<commit_before>/**
 * @author Jordi Torres
 */

define( [
    'osg/Vec3',
    'osg/Matrix',
    'osgUtil/TriangleIntersector'
], function ( Vec3, Matrix, TriangleIntersector ) {

    'use strict';

    var LineSegmentIntersector = function () {
        this._start = Vec3.create();
        this._end = Vec3.create();
        this._iStart = Vec3.create();
        this._iEnd = Vec3.create();
        this._intersections = [];
    };

    LineSegmentIntersector.prototype = {
        set: function ( start, end ) {
            Vec3.copy( start, this._start );
            Vec3.copy( end, this._end );
        },
        setStart: function ( start ) {
            Vec3.copy( start, this._start );
        },
        setEnd: function ( end ) {
            Vec3.copy( end, this._end );
        },
        reset: function () {
            // Clear the intersections vector
            this._intersections.length = 0;
        },
        enter: function ( node ) {
            // Not working if culling disabled ??
            return !node.isCullingActive() || this.intersects( node.getBound() );
        },
        // Optimized Intersection Segment/Sphere
        // From Real-Time Rendering, by Tomas Akenine-Möller, Eric Haines, and Naty Hoffman. Pages 738-741
        intersects: ( function () {
            var l = Vec3.create();
            return function ( bsphere ) {
                if ( !bsphere.valid() ) return false;
                Vec3.sub( bsphere.center(), this._iStart, l );
                var l2 = Vec3.length2( l );
                if ( l2 <= bsphere.radius2() ) return true;
                var s = Vec3.dot( l, this._iEnd );
                if ( s < 0 ) return false;
                var m2 = l2 - ( s * s );
                if ( m2 > bsphere.radius2() ) return false;
                return true;
            };
        } )(),

        intersect: function ( iv, node ) {
            var kdtree = node.getShape();
            if ( kdtree ) {
                // Use KDTREES
                return kdtree.intersectRay( this._iStart, this._iEnd, this._intersections, iv.nodePath );
            } else {
                // Use the TriangleIntersector
                var ti = new TriangleIntersector();
                ti.setNodePath( iv.nodePath );
                ti.set( this._iStart, this._iEnd );
                ti.apply( node );
                var l = ti._intersections.length;
                if ( l > 0 ) {
                    // Intersection/s exists
                    for ( var i = 0; i < l; i++ ) {
                        this._intersections.push( ti._intersections[ i ] );
                    }
                    return true;
                }
                // No intersection found
                return false;
            }
            return false;
        },
        getIntersections: function () {
            return this._intersections;
        },
        setCurrentTransformation: function ( matrix ) {
            Matrix.inverse( matrix, matrix );
            Matrix.transformVec3( matrix, this._start, this._iStart );
            Matrix.transformVec3( matrix, this._end, this._iEnd );
        }
    };

    return LineSegmentIntersector;
} );
<commit_msg>Fixed float comparison<commit_after>/**
 * @author Jordi Torres
 */

define( [
    'osg/Vec3',
    'osg/Matrix',
    'osgUtil/TriangleIntersector'
], function ( Vec3, Matrix, TriangleIntersector ) {

    'use strict';

    var LineSegmentIntersector = function () {
        this._start = Vec3.create();
        this._end = Vec3.create();
        this._iStart = Vec3.create();
        this._iEnd = Vec3.create();
        this._intersections = [];
    };

    LineSegmentIntersector.prototype = {
        set: function ( start, end ) {
            Vec3.copy( start, this._start );
            Vec3.copy( end, this._end );
        },
        setStart: function ( start ) {
            Vec3.copy( start, this._start );
        },
        setEnd: function ( end ) {
            Vec3.copy( end, this._end );
        },
        reset: function () {
            // Clear the intersections vector
            this._intersections.length = 0;
        },
        enter: function ( node ) {
            // Not working if culling disabled ??
            return !node.isCullingActive() || this.intersects( node.getBound() );
        },
        // Optimized Intersection Segment/Sphere
        // From Real-Time Rendering, by Tomas Akenine-Möller, Eric Haines, and Naty Hoffman. Pages 738-741
        intersects: ( function () {
            var l = Vec3.create();
            return function ( bsphere ) {
                if ( !bsphere.valid() ) return false;
                Vec3.sub( bsphere.center(), this._iStart, l );
                var l2 = Vec3.length2( l );
                if ( l2 <= bsphere.radius2() ) return true;
                var s = Vec3.dot( l, this._iEnd );
                if ( s < 0.0 ) return false;
                var m2 = l2 - ( s * s );
                if ( m2 > bsphere.radius2() ) return false;
                return true;
            };
        } )(),

        intersect: function ( iv, node ) {
            var kdtree = node.getShape();
            if ( kdtree ) {
                // Use KDTREES
                return kdtree.intersectRay( this._iStart, this._iEnd, this._intersections, iv.nodePath );
            } else {
                // Use the TriangleIntersector
                var ti = new TriangleIntersector();
                ti.setNodePath( iv.nodePath );
                ti.set( this._iStart, this._iEnd );
                ti.apply( node );
                var l = ti._intersections.length;
                if ( l > 0 ) {
                    // Intersection/s exists
                    for ( var i = 0; i < l; i++ ) {
                        this._intersections.push( ti._intersections[ i ] );
                    }
                    return true;
                }
                // No intersection found
                return false;
            }
            return false;
        },
        getIntersections: function () {
            return this._intersections;
        },
        setCurrentTransformation: function ( matrix ) {
            Matrix.inverse( matrix, matrix );
            Matrix.transformVec3( matrix, this._start, this._iStart );
            Matrix.transformVec3( matrix, this._end, this._iEnd );
        }
    };

    return LineSegmentIntersector;
} );
<|endoftext|>


<commit_before>/*
	This file is the meat & potatoes of this site - as it were.
	The intention is for this file to be 100% open source which means that
	adding tests and sending pull requests is absolutely encouraged!

	Having said that, there are a few rules:

	1. Commas at the beginning of the translation. This is to make it easier to
		add new translations as we go along without worry of missing a comma.
	2. Make sure that any translations reflect the following syntax:
		{
			name:'', // Essentially: what this translation matches for in plain old English.
			in:'',   // The regex that determines whether what the user has input has a matching translation.
			out:''   // The regex that the user was after.
		}

	NOTE: There's no need to include any negations. To save duplicating too much stuff below, the negation works
			by checking if the user typed 'no'/'not' before any part of the query and stripping that out. If the
			regex returned by any of the individual translations below is within a range (ie: '[...]'), then `^`
			will automatically be prepended inside.
 */
define({
	list:[
		 {
			name:'anything',
			in:'anything',
			out:'.*'
		 }
		,{
			name:'start of the line',
			in:'(from the )?(start|beginning) of (the )?line',
			out:'^'
		 }
		,{
			name:'end of the line',
			in:'(to the )?end of (the )?line',
			out:'$'
		 }
		,{
			name:'new line',
			in:'(new( |\-)?line|enter)',
			out:'(\\r)?\\n'
		 }
		,{
			name:'non white space',
			in:'no(n|t)? white ?space',
			out:'\\S'
		 }
		,{
			name:'white space',
			in:'white ?space',
			out:'\\s'
		 }
		,{
			name:'a number',
			in:'(a |a single |one |1 )?number',
			out:'[0-9]'
		 }
		,{
			name:'numbers',
			in:'(one or more )?numbers',
			out:'[0-9]+'
		 }
		,{
			name:'any amount of numbers',
			in:'any( number of| amount of)? numbers',
			out:'[0-9]+'
		 }
		,{
			name:'? numbers',
			in:'([0-9]+ ) numbers?',
			out:'[0-9]{$1}'
		 }
		,{
			name:'between ? and ? numbers',
			in:'(between |from )?([0-9]+) (and|to) ([0-9]+) numbers',
			out:'[0-9]{$2,$4}'
		 }
		,{
			name:'a letter',
			in:'(a|a single|one|1)( uppercase or lowercase| uppercase/lowercase| lowercase or uppercase| lowercase/uppercase)? letter',
			out:'[a-zA-Z]'
		 }
		,{
			name:'letters',
			in:'(one or more )?( uppercase or lowercase| uppercase/lowercase| lowercase or uppercase| lowercase/uppercase)? letters',
			out:'[a-zA-Z]+'
		 }
		,{
			name:'one or more letters',
			in:'(1|one) or more letters',
			out:'[a-zA-Z]+'
		}
		,{
			name:'any amount of letters',
			in:'any( number of| amount of)?( uppercase or lowercase| uppercase/lowercase| lowercase or uppercase| lowercase/uppercase)? letters',
			out:'[a-zA-Z]+'
		 }
		,{
			name:'? letters',
			in:'([0-9]+)( uppercase or lowercase| uppercase/lowercase| lowercase or uppercase| lowercase/uppercase)? letters',
			out:'[a-zA-Z]{$1}'
		 }
		,{
			name:'between ? and ? letters',
			in:'(between |from )?([0-9]+) (and|to) ([0-9]+)( uppercase or lowercase| uppercase/lowercase| lowercase or uppercase| lowercase/uppercase)? letters',
			out:'[a-zA-Z]{$2,$4}'
		 }
		,{
			name:'a lowercase letter',
			in:'(a|a single|one|1) lowercase letter',
			out:'[a-z]'
		 }
		,{
			name:'lowercase letters',
			in:'(one or more )?lowercase letters',
			out:'[a-z]+'
		 }
		,{
			name:'any amount of lowercase letters',
			in:'any( number of| amount of)? lowercase letters',
			out:'[a-z]+'
		 }
		,{
			name:'? lowercase letters',
			in:'([0-9]+) lowercase letters',
			out:'[a-z]{$1}'
		 }
		,{
			name:'between ? and ? lowercase letters',
			in:'(between |from )?([0-9]+) (and|to) ([0-9]+) lowercase letters',
			out:'[a-z]{$2,$4}'
		 }
		,{
			name:'an uppercase letter',
			in:'(a|an|a single|one|1) uppercase letter',
			out:'[A-Z]'
		 }
		,{
			name:'uppercase letters',
			in:'(one or more )?uppercase letters',
			out:'[A-Z]+'
		 }
		,{
			name:'any amount of uppercase letters',
			in:'any( number of| amount of)? uppercase letters',
			out:'[A-Z]+'
		 }
		,{
			name:'? uppercase letters',
			in:'([0-9]+) uppercase letters',
			out:'[A-Z]{$1}'
		 }
		,{
			name:'between ? and ? uppercase letters',
			in:'(between |from )?([0-9]+) (and|to) ([0-9]+) uppercase letters',
			out:'[A-Z]{$2,$4}'
		 }
		,{
			name:'a number and/or letter',
			in:'(a )?number( &| and| or)?( uppercase or lowercase| uppercase/lowercase| lowercase or uppercase| lowercase/uppercase)? letter',
			out:'[a-zA-Z0-9]'
		 }
		,{
			name:'numbers and/or letters',
			in:'(one or more )?numbers( &| and| or)?( uppercase or lowercase| uppercase/lowercase| lowercase or uppercase| lowercase/uppercase)? letters',
			out:'[a-zA-Z0-9]+'
		 }
		,{
			name:'any amount of numbers and/or letters',
			in:'any( number of| amount of)? numbers( &| and| or)?( uppercase or lowercase| uppercase/lowercase| lowercase or uppercase| lowercase/uppercase)? letters',
			out:'[a-zA-Z0-9]+'
		 }
		,{
			name:'a number and/or lowercase letter',
			in:'(a |1 |a single )?number( &| and| or)? lowercase letter',
			out:'[a-z0-9]'
		 }
		,{
			name:'numbers and/or lowercase letters',
			in:'(one or more )?numbers( &| and| or)? lowercase letters',
			out:'[a-z0-9]+'
		 }
		,{
			name:'any amount of numbers and/or lowercase letters',
			in:'any( number of| amount of)? numbers( &| and| or)? lowercase letters',
			out:'[a-z0-9]+'
		 }
		,{
			name:'a number and/or uppercase letter',
			in:'(a |1 | a single )?number( &| and| or)? uppercase letter',
			out:'[A-Z0-9]'
		 }
		,{
			name:'numbers and/or uppercase letters',
			in:'(one or more )?numbers( &| and| or)? uppercase letters',
			out:'[A-Z0-9]+'
		 }
		,{
			name:'any amount of numbers and/or uppercase letters',
			in:'any( number of| amount of)? numbers( &| and| or)? uppercase letters',
			out:'[a-zA-Z0-9]+'
		 }
		,{
			name:'a (letter|number) and/or (number|letter)',
			in:'(a|one|1) (letter|number)( &| and| or) (number|letter)',
			out:'[a-zA-Z0-9]{2}'
		}
		,{
			name:'? numbers and/or lowercase letters',
			in:'([0-9]+) numbers( &| and| or) lowercase letters',
			out:'[a-z0-9]{$1}'
		}
		,{
			name:'? numbers and/or uppercase letters',
			in:'([0-9]+) numbers( &| and| or) uppercase letters',
			out:'[A-Z0-9]{$1}'
		}
		,{
			name:'? (letters|numbers) and/or (numbers|letters)',
			in:'([0-9]+) (letters|numbers)( &| and| or) (numbers|letters)',
			out:'[a-zA-Z0-9]{$1}'
		}
		,{
			name:'? to ? (letters|numbers) and/or (numbers|letters)',
			in:'([0-9]+) to ([0-9]+) (letters|numbers)( &| and| or) (numbers|letters)',
			out:'[a-zA-Z0-9]{$1,$2}'
		}
		,{
			name:'a word',
			in:'(a|one|1) word',
			out:'\\w'
		 }
		,{
			name:'words',
			in:'(one or more )?words',
			out:'\\w+'
		 }
		,{
			name:'any amount of words',
			in:'any( number of| amount of)? words',
			out:'\\w+'
		 }
		,{
			name:'? words',
			in:'([0-9]+) words',
			out:'\\w{$1}'
		 }
		,{
			name:'between ? and ? words',
			in:'(between |from )?([0-9]+) (and|to) ([0-9]+) words',
			out:'\\w{$2,$4}'
		 }
		,{
			name:'a non-word',
			in:'(a|one|1) non-?word',
			out:'\\W'
		 }
		,{
			name:'non-words',
			in:'(one or more )?non-?words',
			out:'\\W+'
		 }
		,{
			name:'any amount of non-words',
			in:'any( number of| amount of)? non-?words',
			out:'\\W+'
		 }
		,{
			name:'? non-words',
			in:'([0-9]+) non-?words',
			out:'\\W{$1}'
		 }
		,{
			name:'between ? and ? non-words',
			in:'(between |from )?([0-9]+) (and|to) ([0-9]+) non-?words',
			out:'\\W{$2,$4}'
		 }
		,{
			name:'a digit',
			in:'(a|one|1) digit',
			out:'\\d'
		 }
		,{
			name:'digits',
			in:'(one or more )?digits',
			out:'\\d+'
		 }
		,{
			name:'any amount of digits',
			in:'any( number of| amount of)? digits',
			out:'\\d+'
		 }
		,{
			name:'? digits',
			in:'([0-9]+) digits',
			out:'\\d{$1}'
		 }
		,{
			name:'between ? and ? digits',
			in:'(between |from )?([0-9]+) (and|to) ([0-9]+) digits',
			out:'\\d{$2,$4}'
		 }
		,{
			name:'a non-digit',
			in:'(a|one|1) non-?digit',
			out:'\\D'
		 }
		,{
			name:'non-digits',
			in:'(one or more )?non-?digits',
			out:'\\D+'
		 }
		,{
			name:'any amount of non-digits',
			in:'any( number of| amount of)? non-?digits',
			out:'\\D+'
		 }
		,{
			name:'? non-digits',
			in:'([0-9]+) non-?digits',
			out:'\\D{$1}'
		 }
		,{
			name:'between ? and ? non-digits',
			in:'(between |from )?([0-9]+) (and|to) ([0-9]+) non-?digits',
			out:'\\D{$2,$4}'
		 }
	],
	shortcuts: [
		 {
			name:'email', // modified to include lowercase letters from http://www.regular-expressions.info/email.html
			in:'email',
			out:'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$'
		 }
		,{
		 	name:'uk postcode', // http://regexlib.com/REDetails.aspx?regexp_id=260
		 	in:'(uk|UK) post(al)? ?code',
		 	out:'^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$'
		 }
		,{
			name:'a vowel',
			in:'(a |one |1 )?vowel',
			out:'[aeiou]'
		 }
		,{
			name:'vowels',
			in:'(one or more )?vowels',
			out:'[aeiou]+'
		 }
		,{
			name:'? vowels',
			in:'([0-9]+) vowels',
			out:'[aeiou]{$1}'
		 }
		,{
			name:'between ? and ? vowels',
			in:'(between |from )?([0-9]+) (and|to) ([0-9]+) vowels',
			out:'[aeiou]{$2,$4}'
		 }
		,{
			name:'IP address', // http://regexlib.com/REDetails.aspx?regexp_id=32
			in:'(ip address|IP|^ip$)( address)?',
			out:'^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$'
		 }
		,{
			name:'Phone Number', // http://regexlib.com/REDetails.aspx?regexp_id=73
			in:'([tT]ele)?([pP]hone) num(ber)?',
			out:'^(\(?\+?[0-9]*\)?)?[0-9_\- \(\)]*$'
		 }
		,{
			name:'HTML tag', // http://www.regular-expressions.info/examples.html
			in:'(HTML|html)( tag)?',
			out:'<([a-zA-Z][a-zA-Z0-9]*)\b[^>]*>(.*?)</\1>'
		 }
		,{
			name:'Hex colour', // http://stackoverflow.com/questions/1636350/how-to-identify-a-given-string-is-hex-color-format#1636354
			in:'[hH]ex [cC]olou?r',
			out:'^#(?:[0-9a-fA-F]{3}){1,2}$'
		 }
		,{
			name:'URL', // http://net.tutsplus.com/tutorials/other/8-regular-expressions-you-should-know/
			in:'(url|URL)',
			out:'^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$'
		 }
	]
});
<commit_msg>add test for ? numbers and lower/uppercase letters<commit_after>/*
	This file is the meat & potatoes of this site - as it were.
	The intention is for this file to be 100% open source which means that
	adding tests and sending pull requests is absolutely encouraged!

	Having said that, there are a few rules:

	1. Commas at the beginning of the translation. This is to make it easier to
		add new translations as we go along without worry of missing a comma.
	2. Make sure that any translations reflect the following syntax:
		{
			name:'', // Essentially: what this translation matches for in plain old English.
			in:'',   // The regex that determines whether what the user has input has a matching translation.
			out:''   // The regex that the user was after.
		}

	NOTE: There's no need to include any negations. To save duplicating too much stuff below, the negation works
			by checking if the user typed 'no'/'not' before any part of the query and stripping that out. If the
			regex returned by any of the individual translations below is within a range (ie: '[...]'), then `^`
			will automatically be prepended inside.
 */
define({
	list:[
		 {
			name:'anything',
			in:'anything',
			out:'.*'
		 }
		,{
			name:'start of the line',
			in:'(from the )?(start|beginning) of (the )?line',
			out:'^'
		 }
		,{
			name:'end of the line',
			in:'(to the )?end of (the )?line',
			out:'$'
		 }
		,{
			name:'new line',
			in:'(new( |\-)?line|enter)',
			out:'(\\r)?\\n'
		 }
		,{
			name:'non white space',
			in:'no(n|t)? white ?space',
			out:'\\S'
		 }
		,{
			name:'white space',
			in:'white ?space',
			out:'\\s'
		 }
		,{
			name:'a number',
			in:'(a |a single |one |1 )?number',
			out:'[0-9]'
		 }
		,{
			name:'numbers',
			in:'(one or more )?numbers',
			out:'[0-9]+'
		 }
		,{
			name:'any amount of numbers',
			in:'any( number of| amount of)? numbers',
			out:'[0-9]+'
		 }
		,{
			name:'? numbers',
			in:'([0-9]+ ) numbers?',
			out:'[0-9]{$1}'
		 }
		,{
			name:'between ? and ? numbers',
			in:'(between |from )?([0-9]+) (and|to) ([0-9]+) numbers',
			out:'[0-9]{$2,$4}'
		 }
		,{
			name:'a letter',
			in:'(a|a single|one|1)( uppercase or lowercase| uppercase/lowercase| lowercase or uppercase| lowercase/uppercase)? letter',
			out:'[a-zA-Z]'
		 }
		,{
			name:'letters',
			in:'(one or more )?( uppercase or lowercase| uppercase/lowercase| lowercase or uppercase| lowercase/uppercase)? letters',
			out:'[a-zA-Z]+'
		 }
		,{
			name:'one or more letters',
			in:'(1|one) or more letters',
			out:'[a-zA-Z]+'
		}
		,{
			name:'any amount of letters',
			in:'any( number of| amount of)?( uppercase or lowercase| uppercase/lowercase| lowercase or uppercase| lowercase/uppercase)? letters',
			out:'[a-zA-Z]+'
		 }
		,{
			name:'? letters',
			in:'([0-9]+)( uppercase or lowercase| uppercase/lowercase| lowercase or uppercase| lowercase/uppercase)? letters',
			out:'[a-zA-Z]{$1}'
		 }
		,{
			name:'between ? and ? letters',
			in:'(between |from )?([0-9]+) (and|to) ([0-9]+)( uppercase or lowercase| uppercase/lowercase| lowercase or uppercase| lowercase/uppercase)? letters',
			out:'[a-zA-Z]{$2,$4}'
		 }
		,{
			name:'a lowercase letter',
			in:'(a|a single|one|1) lowercase letter',
			out:'[a-z]'
		 }
		,{
			name:'lowercase letters',
			in:'(one or more )?lowercase letters',
			out:'[a-z]+'
		 }
		,{
			name:'any amount of lowercase letters',
			in:'any( number of| amount of)? lowercase letters',
			out:'[a-z]+'
		 }
		,{
			name:'? lowercase letters',
			in:'([0-9]+) lowercase letters',
			out:'[a-z]{$1}'
		 }
		,{
			name:'between ? and ? lowercase letters',
			in:'(between |from )?([0-9]+) (and|to) ([0-9]+) lowercase letters',
			out:'[a-z]{$2,$4}'
		 }
		,{
			name:'an uppercase letter',
			in:'(a|an|a single|one|1) uppercase letter',
			out:'[A-Z]'
		 }
		,{
			name:'uppercase letters',
			in:'(one or more )?uppercase letters',
			out:'[A-Z]+'
		 }
		,{
			name:'any amount of uppercase letters',
			in:'any( number of| amount of)? uppercase letters',
			out:'[A-Z]+'
		 }
		,{
			name:'? uppercase letters',
			in:'([0-9]+) uppercase letters',
			out:'[A-Z]{$1}'
		 }
		,{
			name:'between ? and ? uppercase letters',
			in:'(between |from )?([0-9]+) (and|to) ([0-9]+) uppercase letters',
			out:'[A-Z]{$2,$4}'
		 }
		,{
			name:'a number and/or letter',
			in:'(a )?number( &| and| or)?( uppercase or lowercase| uppercase/lowercase| lowercase or uppercase| lowercase/uppercase)? letter',
			out:'[a-zA-Z0-9]'
		 }
		,{
			name:'numbers and/or letters',
			in:'(one or more )?numbers( &| and| or)?( uppercase or lowercase| uppercase/lowercase| lowercase or uppercase| lowercase/uppercase)? letters',
			out:'[a-zA-Z0-9]+'
		 }
		,{
			name:'any amount of numbers and/or letters',
			in:'any( number of| amount of)? numbers( &| and| or)?( uppercase or lowercase| uppercase/lowercase| lowercase or uppercase| lowercase/uppercase)? letters',
			out:'[a-zA-Z0-9]+'
		 }
		,{
			name:'a number and/or lowercase letter',
			in:'(a |1 |a single )?number( &| and| or)? lowercase letter',
			out:'[a-z0-9]'
		 }
		,{
			name:'numbers and/or lowercase letters',
			in:'(one or more )?numbers( &| and| or)? lowercase letters',
			out:'[a-z0-9]+'
		 }
		,{
			name:'any amount of numbers and/or lowercase letters',
			in:'any( number of| amount of)? numbers( &| and| or)? lowercase letters',
			out:'[a-z0-9]+'
		 }
		,{
			name:'a number and/or uppercase letter',
			in:'(a |1 | a single )?number( &| and| or)? uppercase letter',
			out:'[A-Z0-9]'
		 }
		,{
			name:'numbers and/or uppercase letters',
			in:'(one or more )?numbers( &| and| or)? uppercase letters',
			out:'[A-Z0-9]+'
		 }
		,{
			name:'any amount of numbers and/or uppercase letters',
			in:'any( number of| amount of)? numbers( &| and| or)? uppercase letters',
			out:'[a-zA-Z0-9]+'
		 }
		,{
			name:'a (letter|number) and/or (number|letter)',
			in:'(a|one|1) (letter|number)( &| and| or) (number|letter)',
			out:'[a-zA-Z0-9]{2}'
		}
		,{
			name:'? numbers and/or lowercase/uppercase letters',
			in:'([0-9]+) numbers( &| and| or) (lowercase|uppercase)( &| and| or) (uppercase|lowercase) letters',
			out:'[a-zA-Z0-9]{$1}'
		}
		,{
			name:'? numbers and/or lowercase letters',
			in:'([0-9]+) numbers( &| and| or) lowercase letters',
			out:'[a-z0-9]{$1}'
		}
		,{
			name:'? numbers and/or uppercase letters',
			in:'([0-9]+) numbers( &| and| or) uppercase letters',
			out:'[A-Z0-9]{$1}'
		}
		,{
			name:'? (letters|numbers) and/or (numbers|letters)',
			in:'([0-9]+) (letters|numbers)( &| and| or) (numbers|letters)',
			out:'[a-zA-Z0-9]{$1}'
		}
		,{
			name:'? to ? (letters|numbers) and/or (numbers|letters)',
			in:'([0-9]+) to ([0-9]+) (letters|numbers)( &| and| or) (numbers|letters)',
			out:'[a-zA-Z0-9]{$1,$2}'
		}
		,{
			name:'a word',
			in:'(a|one|1) word',
			out:'\\w'
		 }
		,{
			name:'words',
			in:'(one or more )?words',
			out:'\\w+'
		 }
		,{
			name:'any amount of words',
			in:'any( number of| amount of)? words',
			out:'\\w+'
		 }
		,{
			name:'? words',
			in:'([0-9]+) words',
			out:'\\w{$1}'
		 }
		,{
			name:'between ? and ? words',
			in:'(between |from )?([0-9]+) (and|to) ([0-9]+) words',
			out:'\\w{$2,$4}'
		 }
		,{
			name:'a non-word',
			in:'(a|one|1) non-?word',
			out:'\\W'
		 }
		,{
			name:'non-words',
			in:'(one or more )?non-?words',
			out:'\\W+'
		 }
		,{
			name:'any amount of non-words',
			in:'any( number of| amount of)? non-?words',
			out:'\\W+'
		 }
		,{
			name:'? non-words',
			in:'([0-9]+) non-?words',
			out:'\\W{$1}'
		 }
		,{
			name:'between ? and ? non-words',
			in:'(between |from )?([0-9]+) (and|to) ([0-9]+) non-?words',
			out:'\\W{$2,$4}'
		 }
		,{
			name:'a digit',
			in:'(a|one|1) digit',
			out:'\\d'
		 }
		,{
			name:'digits',
			in:'(one or more )?digits',
			out:'\\d+'
		 }
		,{
			name:'any amount of digits',
			in:'any( number of| amount of)? digits',
			out:'\\d+'
		 }
		,{
			name:'? digits',
			in:'([0-9]+) digits',
			out:'\\d{$1}'
		 }
		,{
			name:'between ? and ? digits',
			in:'(between |from )?([0-9]+) (and|to) ([0-9]+) digits',
			out:'\\d{$2,$4}'
		 }
		,{
			name:'a non-digit',
			in:'(a|one|1) non-?digit',
			out:'\\D'
		 }
		,{
			name:'non-digits',
			in:'(one or more )?non-?digits',
			out:'\\D+'
		 }
		,{
			name:'any amount of non-digits',
			in:'any( number of| amount of)? non-?digits',
			out:'\\D+'
		 }
		,{
			name:'? non-digits',
			in:'([0-9]+) non-?digits',
			out:'\\D{$1}'
		 }
		,{
			name:'between ? and ? non-digits',
			in:'(between |from )?([0-9]+) (and|to) ([0-9]+) non-?digits',
			out:'\\D{$2,$4}'
		 }
	],
	shortcuts: [
		 {
			name:'email', // modified to include lowercase letters from http://www.regular-expressions.info/email.html
			in:'email',
			out:'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$'
		 }
		,{
		 	name:'uk postcode', // http://regexlib.com/REDetails.aspx?regexp_id=260
		 	in:'(uk|UK) post(al)? ?code',
		 	out:'^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$'
		 }
		,{
			name:'a vowel',
			in:'(a |one |1 )?vowel',
			out:'[aeiou]'
		 }
		,{
			name:'vowels',
			in:'(one or more )?vowels',
			out:'[aeiou]+'
		 }
		,{
			name:'? vowels',
			in:'([0-9]+) vowels',
			out:'[aeiou]{$1}'
		 }
		,{
			name:'between ? and ? vowels',
			in:'(between |from )?([0-9]+) (and|to) ([0-9]+) vowels',
			out:'[aeiou]{$2,$4}'
		 }
		,{
			name:'IP address', // http://regexlib.com/REDetails.aspx?regexp_id=32
			in:'(ip address|IP|^ip$)( address)?',
			out:'^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$'
		 }
		,{
			name:'Phone Number', // http://regexlib.com/REDetails.aspx?regexp_id=73
			in:'([tT]ele)?([pP]hone) num(ber)?',
			out:'^(\(?\+?[0-9]*\)?)?[0-9_\- \(\)]*$'
		 }
		,{
			name:'HTML tag', // http://www.regular-expressions.info/examples.html
			in:'(HTML|html)( tag)?',
			out:'<([a-zA-Z][a-zA-Z0-9]*)\b[^>]*>(.*?)</\1>'
		 }
		,{
			name:'Hex colour', // http://stackoverflow.com/questions/1636350/how-to-identify-a-given-string-is-hex-color-format#1636354
			in:'[hH]ex [cC]olou?r',
			out:'^#(?:[0-9a-fA-F]{3}){1,2}$'
		 }
		,{
			name:'URL', // http://net.tutsplus.com/tutorials/other/8-regular-expressions-you-should-know/
			in:'(url|URL)',
			out:'^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$'
		 }
	]
});
<|endoftext|>


<commit_before>var mongo = require('mongoskin');
// mLab connection URI
var uri = process.env.MONGODB_URI;
// promisify mongoskin with bluebird
Object.keys(mongo).forEach(function (key) {
    var value = mongo[key];
    if (typeof value === "function") {
        Promise.promisifyAll(value);
        Promise.promisifyAll(value.prototype);
    }
});
Promise.promisifyAll(mongo);

module.exports = function (userId) {
    var Trello = require('node-trello');
    var encryption = require('./encryption.js');
    var Promise = require("bluebird");
    var key = process.env.HUBOT_TRELLO_KEY;
    var Promise = require("bluebird");
    var q = require('q')
    var deferred = q.defer();

    // connect to mLab database
    var db = mongo.MongoClient.connect(uri);

    // var db = require('./mlab-login').db();
    var collection = db.collectionAsync('trelloTokens');
    collection.find({ id: userId }).toArrayAsync()
        .then(function (dbData) {
            console.log(dbData)
            var decryptedToken = dbData[0].token;
            console.log(decryptedToken);
            let token = encryption.decrypt(decryptedToken);
            let userId = dbData[0].id;
            let username = dbData[0].username;
            let t = new Trello(key, token);
            var trello = Promise.promisifyAll(t);
            deferred.resolve(trello);
            // in some way CHECK TOKEN VALIDATION
        })
        .catch(dbError => {
            console.log(dbError)
            deferred.reject(dbError);

        })
    return deferred.promise;
}
<commit_msg>testing<commit_after>var mongo = require('mongoskin');
var Promise = require("bluebird");
// mLab connection URI
var uri = process.env.MONGODB_URI;
// promisify mongoskin with bluebird
Object.keys(mongo).forEach(function (key) {
    var value = mongo[key];
    if (typeof value === "function") {
        Promise.promisifyAll(value);
        Promise.promisifyAll(value.prototype);
    }
});
Promise.promisifyAll(mongo);

module.exports = function (userId) {
    var Trello = require('node-trello');
    var encryption = require('./encryption.js');
    var Promise = require("bluebird");
    var key = process.env.HUBOT_TRELLO_KEY;
    var q = require('q')
    var deferred = q.defer();

    // connect to mLab database
    var db = mongo.MongoClient.connect(uri);

    // var db = require('./mlab-login').db();
    var collection = db.collectionAsync('trelloTokens');
    collection.find({ id: userId }).toArrayAsync()
        .then(function (dbData) {
            console.log(dbData)
            var decryptedToken = dbData[0].token;
            console.log(decryptedToken);
            let token = encryption.decrypt(decryptedToken);
            let userId = dbData[0].id;
            let username = dbData[0].username;
            let t = new Trello(key, token);
            var trello = Promise.promisifyAll(t);
            deferred.resolve(trello);
            // in some way CHECK TOKEN VALIDATION
        })
        .catch(dbError => {
            console.log(dbError)
            deferred.reject(dbError);

        })
    return deferred.promise;
}
<|endoftext|>


<commit_before>function validateSentence(sentence) {
    // 参考
    // https://www.jtf.jp/jp/style_guide/pdf/jtf_style_guide.pdf
    // 2.1.5. カタカナ
    // カタカナは「全角」で表記します。半角カタカナは特殊な用途を除いて、原則として使いません。
    var terms = [
        {
            'expected':'[ァ-ンヲ]',
            'pattern':['[ｧ-ﾝｦ]'],
        }
    ];

    var regex = new RegExp( terms[0]['pattern'], 'g');
    // 形態素解析するかどうか
    if ( sentence.content.match(regex) ) {
        addError('半角のカタカナが含まれています。全角に修正してください', sentence);
    };
};
<commit_msg>modify<commit_after>function validateSentence(sentence) {
    // 参考
    // https://www.jtf.jp/jp/style_guide/pdf/jtf_style_guide.pdf
    // 2.1.5. カタカナ
    // カタカナは「全角」で表記します。半角カタカナは特殊な用途を除いて、原則として使いません。
    var terms = [
        {
            'expected':'[ァ-ンヲ]',
            'pattern':['[ｧ-ﾝｦ]'],
        }
    ];

    var regex = new RegExp( terms[0]['pattern'], 'g');
    // 形態素解析するかどうか
    if ( sentence.content.match(regex) ) {
        addError('半角のカタカナが含まれています。全角に修正してください', sentence);
    }
}
<|endoftext|>